blob: 79d4ae6d62b30a9a175fd3b7ec213f74e5664fa1 [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
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800218 return setDeviceConnectionStateInt(device, state, device_address);
219}
220
221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
222 audio_policy_dev_state_t state,
223 const char *device_address)
224{
Eric Laurent22226012014-08-01 17:00:54 -0700225 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700226 // handle legacy remote submix case where the address was not always specified
227 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
228 address = String8("0");
229 }
Eric Laurente552edb2014-03-10 17:42:56 -0700230
Eric Laurent22226012014-08-01 17:00:54 -0700231 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
232 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700233
234 // connect/disconnect only 1 device at a time
235 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
236
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output devices
238 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700239 SortedVector <audio_io_handle_t> outputs;
240
Eric Laurent1afeecb2014-05-14 08:52:28 -0700241 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
242 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // save a copy of the opened output descriptors before any output is opened or closed
246 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
247 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 switch (state)
249 {
250 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700253 ALOGW("setDeviceConnectionState() device already connected: %x", device);
254 return INVALID_OPERATION;
255 }
256 ALOGV("setDeviceConnectionState() connecting device %x", device);
257
Eric Laurente552edb2014-03-10 17:42:56 -0700258 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 index = mAvailableOutputDevices.add(devDesc);
260 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700261 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700262 if (module == 0) {
263 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
264 device);
265 mAvailableOutputDevices.remove(devDesc);
266 return INVALID_OPERATION;
267 }
268 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700269 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 } else {
271 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700272 }
273
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700274 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700275 mAvailableOutputDevices.remove(devDesc);
276 return INVALID_OPERATION;
277 }
278 // outputs should never be empty here
279 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
280 "checkOutputsForDevice() returned no outputs but status OK");
281 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
282 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700283 break;
284 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700285 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700287 ALOGW("setDeviceConnectionState() device not connected: %x", device);
288 return INVALID_OPERATION;
289 }
290
Paul McLean5c477aa2014-08-20 16:47:57 -0700291 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
292
293 // Set Disconnect to HALs
294 AudioParameter param = AudioParameter(address);
295 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
296 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700300
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700301 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700302 } break;
303
304 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
310 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700311 checkA2dpSuspend();
312 checkOutputForAllStrategies();
313 // outputs must be closed after checkOutputForAllStrategies() is executed
314 if (!outputs.isEmpty()) {
315 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700316 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 // close unused outputs after device disconnection or direct outputs that have been
318 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700319 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700320 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
321 (desc->mDirectOpenCount == 0))) {
322 closeOutput(outputs[i]);
323 }
324 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 // check again after closing A2DP output to reset mA2dpSuspended if needed
326 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700327 }
328
329 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 if (mPhoneState == AUDIO_MODE_IN_CALL) {
331 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
332 updateCallRouting(newDevice);
333 }
Eric Laurente552edb2014-03-10 17:42:56 -0700334 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700335 audio_io_handle_t output = mOutputs.keyAt(i);
336 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
337 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
338 true /*fromCache*/);
339 // do not force device change on duplicated output because if device is 0, it will
340 // also force a device 0 for the two outputs it is duplicated to which may override
341 // a valid device selection on those outputs.
342 bool force = !mOutputs.valueAt(i)->isDuplicated()
343 && (!deviceDistinguishesOnAddress(device)
344 // always force when disconnecting (a non-duplicated device)
345 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
346 setOutputDevice(output, newDevice, force, 0);
347 }
Eric Laurente552edb2014-03-10 17:42:56 -0700348 }
349
Eric Laurent72aa32f2014-05-30 18:51:48 -0700350 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700351 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700352 } // end if is output device
353
Eric Laurente552edb2014-03-10 17:42:56 -0700354 // handle input devices
355 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700356 SortedVector <audio_io_handle_t> inputs;
357
Eric Laurent1afeecb2014-05-14 08:52:28 -0700358 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
359 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700361 switch (state)
362 {
363 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700364 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700365 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700366 ALOGW("setDeviceConnectionState() device already connected: %d", device);
367 return INVALID_OPERATION;
368 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700369 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700370 if (module == NULL) {
371 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
372 device);
373 return INVALID_OPERATION;
374 }
Eric Laurentd4692962014-05-05 18:13:44 -0700375 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
376 return INVALID_OPERATION;
377 }
378
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 index = mAvailableInputDevices.add(devDesc);
380 if (index >= 0) {
381 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700382 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 } else {
384 return NO_MEMORY;
385 }
Eric Laurentd4692962014-05-05 18:13:44 -0700386 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700387
388 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700389 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700390 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700391 ALOGW("setDeviceConnectionState() device not connected: %d", device);
392 return INVALID_OPERATION;
393 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700394
395 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
396
397 // Set Disconnect to HALs
398 AudioParameter param = AudioParameter(address);
399 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 default:
408 ALOGE("setDeviceConnectionState() invalid state: %x", state);
409 return BAD_VALUE;
410 }
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700413
Eric Laurentc2730ba2014-07-20 15:47:07 -0700414 if (mPhoneState == AUDIO_MODE_IN_CALL) {
415 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
416 updateCallRouting(newDevice);
417 }
418
Eric Laurentb52c1522014-05-20 11:27:36 -0700419 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700421 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700422
423 ALOGW("setDeviceConnectionState() invalid device: %x", device);
424 return BAD_VALUE;
425}
426
Eric Laurente0720872014-03-11 09:30:41 -0700427audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700428 const char *device_address)
429{
Eric Laurent3b73df72014-03-11 09:06:29 -0700430 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700431 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700432 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700433 // handle legacy remote submix case where the address was not always specified
434 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
435 devDesc->mAddress = String8("0");
436 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 ssize_t index;
438 DeviceVector *deviceVector;
439
Eric Laurente552edb2014-03-10 17:42:56 -0700440 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700441 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700442 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 deviceVector = &mAvailableInputDevices;
444 } else {
445 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700447 }
448
Eric Laurent3a4311c2014-03-17 12:00:47 -0700449 index = deviceVector->indexOf(devDesc);
450 if (index >= 0) {
451 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
452 } else {
453 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
454 }
Eric Laurente552edb2014-03-10 17:42:56 -0700455}
456
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
458{
459 bool createTxPatch = false;
460 struct audio_patch patch;
461 patch.num_sources = 1;
462 patch.num_sinks = 1;
463 status_t status;
464 audio_patch_handle_t afPatchHandle;
465 DeviceVector deviceList;
466
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800467 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
469
470 // release existing RX patch if any
471 if (mCallRxPatch != 0) {
472 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
473 mCallRxPatch.clear();
474 }
475 // release TX patch if any
476 if (mCallTxPatch != 0) {
477 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
478 mCallTxPatch.clear();
479 }
480
481 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
482 // via setOutputDevice() on primary output.
483 // Otherwise, create two audio patches for TX and RX path.
484 if (availablePrimaryOutputDevices() & rxDevice) {
485 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
486 // If the TX device is also on the primary HW module, setOutputDevice() will take care
487 // of it due to legacy implementation. If not, create a patch.
488 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
489 == AUDIO_DEVICE_NONE) {
490 createTxPatch = true;
491 }
492 } else {
493 // create RX path audio patch
494 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
495 ALOG_ASSERT(!deviceList.isEmpty(),
496 "updateCallRouting() selected device not in output device list");
497 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
498 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
499 ALOG_ASSERT(!deviceList.isEmpty(),
500 "updateCallRouting() no telephony RX device");
501 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
502
503 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
504 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
505
506 // request to reuse existing output stream if one is already opened to reach the RX device
507 SortedVector<audio_io_handle_t> outputs =
508 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700509 audio_io_handle_t output = selectOutput(outputs,
510 AUDIO_OUTPUT_FLAG_NONE,
511 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700512 if (output != AUDIO_IO_HANDLE_NONE) {
513 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
514 ALOG_ASSERT(!outputDesc->isDuplicated(),
515 "updateCallRouting() RX device output is duplicated");
516 outputDesc->toAudioPortConfig(&patch.sources[1]);
517 patch.num_sources = 2;
518 }
519
520 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
521 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
522 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
523 status);
524 if (status == NO_ERROR) {
525 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
526 &patch, mUidCached);
527 mCallRxPatch->mAfPatchHandle = afPatchHandle;
528 mCallRxPatch->mUid = mUidCached;
529 }
530 createTxPatch = true;
531 }
532 if (createTxPatch) {
533
534 struct audio_patch patch;
535 patch.num_sources = 1;
536 patch.num_sinks = 1;
537 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
538 ALOG_ASSERT(!deviceList.isEmpty(),
539 "updateCallRouting() selected device not in input device list");
540 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
541 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
542 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
543 ALOG_ASSERT(!deviceList.isEmpty(),
544 "updateCallRouting() no telephony TX device");
545 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
546 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
547
548 SortedVector<audio_io_handle_t> outputs =
549 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700550 audio_io_handle_t output = selectOutput(outputs,
551 AUDIO_OUTPUT_FLAG_NONE,
552 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700553 // request to reuse existing output stream if one is already opened to reach the TX
554 // path output device
555 if (output != AUDIO_IO_HANDLE_NONE) {
556 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
557 ALOG_ASSERT(!outputDesc->isDuplicated(),
558 "updateCallRouting() RX device output is duplicated");
559 outputDesc->toAudioPortConfig(&patch.sources[1]);
560 patch.num_sources = 2;
561 }
562
563 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
564 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
565 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
566 status);
567 if (status == NO_ERROR) {
568 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
569 &patch, mUidCached);
570 mCallTxPatch->mAfPatchHandle = afPatchHandle;
571 mCallTxPatch->mUid = mUidCached;
572 }
573 }
574}
575
Eric Laurente0720872014-03-11 09:30:41 -0700576void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700577{
578 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700579 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700580 ALOGW("setPhoneState() invalid state %d", state);
581 return;
582 }
583
584 if (state == mPhoneState ) {
585 ALOGW("setPhoneState() setting same state %d", state);
586 return;
587 }
588
589 // if leaving call state, handle special case of active streams
590 // pertaining to sonification strategy see handleIncallSonification()
591 if (isInCall()) {
592 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700593 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800594 if (stream == AUDIO_STREAM_PATCH) {
595 continue;
596 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700597 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700598 }
599 }
600
601 // store previous phone state for management of sonification strategy below
602 int oldState = mPhoneState;
603 mPhoneState = state;
604 bool force = false;
605
606 // are we entering or starting a call
607 if (!isStateInCall(oldState) && isStateInCall(state)) {
608 ALOGV(" Entering call in setPhoneState()");
609 // force routing command to audio hardware when starting a call
610 // even if no device change is needed
611 force = true;
612 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
613 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
614 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
615 }
616 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
617 ALOGV(" Exiting call in setPhoneState()");
618 // force routing command to audio hardware when exiting a call
619 // even if no device change is needed
620 force = true;
621 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
622 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
623 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
624 }
625 } else if (isStateInCall(state) && (state != oldState)) {
626 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
627 // force routing command to audio hardware when switching between telephony and VoIP
628 // even if no device change is needed
629 force = true;
630 }
631
632 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700633 checkA2dpSuspend();
634 checkOutputForAllStrategies();
635 updateDevicesAndOutputs();
636
Eric Laurent1f2f2232014-06-02 12:01:23 -0700637 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700638
Eric Laurente552edb2014-03-10 17:42:56 -0700639 int delayMs = 0;
640 if (isStateInCall(state)) {
641 nsecs_t sysTime = systemTime();
642 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700643 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700644 // mute media and sonification strategies and delay device switch by the largest
645 // latency of any output where either strategy is active.
646 // This avoid sending the ring tone or music tail into the earpiece or headset.
647 if ((desc->isStrategyActive(STRATEGY_MEDIA,
648 SONIFICATION_HEADSET_MUSIC_DELAY,
649 sysTime) ||
650 desc->isStrategyActive(STRATEGY_SONIFICATION,
651 SONIFICATION_HEADSET_MUSIC_DELAY,
652 sysTime)) &&
653 (delayMs < (int)desc->mLatency*2)) {
654 delayMs = desc->mLatency*2;
655 }
656 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
657 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
658 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
659 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
660 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
661 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
662 }
663 }
664
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
666 // the device returned is not necessarily reachable via this output
667 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
668 // force routing command to audio hardware when ending call
669 // even if no device change is needed
670 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
671 rxDevice = hwOutputDesc->device();
672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674 if (state == AUDIO_MODE_IN_CALL) {
675 updateCallRouting(rxDevice, delayMs);
676 } else if (oldState == AUDIO_MODE_IN_CALL) {
677 if (mCallRxPatch != 0) {
678 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
679 mCallRxPatch.clear();
680 }
681 if (mCallTxPatch != 0) {
682 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
683 mCallTxPatch.clear();
684 }
685 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
686 } else {
687 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689 // if entering in call state, handle special case of active streams
690 // pertaining to sonification strategy see handleIncallSonification()
691 if (isStateInCall(state)) {
692 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700693 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800694 if (stream == AUDIO_STREAM_PATCH) {
695 continue;
696 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700697 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700698 }
699 }
700
701 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700702 if (state == AUDIO_MODE_RINGTONE &&
703 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700704 mLimitRingtoneVolume = true;
705 } else {
706 mLimitRingtoneVolume = false;
707 }
708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700712{
713 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
714
715 bool forceVolumeReeval = false;
716 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700717 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
718 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
719 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700720 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
721 return;
722 }
723 forceVolumeReeval = true;
724 mForceUse[usage] = config;
725 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700726 case AUDIO_POLICY_FORCE_FOR_MEDIA:
727 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
728 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
729 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
730 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800731 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700732 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
733 return;
734 }
735 mForceUse[usage] = config;
736 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700737 case AUDIO_POLICY_FORCE_FOR_RECORD:
738 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
739 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700740 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
741 return;
742 }
743 mForceUse[usage] = config;
744 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700745 case AUDIO_POLICY_FORCE_FOR_DOCK:
746 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
747 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
748 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
749 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
750 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700751 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
752 }
753 forceVolumeReeval = true;
754 mForceUse[usage] = config;
755 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
757 if (config != AUDIO_POLICY_FORCE_NONE &&
758 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700759 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
760 }
761 forceVolumeReeval = true;
762 mForceUse[usage] = config;
763 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900764 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
765 if (config != AUDIO_POLICY_FORCE_NONE &&
766 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
767 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
768 }
769 mForceUse[usage] = config;
770 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700771 default:
772 ALOGW("setForceUse() invalid usage %d", usage);
773 break;
774 }
775
776 // check for device and output changes triggered by new force usage
777 checkA2dpSuspend();
778 checkOutputForAllStrategies();
779 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700780 if (mPhoneState == AUDIO_MODE_IN_CALL) {
781 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
782 updateCallRouting(newDevice);
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784 for (size_t i = 0; i < mOutputs.size(); i++) {
785 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700786 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700787 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
788 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
789 }
Eric Laurente552edb2014-03-10 17:42:56 -0700790 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
791 applyStreamVolumes(output, newDevice, 0, true);
792 }
793 }
794
795 audio_io_handle_t activeInput = getActiveInput();
796 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700797 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700798 }
799
800}
801
Eric Laurente0720872014-03-11 09:30:41 -0700802audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700803{
804 return mForceUse[usage];
805}
806
Eric Laurente0720872014-03-11 09:30:41 -0700807void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700808{
809 ALOGV("setSystemProperty() property %s, value %s", property, value);
810}
811
812// Find a direct output profile compatible with the parameters passed, even if the input flags do
813// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700814sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700815 audio_devices_t device,
816 uint32_t samplingRate,
817 audio_format_t format,
818 audio_channel_mask_t channelMask,
819 audio_output_flags_t flags)
820{
821 for (size_t i = 0; i < mHwModules.size(); i++) {
822 if (mHwModules[i]->mHandle == 0) {
823 continue;
824 }
825 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700826 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800827 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700828 NULL /*updatedSamplingRate*/, format, channelMask,
829 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
830 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700831 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
832 return profile;
833 }
Eric Laurente552edb2014-03-10 17:42:56 -0700834 }
835 }
836 return 0;
837}
838
Eric Laurente0720872014-03-11 09:30:41 -0700839audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700840 uint32_t samplingRate,
841 audio_format_t format,
842 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700843 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700844 const audio_offload_info_t *offloadInfo)
845{
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
848 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
849 device, stream, samplingRate, format, channelMask, flags);
850
Eric Laurente83b55d2014-11-14 10:06:21 -0800851 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
852 stream, samplingRate,format, channelMask,
853 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700854}
855
Eric Laurente83b55d2014-11-14 10:06:21 -0800856status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
857 audio_io_handle_t *output,
858 audio_session_t session,
859 audio_stream_type_t *stream,
860 uint32_t samplingRate,
861 audio_format_t format,
862 audio_channel_mask_t channelMask,
863 audio_output_flags_t flags,
864 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865{
Eric Laurente83b55d2014-11-14 10:06:21 -0800866 audio_attributes_t attributes;
867 if (attr != NULL) {
868 if (!isValidAttributes(attr)) {
869 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
870 attr->usage, attr->content_type, attr->flags,
871 attr->tags);
872 return BAD_VALUE;
873 }
874 attributes = *attr;
875 } else {
876 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
877 ALOGE("getOutputForAttr(): invalid stream type");
878 return BAD_VALUE;
879 }
880 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700881 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800882
Eric Laurent275e8e92014-11-30 15:14:47 -0800883 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
884 sp<AudioOutputDescriptor> desc;
885 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
886 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
887 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
888 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
889 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
890 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
891 desc = mPolicyMixes[i]->mOutput;
892 break;
893 }
894 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
895 strncmp(attributes.tags + strlen("addr="),
896 mPolicyMixes[i]->mMix.mRegistrationId.string(),
897 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
898 desc = mPolicyMixes[i]->mOutput;
899 break;
900 }
901 }
902 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
903 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
904 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
905 strncmp(attributes.tags + strlen("addr="),
906 mPolicyMixes[i]->mMix.mRegistrationId.string(),
907 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
908 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800909 }
910 }
911 if (desc != 0) {
912 if (!audio_is_linear_pcm(format)) {
913 return BAD_VALUE;
914 }
Eric Laurentc722f302014-12-10 11:21:49 -0800915 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800916 *stream = streamTypefromAttributesInt(&attributes);
917 *output = desc->mIoHandle;
918 ALOGV("getOutputForAttr() returns output %d", *output);
919 return NO_ERROR;
920 }
921 }
922 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
923 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
924 return BAD_VALUE;
925 }
926
Eric Laurent93c3d412014-08-01 14:48:35 -0700927 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800928 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700929
Eric Laurente83b55d2014-11-14 10:06:21 -0800930 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700931 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700934 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
935 }
936
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700937 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700938 device, samplingRate, format, channelMask, flags);
939
Eric Laurente83b55d2014-11-14 10:06:21 -0800940 *stream = streamTypefromAttributesInt(&attributes);
941 *output = getOutputForDevice(device, session, *stream,
942 samplingRate, format, channelMask,
943 flags, offloadInfo);
944 if (*output == AUDIO_IO_HANDLE_NONE) {
945 return INVALID_OPERATION;
946 }
947 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700948}
949
950audio_io_handle_t AudioPolicyManager::getOutputForDevice(
951 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800952 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700953 audio_stream_type_t stream,
954 uint32_t samplingRate,
955 audio_format_t format,
956 audio_channel_mask_t channelMask,
957 audio_output_flags_t flags,
958 const audio_offload_info_t *offloadInfo)
959{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700960 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700961 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700963
Eric Laurente552edb2014-03-10 17:42:56 -0700964#ifdef AUDIO_POLICY_TEST
965 if (mCurOutput != 0) {
966 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
967 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
968
969 if (mTestOutputs[mCurOutput] == 0) {
970 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700971 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700972 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700974 outputDesc->mFlags =
975 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700976 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700977 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
978 config.sample_rate = mTestSamplingRate;
979 config.channel_mask = mTestChannels;
980 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700981 if (offloadInfo != NULL) {
982 config.offload_info = *offloadInfo;
983 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700984 status = mpClientInterface->openOutput(0,
985 &mTestOutputs[mCurOutput],
986 &config,
987 &outputDesc->mDevice,
988 String8(""),
989 &outputDesc->mLatency,
990 outputDesc->mFlags);
991 if (status == NO_ERROR) {
992 outputDesc->mSamplingRate = config.sample_rate;
993 outputDesc->mFormat = config.format;
994 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700995 AudioParameter outputCmd = AudioParameter();
996 outputCmd.addInt(String8("set_id"),mCurOutput);
997 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
998 addOutput(mTestOutputs[mCurOutput], outputDesc);
999 }
1000 }
1001 return mTestOutputs[mCurOutput];
1002 }
1003#endif //AUDIO_POLICY_TEST
1004
1005 // open a direct output if required by specified parameters
1006 //force direct flag if offload flag is set: offloading implies a direct output stream
1007 // and all common behaviors are driven by checking only the direct flag
1008 // this should normally be set appropriately in the policy configuration file
1009 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001010 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001011 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001012 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1013 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1014 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001015 // only allow deep buffering for music stream type
1016 if (stream != AUDIO_STREAM_MUSIC) {
1017 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1018 }
Eric Laurente552edb2014-03-10 17:42:56 -07001019
Eric Laurentb732cf52014-09-24 19:08:21 -07001020 sp<IOProfile> profile;
1021
1022 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001023 // and not explicitly requested
1024 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1025 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001026 audio_channel_count_from_out_mask(channelMask) <= 2) {
1027 goto non_direct_output;
1028 }
1029
Eric Laurente552edb2014-03-10 17:42:56 -07001030 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1031 // creating an offloaded track and tearing it down immediately after start when audioflinger
1032 // detects there is an active non offloadable effect.
1033 // FIXME: We should check the audio session here but we do not have it in this context.
1034 // This may prevent offloading in rare situations where effects are left active by apps
1035 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001036
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1038 !isNonOffloadableEffectEnabled()) {
1039 profile = getProfileForDirectOutput(device,
1040 samplingRate,
1041 format,
1042 channelMask,
1043 (audio_output_flags_t)flags);
1044 }
1045
Eric Laurent1c333e22014-05-20 10:48:17 -07001046 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001047 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001048
1049 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001050 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1052 outputDesc = desc;
1053 // reuse direct output if currently open and configured with same parameters
1054 if ((samplingRate == outputDesc->mSamplingRate) &&
1055 (format == outputDesc->mFormat) &&
1056 (channelMask == outputDesc->mChannelMask)) {
1057 outputDesc->mDirectOpenCount++;
1058 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1059 return mOutputs.keyAt(i);
1060 }
1061 }
1062 }
1063 // close direct output if currently open and configured with different parameters
1064 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001065 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001066 }
1067 outputDesc = new AudioOutputDescriptor(profile);
1068 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001069 outputDesc->mLatency = 0;
1070 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001071 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1072 config.sample_rate = samplingRate;
1073 config.channel_mask = channelMask;
1074 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001075 if (offloadInfo != NULL) {
1076 config.offload_info = *offloadInfo;
1077 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001078 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1079 &output,
1080 &config,
1081 &outputDesc->mDevice,
1082 String8(""),
1083 &outputDesc->mLatency,
1084 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001087 if (status != NO_ERROR ||
1088 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1089 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1090 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001091 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1092 "format %d %d, channelMask %04x %04x", output, samplingRate,
1093 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1094 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001096 mpClientInterface->closeOutput(output);
1097 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001098 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001099 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001100 outputDesc->mSamplingRate = config.sample_rate;
1101 outputDesc->mChannelMask = config.channel_mask;
1102 outputDesc->mFormat = config.format;
1103 outputDesc->mRefCount[stream] = 0;
1104 outputDesc->mStopTime[stream] = 0;
1105 outputDesc->mDirectOpenCount = 1;
1106
Eric Laurente552edb2014-03-10 17:42:56 -07001107 audio_io_handle_t srcOutput = getOutputForEffect();
1108 addOutput(output, outputDesc);
1109 audio_io_handle_t dstOutput = getOutputForEffect();
1110 if (dstOutput == output) {
1111 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1112 }
1113 mPreviousOutputs = mOutputs;
1114 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001115 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001116 return output;
1117 }
1118
Eric Laurentb732cf52014-09-24 19:08:21 -07001119non_direct_output:
1120
Eric Laurente552edb2014-03-10 17:42:56 -07001121 // ignoring channel mask due to downmix capability in mixer
1122
1123 // open a non direct output
1124
1125 // for non direct outputs, only PCM is supported
1126 if (audio_is_linear_pcm(format)) {
1127 // get which output is suitable for the specified stream. The actual
1128 // routing change will happen when startOutput() will be called
1129 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1130
Eric Laurent8838a382014-09-08 16:44:28 -07001131 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1132 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1133 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001134 }
1135 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1136 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1137
1138 ALOGV("getOutput() returns output %d", output);
1139
1140 return output;
1141}
1142
Eric Laurente0720872014-03-11 09:30:41 -07001143audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001144 audio_output_flags_t flags,
1145 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001146{
1147 // select one output among several that provide a path to a particular device or set of
1148 // devices (the list was previously build by getOutputsForDevice()).
1149 // The priority is as follows:
1150 // 1: the output with the highest number of requested policy flags
1151 // 2: the primary output
1152 // 3: the first output in the list
1153
1154 if (outputs.size() == 0) {
1155 return 0;
1156 }
1157 if (outputs.size() == 1) {
1158 return outputs[0];
1159 }
1160
1161 int maxCommonFlags = 0;
1162 audio_io_handle_t outputFlags = 0;
1163 audio_io_handle_t outputPrimary = 0;
1164
1165 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001166 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001167 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001168 // if a valid format is specified, skip output if not compatible
1169 if (format != AUDIO_FORMAT_INVALID) {
1170 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1171 if (format != outputDesc->mFormat) {
1172 continue;
1173 }
1174 } else if (!audio_is_linear_pcm(format)) {
1175 continue;
1176 }
1177 }
1178
Eric Laurent3b73df72014-03-11 09:06:29 -07001179 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 if (commonFlags > maxCommonFlags) {
1181 outputFlags = outputs[i];
1182 maxCommonFlags = commonFlags;
1183 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1184 }
1185 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1186 outputPrimary = outputs[i];
1187 }
1188 }
1189 }
1190
1191 if (outputFlags != 0) {
1192 return outputFlags;
1193 }
1194 if (outputPrimary != 0) {
1195 return outputPrimary;
1196 }
1197
1198 return outputs[0];
1199}
1200
Eric Laurente0720872014-03-11 09:30:41 -07001201status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001202 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001203 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
1205 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1206 ssize_t index = mOutputs.indexOfKey(output);
1207 if (index < 0) {
1208 ALOGW("startOutput() unknown output %d", output);
1209 return BAD_VALUE;
1210 }
1211
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001212 // cannot start playback of STREAM_TTS if any other output is being used
1213 uint32_t beaconMuteLatency = 0;
1214 if (stream == AUDIO_STREAM_TTS) {
1215 ALOGV("\t found BEACON stream");
1216 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1217 return INVALID_OPERATION;
1218 } else {
1219 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1220 }
1221 } else {
1222 // some playback other than beacon starts
1223 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1224 }
1225
Eric Laurent1f2f2232014-06-02 12:01:23 -07001226 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001227
1228 // increment usage count for this stream on the requested output:
1229 // NOTE that the usage count is the same for duplicated output and hardware output which is
1230 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1231 outputDesc->changeRefCount(stream, 1);
1232
1233 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001234 // starting an output being rerouted?
1235 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001236 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001237 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1238 } else {
1239 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1240 }
Eric Laurente552edb2014-03-10 17:42:56 -07001241 routing_strategy strategy = getStrategy(stream);
1242 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1244 (beaconMuteLatency > 0);
1245 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001246 bool force = false;
1247 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 if (desc != outputDesc) {
1250 // force a device change if any other output is managed by the same hw
1251 // module and has a current device selection that differs from selected device.
1252 // In this case, the audio HAL must receive the new device selection so that it can
1253 // change the device currently selected by the other active output.
1254 if (outputDesc->sharesHwModuleWith(desc) &&
1255 desc->device() != newDevice) {
1256 force = true;
1257 }
1258 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001259 // a notification so that audio focus effect can propagate, or that a mute/unmute
1260 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001261 uint32_t latency = desc->latency();
1262 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1263 waitMs = latency;
1264 }
1265 }
1266 }
1267 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1268
1269 // handle special case for sonification while in call
1270 if (isInCall()) {
1271 handleIncallSonification(stream, true, false);
1272 }
1273
1274 // apply volume rules for current stream and device if necessary
1275 checkAndSetVolume(stream,
1276 mStreams[stream].getVolumeIndex(newDevice),
1277 output,
1278 newDevice);
1279
1280 // update the outputs if starting an output with a stream that can affect notification
1281 // routing
1282 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001283
1284 // Automatically enable the remote submix input when output is started on a re routing mix
1285 // of type MIX_TYPE_RECORDERS
1286 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1287 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001288 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001289 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1290 outputDesc->mPolicyMix->mRegistrationId);
1291 }
1292
Eric Laurente552edb2014-03-10 17:42:56 -07001293 if (waitMs > muteWaitMs) {
1294 usleep((waitMs - muteWaitMs) * 2 * 1000);
1295 }
1296 }
1297 return NO_ERROR;
1298}
1299
1300
Eric Laurente0720872014-03-11 09:30:41 -07001301status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001302 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001303 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001304{
1305 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1306 ssize_t index = mOutputs.indexOfKey(output);
1307 if (index < 0) {
1308 ALOGW("stopOutput() unknown output %d", output);
1309 return BAD_VALUE;
1310 }
1311
Eric Laurent1f2f2232014-06-02 12:01:23 -07001312 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001313
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001314 // always handle stream stop, check which stream type is stopping
1315 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1316
Eric Laurente552edb2014-03-10 17:42:56 -07001317 // handle special case for sonification while in call
1318 if (isInCall()) {
1319 handleIncallSonification(stream, false, false);
1320 }
1321
1322 if (outputDesc->mRefCount[stream] > 0) {
1323 // decrement usage count of this stream on the output
1324 outputDesc->changeRefCount(stream, -1);
1325 // store time at which the stream was stopped - see isStreamActive()
1326 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001327 // Automatically disable the remote submix input when output is stopped on a
1328 // re routing mix of type MIX_TYPE_RECORDERS
1329 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1330 outputDesc->mPolicyMix != NULL &&
1331 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001332 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001333 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1334 outputDesc->mPolicyMix->mRegistrationId);
1335 }
1336
Eric Laurente552edb2014-03-10 17:42:56 -07001337 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001338 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 // delay the device switch by twice the latency because stopOutput() is executed when
1340 // the track stop() command is received and at that time the audio track buffer can
1341 // still contain data that needs to be drained. The latency only covers the audio HAL
1342 // and kernel buffers. Also the latency does not always include additional delay in the
1343 // audio path (audio DSP, CODEC ...)
1344 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1345
1346 // force restoring the device selection on other active outputs if it differs from the
1347 // one being selected for this output
1348 for (size_t i = 0; i < mOutputs.size(); i++) {
1349 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001350 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001351 if (curOutput != output &&
1352 desc->isActive() &&
1353 outputDesc->sharesHwModuleWith(desc) &&
1354 (newDevice != desc->device())) {
1355 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001356 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001357 true,
1358 outputDesc->mLatency*2);
1359 }
1360 }
1361 // update the outputs if stopping one with a stream that can affect notification routing
1362 handleNotificationRoutingForStream(stream);
1363 }
1364 return NO_ERROR;
1365 } else {
1366 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1367 return INVALID_OPERATION;
1368 }
1369}
1370
Eric Laurente83b55d2014-11-14 10:06:21 -08001371void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001372 audio_stream_type_t stream __unused,
1373 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001374{
1375 ALOGV("releaseOutput() %d", output);
1376 ssize_t index = mOutputs.indexOfKey(output);
1377 if (index < 0) {
1378 ALOGW("releaseOutput() releasing unknown output %d", output);
1379 return;
1380 }
1381
1382#ifdef AUDIO_POLICY_TEST
1383 int testIndex = testOutputIndex(output);
1384 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001385 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001386 if (outputDesc->isActive()) {
1387 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001388 mOutputs.removeItem(output);
1389 mTestOutputs[testIndex] = 0;
1390 }
1391 return;
1392 }
1393#endif //AUDIO_POLICY_TEST
1394
Eric Laurent1f2f2232014-06-02 12:01:23 -07001395 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001396 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001397 if (desc->mDirectOpenCount <= 0) {
1398 ALOGW("releaseOutput() invalid open count %d for output %d",
1399 desc->mDirectOpenCount, output);
1400 return;
1401 }
1402 if (--desc->mDirectOpenCount == 0) {
1403 closeOutput(output);
1404 // If effects where present on the output, audioflinger moved them to the primary
1405 // output by default: move them back to the appropriate output.
1406 audio_io_handle_t dstOutput = getOutputForEffect();
1407 if (dstOutput != mPrimaryOutput) {
1408 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1409 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001410 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001411 }
1412 }
1413}
1414
1415
Eric Laurentcaf7f482014-11-25 17:50:47 -08001416status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1417 audio_io_handle_t *input,
1418 audio_session_t session,
1419 uint32_t samplingRate,
1420 audio_format_t format,
1421 audio_channel_mask_t channelMask,
1422 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001423{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001424 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1425 "session %d, flags %#x",
1426 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001427
Eric Laurentcaf7f482014-11-25 17:50:47 -08001428 *input = AUDIO_IO_HANDLE_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001429 audio_devices_t device;
1430 // handle legacy remote submix case where the address was not always specified
1431 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001432 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001433 audio_source_t halInputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001434 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001435
1436 if (attr->source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1437 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1438 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1439 address = String8(attr->tags + strlen("addr="));
1440 ssize_t index = mPolicyMixes.indexOfKey(address);
1441 if (index < 0) {
1442 ALOGW("getInputForAttr() no policy for address %s", address.string());
1443 return BAD_VALUE;
1444 }
Eric Laurentc722f302014-12-10 11:21:49 -08001445 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1446 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1447 return BAD_VALUE;
1448 }
1449 policyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08001450 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001451 device = getDeviceAndMixForInputSource(attr->source, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001452 if (device == AUDIO_DEVICE_NONE) {
1453 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1454 return BAD_VALUE;
1455 }
Eric Laurentc722f302014-12-10 11:21:49 -08001456 if (policyMix != NULL) {
1457 address = policyMix->mRegistrationId;
1458 } else if (audio_is_remote_submix_device(device)) {
1459 address = String8("0");
1460 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001461 // adapt channel selection to input source
1462 switch (attr->source) {
1463 case AUDIO_SOURCE_VOICE_UPLINK:
1464 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1465 break;
1466 case AUDIO_SOURCE_VOICE_DOWNLINK:
1467 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1468 break;
1469 case AUDIO_SOURCE_VOICE_CALL:
1470 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1471 break;
1472 default:
1473 break;
1474 }
1475 if (attr->source == AUDIO_SOURCE_HOTWORD) {
1476 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1477 if (index >= 0) {
1478 *input = mSoundTriggerSessions.valueFor(session);
1479 isSoundTrigger = true;
1480 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1481 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1482 } else {
1483 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1484 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001485 }
1486 }
1487
Eric Laurent275e8e92014-11-30 15:14:47 -08001488 sp<IOProfile> profile = getInputProfile(device, address,
1489 samplingRate, format, channelMask,
1490 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001491 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001492 //retry without flags
1493 audio_input_flags_t log_flags = flags;
1494 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001495 profile = getInputProfile(device, address,
1496 samplingRate, format, channelMask,
1497 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001498 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001499 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1500 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001501 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001502 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001503 }
Eric Laurente552edb2014-03-10 17:42:56 -07001504 }
1505
1506 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001507 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1508 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001509 }
1510
1511 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1512 config.sample_rate = samplingRate;
1513 config.channel_mask = channelMask;
1514 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001515
Eric Laurentcf2c0212014-07-25 16:20:43 -07001516 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001517 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001518 &config,
1519 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001520 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001521 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001522 flags);
1523
1524 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001525 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001526 (samplingRate != config.sample_rate) ||
1527 (format != config.format) ||
1528 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001529 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001530 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001531 if (*input != AUDIO_IO_HANDLE_NONE) {
1532 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001533 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001534 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001535 }
1536
Eric Laurent1f2f2232014-06-02 12:01:23 -07001537 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001538 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001539 inputDesc->mRefCount = 0;
1540 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001541 inputDesc->mSamplingRate = samplingRate;
1542 inputDesc->mFormat = format;
1543 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001544 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001545 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001546 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001547 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001548
Eric Laurentcaf7f482014-11-25 17:50:47 -08001549 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001550 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001551 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001552}
1553
Eric Laurent4dc68062014-07-28 17:26:49 -07001554status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1555 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001556{
1557 ALOGV("startInput() input %d", input);
1558 ssize_t index = mInputs.indexOfKey(input);
1559 if (index < 0) {
1560 ALOGW("startInput() unknown input %d", input);
1561 return BAD_VALUE;
1562 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001563 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001564
Eric Laurentc722f302014-12-10 11:21:49 -08001565 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001566 if (index < 0) {
1567 ALOGW("startInput() unknown session %d on input %d", session, input);
1568 return BAD_VALUE;
1569 }
1570
Glenn Kasten74a8e252014-07-24 14:09:55 -07001571 // virtual input devices are compatible with other input devices
1572 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1573
1574 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001575 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001576 if (activeInput != 0 && activeInput != input) {
1577
1578 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1579 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001580 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001581 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001582 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001583 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1584 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001585 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001586 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001587 return INVALID_OPERATION;
1588 }
1589 }
1590 }
1591
Glenn Kasten74a8e252014-07-24 14:09:55 -07001592 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001593 if (activeInputsCount() == 0) {
1594 SoundTrigger::setCaptureState(true);
1595 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001596 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001597
Eric Laurentc722f302014-12-10 11:21:49 -08001598 // automatically enable the remote submix output when input is started if not
1599 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001600 // For remote submix (a virtual device), we open only one input per capture request.
1601 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001602 String8 address = String8("");
1603 if (inputDesc->mPolicyMix == NULL) {
1604 address = String8("0");
1605 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1606 address = inputDesc->mPolicyMix->mRegistrationId;
1607 }
1608 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001609 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001610 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1611 address);
1612 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001613 }
Eric Laurente552edb2014-03-10 17:42:56 -07001614 }
1615
Eric Laurente552edb2014-03-10 17:42:56 -07001616 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1617
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001618 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001619 return NO_ERROR;
1620}
1621
Eric Laurent4dc68062014-07-28 17:26:49 -07001622status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1623 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001624{
1625 ALOGV("stopInput() input %d", input);
1626 ssize_t index = mInputs.indexOfKey(input);
1627 if (index < 0) {
1628 ALOGW("stopInput() unknown input %d", input);
1629 return BAD_VALUE;
1630 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001631 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001632
Eric Laurentc722f302014-12-10 11:21:49 -08001633 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001634 if (index < 0) {
1635 ALOGW("stopInput() unknown session %d on input %d", session, input);
1636 return BAD_VALUE;
1637 }
1638
Eric Laurente552edb2014-03-10 17:42:56 -07001639 if (inputDesc->mRefCount == 0) {
1640 ALOGW("stopInput() input %d already stopped", input);
1641 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001642 }
1643
1644 inputDesc->mRefCount--;
1645 if (inputDesc->mRefCount == 0) {
1646
Eric Laurentc722f302014-12-10 11:21:49 -08001647 // automatically disable the remote submix output when input is stopped if not
1648 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001649 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001650 String8 address = String8("");
1651 if (inputDesc->mPolicyMix == NULL) {
1652 address = String8("0");
1653 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1654 address = inputDesc->mPolicyMix->mRegistrationId;
1655 }
1656 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001657 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001658 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1659 address);
1660 }
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662
Eric Laurent1c333e22014-05-20 10:48:17 -07001663 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001664
1665 if (activeInputsCount() == 0) {
1666 SoundTrigger::setCaptureState(false);
1667 }
Eric Laurente552edb2014-03-10 17:42:56 -07001668 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001669 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001670}
1671
Eric Laurent4dc68062014-07-28 17:26:49 -07001672void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1673 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001674{
1675 ALOGV("releaseInput() %d", input);
1676 ssize_t index = mInputs.indexOfKey(input);
1677 if (index < 0) {
1678 ALOGW("releaseInput() releasing unknown input %d", input);
1679 return;
1680 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001681 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1682 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001683
Eric Laurentc722f302014-12-10 11:21:49 -08001684 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001685 if (index < 0) {
1686 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1687 return;
1688 }
Eric Laurentc722f302014-12-10 11:21:49 -08001689 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001690 if (inputDesc->mOpenRefCount == 0) {
1691 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1692 return;
1693 }
1694 inputDesc->mOpenRefCount--;
1695 if (inputDesc->mOpenRefCount > 0) {
1696 ALOGV("releaseInput() exit > 0");
1697 return;
1698 }
1699
Eric Laurent05b90f82014-08-27 15:32:29 -07001700 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001701 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001702 ALOGV("releaseInput() exit");
1703}
1704
Eric Laurentd4692962014-05-05 18:13:44 -07001705void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001706 bool patchRemoved = false;
1707
Eric Laurentd4692962014-05-05 18:13:44 -07001708 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001709 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1710 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1711 if (patch_index >= 0) {
1712 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1713 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1714 mAudioPatches.removeItemsAt(patch_index);
1715 patchRemoved = true;
1716 }
Eric Laurentd4692962014-05-05 18:13:44 -07001717 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1718 }
1719 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001720 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001721
1722 if (patchRemoved) {
1723 mpClientInterface->onAudioPatchListUpdate();
1724 }
Eric Laurentd4692962014-05-05 18:13:44 -07001725}
1726
Eric Laurente0720872014-03-11 09:30:41 -07001727void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001728 int indexMin,
1729 int indexMax)
1730{
1731 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1732 if (indexMin < 0 || indexMin >= indexMax) {
1733 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1734 return;
1735 }
1736 mStreams[stream].mIndexMin = indexMin;
1737 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001738 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1739 if (stream == AUDIO_STREAM_MUSIC) {
1740 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1741 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1742 }
Eric Laurente552edb2014-03-10 17:42:56 -07001743}
1744
Eric Laurente0720872014-03-11 09:30:41 -07001745status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001746 int index,
1747 audio_devices_t device)
1748{
1749
1750 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1751 return BAD_VALUE;
1752 }
1753 if (!audio_is_output_device(device)) {
1754 return BAD_VALUE;
1755 }
1756
1757 // Force max volume if stream cannot be muted
1758 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1759
1760 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1761 stream, device, index);
1762
1763 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1764 // clear all device specific values
1765 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1766 mStreams[stream].mIndexCur.clear();
1767 }
1768 mStreams[stream].mIndexCur.add(device, index);
1769
Eric Laurent31551f82014-10-10 18:21:56 -07001770 // update volume on all outputs whose current device is also selected by the same
1771 // strategy as the device specified by the caller
1772 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001773
1774
1775 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1776 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1777 if (stream == AUDIO_STREAM_MUSIC) {
1778 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1779 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1780 }
1781 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1782 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001783 return NO_ERROR;
1784 }
Eric Laurente552edb2014-03-10 17:42:56 -07001785 status_t status = NO_ERROR;
1786 for (size_t i = 0; i < mOutputs.size(); i++) {
1787 audio_devices_t curDevice =
1788 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001789 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001790 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1791 if (volStatus != NO_ERROR) {
1792 status = volStatus;
1793 }
1794 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001795 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1796 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1797 index, mOutputs.keyAt(i), curDevice);
1798 }
Eric Laurente552edb2014-03-10 17:42:56 -07001799 }
1800 return status;
1801}
1802
Eric Laurente0720872014-03-11 09:30:41 -07001803status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001804 int *index,
1805 audio_devices_t device)
1806{
1807 if (index == NULL) {
1808 return BAD_VALUE;
1809 }
1810 if (!audio_is_output_device(device)) {
1811 return BAD_VALUE;
1812 }
1813 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1814 // the strategy the stream belongs to.
1815 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1816 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1817 }
1818 device = getDeviceForVolume(device);
1819
1820 *index = mStreams[stream].getVolumeIndex(device);
1821 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1822 return NO_ERROR;
1823}
1824
Eric Laurente0720872014-03-11 09:30:41 -07001825audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001826 const SortedVector<audio_io_handle_t>& outputs)
1827{
1828 // select one output among several suitable for global effects.
1829 // The priority is as follows:
1830 // 1: An offloaded output. If the effect ends up not being offloadable,
1831 // AudioFlinger will invalidate the track and the offloaded output
1832 // will be closed causing the effect to be moved to a PCM output.
1833 // 2: A deep buffer output
1834 // 3: the first output in the list
1835
1836 if (outputs.size() == 0) {
1837 return 0;
1838 }
1839
1840 audio_io_handle_t outputOffloaded = 0;
1841 audio_io_handle_t outputDeepBuffer = 0;
1842
1843 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001844 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001845 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001846 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1847 outputOffloaded = outputs[i];
1848 }
1849 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1850 outputDeepBuffer = outputs[i];
1851 }
1852 }
1853
1854 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1855 outputOffloaded, outputDeepBuffer);
1856 if (outputOffloaded != 0) {
1857 return outputOffloaded;
1858 }
1859 if (outputDeepBuffer != 0) {
1860 return outputDeepBuffer;
1861 }
1862
1863 return outputs[0];
1864}
1865
Eric Laurente0720872014-03-11 09:30:41 -07001866audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001867{
1868 // apply simple rule where global effects are attached to the same output as MUSIC streams
1869
Eric Laurent3b73df72014-03-11 09:06:29 -07001870 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001871 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1872 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1873
1874 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1875 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1876 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1877
1878 return output;
1879}
1880
Eric Laurente0720872014-03-11 09:30:41 -07001881status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001882 audio_io_handle_t io,
1883 uint32_t strategy,
1884 int session,
1885 int id)
1886{
1887 ssize_t index = mOutputs.indexOfKey(io);
1888 if (index < 0) {
1889 index = mInputs.indexOfKey(io);
1890 if (index < 0) {
1891 ALOGW("registerEffect() unknown io %d", io);
1892 return INVALID_OPERATION;
1893 }
1894 }
1895
1896 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1897 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1898 desc->name, desc->memoryUsage);
1899 return INVALID_OPERATION;
1900 }
1901 mTotalEffectsMemory += desc->memoryUsage;
1902 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1903 desc->name, io, strategy, session, id);
1904 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1905
Eric Laurent1f2f2232014-06-02 12:01:23 -07001906 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1907 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1908 effectDesc->mIo = io;
1909 effectDesc->mStrategy = (routing_strategy)strategy;
1910 effectDesc->mSession = session;
1911 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001912
Eric Laurent1f2f2232014-06-02 12:01:23 -07001913 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001914
1915 return NO_ERROR;
1916}
1917
Eric Laurente0720872014-03-11 09:30:41 -07001918status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001919{
1920 ssize_t index = mEffects.indexOfKey(id);
1921 if (index < 0) {
1922 ALOGW("unregisterEffect() unknown effect ID %d", id);
1923 return INVALID_OPERATION;
1924 }
1925
Eric Laurent1f2f2232014-06-02 12:01:23 -07001926 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001927
Eric Laurent1f2f2232014-06-02 12:01:23 -07001928 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001929
Eric Laurent1f2f2232014-06-02 12:01:23 -07001930 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001931 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001932 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1933 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001934 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001935 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001936 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001937 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001938
1939 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001940
1941 return NO_ERROR;
1942}
1943
Eric Laurente0720872014-03-11 09:30:41 -07001944status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001945{
1946 ssize_t index = mEffects.indexOfKey(id);
1947 if (index < 0) {
1948 ALOGW("unregisterEffect() unknown effect ID %d", id);
1949 return INVALID_OPERATION;
1950 }
1951
1952 return setEffectEnabled(mEffects.valueAt(index), enabled);
1953}
1954
Eric Laurent1f2f2232014-06-02 12:01:23 -07001955status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001956{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001957 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001958 ALOGV("setEffectEnabled(%s) effect already %s",
1959 enabled?"true":"false", enabled?"enabled":"disabled");
1960 return INVALID_OPERATION;
1961 }
1962
1963 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001964 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001965 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001966 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001967 return INVALID_OPERATION;
1968 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001969 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001970 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1971 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001972 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001973 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001974 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1975 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001976 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001977 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001978 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1979 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001980 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001981 return NO_ERROR;
1982}
1983
Eric Laurente0720872014-03-11 09:30:41 -07001984bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001985{
1986 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001987 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1988 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1989 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001990 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001991 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001992 return true;
1993 }
1994 }
1995 return false;
1996}
1997
Eric Laurente0720872014-03-11 09:30:41 -07001998bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001999{
2000 nsecs_t sysTime = systemTime();
2001 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002002 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002003 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002004 return true;
2005 }
2006 }
2007 return false;
2008}
2009
Eric Laurente0720872014-03-11 09:30:41 -07002010bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002011 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002012{
2013 nsecs_t sysTime = systemTime();
2014 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002015 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002016 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002017 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002018 // do not consider re routing (when the output is going to a dynamic policy)
2019 // as "remote playback"
2020 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002021 return true;
2022 }
Eric Laurente552edb2014-03-10 17:42:56 -07002023 }
2024 }
2025 return false;
2026}
2027
Eric Laurente0720872014-03-11 09:30:41 -07002028bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002029{
2030 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002031 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002032 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002033 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07002034 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
2035 && (inputDescriptor->mRefCount > 0)) {
2036 return true;
2037 }
2038 }
2039 return false;
2040}
2041
Eric Laurent275e8e92014-11-30 15:14:47 -08002042// Register a list of custom mixes with their attributes and format.
2043// When a mix is registered, corresponding input and output profiles are
2044// added to the remote submix hw module. The profile contains only the
2045// parameters (sampling rate, format...) specified by the mix.
2046// The corresponding input remote submix device is also connected.
2047//
2048// When a remote submix device is connected, the address is checked to select the
2049// appropriate profile and the corresponding input or output stream is opened.
2050//
2051// When capture starts, getInputForAttr() will:
2052// - 1 look for a mix matching the address passed in attribtutes tags if any
2053// - 2 if none found, getDeviceForInputSource() will:
2054// - 2.1 look for a mix matching the attributes source
2055// - 2.2 if none found, default to device selection by policy rules
2056// At this time, the corresponding output remote submix device is also connected
2057// and active playback use cases can be transferred to this mix if needed when reconnecting
2058// after AudioTracks are invalidated
2059//
2060// When playback starts, getOutputForAttr() will:
2061// - 1 look for a mix matching the address passed in attribtutes tags if any
2062// - 2 if none found, look for a mix matching the attributes usage
2063// - 3 if none found, default to device and output selection by policy rules.
2064
2065status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2066{
2067 sp<HwModule> module;
2068 for (size_t i = 0; i < mHwModules.size(); i++) {
2069 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2070 mHwModules[i]->mHandle != 0) {
2071 module = mHwModules[i];
2072 break;
2073 }
2074 }
2075
2076 if (module == 0) {
2077 return INVALID_OPERATION;
2078 }
2079
2080 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2081
2082 for (size_t i = 0; i < mixes.size(); i++) {
2083 String8 address = mixes[i].mRegistrationId;
2084 ssize_t index = mPolicyMixes.indexOfKey(address);
2085 if (index >= 0) {
2086 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2087 continue;
2088 }
2089 audio_config_t outputConfig = mixes[i].mFormat;
2090 audio_config_t inputConfig = mixes[i].mFormat;
2091 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2092 // stereo and let audio flinger do the channel conversion if needed.
2093 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2094 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2095 module->addOutputProfile(address, &outputConfig,
2096 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2097 module->addInputProfile(address, &inputConfig,
2098 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2099 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2100 policyMix->mMix = mixes[i];
2101 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002102 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002103 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002104 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2105 address.string());
2106 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002107 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002108 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2109 address.string());
2110 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002111 }
2112 return NO_ERROR;
2113}
2114
2115status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2116{
2117 sp<HwModule> module;
2118 for (size_t i = 0; i < mHwModules.size(); i++) {
2119 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2120 mHwModules[i]->mHandle != 0) {
2121 module = mHwModules[i];
2122 break;
2123 }
2124 }
2125
2126 if (module == 0) {
2127 return INVALID_OPERATION;
2128 }
2129
2130 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2131
2132 for (size_t i = 0; i < mixes.size(); i++) {
2133 String8 address = mixes[i].mRegistrationId;
2134 ssize_t index = mPolicyMixes.indexOfKey(address);
2135 if (index < 0) {
2136 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2137 continue;
2138 }
2139
2140 mPolicyMixes.removeItemsAt(index);
2141
Eric Laurentc722f302014-12-10 11:21:49 -08002142 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2143 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2144 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002145 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002146 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2147 address.string());
2148 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002149
2150 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2151 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2152 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002153 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002154 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2155 address.string());
2156 }
2157 module->removeOutputProfile(address);
2158 module->removeInputProfile(address);
2159 }
2160 return NO_ERROR;
2161}
2162
Eric Laurente552edb2014-03-10 17:42:56 -07002163
Eric Laurente0720872014-03-11 09:30:41 -07002164status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002165{
2166 const size_t SIZE = 256;
2167 char buffer[SIZE];
2168 String8 result;
2169
2170 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2171 result.append(buffer);
2172
2173 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2174 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002175 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2176 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002177 snprintf(buffer, SIZE, " Force use for communications %d\n",
2178 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002179 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002180 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002181 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002182 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002183 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002184 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002185 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002186 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002187 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002188 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2189 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2190 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002191
Eric Laurent3a4311c2014-03-17 12:00:47 -07002192 snprintf(buffer, SIZE, " Available output devices:\n");
2193 result.append(buffer);
2194 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002195 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002196 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002197 }
2198 snprintf(buffer, SIZE, "\n Available input devices:\n");
2199 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002200 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002201 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002202 }
Eric Laurente552edb2014-03-10 17:42:56 -07002203
2204 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2205 write(fd, buffer, strlen(buffer));
2206 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002207 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002208 write(fd, buffer, strlen(buffer));
2209 mHwModules[i]->dump(fd);
2210 }
2211
2212 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2213 write(fd, buffer, strlen(buffer));
2214 for (size_t i = 0; i < mOutputs.size(); i++) {
2215 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2216 write(fd, buffer, strlen(buffer));
2217 mOutputs.valueAt(i)->dump(fd);
2218 }
2219
2220 snprintf(buffer, SIZE, "\nInputs dump:\n");
2221 write(fd, buffer, strlen(buffer));
2222 for (size_t i = 0; i < mInputs.size(); i++) {
2223 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2224 write(fd, buffer, strlen(buffer));
2225 mInputs.valueAt(i)->dump(fd);
2226 }
2227
2228 snprintf(buffer, SIZE, "\nStreams dump:\n");
2229 write(fd, buffer, strlen(buffer));
2230 snprintf(buffer, SIZE,
2231 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2232 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002233 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002234 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002235 write(fd, buffer, strlen(buffer));
2236 mStreams[i].dump(fd);
2237 }
2238
2239 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2240 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2241 write(fd, buffer, strlen(buffer));
2242
2243 snprintf(buffer, SIZE, "Registered effects:\n");
2244 write(fd, buffer, strlen(buffer));
2245 for (size_t i = 0; i < mEffects.size(); i++) {
2246 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2247 write(fd, buffer, strlen(buffer));
2248 mEffects.valueAt(i)->dump(fd);
2249 }
2250
Eric Laurent4d416952014-08-10 14:07:09 -07002251 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2252 write(fd, buffer, strlen(buffer));
2253 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2254 mAudioPatches[i]->dump(fd, 2, i);
2255 }
Eric Laurente552edb2014-03-10 17:42:56 -07002256
2257 return NO_ERROR;
2258}
2259
2260// This function checks for the parameters which can be offloaded.
2261// This can be enhanced depending on the capability of the DSP and policy
2262// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002263bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002264{
2265 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002266 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002267 offloadInfo.sample_rate, offloadInfo.channel_mask,
2268 offloadInfo.format,
2269 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2270 offloadInfo.has_video);
2271
2272 // Check if offload has been disabled
2273 char propValue[PROPERTY_VALUE_MAX];
2274 if (property_get("audio.offload.disable", propValue, "0")) {
2275 if (atoi(propValue) != 0) {
2276 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2277 return false;
2278 }
2279 }
2280
2281 // Check if stream type is music, then only allow offload as of now.
2282 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2283 {
2284 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2285 return false;
2286 }
2287
2288 //TODO: enable audio offloading with video when ready
2289 if (offloadInfo.has_video)
2290 {
2291 ALOGV("isOffloadSupported: has_video == true, returning false");
2292 return false;
2293 }
2294
2295 //If duration is less than minimum value defined in property, return false
2296 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2297 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2298 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2299 return false;
2300 }
2301 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2302 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2303 return false;
2304 }
2305
2306 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2307 // creating an offloaded track and tearing it down immediately after start when audioflinger
2308 // detects there is an active non offloadable effect.
2309 // FIXME: We should check the audio session here but we do not have it in this context.
2310 // This may prevent offloading in rare situations where effects are left active by apps
2311 // in the background.
2312 if (isNonOffloadableEffectEnabled()) {
2313 return false;
2314 }
2315
2316 // See if there is a profile to support this.
2317 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002318 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002319 offloadInfo.sample_rate,
2320 offloadInfo.format,
2321 offloadInfo.channel_mask,
2322 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002323 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2324 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002325}
2326
Eric Laurent6a94d692014-05-20 11:18:06 -07002327status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2328 audio_port_type_t type,
2329 unsigned int *num_ports,
2330 struct audio_port *ports,
2331 unsigned int *generation)
2332{
2333 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2334 generation == NULL) {
2335 return BAD_VALUE;
2336 }
2337 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2338 if (ports == NULL) {
2339 *num_ports = 0;
2340 }
2341
2342 size_t portsWritten = 0;
2343 size_t portsMax = *num_ports;
2344 *num_ports = 0;
2345 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2346 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2347 for (size_t i = 0;
2348 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2349 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2350 }
2351 *num_ports += mAvailableOutputDevices.size();
2352 }
2353 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2354 for (size_t i = 0;
2355 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2356 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2357 }
2358 *num_ports += mAvailableInputDevices.size();
2359 }
2360 }
2361 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2362 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2363 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2364 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2365 }
2366 *num_ports += mInputs.size();
2367 }
2368 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002369 size_t numOutputs = 0;
2370 for (size_t i = 0; i < mOutputs.size(); i++) {
2371 if (!mOutputs[i]->isDuplicated()) {
2372 numOutputs++;
2373 if (portsWritten < portsMax) {
2374 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2375 }
2376 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002377 }
Eric Laurent84c70242014-06-23 08:46:27 -07002378 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002379 }
2380 }
2381 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002382 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002383 return NO_ERROR;
2384}
2385
2386status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2387{
2388 return NO_ERROR;
2389}
2390
Eric Laurent1f2f2232014-06-02 12:01:23 -07002391sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002392 audio_port_handle_t id) const
2393{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002394 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002395 for (size_t i = 0; i < mOutputs.size(); i++) {
2396 outputDesc = mOutputs.valueAt(i);
2397 if (outputDesc->mId == id) {
2398 break;
2399 }
2400 }
2401 return outputDesc;
2402}
2403
Eric Laurent1f2f2232014-06-02 12:01:23 -07002404sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 audio_port_handle_t id) const
2406{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002407 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002408 for (size_t i = 0; i < mInputs.size(); i++) {
2409 inputDesc = mInputs.valueAt(i);
2410 if (inputDesc->mId == id) {
2411 break;
2412 }
2413 }
2414 return inputDesc;
2415}
2416
Eric Laurent1f2f2232014-06-02 12:01:23 -07002417sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2418 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002419{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002420 sp <HwModule> module;
2421
Eric Laurent6a94d692014-05-20 11:18:06 -07002422 for (size_t i = 0; i < mHwModules.size(); i++) {
2423 if (mHwModules[i]->mHandle == 0) {
2424 continue;
2425 }
2426 if (audio_is_output_device(device)) {
2427 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2428 {
2429 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2430 return mHwModules[i];
2431 }
2432 }
2433 } else {
2434 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2435 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2436 device & ~AUDIO_DEVICE_BIT_IN) {
2437 return mHwModules[i];
2438 }
2439 }
2440 }
2441 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002442 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002443}
2444
Eric Laurent1f2f2232014-06-02 12:01:23 -07002445sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002446{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002447 sp <HwModule> module;
2448
Eric Laurent1afeecb2014-05-14 08:52:28 -07002449 for (size_t i = 0; i < mHwModules.size(); i++)
2450 {
2451 if (strcmp(mHwModules[i]->mName, name) == 0) {
2452 return mHwModules[i];
2453 }
2454 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002455 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002456}
2457
Eric Laurentc2730ba2014-07-20 15:47:07 -07002458audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2459{
2460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2461 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2462 return devices & mAvailableOutputDevices.types();
2463}
2464
2465audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2466{
2467 audio_module_handle_t primaryHandle =
2468 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2469 audio_devices_t devices = AUDIO_DEVICE_NONE;
2470 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2471 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2472 devices |= mAvailableInputDevices[i]->mDeviceType;
2473 }
2474 }
2475 return devices;
2476}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002477
Eric Laurent6a94d692014-05-20 11:18:06 -07002478status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2479 audio_patch_handle_t *handle,
2480 uid_t uid)
2481{
2482 ALOGV("createAudioPatch()");
2483
2484 if (handle == NULL || patch == NULL) {
2485 return BAD_VALUE;
2486 }
2487 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2488
Eric Laurent874c42872014-08-08 15:13:39 -07002489 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2490 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2491 return BAD_VALUE;
2492 }
2493 // only one source per audio patch supported for now
2494 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 return INVALID_OPERATION;
2496 }
Eric Laurent874c42872014-08-08 15:13:39 -07002497
2498 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002499 return INVALID_OPERATION;
2500 }
Eric Laurent874c42872014-08-08 15:13:39 -07002501 for (size_t i = 0; i < patch->num_sinks; i++) {
2502 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2503 return INVALID_OPERATION;
2504 }
2505 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002506
2507 sp<AudioPatch> patchDesc;
2508 ssize_t index = mAudioPatches.indexOfKey(*handle);
2509
Eric Laurent6a94d692014-05-20 11:18:06 -07002510 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2511 patch->sources[0].role,
2512 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002513#if LOG_NDEBUG == 0
2514 for (size_t i = 0; i < patch->num_sinks; i++) {
2515 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2516 patch->sinks[i].role,
2517 patch->sinks[i].type);
2518 }
2519#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002520
2521 if (index >= 0) {
2522 patchDesc = mAudioPatches.valueAt(index);
2523 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2524 mUidCached, patchDesc->mUid, uid);
2525 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2526 return INVALID_OPERATION;
2527 }
2528 } else {
2529 *handle = 0;
2530 }
2531
2532 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002533 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002534 if (outputDesc == NULL) {
2535 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2536 return BAD_VALUE;
2537 }
Eric Laurent84c70242014-06-23 08:46:27 -07002538 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2539 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002540 if (patchDesc != 0) {
2541 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2542 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2543 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2544 return BAD_VALUE;
2545 }
2546 }
Eric Laurent874c42872014-08-08 15:13:39 -07002547 DeviceVector devices;
2548 for (size_t i = 0; i < patch->num_sinks; i++) {
2549 // Only support mix to devices connection
2550 // TODO add support for mix to mix connection
2551 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2552 ALOGV("createAudioPatch() source mix but sink is not a device");
2553 return INVALID_OPERATION;
2554 }
2555 sp<DeviceDescriptor> devDesc =
2556 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2557 if (devDesc == 0) {
2558 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2559 return BAD_VALUE;
2560 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002561
Eric Laurent874c42872014-08-08 15:13:39 -07002562 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002563 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002564 patch->sources[0].sample_rate,
2565 NULL, // updatedSamplingRate
2566 patch->sources[0].format,
2567 patch->sources[0].channel_mask,
2568 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2569 ALOGV("createAudioPatch() profile not supported for device %08x",
2570 devDesc->mDeviceType);
2571 return INVALID_OPERATION;
2572 }
2573 devices.add(devDesc);
2574 }
2575 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002576 return INVALID_OPERATION;
2577 }
Eric Laurent874c42872014-08-08 15:13:39 -07002578
Eric Laurent6a94d692014-05-20 11:18:06 -07002579 // TODO: reconfigure output format and channels here
2580 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002581 devices.types(), outputDesc->mIoHandle);
2582 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002583 index = mAudioPatches.indexOfKey(*handle);
2584 if (index >= 0) {
2585 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2586 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2587 }
2588 patchDesc = mAudioPatches.valueAt(index);
2589 patchDesc->mUid = uid;
2590 ALOGV("createAudioPatch() success");
2591 } else {
2592 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2593 return INVALID_OPERATION;
2594 }
2595 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2596 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2597 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002598 // only one sink supported when connecting an input device to a mix
2599 if (patch->num_sinks > 1) {
2600 return INVALID_OPERATION;
2601 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002602 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002603 if (inputDesc == NULL) {
2604 return BAD_VALUE;
2605 }
2606 if (patchDesc != 0) {
2607 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2608 return BAD_VALUE;
2609 }
2610 }
2611 sp<DeviceDescriptor> devDesc =
2612 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2613 if (devDesc == 0) {
2614 return BAD_VALUE;
2615 }
2616
Eric Laurent84c70242014-06-23 08:46:27 -07002617 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002618 devDesc->mAddress,
2619 patch->sinks[0].sample_rate,
2620 NULL, /*updatedSampleRate*/
2621 patch->sinks[0].format,
2622 patch->sinks[0].channel_mask,
2623 // FIXME for the parameter type,
2624 // and the NONE
2625 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002626 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002627 return INVALID_OPERATION;
2628 }
2629 // TODO: reconfigure output format and channels here
2630 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002631 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002632 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002633 index = mAudioPatches.indexOfKey(*handle);
2634 if (index >= 0) {
2635 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2636 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2637 }
2638 patchDesc = mAudioPatches.valueAt(index);
2639 patchDesc->mUid = uid;
2640 ALOGV("createAudioPatch() success");
2641 } else {
2642 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2643 return INVALID_OPERATION;
2644 }
2645 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2646 // device to device connection
2647 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002648 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002649 return BAD_VALUE;
2650 }
2651 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002652 sp<DeviceDescriptor> srcDeviceDesc =
2653 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002654 if (srcDeviceDesc == 0) {
2655 return BAD_VALUE;
2656 }
Eric Laurent874c42872014-08-08 15:13:39 -07002657
Eric Laurent6a94d692014-05-20 11:18:06 -07002658 //update source and sink with our own data as the data passed in the patch may
2659 // be incomplete.
2660 struct audio_patch newPatch = *patch;
2661 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002662
Eric Laurent874c42872014-08-08 15:13:39 -07002663 for (size_t i = 0; i < patch->num_sinks; i++) {
2664 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2665 ALOGV("createAudioPatch() source device but one sink is not a device");
2666 return INVALID_OPERATION;
2667 }
2668
2669 sp<DeviceDescriptor> sinkDeviceDesc =
2670 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2671 if (sinkDeviceDesc == 0) {
2672 return BAD_VALUE;
2673 }
2674 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2675
2676 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2677 // only one sink supported when connected devices across HW modules
2678 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002679 return INVALID_OPERATION;
2680 }
Eric Laurent874c42872014-08-08 15:13:39 -07002681 SortedVector<audio_io_handle_t> outputs =
2682 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2683 mOutputs);
2684 // if the sink device is reachable via an opened output stream, request to go via
2685 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002686 audio_io_handle_t output = selectOutput(outputs,
2687 AUDIO_OUTPUT_FLAG_NONE,
2688 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002689 if (output != AUDIO_IO_HANDLE_NONE) {
2690 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2691 if (outputDesc->isDuplicated()) {
2692 return INVALID_OPERATION;
2693 }
2694 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2695 newPatch.num_sources = 2;
2696 }
Eric Laurent83b88082014-06-20 18:31:16 -07002697 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002698 }
2699 // TODO: check from routing capabilities in config file and other conflicting patches
2700
2701 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2702 if (index >= 0) {
2703 afPatchHandle = patchDesc->mAfPatchHandle;
2704 }
2705
2706 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2707 &afPatchHandle,
2708 0);
2709 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2710 status, afPatchHandle);
2711 if (status == NO_ERROR) {
2712 if (index < 0) {
2713 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2714 &newPatch, uid);
2715 addAudioPatch(patchDesc->mHandle, patchDesc);
2716 } else {
2717 patchDesc->mPatch = newPatch;
2718 }
2719 patchDesc->mAfPatchHandle = afPatchHandle;
2720 *handle = patchDesc->mHandle;
2721 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002722 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002723 } else {
2724 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2725 status);
2726 return INVALID_OPERATION;
2727 }
2728 } else {
2729 return BAD_VALUE;
2730 }
2731 } else {
2732 return BAD_VALUE;
2733 }
2734 return NO_ERROR;
2735}
2736
2737status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2738 uid_t uid)
2739{
2740 ALOGV("releaseAudioPatch() patch %d", handle);
2741
2742 ssize_t index = mAudioPatches.indexOfKey(handle);
2743
2744 if (index < 0) {
2745 return BAD_VALUE;
2746 }
2747 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2748 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2749 mUidCached, patchDesc->mUid, uid);
2750 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2751 return INVALID_OPERATION;
2752 }
2753
2754 struct audio_patch *patch = &patchDesc->mPatch;
2755 patchDesc->mUid = mUidCached;
2756 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002757 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002758 if (outputDesc == NULL) {
2759 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2760 return BAD_VALUE;
2761 }
2762
2763 setOutputDevice(outputDesc->mIoHandle,
2764 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2765 true,
2766 0,
2767 NULL);
2768 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2769 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002770 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002771 if (inputDesc == NULL) {
2772 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2773 return BAD_VALUE;
2774 }
2775 setInputDevice(inputDesc->mIoHandle,
2776 getNewInputDevice(inputDesc->mIoHandle),
2777 true,
2778 NULL);
2779 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2780 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2781 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2782 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2783 status, patchDesc->mAfPatchHandle);
2784 removeAudioPatch(patchDesc->mHandle);
2785 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002786 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002787 } else {
2788 return BAD_VALUE;
2789 }
2790 } else {
2791 return BAD_VALUE;
2792 }
2793 return NO_ERROR;
2794}
2795
2796status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2797 struct audio_patch *patches,
2798 unsigned int *generation)
2799{
2800 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2801 generation == NULL) {
2802 return BAD_VALUE;
2803 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002804 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 *num_patches, patches, mAudioPatches.size());
2806 if (patches == NULL) {
2807 *num_patches = 0;
2808 }
2809
2810 size_t patchesWritten = 0;
2811 size_t patchesMax = *num_patches;
2812 for (size_t i = 0;
2813 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2814 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2815 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002816 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002817 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2818 }
2819 *num_patches = mAudioPatches.size();
2820
2821 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002822 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 return NO_ERROR;
2824}
2825
Eric Laurente1715a42014-05-20 11:30:42 -07002826status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002827{
Eric Laurente1715a42014-05-20 11:30:42 -07002828 ALOGV("setAudioPortConfig()");
2829
2830 if (config == NULL) {
2831 return BAD_VALUE;
2832 }
2833 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2834 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002835 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2836 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002837 }
2838
Eric Laurenta121f902014-06-03 13:32:54 -07002839 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002840 if (config->type == AUDIO_PORT_TYPE_MIX) {
2841 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002842 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002843 if (outputDesc == NULL) {
2844 return BAD_VALUE;
2845 }
Eric Laurent84c70242014-06-23 08:46:27 -07002846 ALOG_ASSERT(!outputDesc->isDuplicated(),
2847 "setAudioPortConfig() called on duplicated output %d",
2848 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002849 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002850 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002851 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002852 if (inputDesc == NULL) {
2853 return BAD_VALUE;
2854 }
Eric Laurenta121f902014-06-03 13:32:54 -07002855 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002856 } else {
2857 return BAD_VALUE;
2858 }
2859 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2860 sp<DeviceDescriptor> deviceDesc;
2861 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2862 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2863 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2864 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2865 } else {
2866 return BAD_VALUE;
2867 }
2868 if (deviceDesc == NULL) {
2869 return BAD_VALUE;
2870 }
Eric Laurenta121f902014-06-03 13:32:54 -07002871 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002872 } else {
2873 return BAD_VALUE;
2874 }
2875
Eric Laurenta121f902014-06-03 13:32:54 -07002876 struct audio_port_config backupConfig;
2877 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2878 if (status == NO_ERROR) {
2879 struct audio_port_config newConfig;
2880 audioPortConfig->toAudioPortConfig(&newConfig, config);
2881 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002882 }
Eric Laurenta121f902014-06-03 13:32:54 -07002883 if (status != NO_ERROR) {
2884 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002885 }
Eric Laurente1715a42014-05-20 11:30:42 -07002886
2887 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002888}
2889
2890void AudioPolicyManager::clearAudioPatches(uid_t uid)
2891{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002892 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002893 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2894 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002895 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002896 }
2897 }
2898}
2899
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002900status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2901 audio_io_handle_t *ioHandle,
2902 audio_devices_t *device)
2903{
2904 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2905 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002906 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002907
2908 mSoundTriggerSessions.add(*session, *ioHandle);
2909
2910 return NO_ERROR;
2911}
2912
2913status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2914{
2915 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2916 if (index < 0) {
2917 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2918 return BAD_VALUE;
2919 }
2920
2921 mSoundTriggerSessions.removeItem(session);
2922 return NO_ERROR;
2923}
2924
Eric Laurent6a94d692014-05-20 11:18:06 -07002925status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2926 const sp<AudioPatch>& patch)
2927{
2928 ssize_t index = mAudioPatches.indexOfKey(handle);
2929
2930 if (index >= 0) {
2931 ALOGW("addAudioPatch() patch %d already in", handle);
2932 return ALREADY_EXISTS;
2933 }
2934 mAudioPatches.add(handle, patch);
2935 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2936 "sink handle %d",
2937 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2938 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2939 return NO_ERROR;
2940}
2941
2942status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2943{
2944 ssize_t index = mAudioPatches.indexOfKey(handle);
2945
2946 if (index < 0) {
2947 ALOGW("removeAudioPatch() patch %d not in", handle);
2948 return ALREADY_EXISTS;
2949 }
2950 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2951 mAudioPatches.valueAt(index)->mAfPatchHandle);
2952 mAudioPatches.removeItemsAt(index);
2953 return NO_ERROR;
2954}
2955
Eric Laurente552edb2014-03-10 17:42:56 -07002956// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002957// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002958// ----------------------------------------------------------------------------
2959
Eric Laurent3a4311c2014-03-17 12:00:47 -07002960uint32_t AudioPolicyManager::nextUniqueId()
2961{
2962 return android_atomic_inc(&mNextUniqueId);
2963}
2964
Eric Laurent6a94d692014-05-20 11:18:06 -07002965uint32_t AudioPolicyManager::nextAudioPortGeneration()
2966{
2967 return android_atomic_inc(&mAudioPortGeneration);
2968}
2969
Eric Laurente0720872014-03-11 09:30:41 -07002970AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002971 :
2972#ifdef AUDIO_POLICY_TEST
2973 Thread(false),
2974#endif //AUDIO_POLICY_TEST
2975 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002976 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002977 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2978 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002979 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002980 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002981 mAudioPortGeneration(1),
2982 mBeaconMuteRefCount(0),
2983 mBeaconPlayingRefCount(0),
2984 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002985{
Eric Laurent6a94d692014-05-20 11:18:06 -07002986 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002987 mpClientInterface = clientInterface;
2988
Eric Laurent3b73df72014-03-11 09:06:29 -07002989 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2990 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002991 }
2992
Eric Laurent1afeecb2014-05-14 08:52:28 -07002993 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002994 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2995 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2996 ALOGE("could not load audio policy configuration file, setting defaults");
2997 defaultAudioPolicyConfig();
2998 }
2999 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003000 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003001
3002 // must be done after reading the policy
3003 initializeVolumeCurves();
3004
3005 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003006 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3007 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003008 for (size_t i = 0; i < mHwModules.size(); i++) {
3009 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3010 if (mHwModules[i]->mHandle == 0) {
3011 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3012 continue;
3013 }
3014 // open all output streams needed to access attached devices
3015 // except for direct output streams that are only opened when they are actually
3016 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003017 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003018 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3019 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003020 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003021
Eric Laurent3a4311c2014-03-17 12:00:47 -07003022 if (outProfile->mSupportedDevices.isEmpty()) {
3023 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3024 continue;
3025 }
3026
Eric Laurentd78f1532014-09-16 16:38:20 -07003027 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3028 continue;
3029 }
Eric Laurent83b88082014-06-20 18:31:16 -07003030 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3031 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3032 profileType = mDefaultOutputDevice->mDeviceType;
3033 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003034 // chose first device present in mSupportedDevices also part of
3035 // outputDeviceTypes
3036 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3037 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3038 if ((profileType & outputDeviceTypes) != 0) {
3039 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003040 }
Eric Laurente552edb2014-03-10 17:42:56 -07003041 }
3042 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003043 if ((profileType & outputDeviceTypes) == 0) {
3044 continue;
3045 }
3046 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3047
3048 outputDesc->mDevice = profileType;
3049 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3050 config.sample_rate = outputDesc->mSamplingRate;
3051 config.channel_mask = outputDesc->mChannelMask;
3052 config.format = outputDesc->mFormat;
3053 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3054 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3055 &output,
3056 &config,
3057 &outputDesc->mDevice,
3058 String8(""),
3059 &outputDesc->mLatency,
3060 outputDesc->mFlags);
3061
3062 if (status != NO_ERROR) {
3063 ALOGW("Cannot open output stream for device %08x on hw module %s",
3064 outputDesc->mDevice,
3065 mHwModules[i]->mName);
3066 } else {
3067 outputDesc->mSamplingRate = config.sample_rate;
3068 outputDesc->mChannelMask = config.channel_mask;
3069 outputDesc->mFormat = config.format;
3070
3071 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3072 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3073 ssize_t index =
3074 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3075 // give a valid ID to an attached device once confirmed it is reachable
3076 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3077 mAvailableOutputDevices[index]->mId = nextUniqueId();
3078 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3079 }
3080 }
3081 if (mPrimaryOutput == 0 &&
3082 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3083 mPrimaryOutput = output;
3084 }
3085 addOutput(output, outputDesc);
3086 setOutputDevice(output,
3087 outputDesc->mDevice,
3088 true);
3089 }
Eric Laurente552edb2014-03-10 17:42:56 -07003090 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003091 // open input streams needed to access attached devices to validate
3092 // mAvailableInputDevices list
3093 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3094 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003095 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003096
Eric Laurent3a4311c2014-03-17 12:00:47 -07003097 if (inProfile->mSupportedDevices.isEmpty()) {
3098 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3099 continue;
3100 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003101 // chose first device present in mSupportedDevices also part of
3102 // inputDeviceTypes
3103 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3104 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3105 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3106 if (profileType & inputDeviceTypes) {
3107 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003108 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003109 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003110 if ((profileType & inputDeviceTypes) == 0) {
3111 continue;
3112 }
3113 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3114
3115 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3116 inputDesc->mDevice = profileType;
3117
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003118 // find the address
3119 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3120 // the inputs vector must be of size 1, but we don't want to crash here
3121 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3122 : String8("");
3123 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3124 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3125
Eric Laurentd78f1532014-09-16 16:38:20 -07003126 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3127 config.sample_rate = inputDesc->mSamplingRate;
3128 config.channel_mask = inputDesc->mChannelMask;
3129 config.format = inputDesc->mFormat;
3130 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3131 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3132 &input,
3133 &config,
3134 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003135 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003136 AUDIO_SOURCE_MIC,
3137 AUDIO_INPUT_FLAG_NONE);
3138
3139 if (status == NO_ERROR) {
3140 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3141 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3142 ssize_t index =
3143 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3144 // give a valid ID to an attached device once confirmed it is reachable
3145 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3146 mAvailableInputDevices[index]->mId = nextUniqueId();
3147 mAvailableInputDevices[index]->mModule = mHwModules[i];
3148 }
3149 }
3150 mpClientInterface->closeInput(input);
3151 } else {
3152 ALOGW("Cannot open input stream for device %08x on hw module %s",
3153 inputDesc->mDevice,
3154 mHwModules[i]->mName);
3155 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003156 }
3157 }
3158 // make sure all attached devices have been allocated a unique ID
3159 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3160 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003161 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003162 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3163 continue;
3164 }
3165 i++;
3166 }
3167 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3168 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003169 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003170 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3171 continue;
3172 }
3173 i++;
3174 }
3175 // make sure default device is reachable
3176 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003177 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003178 }
Eric Laurente552edb2014-03-10 17:42:56 -07003179
3180 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3181
3182 updateDevicesAndOutputs();
3183
3184#ifdef AUDIO_POLICY_TEST
3185 if (mPrimaryOutput != 0) {
3186 AudioParameter outputCmd = AudioParameter();
3187 outputCmd.addInt(String8("set_id"), 0);
3188 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3189
3190 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3191 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003192 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3193 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003194 mTestLatencyMs = 0;
3195 mCurOutput = 0;
3196 mDirectOutput = false;
3197 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3198 mTestOutputs[i] = 0;
3199 }
3200
3201 const size_t SIZE = 256;
3202 char buffer[SIZE];
3203 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3204 run(buffer, ANDROID_PRIORITY_AUDIO);
3205 }
3206#endif //AUDIO_POLICY_TEST
3207}
3208
Eric Laurente0720872014-03-11 09:30:41 -07003209AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003210{
3211#ifdef AUDIO_POLICY_TEST
3212 exit();
3213#endif //AUDIO_POLICY_TEST
3214 for (size_t i = 0; i < mOutputs.size(); i++) {
3215 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003216 }
3217 for (size_t i = 0; i < mInputs.size(); i++) {
3218 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003219 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003220 mAvailableOutputDevices.clear();
3221 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003222 mOutputs.clear();
3223 mInputs.clear();
3224 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003225}
3226
Eric Laurente0720872014-03-11 09:30:41 -07003227status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003228{
3229 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3230}
3231
3232#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003233bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003234{
3235 ALOGV("entering threadLoop()");
3236 while (!exitPending())
3237 {
3238 String8 command;
3239 int valueInt;
3240 String8 value;
3241
3242 Mutex::Autolock _l(mLock);
3243 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3244
3245 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3246 AudioParameter param = AudioParameter(command);
3247
3248 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3249 valueInt != 0) {
3250 ALOGV("Test command %s received", command.string());
3251 String8 target;
3252 if (param.get(String8("target"), target) != NO_ERROR) {
3253 target = "Manager";
3254 }
3255 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3256 param.remove(String8("test_cmd_policy_output"));
3257 mCurOutput = valueInt;
3258 }
3259 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3260 param.remove(String8("test_cmd_policy_direct"));
3261 if (value == "false") {
3262 mDirectOutput = false;
3263 } else if (value == "true") {
3264 mDirectOutput = true;
3265 }
3266 }
3267 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3268 param.remove(String8("test_cmd_policy_input"));
3269 mTestInput = valueInt;
3270 }
3271
3272 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3273 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003274 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003275 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003276 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003277 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003278 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003279 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003280 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003281 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003282 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003283 if (target == "Manager") {
3284 mTestFormat = format;
3285 } else if (mTestOutputs[mCurOutput] != 0) {
3286 AudioParameter outputParam = AudioParameter();
3287 outputParam.addInt(String8("format"), format);
3288 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3289 }
3290 }
3291 }
3292 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3293 param.remove(String8("test_cmd_policy_channels"));
3294 int channels = 0;
3295
3296 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003297 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003299 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 }
3301 if (channels != 0) {
3302 if (target == "Manager") {
3303 mTestChannels = channels;
3304 } else if (mTestOutputs[mCurOutput] != 0) {
3305 AudioParameter outputParam = AudioParameter();
3306 outputParam.addInt(String8("channels"), channels);
3307 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3308 }
3309 }
3310 }
3311 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3312 param.remove(String8("test_cmd_policy_sampleRate"));
3313 if (valueInt >= 0 && valueInt <= 96000) {
3314 int samplingRate = valueInt;
3315 if (target == "Manager") {
3316 mTestSamplingRate = samplingRate;
3317 } else if (mTestOutputs[mCurOutput] != 0) {
3318 AudioParameter outputParam = AudioParameter();
3319 outputParam.addInt(String8("sampling_rate"), samplingRate);
3320 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3321 }
3322 }
3323 }
3324
3325 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3326 param.remove(String8("test_cmd_policy_reopen"));
3327
Eric Laurent1f2f2232014-06-02 12:01:23 -07003328 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003329 mpClientInterface->closeOutput(mPrimaryOutput);
3330
3331 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3332
Eric Laurente552edb2014-03-10 17:42:56 -07003333 mOutputs.removeItem(mPrimaryOutput);
3334
Eric Laurent1f2f2232014-06-02 12:01:23 -07003335 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003336 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003337 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3338 config.sample_rate = outputDesc->mSamplingRate;
3339 config.channel_mask = outputDesc->mChannelMask;
3340 config.format = outputDesc->mFormat;
3341 status_t status = mpClientInterface->openOutput(moduleHandle,
3342 &mPrimaryOutput,
3343 &config,
3344 &outputDesc->mDevice,
3345 String8(""),
3346 &outputDesc->mLatency,
3347 outputDesc->mFlags);
3348 if (status != NO_ERROR) {
3349 ALOGE("Failed to reopen hardware output stream, "
3350 "samplingRate: %d, format %d, channels %d",
3351 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003352 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003353 outputDesc->mSamplingRate = config.sample_rate;
3354 outputDesc->mChannelMask = config.channel_mask;
3355 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003356 AudioParameter outputCmd = AudioParameter();
3357 outputCmd.addInt(String8("set_id"), 0);
3358 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3359 addOutput(mPrimaryOutput, outputDesc);
3360 }
3361 }
3362
3363
3364 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3365 }
3366 }
3367 return false;
3368}
3369
Eric Laurente0720872014-03-11 09:30:41 -07003370void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003371{
3372 {
3373 AutoMutex _l(mLock);
3374 requestExit();
3375 mWaitWorkCV.signal();
3376 }
3377 requestExitAndWait();
3378}
3379
Eric Laurente0720872014-03-11 09:30:41 -07003380int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003381{
3382 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3383 if (output == mTestOutputs[i]) return i;
3384 }
3385 return 0;
3386}
3387#endif //AUDIO_POLICY_TEST
3388
3389// ---
3390
Eric Laurent1f2f2232014-06-02 12:01:23 -07003391void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003392{
Eric Laurent1c333e22014-05-20 10:48:17 -07003393 outputDesc->mIoHandle = output;
3394 outputDesc->mId = nextUniqueId();
3395 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003396 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003397}
3398
Eric Laurent1f2f2232014-06-02 12:01:23 -07003399void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003400{
Eric Laurent1c333e22014-05-20 10:48:17 -07003401 inputDesc->mIoHandle = input;
3402 inputDesc->mId = nextUniqueId();
3403 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003404 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003405}
Eric Laurente552edb2014-03-10 17:42:56 -07003406
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003407void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3408 const String8 address /*in*/,
3409 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3410 // look for a match on the given address on the addresses of the outputs:
3411 // find the address by finding the patch that maps to this output
3412 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3413 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3414 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3415 if (patchIdx >= 0) {
3416 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3417 const int numSinks = patchDesc->mPatch.num_sinks;
3418 for (ssize_t j=0; j < numSinks; j++) {
3419 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3420 const char* patchAddr =
3421 patchDesc->mPatch.sinks[j].ext.device.address;
3422 if (strncmp(patchAddr,
3423 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003424 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003425 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3426 outputs.add(desc->mIoHandle);
3427 break;
3428 }
3429 }
3430 }
3431 }
3432}
3433
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003434status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003435 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003436 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003437 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003438{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003439 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003440 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003441 // erase all current sample rates, formats and channel masks
3442 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003443
Eric Laurent3b73df72014-03-11 09:06:29 -07003444 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003445 // first list already open outputs that can be routed to this device
3446 for (size_t i = 0; i < mOutputs.size(); i++) {
3447 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003448 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003449 if (!deviceDistinguishesOnAddress(device)) {
3450 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3451 outputs.add(mOutputs.keyAt(i));
3452 } else {
3453 ALOGV(" checking address match due to device 0x%x", device);
3454 findIoHandlesByAddress(desc, address, outputs);
3455 }
Eric Laurente552edb2014-03-10 17:42:56 -07003456 }
3457 }
3458 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003459 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003460 for (size_t i = 0; i < mHwModules.size(); i++)
3461 {
3462 if (mHwModules[i]->mHandle == 0) {
3463 continue;
3464 }
3465 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3466 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003467 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3468 if (profile->mSupportedDevices.types() & device) {
3469 if (!deviceDistinguishesOnAddress(device) ||
3470 address == profile->mSupportedDevices[0]->mAddress) {
3471 profiles.add(profile);
3472 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3473 }
Eric Laurente552edb2014-03-10 17:42:56 -07003474 }
3475 }
3476 }
3477
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003478 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3479
Eric Laurente552edb2014-03-10 17:42:56 -07003480 if (profiles.isEmpty() && outputs.isEmpty()) {
3481 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3482 return BAD_VALUE;
3483 }
3484
3485 // open outputs for matching profiles if needed. Direct outputs are also opened to
3486 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3487 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003488 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003489
3490 // nothing to do if one output is already opened for this profile
3491 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003492 for (j = 0; j < outputs.size(); j++) {
3493 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003494 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003495 // matching profile: save the sample rates, format and channel masks supported
3496 // by the profile in our device descriptor
3497 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003498 break;
3499 }
3500 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003501 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003502 continue;
3503 }
3504
Eric Laurent83b88082014-06-20 18:31:16 -07003505 ALOGV("opening output for device %08x with params %s profile %p",
3506 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003507 desc = new AudioOutputDescriptor(profile);
3508 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003509 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3510 config.sample_rate = desc->mSamplingRate;
3511 config.channel_mask = desc->mChannelMask;
3512 config.format = desc->mFormat;
3513 config.offload_info.sample_rate = desc->mSamplingRate;
3514 config.offload_info.channel_mask = desc->mChannelMask;
3515 config.offload_info.format = desc->mFormat;
3516 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3517 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3518 &output,
3519 &config,
3520 &desc->mDevice,
3521 address,
3522 &desc->mLatency,
3523 desc->mFlags);
3524 if (status == NO_ERROR) {
3525 desc->mSamplingRate = config.sample_rate;
3526 desc->mChannelMask = config.channel_mask;
3527 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003528
Eric Laurentd4692962014-05-05 18:13:44 -07003529 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003531 char *param = audio_device_address_to_parameter(device, address);
3532 mpClientInterface->setParameters(output, String8(param));
3533 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003534 }
3535
Eric Laurentd4692962014-05-05 18:13:44 -07003536 // Here is where we step through and resolve any "dynamic" fields
3537 String8 reply;
3538 char *value;
3539 if (profile->mSamplingRates[0] == 0) {
3540 reply = mpClientInterface->getParameters(output,
3541 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003542 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003543 reply.string());
3544 value = strpbrk((char *)reply.string(), "=");
3545 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003546 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003547 }
Eric Laurentd4692962014-05-05 18:13:44 -07003548 }
3549 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3550 reply = mpClientInterface->getParameters(output,
3551 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003552 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003553 reply.string());
3554 value = strpbrk((char *)reply.string(), "=");
3555 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003556 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003557 }
Eric Laurentd4692962014-05-05 18:13:44 -07003558 }
3559 if (profile->mChannelMasks[0] == 0) {
3560 reply = mpClientInterface->getParameters(output,
3561 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003562 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003563 reply.string());
3564 value = strpbrk((char *)reply.string(), "=");
3565 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003566 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003567 }
Eric Laurentd4692962014-05-05 18:13:44 -07003568 }
3569 if (((profile->mSamplingRates[0] == 0) &&
3570 (profile->mSamplingRates.size() < 2)) ||
3571 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3572 (profile->mFormats.size() < 2)) ||
3573 ((profile->mChannelMasks[0] == 0) &&
3574 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003575 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003576 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003577 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003578 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3579 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003580 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003581 config.sample_rate = profile->pickSamplingRate();
3582 config.channel_mask = profile->pickChannelMask();
3583 config.format = profile->pickFormat();
3584 config.offload_info.sample_rate = config.sample_rate;
3585 config.offload_info.channel_mask = config.channel_mask;
3586 config.offload_info.format = config.format;
3587 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3588 &output,
3589 &config,
3590 &desc->mDevice,
3591 address,
3592 &desc->mLatency,
3593 desc->mFlags);
3594 if (status == NO_ERROR) {
3595 desc->mSamplingRate = config.sample_rate;
3596 desc->mChannelMask = config.channel_mask;
3597 desc->mFormat = config.format;
3598 } else {
3599 output = AUDIO_IO_HANDLE_NONE;
3600 }
Eric Laurentd4692962014-05-05 18:13:44 -07003601 }
3602
Eric Laurentcf2c0212014-07-25 16:20:43 -07003603 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003604 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003605 if (deviceDistinguishesOnAddress(device) && address != "0") {
3606 ssize_t index = mPolicyMixes.indexOfKey(address);
3607 if (index >= 0) {
3608 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003609 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003610 } else {
3611 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3612 address.string());
3613 }
Eric Laurentc722f302014-12-10 11:21:49 -08003614 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3615 // no duplicated output for direct outputs and
3616 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003617 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003618
Eric Laurentd4692962014-05-05 18:13:44 -07003619 // set initial stream volume for device
3620 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003621
Eric Laurentd4692962014-05-05 18:13:44 -07003622 //TODO: configure audio effect output stage here
3623
3624 // open a duplicating output thread for the new output and the primary output
3625 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3626 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003627 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003628 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003629 sp<AudioOutputDescriptor> dupOutputDesc =
3630 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003631 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3632 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3633 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3634 dupOutputDesc->mFormat = desc->mFormat;
3635 dupOutputDesc->mChannelMask = desc->mChannelMask;
3636 dupOutputDesc->mLatency = desc->mLatency;
3637 addOutput(duplicatedOutput, dupOutputDesc);
3638 applyStreamVolumes(duplicatedOutput, device, 0, true);
3639 } else {
3640 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3641 mPrimaryOutput, output);
3642 mpClientInterface->closeOutput(output);
3643 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003644 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003645 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003646 }
Eric Laurente552edb2014-03-10 17:42:56 -07003647 }
3648 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003649 } else {
3650 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003651 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003652 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003653 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003654 profiles.removeAt(profile_index);
3655 profile_index--;
3656 } else {
3657 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003658 devDesc->importAudioPort(profile);
3659
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003660 if (deviceDistinguishesOnAddress(device)) {
3661 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3662 device, address.string());
3663 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3664 NULL/*patch handle*/, address.string());
3665 }
Eric Laurente552edb2014-03-10 17:42:56 -07003666 ALOGV("checkOutputsForDevice(): adding output %d", output);
3667 }
3668 }
3669
3670 if (profiles.isEmpty()) {
3671 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3672 return BAD_VALUE;
3673 }
Eric Laurentd4692962014-05-05 18:13:44 -07003674 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003675 // check if one opened output is not needed any more after disconnecting one device
3676 for (size_t i = 0; i < mOutputs.size(); i++) {
3677 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003678 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003679 // exact match on device
3680 if (deviceDistinguishesOnAddress(device) &&
3681 (desc->mProfile->mSupportedDevices.types() == device)) {
3682 findIoHandlesByAddress(desc, address, outputs);
3683 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003684 & mAvailableOutputDevices.types())) {
3685 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3686 mOutputs.keyAt(i));
3687 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003688 }
Eric Laurente552edb2014-03-10 17:42:56 -07003689 }
3690 }
Eric Laurentd4692962014-05-05 18:13:44 -07003691 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003692 for (size_t i = 0; i < mHwModules.size(); i++)
3693 {
3694 if (mHwModules[i]->mHandle == 0) {
3695 continue;
3696 }
3697 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3698 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003699 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003700 if (profile->mSupportedDevices.types() & device) {
3701 ALOGV("checkOutputsForDevice(): "
3702 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003703 if (profile->mSamplingRates[0] == 0) {
3704 profile->mSamplingRates.clear();
3705 profile->mSamplingRates.add(0);
3706 }
3707 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3708 profile->mFormats.clear();
3709 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3710 }
3711 if (profile->mChannelMasks[0] == 0) {
3712 profile->mChannelMasks.clear();
3713 profile->mChannelMasks.add(0);
3714 }
3715 }
3716 }
3717 }
3718 }
3719 return NO_ERROR;
3720}
3721
Eric Laurentd4692962014-05-05 18:13:44 -07003722status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3723 audio_policy_dev_state_t state,
3724 SortedVector<audio_io_handle_t>& inputs,
3725 const String8 address)
3726{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003727 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003728 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3729 // first list already open inputs that can be routed to this device
3730 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3731 desc = mInputs.valueAt(input_index);
3732 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3733 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3734 inputs.add(mInputs.keyAt(input_index));
3735 }
3736 }
3737
3738 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003739 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003740 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3741 {
3742 if (mHwModules[module_idx]->mHandle == 0) {
3743 continue;
3744 }
3745 for (size_t profile_index = 0;
3746 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3747 profile_index++)
3748 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003749 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3750
3751 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3752 if (!deviceDistinguishesOnAddress(device) ||
3753 address == profile->mSupportedDevices[0]->mAddress) {
3754 profiles.add(profile);
3755 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3756 profile_index, module_idx);
3757 }
Eric Laurentd4692962014-05-05 18:13:44 -07003758 }
3759 }
3760 }
3761
3762 if (profiles.isEmpty() && inputs.isEmpty()) {
3763 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3764 return BAD_VALUE;
3765 }
3766
3767 // open inputs for matching profiles if needed. Direct inputs are also opened to
3768 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3769 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3770
Eric Laurent1c333e22014-05-20 10:48:17 -07003771 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003772 // nothing to do if one input is already opened for this profile
3773 size_t input_index;
3774 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3775 desc = mInputs.valueAt(input_index);
3776 if (desc->mProfile == profile) {
3777 break;
3778 }
3779 }
3780 if (input_index != mInputs.size()) {
3781 continue;
3782 }
3783
3784 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3785 desc = new AudioInputDescriptor(profile);
3786 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003787 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3788 config.sample_rate = desc->mSamplingRate;
3789 config.channel_mask = desc->mChannelMask;
3790 config.format = desc->mFormat;
3791 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3792 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3793 &input,
3794 &config,
3795 &desc->mDevice,
3796 address,
3797 AUDIO_SOURCE_MIC,
3798 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003799
Eric Laurentcf2c0212014-07-25 16:20:43 -07003800 if (status == NO_ERROR) {
3801 desc->mSamplingRate = config.sample_rate;
3802 desc->mChannelMask = config.channel_mask;
3803 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003804
Eric Laurentd4692962014-05-05 18:13:44 -07003805 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003806 char *param = audio_device_address_to_parameter(device, address);
3807 mpClientInterface->setParameters(input, String8(param));
3808 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003809 }
3810
3811 // Here is where we step through and resolve any "dynamic" fields
3812 String8 reply;
3813 char *value;
3814 if (profile->mSamplingRates[0] == 0) {
3815 reply = mpClientInterface->getParameters(input,
3816 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3817 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3818 reply.string());
3819 value = strpbrk((char *)reply.string(), "=");
3820 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003821 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003822 }
3823 }
3824 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3825 reply = mpClientInterface->getParameters(input,
3826 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3827 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3828 value = strpbrk((char *)reply.string(), "=");
3829 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003830 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003831 }
3832 }
3833 if (profile->mChannelMasks[0] == 0) {
3834 reply = mpClientInterface->getParameters(input,
3835 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3836 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3837 reply.string());
3838 value = strpbrk((char *)reply.string(), "=");
3839 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003840 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003841 }
3842 }
3843 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3844 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3845 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3846 ALOGW("checkInputsForDevice() direct input missing param");
3847 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003848 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003849 }
3850
3851 if (input != 0) {
3852 addInput(input, desc);
3853 }
3854 } // endif input != 0
3855
Eric Laurentcf2c0212014-07-25 16:20:43 -07003856 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003857 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003858 profiles.removeAt(profile_index);
3859 profile_index--;
3860 } else {
3861 inputs.add(input);
3862 ALOGV("checkInputsForDevice(): adding input %d", input);
3863 }
3864 } // end scan profiles
3865
3866 if (profiles.isEmpty()) {
3867 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3868 return BAD_VALUE;
3869 }
3870 } else {
3871 // Disconnect
3872 // check if one opened input is not needed any more after disconnecting one device
3873 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3874 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003875 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3876 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003877 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3878 mInputs.keyAt(input_index));
3879 inputs.add(mInputs.keyAt(input_index));
3880 }
3881 }
3882 // Clear any profiles associated with the disconnected device.
3883 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3884 if (mHwModules[module_index]->mHandle == 0) {
3885 continue;
3886 }
3887 for (size_t profile_index = 0;
3888 profile_index < mHwModules[module_index]->mInputProfiles.size();
3889 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003890 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003891 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003892 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003893 profile_index, module_index);
3894 if (profile->mSamplingRates[0] == 0) {
3895 profile->mSamplingRates.clear();
3896 profile->mSamplingRates.add(0);
3897 }
3898 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3899 profile->mFormats.clear();
3900 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3901 }
3902 if (profile->mChannelMasks[0] == 0) {
3903 profile->mChannelMasks.clear();
3904 profile->mChannelMasks.add(0);
3905 }
3906 }
3907 }
3908 }
3909 } // end disconnect
3910
3911 return NO_ERROR;
3912}
3913
3914
Eric Laurente0720872014-03-11 09:30:41 -07003915void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003916{
3917 ALOGV("closeOutput(%d)", output);
3918
Eric Laurent1f2f2232014-06-02 12:01:23 -07003919 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003920 if (outputDesc == NULL) {
3921 ALOGW("closeOutput() unknown output %d", output);
3922 return;
3923 }
3924
Eric Laurent275e8e92014-11-30 15:14:47 -08003925 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3926 if (mPolicyMixes[i]->mOutput == outputDesc) {
3927 mPolicyMixes[i]->mOutput.clear();
3928 }
3929 }
3930
Eric Laurente552edb2014-03-10 17:42:56 -07003931 // look for duplicated outputs connected to the output being removed.
3932 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003933 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003934 if (dupOutputDesc->isDuplicated() &&
3935 (dupOutputDesc->mOutput1 == outputDesc ||
3936 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003937 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003938 if (dupOutputDesc->mOutput1 == outputDesc) {
3939 outputDesc2 = dupOutputDesc->mOutput2;
3940 } else {
3941 outputDesc2 = dupOutputDesc->mOutput1;
3942 }
3943 // As all active tracks on duplicated output will be deleted,
3944 // and as they were also referenced on the other output, the reference
3945 // count for their stream type must be adjusted accordingly on
3946 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003947 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003948 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003949 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003950 }
3951 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3952 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3953
3954 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003955 mOutputs.removeItem(duplicatedOutput);
3956 }
3957 }
3958
Eric Laurent05b90f82014-08-27 15:32:29 -07003959 nextAudioPortGeneration();
3960
3961 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3962 if (index >= 0) {
3963 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3964 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3965 mAudioPatches.removeItemsAt(index);
3966 mpClientInterface->onAudioPatchListUpdate();
3967 }
3968
Eric Laurente552edb2014-03-10 17:42:56 -07003969 AudioParameter param;
3970 param.add(String8("closing"), String8("true"));
3971 mpClientInterface->setParameters(output, param.toString());
3972
3973 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003974 mOutputs.removeItem(output);
3975 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003976}
3977
3978void AudioPolicyManager::closeInput(audio_io_handle_t input)
3979{
3980 ALOGV("closeInput(%d)", input);
3981
3982 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3983 if (inputDesc == NULL) {
3984 ALOGW("closeInput() unknown input %d", input);
3985 return;
3986 }
3987
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003989
3990 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3991 if (index >= 0) {
3992 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3993 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3994 mAudioPatches.removeItemsAt(index);
3995 mpClientInterface->onAudioPatchListUpdate();
3996 }
3997
3998 mpClientInterface->closeInput(input);
3999 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004000}
4001
Eric Laurente0720872014-03-11 09:30:41 -07004002SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004003 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004004{
4005 SortedVector<audio_io_handle_t> outputs;
4006
4007 ALOGVV("getOutputsForDevice() device %04x", device);
4008 for (size_t i = 0; i < openOutputs.size(); i++) {
4009 ALOGVV("output %d isDuplicated=%d device=%04x",
4010 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4011 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4012 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4013 outputs.add(openOutputs.keyAt(i));
4014 }
4015 }
4016 return outputs;
4017}
4018
Eric Laurente0720872014-03-11 09:30:41 -07004019bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004020 SortedVector<audio_io_handle_t>& outputs2)
4021{
4022 if (outputs1.size() != outputs2.size()) {
4023 return false;
4024 }
4025 for (size_t i = 0; i < outputs1.size(); i++) {
4026 if (outputs1[i] != outputs2[i]) {
4027 return false;
4028 }
4029 }
4030 return true;
4031}
4032
Eric Laurente0720872014-03-11 09:30:41 -07004033void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004034{
4035 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4036 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4037 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4038 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4039
4040 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4041 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4042 strategy, srcOutputs[0], dstOutputs[0]);
4043 // mute strategy while moving tracks from one output to another
4044 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004045 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004046 if (desc->isStrategyActive(strategy)) {
4047 setStrategyMute(strategy, true, srcOutputs[i]);
4048 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4049 }
4050 }
4051
4052 // Move effects associated to this strategy from previous output to new output
4053 if (strategy == STRATEGY_MEDIA) {
4054 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4055 SortedVector<audio_io_handle_t> moved;
4056 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004057 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4058 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4059 effectDesc->mIo != fxOutput) {
4060 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004061 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4062 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004063 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004064 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004065 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004066 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004067 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004068 }
4069 }
4070 }
4071 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004072 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004073 if (i == AUDIO_STREAM_PATCH) {
4074 continue;
4075 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004076 if (getStrategy((audio_stream_type_t)i) == strategy) {
4077 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004078 }
4079 }
4080 }
4081}
4082
Eric Laurente0720872014-03-11 09:30:41 -07004083void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004084{
Jon Eklund966095e2014-09-09 15:39:49 -05004085 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4086 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004087 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004088 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4089 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004090 checkOutputForStrategy(STRATEGY_SONIFICATION);
4091 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004092 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004093 checkOutputForStrategy(STRATEGY_MEDIA);
4094 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004095 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004096}
4097
Eric Laurente0720872014-03-11 09:30:41 -07004098audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004099{
Eric Laurente552edb2014-03-10 17:42:56 -07004100 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004101 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4103 return mOutputs.keyAt(i);
4104 }
4105 }
4106
4107 return 0;
4108}
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004111{
Eric Laurente552edb2014-03-10 17:42:56 -07004112 audio_io_handle_t a2dpOutput = getA2dpOutput();
4113 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004114 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004115 return;
4116 }
4117
Eric Laurent3a4311c2014-03-17 12:00:47 -07004118 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004119 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4120 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4121 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004122 // suspend A2DP output if:
4123 // (NOT already suspended) &&
4124 // ((SCO device is connected &&
4125 // (forced usage for communication || for record is SCO))) ||
4126 // (phone state is ringing || in call)
4127 //
4128 // restore A2DP output if:
4129 // (Already suspended) &&
4130 // ((SCO device is NOT connected ||
4131 // (forced usage NOT for communication && NOT for record is SCO))) &&
4132 // (phone state is NOT ringing && NOT in call)
4133 //
4134 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004135 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004136 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4137 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4138 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4139 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004140
4141 mpClientInterface->restoreOutput(a2dpOutput);
4142 mA2dpSuspended = false;
4143 }
4144 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004145 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004146 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4147 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4148 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4149 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004150
4151 mpClientInterface->suspendOutput(a2dpOutput);
4152 mA2dpSuspended = true;
4153 }
4154 }
4155}
4156
Eric Laurent1c333e22014-05-20 10:48:17 -07004157audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004158{
4159 audio_devices_t device = AUDIO_DEVICE_NONE;
4160
Eric Laurent1f2f2232014-06-02 12:01:23 -07004161 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004162
4163 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4164 if (index >= 0) {
4165 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4166 if (patchDesc->mUid != mUidCached) {
4167 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4168 outputDesc->device(), outputDesc->mPatchHandle);
4169 return outputDesc->device();
4170 }
4171 }
4172
Eric Laurente552edb2014-03-10 17:42:56 -07004173 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004174 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004175 // use device for strategy enforced audible
4176 // 2: we are in call or the strategy phone is active on the output:
4177 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004178 // 3: the strategy for enforced audible is active but not enforced on the output:
4179 // use the device for strategy enforced audible
4180 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004181 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004182 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004183 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004184 // 6: the strategy accessibility is active on the output:
4185 // use device for strategy accessibility
4186 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004187 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004188 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004189 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004190 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004191 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004192 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4193 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004194 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4195 } else if (isInCall() ||
4196 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4197 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004198 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4199 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004200 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4201 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4202 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4203 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004204 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4205 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004206 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4207 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4208 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4209 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004210 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4211 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004212 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4213 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004214 }
4215
Eric Laurent1c333e22014-05-20 10:48:17 -07004216 ALOGV("getNewOutputDevice() selected device %x", device);
4217 return device;
4218}
4219
4220audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4221{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004222 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004223
4224 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4225 if (index >= 0) {
4226 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4227 if (patchDesc->mUid != mUidCached) {
4228 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4229 inputDesc->mDevice, inputDesc->mPatchHandle);
4230 return inputDesc->mDevice;
4231 }
4232 }
4233
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004234 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004235
4236 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004237 return device;
4238}
4239
Eric Laurente0720872014-03-11 09:30:41 -07004240uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004241 return (uint32_t)getStrategy(stream);
4242}
4243
Eric Laurente0720872014-03-11 09:30:41 -07004244audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004245 // By checking the range of stream before calling getStrategy, we avoid
4246 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4247 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004248 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004249 return AUDIO_DEVICE_NONE;
4250 }
4251 audio_devices_t devices;
4252 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4253 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4254 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4255 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004256 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004257 if (outputDesc->isStrategyActive(strategy)) {
4258 devices = outputDesc->device();
4259 break;
4260 }
Eric Laurente552edb2014-03-10 17:42:56 -07004261 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004262
4263 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4264 and doesn't really need to.*/
4265 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4266 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4267 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4268 }
4269
Eric Laurente552edb2014-03-10 17:42:56 -07004270 return devices;
4271}
4272
Eric Laurente0720872014-03-11 09:30:41 -07004273AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004274 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004275
4276 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4277
Eric Laurente552edb2014-03-10 17:42:56 -07004278 // stream to strategy mapping
4279 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004280 case AUDIO_STREAM_VOICE_CALL:
4281 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004282 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004283 case AUDIO_STREAM_RING:
4284 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004285 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004286 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004287 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004288 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004289 return STRATEGY_DTMF;
4290 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004291 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004292 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004293 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4294 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004295 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004296 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004297 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004298 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004299 case AUDIO_STREAM_TTS:
4300 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004301 case AUDIO_STREAM_ACCESSIBILITY:
4302 return STRATEGY_ACCESSIBILITY;
4303 case AUDIO_STREAM_REROUTING:
4304 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004305 }
4306}
4307
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004308uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4309 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004310 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4311 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4312 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004313 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4314 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4315 }
4316
4317 // usage to strategy mapping
4318 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004319 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4320 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4321 return (uint32_t) STRATEGY_SONIFICATION;
4322 }
4323 if (isInCall()) {
4324 return (uint32_t) STRATEGY_PHONE;
4325 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004326 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004327
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004328 case AUDIO_USAGE_MEDIA:
4329 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004330 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4331 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4332 return (uint32_t) STRATEGY_MEDIA;
4333
4334 case AUDIO_USAGE_VOICE_COMMUNICATION:
4335 return (uint32_t) STRATEGY_PHONE;
4336
4337 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4338 return (uint32_t) STRATEGY_DTMF;
4339
4340 case AUDIO_USAGE_ALARM:
4341 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4342 return (uint32_t) STRATEGY_SONIFICATION;
4343
4344 case AUDIO_USAGE_NOTIFICATION:
4345 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4346 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4347 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4348 case AUDIO_USAGE_NOTIFICATION_EVENT:
4349 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4350
4351 case AUDIO_USAGE_UNKNOWN:
4352 default:
4353 return (uint32_t) STRATEGY_MEDIA;
4354 }
4355}
4356
Eric Laurente0720872014-03-11 09:30:41 -07004357void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004360 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4361 updateDevicesAndOutputs();
4362 break;
4363 default:
4364 break;
4365 }
4366}
4367
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004368bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4369 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4370 if (s == (size_t) streamToIgnore) {
4371 continue;
4372 }
4373 for (size_t i = 0; i < mOutputs.size(); i++) {
4374 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4375 if (outputDesc->mRefCount[s] != 0) {
4376 return true;
4377 }
4378 }
4379 }
4380 return false;
4381}
4382
4383uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4384 switch(event) {
4385 case STARTING_OUTPUT:
4386 mBeaconMuteRefCount++;
4387 break;
4388 case STOPPING_OUTPUT:
4389 if (mBeaconMuteRefCount > 0) {
4390 mBeaconMuteRefCount--;
4391 }
4392 break;
4393 case STARTING_BEACON:
4394 mBeaconPlayingRefCount++;
4395 break;
4396 case STOPPING_BEACON:
4397 if (mBeaconPlayingRefCount > 0) {
4398 mBeaconPlayingRefCount--;
4399 }
4400 break;
4401 }
4402
4403 if (mBeaconMuteRefCount > 0) {
4404 // any playback causes beacon to be muted
4405 return setBeaconMute(true);
4406 } else {
4407 // no other playback: unmute when beacon starts playing, mute when it stops
4408 return setBeaconMute(mBeaconPlayingRefCount == 0);
4409 }
4410}
4411
4412uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4413 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4414 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4415 // keep track of muted state to avoid repeating mute/unmute operations
4416 if (mBeaconMuted != mute) {
4417 // mute/unmute AUDIO_STREAM_TTS on all outputs
4418 ALOGV("\t muting %d", mute);
4419 uint32_t maxLatency = 0;
4420 for (size_t i = 0; i < mOutputs.size(); i++) {
4421 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4422 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4423 desc->mIoHandle,
4424 0 /*delay*/, AUDIO_DEVICE_NONE);
4425 const uint32_t latency = desc->latency() * 2;
4426 if (latency > maxLatency) {
4427 maxLatency = latency;
4428 }
4429 }
4430 mBeaconMuted = mute;
4431 return maxLatency;
4432 }
4433 return 0;
4434}
4435
Eric Laurente0720872014-03-11 09:30:41 -07004436audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004437 bool fromCache)
4438{
4439 uint32_t device = AUDIO_DEVICE_NONE;
4440
4441 if (fromCache) {
4442 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4443 strategy, mDeviceForStrategy[strategy]);
4444 return mDeviceForStrategy[strategy];
4445 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004446 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004447 switch (strategy) {
4448
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004449 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4450 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4451 if (!device) {
4452 ALOGE("getDeviceForStrategy() no device found for "\
4453 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4454 }
4455 break;
4456
Eric Laurente552edb2014-03-10 17:42:56 -07004457 case STRATEGY_SONIFICATION_RESPECTFUL:
4458 if (isInCall()) {
4459 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004460 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004461 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4462 // while media is playing on a remote device, use the the sonification behavior.
4463 // Note that we test this usecase before testing if media is playing because
4464 // the isStreamActive() method only informs about the activity of a stream, not
4465 // if it's for local playback. Note also that we use the same delay between both tests
4466 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004467 //user "safe" speaker if available instead of normal speaker to avoid triggering
4468 //other acoustic safety mechanisms for notification
4469 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4470 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004471 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004472 // while media is playing (or has recently played), use the same device
4473 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4474 } else {
4475 // when media is not playing anymore, fall back on the sonification behavior
4476 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004477 //user "safe" speaker if available instead of normal speaker to avoid triggering
4478 //other acoustic safety mechanisms for notification
4479 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4480 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004481 }
4482
4483 break;
4484
4485 case STRATEGY_DTMF:
4486 if (!isInCall()) {
4487 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4488 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4489 break;
4490 }
4491 // when in call, DTMF and PHONE strategies follow the same rules
4492 // FALL THROUGH
4493
4494 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004495 // Force use of only devices on primary output if:
4496 // - in call AND
4497 // - cannot route from voice call RX OR
4498 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4499 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004500 audio_devices_t txDevice =
4501 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004502 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4503 if (((mAvailableInputDevices.types() &
4504 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4505 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004506 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004507 AUDIO_DEVICE_API_VERSION_3_0))) {
4508 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4509 }
4510 }
Eric Laurente552edb2014-03-10 17:42:56 -07004511 // for phone strategy, we first consider the forced use and then the available devices by order
4512 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004513 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4514 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004515 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004516 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if (device) break;
4518 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004519 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004520 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004521 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004522 if (device) break;
4523 // if SCO device is requested but no SCO device is available, fall back to default case
4524 // FALL THROUGH
4525
4526 default: // FORCE_NONE
4527 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004528 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004529 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004530 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004531 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004532 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004533 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004534 if (device) break;
4535 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004536 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004537 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004538 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004539 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004540 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4541 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004542 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004543 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004544 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004545 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004546 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004547 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004548 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004549 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004550 if (device) break;
4551 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004552 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004553 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004554 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004555 if (device == AUDIO_DEVICE_NONE) {
4556 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4557 }
4558 break;
4559
Eric Laurent3b73df72014-03-11 09:06:29 -07004560 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004561 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4562 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004563 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004564 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004565 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004566 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004567 if (device) break;
4568 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004569 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004571 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004573 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004574 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004575 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004576 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004577 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004578 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004579 if (device) break;
4580 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004581 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4582 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004584 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004585 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004586 if (device == AUDIO_DEVICE_NONE) {
4587 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4588 }
4589 break;
4590 }
4591 break;
4592
4593 case STRATEGY_SONIFICATION:
4594
4595 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4596 // handleIncallSonification().
4597 if (isInCall()) {
4598 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4599 break;
4600 }
4601 // FALL THROUGH
4602
4603 case STRATEGY_ENFORCED_AUDIBLE:
4604 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4605 // except:
4606 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4607 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4608
4609 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004610 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004612 if (device == AUDIO_DEVICE_NONE) {
4613 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4614 }
4615 }
4616 // The second device used for sonification is the same as the device used by media strategy
4617 // FALL THROUGH
4618
Eric Laurent223fd5c2014-11-11 13:43:36 -08004619 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4620 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004621 if (strategy == STRATEGY_ACCESSIBILITY) {
4622 // do not route accessibility prompts to a digital output currently configured with a
4623 // compressed format as they would likely not be mixed and dropped.
4624 for (size_t i = 0; i < mOutputs.size(); i++) {
4625 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4626 audio_devices_t devices = desc->device() &
4627 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4628 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4629 devices != AUDIO_DEVICE_NONE) {
4630 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4631 }
4632 }
4633 }
4634 // FALL THROUGH
4635
Eric Laurent223fd5c2014-11-11 13:43:36 -08004636 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004637 case STRATEGY_MEDIA: {
4638 uint32_t device2 = AUDIO_DEVICE_NONE;
4639 if (strategy != STRATEGY_SONIFICATION) {
4640 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004641 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4642 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4643 }
Eric Laurente552edb2014-03-10 17:42:56 -07004644 }
4645 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004646 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004647 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004648 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004649 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004650 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004651 }
4652 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004654 }
4655 }
Hochi Huang327cb702014-09-21 09:47:31 +08004656 if ((device2 == AUDIO_DEVICE_NONE) &&
4657 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4658 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4659 }
Eric Laurente552edb2014-03-10 17:42:56 -07004660 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004661 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004662 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004663 if ((device2 == AUDIO_DEVICE_NONE)) {
4664 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4665 }
Eric Laurente552edb2014-03-10 17:42:56 -07004666 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004667 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004668 }
4669 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004670 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004671 }
4672 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004673 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004674 }
4675 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004676 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004677 }
4678 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4679 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004680 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004681 }
4682 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004683 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004684 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004685 }
4686 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004687 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004688 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004689 int device3 = AUDIO_DEVICE_NONE;
4690 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004691 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004692 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4693 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004694 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004695 }
Eric Laurente552edb2014-03-10 17:42:56 -07004696
Jungshik Jang839e4f32014-06-26 17:23:40 +09004697 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004698 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4699 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4700 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004701
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004702 // If hdmi system audio mode is on, remove speaker out of output list.
4703 if ((strategy == STRATEGY_MEDIA) &&
4704 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4705 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4706 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4707 }
4708
Eric Laurente552edb2014-03-10 17:42:56 -07004709 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004710 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004711 if (device == AUDIO_DEVICE_NONE) {
4712 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4713 }
4714 } break;
4715
4716 default:
4717 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4718 break;
4719 }
4720
4721 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4722 return device;
4723}
4724
Eric Laurente0720872014-03-11 09:30:41 -07004725void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004726{
4727 for (int i = 0; i < NUM_STRATEGIES; i++) {
4728 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4729 }
4730 mPreviousOutputs = mOutputs;
4731}
4732
Eric Laurent1f2f2232014-06-02 12:01:23 -07004733uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004734 audio_devices_t prevDevice,
4735 uint32_t delayMs)
4736{
4737 // mute/unmute strategies using an incompatible device combination
4738 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4739 // if unmuting, unmute only after the specified delay
4740 if (outputDesc->isDuplicated()) {
4741 return 0;
4742 }
4743
4744 uint32_t muteWaitMs = 0;
4745 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004746 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004747
4748 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4749 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004750 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004751 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4752 bool doMute = false;
4753
4754 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4755 doMute = true;
4756 outputDesc->mStrategyMutedByDevice[i] = true;
4757 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4758 doMute = true;
4759 outputDesc->mStrategyMutedByDevice[i] = false;
4760 }
Eric Laurent99401132014-05-07 19:48:15 -07004761 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004762 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004763 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004764 // skip output if it does not share any device with current output
4765 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4766 == AUDIO_DEVICE_NONE) {
4767 continue;
4768 }
4769 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4770 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4771 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4772 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4773 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004774 if (mute) {
4775 // FIXME: should not need to double latency if volume could be applied
4776 // immediately by the audioflinger mixer. We must account for the delay
4777 // between now and the next time the audioflinger thread for this output
4778 // will process a buffer (which corresponds to one buffer size,
4779 // usually 1/2 or 1/4 of the latency).
4780 if (muteWaitMs < desc->latency() * 2) {
4781 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004782 }
4783 }
4784 }
4785 }
4786 }
4787 }
4788
Eric Laurent99401132014-05-07 19:48:15 -07004789 // temporary mute output if device selection changes to avoid volume bursts due to
4790 // different per device volumes
4791 if (outputDesc->isActive() && (device != prevDevice)) {
4792 if (muteWaitMs < outputDesc->latency() * 2) {
4793 muteWaitMs = outputDesc->latency() * 2;
4794 }
4795 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4796 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004797 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004798 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004800 muteWaitMs *2, device);
4801 }
4802 }
4803 }
4804
Eric Laurente552edb2014-03-10 17:42:56 -07004805 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4806 if (muteWaitMs > delayMs) {
4807 muteWaitMs -= delayMs;
4808 usleep(muteWaitMs * 1000);
4809 return muteWaitMs;
4810 }
4811 return 0;
4812}
4813
Eric Laurente0720872014-03-11 09:30:41 -07004814uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004815 audio_devices_t device,
4816 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004818 audio_patch_handle_t *patchHandle,
4819 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004820{
4821 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004822 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004823 AudioParameter param;
4824 uint32_t muteWaitMs;
4825
4826 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004827 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4828 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004829 return muteWaitMs;
4830 }
4831 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4832 // output profile
4833 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004834 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004835 return 0;
4836 }
4837
4838 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004839 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004840
4841 audio_devices_t prevDevice = outputDesc->mDevice;
4842
4843 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4844
4845 if (device != AUDIO_DEVICE_NONE) {
4846 outputDesc->mDevice = device;
4847 }
4848 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4849
4850 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004851 // the requested device is AUDIO_DEVICE_NONE
4852 // OR the requested device is the same as current device
4853 // AND force is not specified
4854 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004855 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004856 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4857 outputDesc->mPatchHandle != 0) {
4858 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4859 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004860 return muteWaitMs;
4861 }
4862
4863 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004864
Eric Laurente552edb2014-03-10 17:42:56 -07004865 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004866 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004869 DeviceVector deviceList = (address == NULL) ?
4870 mAvailableOutputDevices.getDevicesFromType(device)
4871 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004872 if (!deviceList.isEmpty()) {
4873 struct audio_patch patch;
4874 outputDesc->toAudioPortConfig(&patch.sources[0]);
4875 patch.num_sources = 1;
4876 patch.num_sinks = 0;
4877 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4878 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004879 patch.num_sinks++;
4880 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 ssize_t index;
4882 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4883 index = mAudioPatches.indexOfKey(*patchHandle);
4884 } else {
4885 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4886 }
4887 sp< AudioPatch> patchDesc;
4888 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4889 if (index >= 0) {
4890 patchDesc = mAudioPatches.valueAt(index);
4891 afPatchHandle = patchDesc->mAfPatchHandle;
4892 }
4893
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004895 &afPatchHandle,
4896 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4898 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004901 if (index < 0) {
4902 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4903 &patch, mUidCached);
4904 addAudioPatch(patchDesc->mHandle, patchDesc);
4905 } else {
4906 patchDesc->mPatch = patch;
4907 }
4908 patchDesc->mAfPatchHandle = afPatchHandle;
4909 patchDesc->mUid = mUidCached;
4910 if (patchHandle) {
4911 *patchHandle = patchDesc->mHandle;
4912 }
4913 outputDesc->mPatchHandle = patchDesc->mHandle;
4914 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004915 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 }
4917 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004918
4919 // inform all input as well
4920 for (size_t i = 0; i < mInputs.size(); i++) {
4921 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4922 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4923 AudioParameter inputCmd = AudioParameter();
4924 ALOGV("%s: inform input %d of device:%d", __func__,
4925 inputDescriptor->mIoHandle, device);
4926 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4927 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4928 inputCmd.toString(),
4929 delayMs);
4930 }
4931 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004932 }
Eric Laurente552edb2014-03-10 17:42:56 -07004933
4934 // update stream volumes according to new device
4935 applyStreamVolumes(output, device, delayMs);
4936
4937 return muteWaitMs;
4938}
4939
Eric Laurent1c333e22014-05-20 10:48:17 -07004940status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 int delayMs,
4942 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004943{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004944 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 ssize_t index;
4946 if (patchHandle) {
4947 index = mAudioPatches.indexOfKey(*patchHandle);
4948 } else {
4949 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4950 }
4951 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 return INVALID_OPERATION;
4953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4955 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004956 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4957 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 removeAudioPatch(patchDesc->mHandle);
4959 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004960 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004961 return status;
4962}
4963
4964status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4965 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 bool force,
4967 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004968{
4969 status_t status = NO_ERROR;
4970
Eric Laurent1f2f2232014-06-02 12:01:23 -07004971 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004972 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4973 inputDesc->mDevice = device;
4974
4975 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4976 if (!deviceList.isEmpty()) {
4977 struct audio_patch patch;
4978 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004979 // AUDIO_SOURCE_HOTWORD is for internal use only:
4980 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004981 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4982 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004983 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4984 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 patch.num_sinks = 1;
4986 //only one input device for now
4987 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004988 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 ssize_t index;
4990 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4991 index = mAudioPatches.indexOfKey(*patchHandle);
4992 } else {
4993 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4994 }
4995 sp< AudioPatch> patchDesc;
4996 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4997 if (index >= 0) {
4998 patchDesc = mAudioPatches.valueAt(index);
4999 afPatchHandle = patchDesc->mAfPatchHandle;
5000 }
5001
Eric Laurent1c333e22014-05-20 10:48:17 -07005002 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005004 0);
5005 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005007 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 if (index < 0) {
5009 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5010 &patch, mUidCached);
5011 addAudioPatch(patchDesc->mHandle, patchDesc);
5012 } else {
5013 patchDesc->mPatch = patch;
5014 }
5015 patchDesc->mAfPatchHandle = afPatchHandle;
5016 patchDesc->mUid = mUidCached;
5017 if (patchHandle) {
5018 *patchHandle = patchDesc->mHandle;
5019 }
5020 inputDesc->mPatchHandle = patchDesc->mHandle;
5021 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005022 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 }
5024 }
5025 }
5026 return status;
5027}
5028
Eric Laurent6a94d692014-05-20 11:18:06 -07005029status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5030 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005031{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005032 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 ssize_t index;
5034 if (patchHandle) {
5035 index = mAudioPatches.indexOfKey(*patchHandle);
5036 } else {
5037 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5038 }
5039 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005040 return INVALID_OPERATION;
5041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5043 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005044 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5045 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 removeAudioPatch(patchDesc->mHandle);
5047 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005048 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005049 return status;
5050}
5051
5052sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005053 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005054 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005055 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005056 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005057 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005058{
5059 // Choose an input profile based on the requested capture parameters: select the first available
5060 // profile supporting all requested parameters.
5061
5062 for (size_t i = 0; i < mHwModules.size(); i++)
5063 {
5064 if (mHwModules[i]->mHandle == 0) {
5065 continue;
5066 }
5067 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5068 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005069 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005070 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005071 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005072 &samplingRate /*updatedSamplingRate*/,
5073 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005074
Eric Laurente552edb2014-03-10 17:42:56 -07005075 return profile;
5076 }
5077 }
5078 }
5079 return NULL;
5080}
5081
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005082
5083audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005084 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005085{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005086 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5087 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005088
5089 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5090 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5091 continue;
5092 }
5093 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5094 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5095 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5096 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5097 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5098 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005099 if (policyMix != NULL) {
5100 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005101 }
5102 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5103 }
5104 break;
5105 }
5106 }
5107 }
5108
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005109 return getDeviceForInputSource(inputSource);
5110}
5111
5112audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5113{
5114 uint32_t device = AUDIO_DEVICE_NONE;
5115 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5116 ~AUDIO_DEVICE_BIT_IN;
5117
Eric Laurente552edb2014-03-10 17:42:56 -07005118 switch (inputSource) {
5119 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005120 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005121 device = AUDIO_DEVICE_IN_VOICE_CALL;
5122 break;
5123 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005124 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005125
5126 case AUDIO_SOURCE_DEFAULT:
5127 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005128 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5129 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005130 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5131 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5132 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005133 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5134 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5135 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5136 device = AUDIO_DEVICE_IN_USB_DEVICE;
5137 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5138 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005139 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005140 break;
5141
5142 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5143 // Allow only use of devices on primary input if in call and HAL does not support routing
5144 // to voice call path.
5145 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5146 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5147 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5148 }
5149
5150 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5151 case AUDIO_POLICY_FORCE_BT_SCO:
5152 // if SCO device is requested but no SCO device is available, fall back to default case
5153 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5154 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5155 break;
5156 }
5157 // FALL THROUGH
5158
5159 default: // FORCE_NONE
5160 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5161 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5162 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5163 device = AUDIO_DEVICE_IN_USB_DEVICE;
5164 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5165 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5166 }
5167 break;
5168
5169 case AUDIO_POLICY_FORCE_SPEAKER:
5170 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5171 device = AUDIO_DEVICE_IN_BACK_MIC;
5172 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5173 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5174 }
5175 break;
5176 }
5177 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005178
Eric Laurente552edb2014-03-10 17:42:56 -07005179 case AUDIO_SOURCE_VOICE_RECOGNITION:
5180 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005181 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005182 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005183 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005184 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005185 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005186 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5187 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005188 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005189 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5190 }
5191 break;
5192 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005193 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005194 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005195 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005196 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5197 }
5198 break;
5199 case AUDIO_SOURCE_VOICE_DOWNLINK:
5200 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005201 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005202 device = AUDIO_DEVICE_IN_VOICE_CALL;
5203 }
5204 break;
5205 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005206 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005207 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5208 }
5209 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005210 case AUDIO_SOURCE_FM_TUNER:
5211 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5212 device = AUDIO_DEVICE_IN_FM_TUNER;
5213 }
5214 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005215 default:
5216 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5217 break;
5218 }
5219 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5220 return device;
5221}
5222
Eric Laurente0720872014-03-11 09:30:41 -07005223bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005224{
5225 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5226 device &= ~AUDIO_DEVICE_BIT_IN;
5227 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5228 return true;
5229 }
5230 return false;
5231}
5232
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005233bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005234 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005235}
5236
Eric Laurente0720872014-03-11 09:30:41 -07005237audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005238{
5239 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005240 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005241 if ((input_descriptor->mRefCount > 0)
5242 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5243 return mInputs.keyAt(i);
5244 }
5245 }
5246 return 0;
5247}
5248
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005249uint32_t AudioPolicyManager::activeInputsCount() const
5250{
5251 uint32_t count = 0;
5252 for (size_t i = 0; i < mInputs.size(); i++) {
5253 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5254 if (desc->mRefCount > 0) {
5255 return count++;
5256 }
5257 }
5258 return count;
5259}
5260
Eric Laurente552edb2014-03-10 17:42:56 -07005261
Eric Laurente0720872014-03-11 09:30:41 -07005262audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005263{
5264 if (device == AUDIO_DEVICE_NONE) {
5265 // this happens when forcing a route update and no track is active on an output.
5266 // In this case the returned category is not important.
5267 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005268 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005269 // Multiple device selection is either:
5270 // - speaker + one other device: give priority to speaker in this case.
5271 // - one A2DP device + another device: happens with duplicated output. In this case
5272 // retain the device on the A2DP output as the other must not correspond to an active
5273 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005274 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005275 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5276 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005277 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5278 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5279 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5280 device = AUDIO_DEVICE_OUT_AUX_LINE;
5281 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5282 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005283 } else {
5284 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5285 }
5286 }
5287
Jon Eklund11c9fb12014-06-23 14:47:03 -05005288 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5289 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5290 device = AUDIO_DEVICE_OUT_SPEAKER;
5291
Eric Laurent3b73df72014-03-11 09:06:29 -07005292 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005293 "getDeviceForVolume() invalid device combination: %08x",
5294 device);
5295
5296 return device;
5297}
5298
Eric Laurente0720872014-03-11 09:30:41 -07005299AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005300{
5301 switch(getDeviceForVolume(device)) {
5302 case AUDIO_DEVICE_OUT_EARPIECE:
5303 return DEVICE_CATEGORY_EARPIECE;
5304 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5305 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5306 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5307 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5308 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5309 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5310 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005311 case AUDIO_DEVICE_OUT_LINE:
5312 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5313 /*USB? Remote submix?*/
5314 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005315 case AUDIO_DEVICE_OUT_SPEAKER:
5316 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5317 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005318 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5319 case AUDIO_DEVICE_OUT_USB_DEVICE:
5320 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5321 default:
5322 return DEVICE_CATEGORY_SPEAKER;
5323 }
5324}
5325
Eric Laurent223fd5c2014-11-11 13:43:36 -08005326/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005327float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005328 int indexInUi)
5329{
5330 device_category deviceCategory = getDeviceCategory(device);
5331 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5332
5333 // the volume index in the UI is relative to the min and max volume indices for this stream type
5334 int nbSteps = 1 + curve[VOLMAX].mIndex -
5335 curve[VOLMIN].mIndex;
5336 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5337 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5338
5339 // find what part of the curve this index volume belongs to, or if it's out of bounds
5340 int segment = 0;
5341 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5342 return 0.0f;
5343 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5344 segment = 0;
5345 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5346 segment = 1;
5347 } else if (volIdx <= curve[VOLMAX].mIndex) {
5348 segment = 2;
5349 } else { // out of bounds
5350 return 1.0f;
5351 }
5352
5353 // linear interpolation in the attenuation table in dB
5354 float decibels = curve[segment].mDBAttenuation +
5355 ((float)(volIdx - curve[segment].mIndex)) *
5356 ( (curve[segment+1].mDBAttenuation -
5357 curve[segment].mDBAttenuation) /
5358 ((float)(curve[segment+1].mIndex -
5359 curve[segment].mIndex)) );
5360
5361 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5362
5363 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5364 curve[segment].mIndex, volIdx,
5365 curve[segment+1].mIndex,
5366 curve[segment].mDBAttenuation,
5367 decibels,
5368 curve[segment+1].mDBAttenuation,
5369 amplification);
5370
5371 return amplification;
5372}
5373
Eric Laurente0720872014-03-11 09:30:41 -07005374const AudioPolicyManager::VolumeCurvePoint
5375 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005376 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5377};
5378
Eric Laurente0720872014-03-11 09:30:41 -07005379const AudioPolicyManager::VolumeCurvePoint
5380 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005381 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5382};
5383
Eric Laurente0720872014-03-11 09:30:41 -07005384const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005385 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5386 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5387};
5388
5389const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005390 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005391 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5392};
5393
Eric Laurente0720872014-03-11 09:30:41 -07005394const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005395 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005396 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005397};
5398
5399const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005400 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005401 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5402};
5403
Eric Laurente0720872014-03-11 09:30:41 -07005404const AudioPolicyManager::VolumeCurvePoint
5405 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005406 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5407};
5408
5409// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5410// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5411// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5412// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5413
Eric Laurente0720872014-03-11 09:30:41 -07005414const AudioPolicyManager::VolumeCurvePoint
5415 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005416 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5417};
5418
Eric Laurente0720872014-03-11 09:30:41 -07005419const AudioPolicyManager::VolumeCurvePoint
5420 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005421 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5422};
5423
Eric Laurente0720872014-03-11 09:30:41 -07005424const AudioPolicyManager::VolumeCurvePoint
5425 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005426 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5427};
5428
Eric Laurente0720872014-03-11 09:30:41 -07005429const AudioPolicyManager::VolumeCurvePoint
5430 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005431 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5432};
5433
Eric Laurente0720872014-03-11 09:30:41 -07005434const AudioPolicyManager::VolumeCurvePoint
5435 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005436 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5437};
5438
Eric Laurente0720872014-03-11 09:30:41 -07005439const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005440 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5441 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5442};
5443
5444const AudioPolicyManager::VolumeCurvePoint
5445 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5446 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5447};
5448
5449const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005450 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5451 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5452};
5453
5454const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005455 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5456 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005457 { // AUDIO_STREAM_VOICE_CALL
5458 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5459 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005460 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5461 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005462 },
5463 { // AUDIO_STREAM_SYSTEM
5464 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5465 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005466 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5467 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005468 },
5469 { // AUDIO_STREAM_RING
5470 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5471 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005472 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5473 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005474 },
5475 { // AUDIO_STREAM_MUSIC
5476 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5477 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005478 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5479 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005480 },
5481 { // AUDIO_STREAM_ALARM
5482 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5483 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005484 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5485 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005486 },
5487 { // AUDIO_STREAM_NOTIFICATION
5488 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5489 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005490 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5491 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005492 },
5493 { // AUDIO_STREAM_BLUETOOTH_SCO
5494 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5495 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005496 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5497 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005498 },
5499 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5500 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5501 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005502 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5503 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005504 },
5505 { // AUDIO_STREAM_DTMF
5506 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5507 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005508 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5509 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005510 },
5511 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005512 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5513 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5514 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5515 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5516 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005517 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005518 { // AUDIO_STREAM_ACCESSIBILITY
5519 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5520 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5521 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5522 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5523 },
5524 { // AUDIO_STREAM_REROUTING
5525 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5526 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5527 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5528 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5529 },
5530 { // AUDIO_STREAM_PATCH
5531 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5532 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5533 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5534 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5535 },
Eric Laurente552edb2014-03-10 17:42:56 -07005536};
5537
Eric Laurente0720872014-03-11 09:30:41 -07005538void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005539{
5540 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5541 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5542 mStreams[i].mVolumeCurve[j] =
5543 sVolumeProfiles[i][j];
5544 }
5545 }
5546
5547 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5548 if (mSpeakerDrcEnabled) {
5549 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5550 sDefaultSystemVolumeCurveDrc;
5551 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5552 sSpeakerSonificationVolumeCurveDrc;
5553 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5554 sSpeakerSonificationVolumeCurveDrc;
5555 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5556 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005557 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5558 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005559 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5560 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005561 }
5562}
5563
Eric Laurente0720872014-03-11 09:30:41 -07005564float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005565 int index,
5566 audio_io_handle_t output,
5567 audio_devices_t device)
5568{
5569 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005570 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005571 StreamDescriptor &streamDesc = mStreams[stream];
5572
5573 if (device == AUDIO_DEVICE_NONE) {
5574 device = outputDesc->device();
5575 }
5576
Eric Laurente552edb2014-03-10 17:42:56 -07005577 volume = volIndexToAmpl(device, streamDesc, index);
5578
5579 // if a headset is connected, apply the following rules to ring tones and notifications
5580 // to avoid sound level bursts in user's ears:
5581 // - always attenuate ring tones and notifications volume by 6dB
5582 // - if music is playing, always limit the volume to current music volume,
5583 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005584 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005585 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5586 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5587 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5588 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5589 ((stream_strategy == STRATEGY_SONIFICATION)
5590 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005592 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005593 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005594 streamDesc.mCanBeMuted) {
5595 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5596 // when the phone is ringing we must consider that music could have been paused just before
5597 // by the music application and behave as if music was active if the last music track was
5598 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005600 mLimitRingtoneVolume) {
5601 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005602 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5603 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005604 output,
5605 musicDevice);
5606 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5607 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5608 if (volume > minVol) {
5609 volume = minVol;
5610 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5611 }
5612 }
5613 }
5614
5615 return volume;
5616}
5617
Eric Laurente0720872014-03-11 09:30:41 -07005618status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005619 int index,
5620 audio_io_handle_t output,
5621 audio_devices_t device,
5622 int delayMs,
5623 bool force)
5624{
5625
5626 // do not change actual stream volume if the stream is muted
5627 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5628 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5629 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5630 return NO_ERROR;
5631 }
5632
5633 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005634 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5635 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5636 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5637 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005638 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005639 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005640 return INVALID_OPERATION;
5641 }
5642
5643 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005644 // unit gain if rerouting to external policy
5645 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5646 ssize_t index = mOutputs.indexOfKey(output);
5647 if (index >= 0) {
5648 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005649 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005650 ALOGV("max gain when rerouting for output=%d", output);
5651 volume = 1.0f;
5652 }
5653 }
5654
5655 }
Eric Laurente552edb2014-03-10 17:42:56 -07005656 // We actually change the volume if:
5657 // - the float value returned by computeVolume() changed
5658 // - the force flag is set
5659 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5660 force) {
5661 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5662 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5663 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5664 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005665 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5666 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005667 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005668 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005669 }
5670
Eric Laurent3b73df72014-03-11 09:06:29 -07005671 if (stream == AUDIO_STREAM_VOICE_CALL ||
5672 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005673 float voiceVolume;
5674 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005675 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005676 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5677 } else {
5678 voiceVolume = 1.0;
5679 }
5680
5681 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5682 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5683 mLastVoiceVolume = voiceVolume;
5684 }
5685 }
5686
5687 return NO_ERROR;
5688}
5689
Eric Laurente0720872014-03-11 09:30:41 -07005690void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005691 audio_devices_t device,
5692 int delayMs,
5693 bool force)
5694{
5695 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5696
Eric Laurent3b73df72014-03-11 09:06:29 -07005697 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005698 if (stream == AUDIO_STREAM_PATCH) {
5699 continue;
5700 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005701 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005702 mStreams[stream].getVolumeIndex(device),
5703 output,
5704 device,
5705 delayMs,
5706 force);
5707 }
5708}
5709
Eric Laurente0720872014-03-11 09:30:41 -07005710void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005711 bool on,
5712 audio_io_handle_t output,
5713 int delayMs,
5714 audio_devices_t device)
5715{
5716 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005717 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005718 if (stream == AUDIO_STREAM_PATCH) {
5719 continue;
5720 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005721 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5722 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005723 }
5724 }
5725}
5726
Eric Laurente0720872014-03-11 09:30:41 -07005727void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005728 bool on,
5729 audio_io_handle_t output,
5730 int delayMs,
5731 audio_devices_t device)
5732{
5733 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005734 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005735 if (device == AUDIO_DEVICE_NONE) {
5736 device = outputDesc->device();
5737 }
5738
5739 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5740 stream, on, output, outputDesc->mMuteCount[stream], device);
5741
5742 if (on) {
5743 if (outputDesc->mMuteCount[stream] == 0) {
5744 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005745 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5746 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005747 checkAndSetVolume(stream, 0, output, device, delayMs);
5748 }
5749 }
5750 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5751 outputDesc->mMuteCount[stream]++;
5752 } else {
5753 if (outputDesc->mMuteCount[stream] == 0) {
5754 ALOGV("setStreamMute() unmuting non muted stream!");
5755 return;
5756 }
5757 if (--outputDesc->mMuteCount[stream] == 0) {
5758 checkAndSetVolume(stream,
5759 streamDesc.getVolumeIndex(device),
5760 output,
5761 device,
5762 delayMs);
5763 }
5764 }
5765}
5766
Eric Laurente0720872014-03-11 09:30:41 -07005767void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005768 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005769{
5770 // if the stream pertains to sonification strategy and we are in call we must
5771 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5772 // in the device used for phone strategy and play the tone if the selected device does not
5773 // interfere with the device used for phone strategy
5774 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5775 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005776 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005777 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5778 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005779 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005780 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5781 stream, starting, outputDesc->mDevice, stateChange);
5782 if (outputDesc->mRefCount[stream]) {
5783 int muteCount = 1;
5784 if (stateChange) {
5785 muteCount = outputDesc->mRefCount[stream];
5786 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005787 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005788 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5789 for (int i = 0; i < muteCount; i++) {
5790 setStreamMute(stream, starting, mPrimaryOutput);
5791 }
5792 } else {
5793 ALOGV("handleIncallSonification() high visibility");
5794 if (outputDesc->device() &
5795 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5796 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5797 for (int i = 0; i < muteCount; i++) {
5798 setStreamMute(stream, starting, mPrimaryOutput);
5799 }
5800 }
5801 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005802 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5803 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005804 } else {
5805 mpClientInterface->stopTone();
5806 }
5807 }
5808 }
5809 }
5810}
5811
Eric Laurente0720872014-03-11 09:30:41 -07005812bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005813{
5814 return isStateInCall(mPhoneState);
5815}
5816
Eric Laurente0720872014-03-11 09:30:41 -07005817bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005818 return ((state == AUDIO_MODE_IN_CALL) ||
5819 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005820}
5821
Eric Laurente0720872014-03-11 09:30:41 -07005822uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005823{
5824 return MAX_EFFECTS_CPU_LOAD;
5825}
5826
Eric Laurente0720872014-03-11 09:30:41 -07005827uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005828{
5829 return MAX_EFFECTS_MEMORY;
5830}
5831
Eric Laurent6a94d692014-05-20 11:18:06 -07005832
Eric Laurente552edb2014-03-10 17:42:56 -07005833// --- AudioOutputDescriptor class implementation
5834
Eric Laurente0720872014-03-11 09:30:41 -07005835AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005836 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005837 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005838 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005839 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005840 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5841{
5842 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005843 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005844 mRefCount[i] = 0;
5845 mCurVolume[i] = -1.0;
5846 mMuteCount[i] = 0;
5847 mStopTime[i] = 0;
5848 }
5849 for (int i = 0; i < NUM_STRATEGIES; i++) {
5850 mStrategyMutedByDevice[i] = false;
5851 }
5852 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005853 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005854 mSamplingRate = profile->pickSamplingRate();
5855 mFormat = profile->pickFormat();
5856 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005857 if (profile->mGains.size() > 0) {
5858 profile->mGains[0]->getDefaultConfig(&mGain);
5859 }
Eric Laurente552edb2014-03-10 17:42:56 -07005860 }
5861}
5862
Eric Laurente0720872014-03-11 09:30:41 -07005863audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005864{
5865 if (isDuplicated()) {
5866 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5867 } else {
5868 return mDevice;
5869 }
5870}
5871
Eric Laurente0720872014-03-11 09:30:41 -07005872uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005873{
5874 if (isDuplicated()) {
5875 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5876 } else {
5877 return mLatency;
5878 }
5879}
5880
Eric Laurente0720872014-03-11 09:30:41 -07005881bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005882 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005883{
5884 if (isDuplicated()) {
5885 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5886 } else if (outputDesc->isDuplicated()){
5887 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5888 } else {
5889 return (mProfile->mModule == outputDesc->mProfile->mModule);
5890 }
5891}
5892
Eric Laurente0720872014-03-11 09:30:41 -07005893void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005894 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005895{
5896 // forward usage count change to attached outputs
5897 if (isDuplicated()) {
5898 mOutput1->changeRefCount(stream, delta);
5899 mOutput2->changeRefCount(stream, delta);
5900 }
5901 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005902 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5903 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005904 mRefCount[stream] = 0;
5905 return;
5906 }
5907 mRefCount[stream] += delta;
5908 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5909}
5910
Eric Laurente0720872014-03-11 09:30:41 -07005911audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005912{
5913 if (isDuplicated()) {
5914 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5915 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005916 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005917 }
5918}
5919
Eric Laurente0720872014-03-11 09:30:41 -07005920bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005921{
5922 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5923}
5924
Eric Laurente0720872014-03-11 09:30:41 -07005925bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005926 uint32_t inPastMs,
5927 nsecs_t sysTime) const
5928{
5929 if ((sysTime == 0) && (inPastMs != 0)) {
5930 sysTime = systemTime();
5931 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005932 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005933 if (i == AUDIO_STREAM_PATCH) {
5934 continue;
5935 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005936 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005937 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005938 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005939 return true;
5940 }
5941 }
5942 return false;
5943}
5944
Eric Laurente0720872014-03-11 09:30:41 -07005945bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005946 uint32_t inPastMs,
5947 nsecs_t sysTime) const
5948{
5949 if (mRefCount[stream] != 0) {
5950 return true;
5951 }
5952 if (inPastMs == 0) {
5953 return false;
5954 }
5955 if (sysTime == 0) {
5956 sysTime = systemTime();
5957 }
5958 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5959 return true;
5960 }
5961 return false;
5962}
5963
Eric Laurent1c333e22014-05-20 10:48:17 -07005964void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005965 struct audio_port_config *dstConfig,
5966 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005967{
Eric Laurent84c70242014-06-23 08:46:27 -07005968 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5969
Eric Laurent1f2f2232014-06-02 12:01:23 -07005970 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5971 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5972 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005973 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005974 }
5975 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5976
Eric Laurent6a94d692014-05-20 11:18:06 -07005977 dstConfig->id = mId;
5978 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5979 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005980 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5981 dstConfig->ext.mix.handle = mIoHandle;
5982 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005983}
5984
5985void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5986 struct audio_port *port) const
5987{
Eric Laurent84c70242014-06-23 08:46:27 -07005988 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005989 mProfile->toAudioPort(port);
5990 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005991 toAudioPortConfig(&port->active_config);
5992 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005993 port->ext.mix.handle = mIoHandle;
5994 port->ext.mix.latency_class =
5995 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5996}
Eric Laurente552edb2014-03-10 17:42:56 -07005997
Eric Laurente0720872014-03-11 09:30:41 -07005998status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005999{
6000 const size_t SIZE = 256;
6001 char buffer[SIZE];
6002 String8 result;
6003
Eric Laurent4d416952014-08-10 14:07:09 -07006004 snprintf(buffer, SIZE, " ID: %d\n", mId);
6005 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006006 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6007 result.append(buffer);
6008 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6009 result.append(buffer);
6010 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6011 result.append(buffer);
6012 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6013 result.append(buffer);
6014 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6015 result.append(buffer);
6016 snprintf(buffer, SIZE, " Devices %08x\n", device());
6017 result.append(buffer);
6018 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6019 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006020 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6021 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6022 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006023 result.append(buffer);
6024 }
6025 write(fd, result.string(), result.size());
6026
6027 return NO_ERROR;
6028}
6029
6030// --- AudioInputDescriptor class implementation
6031
Eric Laurent1c333e22014-05-20 10:48:17 -07006032AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006033 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006034 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006035 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006036{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006037 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006038 mSamplingRate = profile->pickSamplingRate();
6039 mFormat = profile->pickFormat();
6040 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006041 if (profile->mGains.size() > 0) {
6042 profile->mGains[0]->getDefaultConfig(&mGain);
6043 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006044 }
Eric Laurente552edb2014-03-10 17:42:56 -07006045}
6046
Eric Laurent1c333e22014-05-20 10:48:17 -07006047void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006048 struct audio_port_config *dstConfig,
6049 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006050{
Eric Laurent84c70242014-06-23 08:46:27 -07006051 ALOG_ASSERT(mProfile != 0,
6052 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006053 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6054 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6055 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006056 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006057 }
6058
6059 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6060
Eric Laurent6a94d692014-05-20 11:18:06 -07006061 dstConfig->id = mId;
6062 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6063 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006064 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6065 dstConfig->ext.mix.handle = mIoHandle;
6066 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006067}
6068
6069void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6070 struct audio_port *port) const
6071{
Eric Laurent84c70242014-06-23 08:46:27 -07006072 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6073
Eric Laurent1c333e22014-05-20 10:48:17 -07006074 mProfile->toAudioPort(port);
6075 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006076 toAudioPortConfig(&port->active_config);
6077 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006078 port->ext.mix.handle = mIoHandle;
6079 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6080}
6081
Eric Laurente0720872014-03-11 09:30:41 -07006082status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006083{
6084 const size_t SIZE = 256;
6085 char buffer[SIZE];
6086 String8 result;
6087
Eric Laurent4d416952014-08-10 14:07:09 -07006088 snprintf(buffer, SIZE, " ID: %d\n", mId);
6089 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006090 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6091 result.append(buffer);
6092 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6093 result.append(buffer);
6094 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6095 result.append(buffer);
6096 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6097 result.append(buffer);
6098 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6099 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006100 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6101 result.append(buffer);
6102
Eric Laurente552edb2014-03-10 17:42:56 -07006103 write(fd, result.string(), result.size());
6104
6105 return NO_ERROR;
6106}
6107
6108// --- StreamDescriptor class implementation
6109
Eric Laurente0720872014-03-11 09:30:41 -07006110AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006111 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6112{
6113 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6114}
6115
Eric Laurente0720872014-03-11 09:30:41 -07006116int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006117{
Eric Laurente0720872014-03-11 09:30:41 -07006118 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006119 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6120 if (mIndexCur.indexOfKey(device) < 0) {
6121 device = AUDIO_DEVICE_OUT_DEFAULT;
6122 }
6123 return mIndexCur.valueFor(device);
6124}
6125
Eric Laurente0720872014-03-11 09:30:41 -07006126void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006127{
6128 const size_t SIZE = 256;
6129 char buffer[SIZE];
6130 String8 result;
6131
6132 snprintf(buffer, SIZE, "%s %02d %02d ",
6133 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6134 result.append(buffer);
6135 for (size_t i = 0; i < mIndexCur.size(); i++) {
6136 snprintf(buffer, SIZE, "%04x : %02d, ",
6137 mIndexCur.keyAt(i),
6138 mIndexCur.valueAt(i));
6139 result.append(buffer);
6140 }
6141 result.append("\n");
6142
6143 write(fd, result.string(), result.size());
6144}
6145
6146// --- EffectDescriptor class implementation
6147
Eric Laurente0720872014-03-11 09:30:41 -07006148status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
6150 const size_t SIZE = 256;
6151 char buffer[SIZE];
6152 String8 result;
6153
6154 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6155 result.append(buffer);
6156 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6157 result.append(buffer);
6158 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6159 result.append(buffer);
6160 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6161 result.append(buffer);
6162 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6163 result.append(buffer);
6164 write(fd, result.string(), result.size());
6165
6166 return NO_ERROR;
6167}
6168
Eric Laurent1c333e22014-05-20 10:48:17 -07006169// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006170
Eric Laurente0720872014-03-11 09:30:41 -07006171AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006172 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6173 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006174{
6175}
6176
Eric Laurente0720872014-03-11 09:30:41 -07006177AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006178{
6179 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006180 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006181 }
6182 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006183 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006184 }
6185 free((void *)mName);
6186}
6187
Eric Laurent1afeecb2014-05-14 08:52:28 -07006188status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6189{
6190 cnode *node = root->first_child;
6191
6192 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6193
6194 while (node) {
6195 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6196 profile->loadSamplingRates((char *)node->value);
6197 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6198 profile->loadFormats((char *)node->value);
6199 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6200 profile->loadInChannels((char *)node->value);
6201 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6202 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6203 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006204 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6205 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006206 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6207 profile->loadGains(node);
6208 }
6209 node = node->next;
6210 }
6211 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6212 "loadInput() invalid supported devices");
6213 ALOGW_IF(profile->mChannelMasks.size() == 0,
6214 "loadInput() invalid supported channel masks");
6215 ALOGW_IF(profile->mSamplingRates.size() == 0,
6216 "loadInput() invalid supported sampling rates");
6217 ALOGW_IF(profile->mFormats.size() == 0,
6218 "loadInput() invalid supported formats");
6219 if (!profile->mSupportedDevices.isEmpty() &&
6220 (profile->mChannelMasks.size() != 0) &&
6221 (profile->mSamplingRates.size() != 0) &&
6222 (profile->mFormats.size() != 0)) {
6223
6224 ALOGV("loadInput() adding input Supported Devices %04x",
6225 profile->mSupportedDevices.types());
6226
6227 mInputProfiles.add(profile);
6228 return NO_ERROR;
6229 } else {
6230 return BAD_VALUE;
6231 }
6232}
6233
6234status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6235{
6236 cnode *node = root->first_child;
6237
6238 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6239
6240 while (node) {
6241 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6242 profile->loadSamplingRates((char *)node->value);
6243 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6244 profile->loadFormats((char *)node->value);
6245 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6246 profile->loadOutChannels((char *)node->value);
6247 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6248 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6249 mDeclaredDevices);
6250 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006251 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006252 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6253 profile->loadGains(node);
6254 }
6255 node = node->next;
6256 }
6257 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6258 "loadOutput() invalid supported devices");
6259 ALOGW_IF(profile->mChannelMasks.size() == 0,
6260 "loadOutput() invalid supported channel masks");
6261 ALOGW_IF(profile->mSamplingRates.size() == 0,
6262 "loadOutput() invalid supported sampling rates");
6263 ALOGW_IF(profile->mFormats.size() == 0,
6264 "loadOutput() invalid supported formats");
6265 if (!profile->mSupportedDevices.isEmpty() &&
6266 (profile->mChannelMasks.size() != 0) &&
6267 (profile->mSamplingRates.size() != 0) &&
6268 (profile->mFormats.size() != 0)) {
6269
6270 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6271 profile->mSupportedDevices.types(), profile->mFlags);
6272
6273 mOutputProfiles.add(profile);
6274 return NO_ERROR;
6275 } else {
6276 return BAD_VALUE;
6277 }
6278}
6279
6280status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6281{
6282 cnode *node = root->first_child;
6283
6284 audio_devices_t type = AUDIO_DEVICE_NONE;
6285 while (node) {
6286 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6287 type = parseDeviceNames((char *)node->value);
6288 break;
6289 }
6290 node = node->next;
6291 }
6292 if (type == AUDIO_DEVICE_NONE ||
6293 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6294 ALOGW("loadDevice() bad type %08x", type);
6295 return BAD_VALUE;
6296 }
6297 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6298 deviceDesc->mModule = this;
6299
6300 node = root->first_child;
6301 while (node) {
6302 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6303 deviceDesc->mAddress = String8((char *)node->value);
6304 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6305 if (audio_is_input_device(type)) {
6306 deviceDesc->loadInChannels((char *)node->value);
6307 } else {
6308 deviceDesc->loadOutChannels((char *)node->value);
6309 }
6310 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6311 deviceDesc->loadGains(node);
6312 }
6313 node = node->next;
6314 }
6315
6316 ALOGV("loadDevice() adding device name %s type %08x address %s",
6317 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6318
6319 mDeclaredDevices.add(deviceDesc);
6320
6321 return NO_ERROR;
6322}
6323
Eric Laurent275e8e92014-11-30 15:14:47 -08006324status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6325 audio_devices_t device, String8 address)
6326{
6327 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6328
6329 profile->mSamplingRates.add(config->sample_rate);
6330 profile->mChannelMasks.add(config->channel_mask);
6331 profile->mFormats.add(config->format);
6332
6333 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6334 devDesc->mAddress = address;
6335 profile->mSupportedDevices.add(devDesc);
6336
6337 mOutputProfiles.add(profile);
6338
6339 return NO_ERROR;
6340}
6341
6342status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6343{
6344 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6345 if (mOutputProfiles[i]->mName == name) {
6346 mOutputProfiles.removeAt(i);
6347 break;
6348 }
6349 }
6350
6351 return NO_ERROR;
6352}
6353
6354status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6355 audio_devices_t device, String8 address)
6356{
6357 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6358
6359 profile->mSamplingRates.add(config->sample_rate);
6360 profile->mChannelMasks.add(config->channel_mask);
6361 profile->mFormats.add(config->format);
6362
6363 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6364 devDesc->mAddress = address;
6365 profile->mSupportedDevices.add(devDesc);
6366
6367 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6368
6369 mInputProfiles.add(profile);
6370
6371 return NO_ERROR;
6372}
6373
6374status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6375{
6376 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6377 if (mInputProfiles[i]->mName == name) {
6378 mInputProfiles.removeAt(i);
6379 break;
6380 }
6381 }
6382
6383 return NO_ERROR;
6384}
6385
6386
Eric Laurente0720872014-03-11 09:30:41 -07006387void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006388{
6389 const size_t SIZE = 256;
6390 char buffer[SIZE];
6391 String8 result;
6392
6393 snprintf(buffer, SIZE, " - name: %s\n", mName);
6394 result.append(buffer);
6395 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6396 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006397 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6398 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006399 write(fd, result.string(), result.size());
6400 if (mOutputProfiles.size()) {
6401 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6402 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006403 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006404 write(fd, buffer, strlen(buffer));
6405 mOutputProfiles[i]->dump(fd);
6406 }
6407 }
6408 if (mInputProfiles.size()) {
6409 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6410 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006411 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006412 write(fd, buffer, strlen(buffer));
6413 mInputProfiles[i]->dump(fd);
6414 }
6415 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006416 if (mDeclaredDevices.size()) {
6417 write(fd, " - devices:\n", strlen(" - devices:\n"));
6418 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6419 mDeclaredDevices[i]->dump(fd, 4, i);
6420 }
6421 }
Eric Laurente552edb2014-03-10 17:42:56 -07006422}
6423
Eric Laurent1c333e22014-05-20 10:48:17 -07006424// --- AudioPort class implementation
6425
Eric Laurenta121f902014-06-03 13:32:54 -07006426
6427AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6428 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006429 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006430{
6431 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6432 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6433}
6434
Eric Laurent1c333e22014-05-20 10:48:17 -07006435void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6436{
6437 port->role = mRole;
6438 port->type = mType;
6439 unsigned int i;
6440 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006441 if (mSamplingRates[i] != 0) {
6442 port->sample_rates[i] = mSamplingRates[i];
6443 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006444 }
6445 port->num_sample_rates = i;
6446 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006447 if (mChannelMasks[i] != 0) {
6448 port->channel_masks[i] = mChannelMasks[i];
6449 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006450 }
6451 port->num_channel_masks = i;
6452 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006453 if (mFormats[i] != 0) {
6454 port->formats[i] = mFormats[i];
6455 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006456 }
6457 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006458
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006459 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006460
6461 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6462 port->gains[i] = mGains[i]->mGain;
6463 }
6464 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006465}
6466
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006467void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6468 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6469 const uint32_t rate = port->mSamplingRates.itemAt(k);
6470 if (rate != 0) { // skip "dynamic" rates
6471 bool hasRate = false;
6472 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6473 if (rate == mSamplingRates.itemAt(l)) {
6474 hasRate = true;
6475 break;
6476 }
6477 }
6478 if (!hasRate) { // never import a sampling rate twice
6479 mSamplingRates.add(rate);
6480 }
6481 }
6482 }
6483 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6484 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6485 if (mask != 0) { // skip "dynamic" masks
6486 bool hasMask = false;
6487 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6488 if (mask == mChannelMasks.itemAt(l)) {
6489 hasMask = true;
6490 break;
6491 }
6492 }
6493 if (!hasMask) { // never import a channel mask twice
6494 mChannelMasks.add(mask);
6495 }
6496 }
6497 }
6498 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6499 const audio_format_t format = port->mFormats.itemAt(k);
6500 if (format != 0) { // skip "dynamic" formats
6501 bool hasFormat = false;
6502 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6503 if (format == mFormats.itemAt(l)) {
6504 hasFormat = true;
6505 break;
6506 }
6507 }
6508 if (!hasFormat) { // never import a channel mask twice
6509 mFormats.add(format);
6510 }
6511 }
6512 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006513 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6514 sp<AudioGain> gain = port->mGains.itemAt(k);
6515 if (gain != 0) {
6516 bool hasGain = false;
6517 for (size_t l = 0 ; l < mGains.size() ; l++) {
6518 if (gain == mGains.itemAt(l)) {
6519 hasGain = true;
6520 break;
6521 }
6522 }
6523 if (!hasGain) { // never import a gain twice
6524 mGains.add(gain);
6525 }
6526 }
6527 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006528}
6529
6530void AudioPolicyManager::AudioPort::clearCapabilities() {
6531 mChannelMasks.clear();
6532 mFormats.clear();
6533 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006534 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006535}
Eric Laurent1c333e22014-05-20 10:48:17 -07006536
6537void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6538{
6539 char *str = strtok(name, "|");
6540
6541 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6542 // rates should be read from the output stream after it is opened for the first time
6543 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6544 mSamplingRates.add(0);
6545 return;
6546 }
6547
6548 while (str != NULL) {
6549 uint32_t rate = atoi(str);
6550 if (rate != 0) {
6551 ALOGV("loadSamplingRates() adding rate %d", rate);
6552 mSamplingRates.add(rate);
6553 }
6554 str = strtok(NULL, "|");
6555 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006556}
6557
6558void AudioPolicyManager::AudioPort::loadFormats(char *name)
6559{
6560 char *str = strtok(name, "|");
6561
6562 // by convention, "0' in the first entry in mFormats indicates the supported formats
6563 // should be read from the output stream after it is opened for the first time
6564 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6565 mFormats.add(AUDIO_FORMAT_DEFAULT);
6566 return;
6567 }
6568
6569 while (str != NULL) {
6570 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6571 ARRAY_SIZE(sFormatNameToEnumTable),
6572 str);
6573 if (format != AUDIO_FORMAT_DEFAULT) {
6574 mFormats.add(format);
6575 }
6576 str = strtok(NULL, "|");
6577 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006578}
6579
6580void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6581{
6582 const char *str = strtok(name, "|");
6583
6584 ALOGV("loadInChannels() %s", name);
6585
6586 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6587 mChannelMasks.add(0);
6588 return;
6589 }
6590
6591 while (str != NULL) {
6592 audio_channel_mask_t channelMask =
6593 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6594 ARRAY_SIZE(sInChannelsNameToEnumTable),
6595 str);
6596 if (channelMask != 0) {
6597 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6598 mChannelMasks.add(channelMask);
6599 }
6600 str = strtok(NULL, "|");
6601 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006602}
6603
6604void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6605{
6606 const char *str = strtok(name, "|");
6607
6608 ALOGV("loadOutChannels() %s", name);
6609
6610 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6611 // masks should be read from the output stream after it is opened for the first time
6612 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6613 mChannelMasks.add(0);
6614 return;
6615 }
6616
6617 while (str != NULL) {
6618 audio_channel_mask_t channelMask =
6619 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6620 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6621 str);
6622 if (channelMask != 0) {
6623 mChannelMasks.add(channelMask);
6624 }
6625 str = strtok(NULL, "|");
6626 }
6627 return;
6628}
6629
Eric Laurent1afeecb2014-05-14 08:52:28 -07006630audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6631{
6632 const char *str = strtok(name, "|");
6633
6634 ALOGV("loadGainMode() %s", name);
6635 audio_gain_mode_t mode = 0;
6636 while (str != NULL) {
6637 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6638 ARRAY_SIZE(sGainModeNameToEnumTable),
6639 str);
6640 str = strtok(NULL, "|");
6641 }
6642 return mode;
6643}
6644
Eric Laurenta121f902014-06-03 13:32:54 -07006645void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006646{
6647 cnode *node = root->first_child;
6648
Eric Laurenta121f902014-06-03 13:32:54 -07006649 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006650
6651 while (node) {
6652 if (strcmp(node->name, GAIN_MODE) == 0) {
6653 gain->mGain.mode = loadGainMode((char *)node->value);
6654 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006655 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006656 gain->mGain.channel_mask =
6657 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6658 ARRAY_SIZE(sInChannelsNameToEnumTable),
6659 (char *)node->value);
6660 } else {
6661 gain->mGain.channel_mask =
6662 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6663 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6664 (char *)node->value);
6665 }
6666 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6667 gain->mGain.min_value = atoi((char *)node->value);
6668 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6669 gain->mGain.max_value = atoi((char *)node->value);
6670 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6671 gain->mGain.default_value = atoi((char *)node->value);
6672 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6673 gain->mGain.step_value = atoi((char *)node->value);
6674 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6675 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6676 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6677 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6678 }
6679 node = node->next;
6680 }
6681
6682 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6683 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6684
6685 if (gain->mGain.mode == 0) {
6686 return;
6687 }
6688 mGains.add(gain);
6689}
6690
6691void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6692{
6693 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006694 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006695 while (node) {
6696 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006697 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006698 node = node->next;
6699 }
6700}
6701
Glenn Kastencbd48022014-07-24 13:46:44 -07006702status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006703{
Eric Laurent0daea392014-12-04 19:14:54 -08006704 if (mSamplingRates.isEmpty()) {
6705 return NO_ERROR;
6706 }
6707
Eric Laurenta121f902014-06-03 13:32:54 -07006708 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6709 if (mSamplingRates[i] == samplingRate) {
6710 return NO_ERROR;
6711 }
6712 }
6713 return BAD_VALUE;
6714}
6715
Glenn Kastencbd48022014-07-24 13:46:44 -07006716status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6717 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006718{
Eric Laurent0daea392014-12-04 19:14:54 -08006719 if (mSamplingRates.isEmpty()) {
6720 return NO_ERROR;
6721 }
6722
Glenn Kastencbd48022014-07-24 13:46:44 -07006723 // Search for the closest supported sampling rate that is above (preferred)
6724 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6725 // The sampling rates do not need to be sorted in ascending order.
6726 ssize_t maxBelow = -1;
6727 ssize_t minAbove = -1;
6728 uint32_t candidate;
6729 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6730 candidate = mSamplingRates[i];
6731 if (candidate == samplingRate) {
6732 if (updatedSamplingRate != NULL) {
6733 *updatedSamplingRate = candidate;
6734 }
6735 return NO_ERROR;
6736 }
6737 // candidate < desired
6738 if (candidate < samplingRate) {
6739 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6740 maxBelow = i;
6741 }
6742 // candidate > desired
6743 } else {
6744 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6745 minAbove = i;
6746 }
6747 }
6748 }
6749 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6750 // TODO Move these assumptions out.
6751 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6752 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6753 // due to approximation by an int32_t of the
6754 // phase increments
6755 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6756 if (minAbove >= 0) {
6757 candidate = mSamplingRates[minAbove];
6758 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6759 if (updatedSamplingRate != NULL) {
6760 *updatedSamplingRate = candidate;
6761 }
6762 return NO_ERROR;
6763 }
6764 }
6765 // But if we have to up-sample from a lower sampling rate, that's OK.
6766 if (maxBelow >= 0) {
6767 candidate = mSamplingRates[maxBelow];
6768 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6769 if (updatedSamplingRate != NULL) {
6770 *updatedSamplingRate = candidate;
6771 }
6772 return NO_ERROR;
6773 }
6774 }
6775 // leave updatedSamplingRate unmodified
6776 return BAD_VALUE;
6777}
6778
6779status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6780{
Eric Laurent0daea392014-12-04 19:14:54 -08006781 if (mChannelMasks.isEmpty()) {
6782 return NO_ERROR;
6783 }
6784
Glenn Kastencbd48022014-07-24 13:46:44 -07006785 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006786 if (mChannelMasks[i] == channelMask) {
6787 return NO_ERROR;
6788 }
6789 }
6790 return BAD_VALUE;
6791}
6792
Glenn Kastencbd48022014-07-24 13:46:44 -07006793status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6794 const
6795{
Eric Laurent0daea392014-12-04 19:14:54 -08006796 if (mChannelMasks.isEmpty()) {
6797 return NO_ERROR;
6798 }
6799
Glenn Kastencbd48022014-07-24 13:46:44 -07006800 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6801 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6802 // FIXME Does not handle multi-channel automatic conversions yet
6803 audio_channel_mask_t supported = mChannelMasks[i];
6804 if (supported == channelMask) {
6805 return NO_ERROR;
6806 }
6807 if (isRecordThread) {
6808 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6809 // FIXME Abstract this out to a table.
6810 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6811 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6812 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6813 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6814 return NO_ERROR;
6815 }
6816 }
6817 }
6818 return BAD_VALUE;
6819}
6820
Eric Laurenta121f902014-06-03 13:32:54 -07006821status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6822{
Eric Laurent0daea392014-12-04 19:14:54 -08006823 if (mFormats.isEmpty()) {
6824 return NO_ERROR;
6825 }
6826
Eric Laurenta121f902014-06-03 13:32:54 -07006827 for (size_t i = 0; i < mFormats.size(); i ++) {
6828 if (mFormats[i] == format) {
6829 return NO_ERROR;
6830 }
6831 }
6832 return BAD_VALUE;
6833}
6834
Eric Laurent1e693b52014-07-09 15:03:28 -07006835
6836uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6837{
6838 // special case for uninitialized dynamic profile
6839 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6840 return 0;
6841 }
6842
Eric Laurent828bcff2014-09-07 12:26:06 -07006843 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6844 // channel count / sampling rate combination chosen will be supported by the connected
6845 // sink
6846 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6847 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6848 uint32_t samplingRate = UINT_MAX;
6849 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6850 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6851 samplingRate = mSamplingRates[i];
6852 }
6853 }
6854 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6855 }
6856
Eric Laurent1e693b52014-07-09 15:03:28 -07006857 uint32_t samplingRate = 0;
6858 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6859
6860 // For mixed output and inputs, use max mixer sampling rates. Do not
6861 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006862 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006863 maxRate = UINT_MAX;
6864 }
6865 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6866 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6867 samplingRate = mSamplingRates[i];
6868 }
6869 }
6870 return samplingRate;
6871}
6872
6873audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6874{
6875 // special case for uninitialized dynamic profile
6876 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6877 return AUDIO_CHANNEL_NONE;
6878 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006879 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006880
6881 // For direct outputs, pick minimum channel count: this helps ensuring that the
6882 // channel count / sampling rate combination chosen will be supported by the connected
6883 // sink
6884 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6885 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6886 uint32_t channelCount = UINT_MAX;
6887 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6888 uint32_t cnlCount;
6889 if (mUseInChannelMask) {
6890 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6891 } else {
6892 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6893 }
6894 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6895 channelMask = mChannelMasks[i];
6896 channelCount = cnlCount;
6897 }
6898 }
6899 return channelMask;
6900 }
6901
Eric Laurent1e693b52014-07-09 15:03:28 -07006902 uint32_t channelCount = 0;
6903 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6904
6905 // For mixed output and inputs, use max mixer channel count. Do not
6906 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006907 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006908 maxCount = UINT_MAX;
6909 }
6910 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6911 uint32_t cnlCount;
6912 if (mUseInChannelMask) {
6913 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6914 } else {
6915 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6916 }
6917 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6918 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006919 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006920 }
6921 }
6922 return channelMask;
6923}
6924
Andy Hung9a605382014-07-28 16:16:31 -07006925/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006926const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6927 AUDIO_FORMAT_DEFAULT,
6928 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006929 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006930 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006931 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006932 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006933};
6934
6935int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6936 audio_format_t format2)
6937{
6938 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6939 // compressed format and better than any PCM format. This is by design of pickFormat()
6940 if (!audio_is_linear_pcm(format1)) {
6941 if (!audio_is_linear_pcm(format2)) {
6942 return 0;
6943 }
6944 return 1;
6945 }
6946 if (!audio_is_linear_pcm(format2)) {
6947 return -1;
6948 }
6949
6950 int index1 = -1, index2 = -1;
6951 for (size_t i = 0;
6952 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6953 i ++) {
6954 if (sPcmFormatCompareTable[i] == format1) {
6955 index1 = i;
6956 }
6957 if (sPcmFormatCompareTable[i] == format2) {
6958 index2 = i;
6959 }
6960 }
6961 // format1 not found => index1 < 0 => format2 > format1
6962 // format2 not found => index2 < 0 => format2 < format1
6963 return index1 - index2;
6964}
6965
6966audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6967{
6968 // special case for uninitialized dynamic profile
6969 if (mFormats.size() == 1 && mFormats[0] == 0) {
6970 return AUDIO_FORMAT_DEFAULT;
6971 }
6972
6973 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006974 audio_format_t bestFormat =
6975 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6976 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006977 // For mixed output and inputs, use best mixer output format. Do not
6978 // limit format otherwise
6979 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6980 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006981 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006982 bestFormat = AUDIO_FORMAT_INVALID;
6983 }
6984
6985 for (size_t i = 0; i < mFormats.size(); i ++) {
6986 if ((compareFormats(mFormats[i], format) > 0) &&
6987 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6988 format = mFormats[i];
6989 }
6990 }
6991 return format;
6992}
6993
Eric Laurenta121f902014-06-03 13:32:54 -07006994status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6995 int index) const
6996{
6997 if (index < 0 || (size_t)index >= mGains.size()) {
6998 return BAD_VALUE;
6999 }
7000 return mGains[index]->checkConfig(gainConfig);
7001}
7002
Eric Laurent1afeecb2014-05-14 08:52:28 -07007003void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7004{
7005 const size_t SIZE = 256;
7006 char buffer[SIZE];
7007 String8 result;
7008
7009 if (mName.size() != 0) {
7010 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7011 result.append(buffer);
7012 }
7013
7014 if (mSamplingRates.size() != 0) {
7015 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7016 result.append(buffer);
7017 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007018 if (i == 0 && mSamplingRates[i] == 0) {
7019 snprintf(buffer, SIZE, "Dynamic");
7020 } else {
7021 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7022 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007023 result.append(buffer);
7024 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7025 }
7026 result.append("\n");
7027 }
7028
7029 if (mChannelMasks.size() != 0) {
7030 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7031 result.append(buffer);
7032 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007033 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7034
7035 if (i == 0 && mChannelMasks[i] == 0) {
7036 snprintf(buffer, SIZE, "Dynamic");
7037 } else {
7038 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7039 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007040 result.append(buffer);
7041 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7042 }
7043 result.append("\n");
7044 }
7045
7046 if (mFormats.size() != 0) {
7047 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7048 result.append(buffer);
7049 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007050 const char *formatStr = enumToString(sFormatNameToEnumTable,
7051 ARRAY_SIZE(sFormatNameToEnumTable),
7052 mFormats[i]);
7053 if (i == 0 && strcmp(formatStr, "") == 0) {
7054 snprintf(buffer, SIZE, "Dynamic");
7055 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007056 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007057 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007058 result.append(buffer);
7059 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7060 }
7061 result.append("\n");
7062 }
7063 write(fd, result.string(), result.size());
7064 if (mGains.size() != 0) {
7065 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7066 write(fd, buffer, strlen(buffer) + 1);
7067 result.append(buffer);
7068 for (size_t i = 0; i < mGains.size(); i++) {
7069 mGains[i]->dump(fd, spaces + 2, i);
7070 }
7071 }
7072}
7073
7074// --- AudioGain class implementation
7075
Eric Laurenta121f902014-06-03 13:32:54 -07007076AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007077{
Eric Laurenta121f902014-06-03 13:32:54 -07007078 mIndex = index;
7079 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007080 memset(&mGain, 0, sizeof(struct audio_gain));
7081}
7082
Eric Laurenta121f902014-06-03 13:32:54 -07007083void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7084{
7085 config->index = mIndex;
7086 config->mode = mGain.mode;
7087 config->channel_mask = mGain.channel_mask;
7088 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7089 config->values[0] = mGain.default_value;
7090 } else {
7091 uint32_t numValues;
7092 if (mUseInChannelMask) {
7093 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7094 } else {
7095 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7096 }
7097 for (size_t i = 0; i < numValues; i++) {
7098 config->values[i] = mGain.default_value;
7099 }
7100 }
7101 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7102 config->ramp_duration_ms = mGain.min_ramp_ms;
7103 }
7104}
7105
7106status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7107{
7108 if ((config->mode & ~mGain.mode) != 0) {
7109 return BAD_VALUE;
7110 }
7111 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7112 if ((config->values[0] < mGain.min_value) ||
7113 (config->values[0] > mGain.max_value)) {
7114 return BAD_VALUE;
7115 }
7116 } else {
7117 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7118 return BAD_VALUE;
7119 }
7120 uint32_t numValues;
7121 if (mUseInChannelMask) {
7122 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7123 } else {
7124 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7125 }
7126 for (size_t i = 0; i < numValues; i++) {
7127 if ((config->values[i] < mGain.min_value) ||
7128 (config->values[i] > mGain.max_value)) {
7129 return BAD_VALUE;
7130 }
7131 }
7132 }
7133 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7134 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7135 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7136 return BAD_VALUE;
7137 }
7138 }
7139 return NO_ERROR;
7140}
7141
Eric Laurent1afeecb2014-05-14 08:52:28 -07007142void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7143{
7144 const size_t SIZE = 256;
7145 char buffer[SIZE];
7146 String8 result;
7147
7148 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7149 result.append(buffer);
7150 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7151 result.append(buffer);
7152 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7153 result.append(buffer);
7154 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7155 result.append(buffer);
7156 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7157 result.append(buffer);
7158 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7159 result.append(buffer);
7160 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7161 result.append(buffer);
7162 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7163 result.append(buffer);
7164 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7165 result.append(buffer);
7166
7167 write(fd, result.string(), result.size());
7168}
7169
Eric Laurent1f2f2232014-06-02 12:01:23 -07007170// --- AudioPortConfig class implementation
7171
7172AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7173{
7174 mSamplingRate = 0;
7175 mChannelMask = AUDIO_CHANNEL_NONE;
7176 mFormat = AUDIO_FORMAT_INVALID;
7177 mGain.index = -1;
7178}
7179
Eric Laurenta121f902014-06-03 13:32:54 -07007180status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7181 const struct audio_port_config *config,
7182 struct audio_port_config *backupConfig)
7183{
7184 struct audio_port_config localBackupConfig;
7185 status_t status = NO_ERROR;
7186
7187 localBackupConfig.config_mask = config->config_mask;
7188 toAudioPortConfig(&localBackupConfig);
7189
Marco Nelissen961ec212014-08-25 15:58:39 -07007190 sp<AudioPort> audioport = getAudioPort();
7191 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007192 status = NO_INIT;
7193 goto exit;
7194 }
7195 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007196 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007197 if (status != NO_ERROR) {
7198 goto exit;
7199 }
7200 mSamplingRate = config->sample_rate;
7201 }
7202 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007203 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007204 if (status != NO_ERROR) {
7205 goto exit;
7206 }
7207 mChannelMask = config->channel_mask;
7208 }
7209 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007210 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007211 if (status != NO_ERROR) {
7212 goto exit;
7213 }
7214 mFormat = config->format;
7215 }
7216 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007217 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007218 if (status != NO_ERROR) {
7219 goto exit;
7220 }
7221 mGain = config->gain;
7222 }
7223
7224exit:
7225 if (status != NO_ERROR) {
7226 applyAudioPortConfig(&localBackupConfig);
7227 }
7228 if (backupConfig != NULL) {
7229 *backupConfig = localBackupConfig;
7230 }
7231 return status;
7232}
7233
Eric Laurent1f2f2232014-06-02 12:01:23 -07007234void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7235 struct audio_port_config *dstConfig,
7236 const struct audio_port_config *srcConfig) const
7237{
7238 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7239 dstConfig->sample_rate = mSamplingRate;
7240 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7241 dstConfig->sample_rate = srcConfig->sample_rate;
7242 }
7243 } else {
7244 dstConfig->sample_rate = 0;
7245 }
7246 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7247 dstConfig->channel_mask = mChannelMask;
7248 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7249 dstConfig->channel_mask = srcConfig->channel_mask;
7250 }
7251 } else {
7252 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7253 }
7254 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7255 dstConfig->format = mFormat;
7256 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7257 dstConfig->format = srcConfig->format;
7258 }
7259 } else {
7260 dstConfig->format = AUDIO_FORMAT_INVALID;
7261 }
7262 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7263 dstConfig->gain = mGain;
7264 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7265 dstConfig->gain = srcConfig->gain;
7266 }
7267 } else {
7268 dstConfig->gain.index = -1;
7269 }
7270 if (dstConfig->gain.index != -1) {
7271 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7272 } else {
7273 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7274 }
7275}
7276
Eric Laurent1c333e22014-05-20 10:48:17 -07007277// --- IOProfile class implementation
7278
Eric Laurent1afeecb2014-05-14 08:52:28 -07007279AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007280 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007281 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007282{
7283}
7284
Eric Laurente0720872014-03-11 09:30:41 -07007285AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007286{
7287}
7288
7289// checks if the IO profile is compatible with specified parameters.
7290// Sampling rate, format and channel mask must be specified in order to
7291// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007292bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007293 String8 address,
7294 uint32_t samplingRate,
7295 uint32_t *updatedSamplingRate,
7296 audio_format_t format,
7297 audio_channel_mask_t channelMask,
7298 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007299{
Glenn Kastencbd48022014-07-24 13:46:44 -07007300 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7301 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7302 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007303
Eric Laurent275e8e92014-11-30 15:14:47 -08007304 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007305 return false;
7306 }
7307
7308 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007309 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007310 }
7311 uint32_t myUpdatedSamplingRate = samplingRate;
7312 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007313 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007314 }
7315 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7316 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007317 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007318 }
7319
7320 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7321 return false;
7322 }
7323
7324 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7325 checkExactChannelMask(channelMask) != NO_ERROR)) {
7326 return false;
7327 }
7328 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7329 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7330 return false;
7331 }
7332
7333 if (isPlaybackThread && (mFlags & flags) != flags) {
7334 return false;
7335 }
7336 // The only input flag that is allowed to be different is the fast flag.
7337 // An existing fast stream is compatible with a normal track request.
7338 // An existing normal stream is compatible with a fast track request,
7339 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007340 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007341 ~AUDIO_INPUT_FLAG_FAST)) {
7342 return false;
7343 }
7344
7345 if (updatedSamplingRate != NULL) {
7346 *updatedSamplingRate = myUpdatedSamplingRate;
7347 }
7348 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007349}
7350
Eric Laurente0720872014-03-11 09:30:41 -07007351void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007352{
7353 const size_t SIZE = 256;
7354 char buffer[SIZE];
7355 String8 result;
7356
Eric Laurent1afeecb2014-05-14 08:52:28 -07007357 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007358
Eric Laurente552edb2014-03-10 17:42:56 -07007359 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7360 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007361 snprintf(buffer, SIZE, " - devices:\n");
7362 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007363 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007364 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7365 mSupportedDevices[i]->dump(fd, 6, i);
7366 }
Eric Laurente552edb2014-03-10 17:42:56 -07007367}
7368
Eric Laurentd4692962014-05-05 18:13:44 -07007369void AudioPolicyManager::IOProfile::log()
7370{
7371 const size_t SIZE = 256;
7372 char buffer[SIZE];
7373 String8 result;
7374
7375 ALOGV(" - sampling rates: ");
7376 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7377 ALOGV(" %d", mSamplingRates[i]);
7378 }
7379
7380 ALOGV(" - channel masks: ");
7381 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7382 ALOGV(" 0x%04x", mChannelMasks[i]);
7383 }
7384
7385 ALOGV(" - formats: ");
7386 for (size_t i = 0; i < mFormats.size(); i++) {
7387 ALOGV(" 0x%08x", mFormats[i]);
7388 }
7389
7390 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7391 ALOGV(" - flags: 0x%04x\n", mFlags);
7392}
7393
7394
Eric Laurent3a4311c2014-03-17 12:00:47 -07007395// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007396
Eric Laurent1f2f2232014-06-02 12:01:23 -07007397
7398AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7399 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7400 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7401 AUDIO_PORT_ROLE_SOURCE,
7402 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007403 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007404{
Eric Laurenta121f902014-06-03 13:32:54 -07007405 if (mGains.size() > 0) {
7406 mGains[0]->getDefaultConfig(&mGain);
7407 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007408}
7409
Eric Laurent3a4311c2014-03-17 12:00:47 -07007410bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007411{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007412 // Devices are considered equal if they:
7413 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7414 // - have the same address or one device does not specify the address
7415 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007416 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007417 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007418 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007419 mChannelMask == other->mChannelMask);
7420}
7421
7422void AudioPolicyManager::DeviceVector::refreshTypes()
7423{
Eric Laurent1c333e22014-05-20 10:48:17 -07007424 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007425 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007426 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007427 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007428 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007429}
7430
7431ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7432{
7433 for(size_t i = 0; i < size(); i++) {
7434 if (item->equals(itemAt(i))) {
7435 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007436 }
7437 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007438 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007439}
7440
Eric Laurent3a4311c2014-03-17 12:00:47 -07007441ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007442{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007443 ssize_t ret = indexOf(item);
7444
7445 if (ret < 0) {
7446 ret = SortedVector::add(item);
7447 if (ret >= 0) {
7448 refreshTypes();
7449 }
7450 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007451 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007452 ret = -1;
7453 }
7454 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007455}
7456
Eric Laurent3a4311c2014-03-17 12:00:47 -07007457ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7458{
7459 size_t i;
7460 ssize_t ret = indexOf(item);
7461
7462 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007463 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007464 } else {
7465 ret = SortedVector::removeAt(ret);
7466 if (ret >= 0) {
7467 refreshTypes();
7468 }
7469 }
7470 return ret;
7471}
7472
7473void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7474{
7475 DeviceVector deviceList;
7476
7477 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7478 types &= ~role_bit;
7479
7480 while (types) {
7481 uint32_t i = 31 - __builtin_clz(types);
7482 uint32_t type = 1 << i;
7483 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007484 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007485 }
7486}
7487
Eric Laurent1afeecb2014-05-14 08:52:28 -07007488void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7489 const DeviceVector& declaredDevices)
7490{
7491 char *devName = strtok(name, "|");
7492 while (devName != NULL) {
7493 if (strlen(devName) != 0) {
7494 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7495 ARRAY_SIZE(sDeviceNameToEnumTable),
7496 devName);
7497 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007498 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007499 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7500 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007501 dev->mAddress = String8("0");
7502 }
7503 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007504 } else {
7505 sp<DeviceDescriptor> deviceDesc =
7506 declaredDevices.getDeviceFromName(String8(devName));
7507 if (deviceDesc != 0) {
7508 add(deviceDesc);
7509 }
7510 }
7511 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007512 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007513 }
7514}
7515
Eric Laurent1c333e22014-05-20 10:48:17 -07007516sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7517 audio_devices_t type, String8 address) const
7518{
7519 sp<DeviceDescriptor> device;
7520 for (size_t i = 0; i < size(); i++) {
7521 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007522 if (address == "" || itemAt(i)->mAddress == address) {
7523 device = itemAt(i);
7524 if (itemAt(i)->mAddress == address) {
7525 break;
7526 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007527 }
7528 }
7529 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007530 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007531 type, address.string(), device.get());
7532 return device;
7533}
7534
Eric Laurent6a94d692014-05-20 11:18:06 -07007535sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7536 audio_port_handle_t id) const
7537{
7538 sp<DeviceDescriptor> device;
7539 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007540 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007541 if (itemAt(i)->mId == id) {
7542 device = itemAt(i);
7543 break;
7544 }
7545 }
7546 return device;
7547}
7548
Eric Laurent1c333e22014-05-20 10:48:17 -07007549AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7550 audio_devices_t type) const
7551{
7552 DeviceVector devices;
7553 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7554 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7555 devices.add(itemAt(i));
7556 type &= ~itemAt(i)->mDeviceType;
7557 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7558 itemAt(i)->mDeviceType, itemAt(i).get());
7559 }
7560 }
7561 return devices;
7562}
7563
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007564AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7565 audio_devices_t type, String8 address) const
7566{
7567 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007568 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007569 if (itemAt(i)->mDeviceType == type) {
7570 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007571 devices.add(itemAt(i));
7572 }
7573 }
7574 }
7575 return devices;
7576}
7577
Eric Laurent1afeecb2014-05-14 08:52:28 -07007578sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7579 const String8& name) const
7580{
7581 sp<DeviceDescriptor> device;
7582 for (size_t i = 0; i < size(); i++) {
7583 if (itemAt(i)->mName == name) {
7584 device = itemAt(i);
7585 break;
7586 }
7587 }
7588 return device;
7589}
7590
Eric Laurent6a94d692014-05-20 11:18:06 -07007591void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7592 struct audio_port_config *dstConfig,
7593 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007594{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007595 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7596 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007597 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007598 }
7599
7600 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7601
Eric Laurent6a94d692014-05-20 11:18:06 -07007602 dstConfig->id = mId;
7603 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007605 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007606 dstConfig->ext.device.type = mDeviceType;
7607 dstConfig->ext.device.hw_module = mModule->mHandle;
7608 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007609}
7610
7611void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7612{
Eric Laurent83b88082014-06-20 18:31:16 -07007613 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007614 AudioPort::toAudioPort(port);
7615 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007616 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007617 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007618 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007619 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7620}
7621
Eric Laurent1afeecb2014-05-14 08:52:28 -07007622status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007623{
7624 const size_t SIZE = 256;
7625 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007626 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007627
Eric Laurent1afeecb2014-05-14 08:52:28 -07007628 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7629 result.append(buffer);
7630 if (mId != 0) {
7631 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7632 result.append(buffer);
7633 }
7634 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7635 enumToString(sDeviceNameToEnumTable,
7636 ARRAY_SIZE(sDeviceNameToEnumTable),
7637 mDeviceType));
7638 result.append(buffer);
7639 if (mAddress.size() != 0) {
7640 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7641 result.append(buffer);
7642 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007643 write(fd, result.string(), result.size());
7644 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007645
7646 return NO_ERROR;
7647}
7648
Eric Laurent4d416952014-08-10 14:07:09 -07007649status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7650{
7651 const size_t SIZE = 256;
7652 char buffer[SIZE];
7653 String8 result;
7654
7655
7656 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7657 result.append(buffer);
7658 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7659 result.append(buffer);
7660 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7661 result.append(buffer);
7662 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7663 result.append(buffer);
7664 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7665 result.append(buffer);
7666 for (size_t i = 0; i < mPatch.num_sources; i++) {
7667 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7668 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7669 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7670 ARRAY_SIZE(sDeviceNameToEnumTable),
7671 mPatch.sources[i].ext.device.type));
7672 } else {
7673 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7674 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7675 }
7676 result.append(buffer);
7677 }
7678 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7679 result.append(buffer);
7680 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7681 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7682 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7683 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7684 ARRAY_SIZE(sDeviceNameToEnumTable),
7685 mPatch.sinks[i].ext.device.type));
7686 } else {
7687 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7688 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7689 }
7690 result.append(buffer);
7691 }
7692
7693 write(fd, result.string(), result.size());
7694 return NO_ERROR;
7695}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007696
7697// --- audio_policy.conf file parsing
7698
Eric Laurent5dbe4712014-09-19 19:04:57 -07007699uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007700{
7701 uint32_t flag = 0;
7702
7703 // it is OK to cast name to non const here as we are not going to use it after
7704 // strtok() modifies it
7705 char *flagName = strtok(name, "|");
7706 while (flagName != NULL) {
7707 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007708 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7709 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007710 flagName);
7711 }
7712 flagName = strtok(NULL, "|");
7713 }
7714 //force direct flag if offload flag is set: offloading implies a direct output stream
7715 // and all common behaviors are driven by checking only the direct flag
7716 // this should normally be set appropriately in the policy configuration file
7717 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7718 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7719 }
7720
Eric Laurent5dbe4712014-09-19 19:04:57 -07007721 return flag;
7722}
7723
7724uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7725{
7726 uint32_t flag = 0;
7727
7728 // it is OK to cast name to non const here as we are not going to use it after
7729 // strtok() modifies it
7730 char *flagName = strtok(name, "|");
7731 while (flagName != NULL) {
7732 if (strlen(flagName) != 0) {
7733 flag |= stringToEnum(sInputFlagNameToEnumTable,
7734 ARRAY_SIZE(sInputFlagNameToEnumTable),
7735 flagName);
7736 }
7737 flagName = strtok(NULL, "|");
7738 }
7739 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007740}
7741
Eric Laurente0720872014-03-11 09:30:41 -07007742audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007743{
7744 uint32_t device = 0;
7745
7746 char *devName = strtok(name, "|");
7747 while (devName != NULL) {
7748 if (strlen(devName) != 0) {
7749 device |= stringToEnum(sDeviceNameToEnumTable,
7750 ARRAY_SIZE(sDeviceNameToEnumTable),
7751 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007752 }
Eric Laurente552edb2014-03-10 17:42:56 -07007753 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007754 }
Eric Laurente552edb2014-03-10 17:42:56 -07007755 return device;
7756}
7757
Eric Laurente0720872014-03-11 09:30:41 -07007758void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007759{
Eric Laurente552edb2014-03-10 17:42:56 -07007760 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007761 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007762 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007763
Eric Laurent1afeecb2014-05-14 08:52:28 -07007764 node = config_find(root, DEVICES_TAG);
7765 if (node != NULL) {
7766 node = node->first_child;
7767 while (node) {
7768 ALOGV("loadHwModule() loading device %s", node->name);
7769 status_t tmpStatus = module->loadDevice(node);
7770 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7771 status = tmpStatus;
7772 }
7773 node = node->next;
7774 }
7775 }
7776 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007777 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007778 node = node->first_child;
7779 while (node) {
7780 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007781 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007782 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7783 status = tmpStatus;
7784 }
7785 node = node->next;
7786 }
7787 }
7788 node = config_find(root, INPUTS_TAG);
7789 if (node != NULL) {
7790 node = node->first_child;
7791 while (node) {
7792 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007793 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007794 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7795 status = tmpStatus;
7796 }
7797 node = node->next;
7798 }
7799 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007800 loadGlobalConfig(root, module);
7801
Eric Laurente552edb2014-03-10 17:42:56 -07007802 if (status == NO_ERROR) {
7803 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007804 }
7805}
7806
Eric Laurente0720872014-03-11 09:30:41 -07007807void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007808{
7809 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7810 if (node == NULL) {
7811 return;
7812 }
7813
7814 node = node->first_child;
7815 while (node) {
7816 ALOGV("loadHwModules() loading module %s", node->name);
7817 loadHwModule(node);
7818 node = node->next;
7819 }
7820}
7821
Eric Laurent1f2f2232014-06-02 12:01:23 -07007822void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007823{
7824 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007825
Eric Laurente552edb2014-03-10 17:42:56 -07007826 if (node == NULL) {
7827 return;
7828 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007829 DeviceVector declaredDevices;
7830 if (module != NULL) {
7831 declaredDevices = module->mDeclaredDevices;
7832 }
7833
Eric Laurente552edb2014-03-10 17:42:56 -07007834 node = node->first_child;
7835 while (node) {
7836 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007837 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7838 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007839 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7840 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007841 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007842 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007843 ARRAY_SIZE(sDeviceNameToEnumTable),
7844 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007845 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007846 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007847 } else {
7848 ALOGW("loadGlobalConfig() default device not specified");
7849 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007850 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007851 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007852 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7853 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007854 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007855 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7856 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7857 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007858 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7859 uint32_t major, minor;
7860 sscanf((char *)node->value, "%u.%u", &major, &minor);
7861 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7862 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7863 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007864 }
7865 node = node->next;
7866 }
7867}
7868
Eric Laurente0720872014-03-11 09:30:41 -07007869status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007870{
7871 cnode *root;
7872 char *data;
7873
7874 data = (char *)load_file(path, NULL);
7875 if (data == NULL) {
7876 return -ENODEV;
7877 }
7878 root = config_node("", "");
7879 config_load(root, data);
7880
Eric Laurente552edb2014-03-10 17:42:56 -07007881 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007882 // legacy audio_policy.conf files have one global_configuration section
7883 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007884 config_free(root);
7885 free(root);
7886 free(data);
7887
7888 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7889
7890 return NO_ERROR;
7891}
7892
Eric Laurente0720872014-03-11 09:30:41 -07007893void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007894{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007895 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007896 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007897 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7898 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007899 mAvailableOutputDevices.add(mDefaultOutputDevice);
7900 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007901
7902 module = new HwModule("primary");
7903
Eric Laurent1afeecb2014-05-14 08:52:28 -07007904 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007905 profile->mSamplingRates.add(44100);
7906 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7907 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007908 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007909 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7910 module->mOutputProfiles.add(profile);
7911
Eric Laurent1afeecb2014-05-14 08:52:28 -07007912 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007913 profile->mSamplingRates.add(8000);
7914 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7915 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007916 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007917 module->mInputProfiles.add(profile);
7918
7919 mHwModules.add(module);
7920}
7921
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007922audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7923{
7924 // flags to stream type mapping
7925 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7926 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7927 }
7928 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7929 return AUDIO_STREAM_BLUETOOTH_SCO;
7930 }
7931
7932 // usage to stream type mapping
7933 switch (attr->usage) {
7934 case AUDIO_USAGE_MEDIA:
7935 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007936 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7937 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007938 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007939 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7940 return AUDIO_STREAM_ALARM;
7941 }
7942 if (isStreamActive(AUDIO_STREAM_RING)) {
7943 return AUDIO_STREAM_RING;
7944 }
7945 if (isInCall()) {
7946 return AUDIO_STREAM_VOICE_CALL;
7947 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007948 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007949 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7950 return AUDIO_STREAM_SYSTEM;
7951 case AUDIO_USAGE_VOICE_COMMUNICATION:
7952 return AUDIO_STREAM_VOICE_CALL;
7953
7954 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7955 return AUDIO_STREAM_DTMF;
7956
7957 case AUDIO_USAGE_ALARM:
7958 return AUDIO_STREAM_ALARM;
7959 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7960 return AUDIO_STREAM_RING;
7961
7962 case AUDIO_USAGE_NOTIFICATION:
7963 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7964 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7965 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7966 case AUDIO_USAGE_NOTIFICATION_EVENT:
7967 return AUDIO_STREAM_NOTIFICATION;
7968
7969 case AUDIO_USAGE_UNKNOWN:
7970 default:
7971 return AUDIO_STREAM_MUSIC;
7972 }
7973}
Eric Laurente83b55d2014-11-14 10:06:21 -08007974
7975bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7976 // has flags that map to a strategy?
7977 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7978 return true;
7979 }
7980
7981 // has known usage?
7982 switch (paa->usage) {
7983 case AUDIO_USAGE_UNKNOWN:
7984 case AUDIO_USAGE_MEDIA:
7985 case AUDIO_USAGE_VOICE_COMMUNICATION:
7986 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7987 case AUDIO_USAGE_ALARM:
7988 case AUDIO_USAGE_NOTIFICATION:
7989 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7990 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7991 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7992 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7993 case AUDIO_USAGE_NOTIFICATION_EVENT:
7994 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7995 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7996 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7997 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007998 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08007999 break;
8000 default:
8001 return false;
8002 }
8003 return true;
8004}
8005
Eric Laurente552edb2014-03-10 17:42:56 -07008006}; // namespace android