blob: 850fe861174e01142a7eaf4e0f943159c0893189 [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()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// 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 Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070085 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070090 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050091 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700110 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900111 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122};
123
124const StringToEnum sFormatNameToEnumTable[] = {
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
130 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
131 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700143 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700144 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
146 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
147 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
148 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149};
150
151const StringToEnum sOutChannelsNameToEnumTable[] = {
152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
156 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
157};
158
159const StringToEnum sInChannelsNameToEnumTable[] = {
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
162 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
163};
164
Eric Laurent1afeecb2014-05-14 08:52:28 -0700165const StringToEnum sGainModeNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
168 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
169};
170
Eric Laurent3a4311c2014-03-17 12:00:47 -0700171
172uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
173 size_t size,
174 const char *name)
175{
176 for (size_t i = 0; i < size; i++) {
177 if (strcmp(table[i].name, name) == 0) {
178 ALOGV("stringToEnum() found %s", table[i].name);
179 return table[i].value;
180 }
181 }
182 return 0;
183}
184
185const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
186 size_t size,
187 uint32_t value)
188{
189 for (size_t i = 0; i < size; i++) {
190 if (table[i].value == value) {
191 return table[i].name;
192 }
193 }
194 return "";
195}
196
197bool AudioPolicyManager::stringToBool(const char *value)
198{
199 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
200}
201
202
203// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700204// AudioPolicyInterface implementation
205// ----------------------------------------------------------------------------
206
207
Eric Laurente0720872014-03-11 09:30:41 -0700208status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700209 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700210 const char *device_address)
211{
Eric Laurent22226012014-08-01 17:00:54 -0700212 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurent22226012014-08-01 17:00:54 -0700214 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
215 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700216
217 // connect/disconnect only 1 device at a time
218 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
219
Eric Laurente552edb2014-03-10 17:42:56 -0700220 // handle output devices
221 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700222 SortedVector <audio_io_handle_t> outputs;
223
Eric Laurent1afeecb2014-05-14 08:52:28 -0700224 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
225 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // save a copy of the opened output descriptors before any output is opened or closed
229 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
230 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 switch (state)
232 {
233 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700234 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700235 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700236 ALOGW("setDeviceConnectionState() device already connected: %x", device);
237 return INVALID_OPERATION;
238 }
239 ALOGV("setDeviceConnectionState() connecting device %x", device);
240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700242 index = mAvailableOutputDevices.add(devDesc);
243 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700244 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700245 if (module == 0) {
246 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
247 device);
248 mAvailableOutputDevices.remove(devDesc);
249 return INVALID_OPERATION;
250 }
251 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700252 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 } else {
254 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
256
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700257 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 // outputs should never be empty here
262 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
263 "checkOutputsForDevice() returned no outputs but status OK");
264 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
265 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700266 break;
267 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700268 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700269 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700270 ALOGW("setDeviceConnectionState() device not connected: %x", device);
271 return INVALID_OPERATION;
272 }
273
274 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
275 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700277
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700279 } break;
280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
287 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700288 checkA2dpSuspend();
289 checkOutputForAllStrategies();
290 // outputs must be closed after checkOutputForAllStrategies() is executed
291 if (!outputs.isEmpty()) {
292 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700293 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700294 // close unused outputs after device disconnection or direct outputs that have been
295 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700297 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
298 (desc->mDirectOpenCount == 0))) {
299 closeOutput(outputs[i]);
300 }
301 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 // check again after closing A2DP output to reset mA2dpSuspended if needed
303 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
305
306 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700307 if (mPhoneState == AUDIO_MODE_IN_CALL) {
308 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
309 updateCallRouting(newDevice);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700312 audio_io_handle_t output = mOutputs.keyAt(i);
313 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
314 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
315 true /*fromCache*/);
316 // do not force device change on duplicated output because if device is 0, it will
317 // also force a device 0 for the two outputs it is duplicated to which may override
318 // a valid device selection on those outputs.
319 bool force = !mOutputs.valueAt(i)->isDuplicated()
320 && (!deviceDistinguishesOnAddress(device)
321 // always force when disconnecting (a non-duplicated device)
322 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
323 setOutputDevice(output, newDevice, force, 0);
324 }
Eric Laurente552edb2014-03-10 17:42:56 -0700325 }
326
Eric Laurent72aa32f2014-05-30 18:51:48 -0700327 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700328 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700329 } // end if is output device
330
Eric Laurente552edb2014-03-10 17:42:56 -0700331 // handle input devices
332 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700333 SortedVector <audio_io_handle_t> inputs;
334
Eric Laurent1afeecb2014-05-14 08:52:28 -0700335 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
336 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700337 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700338 switch (state)
339 {
340 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700341 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700342 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700343 ALOGW("setDeviceConnectionState() device already connected: %d", device);
344 return INVALID_OPERATION;
345 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700346 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700347 if (module == NULL) {
348 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
349 device);
350 return INVALID_OPERATION;
351 }
Eric Laurentd4692962014-05-05 18:13:44 -0700352 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
353 return INVALID_OPERATION;
354 }
355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 index = mAvailableInputDevices.add(devDesc);
357 if (index >= 0) {
358 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700359 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 } else {
361 return NO_MEMORY;
362 }
Eric Laurentd4692962014-05-05 18:13:44 -0700363 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700364
365 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700368 ALOGW("setDeviceConnectionState() device not connected: %d", device);
369 return INVALID_OPERATION;
370 }
Eric Laurentd4692962014-05-05 18:13:44 -0700371 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700373 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700374
375 default:
376 ALOGE("setDeviceConnectionState() invalid state: %x", state);
377 return BAD_VALUE;
378 }
379
Eric Laurentd4692962014-05-05 18:13:44 -0700380 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700381
Eric Laurentc2730ba2014-07-20 15:47:07 -0700382 if (mPhoneState == AUDIO_MODE_IN_CALL) {
383 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
384 updateCallRouting(newDevice);
385 }
386
Eric Laurentb52c1522014-05-20 11:27:36 -0700387 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700388 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700389 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700390
391 ALOGW("setDeviceConnectionState() invalid device: %x", device);
392 return BAD_VALUE;
393}
394
Eric Laurente0720872014-03-11 09:30:41 -0700395audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700396 const char *device_address)
397{
Eric Laurent3b73df72014-03-11 09:06:29 -0700398 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700399 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700400 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 ssize_t index;
402 DeviceVector *deviceVector;
403
Eric Laurente552edb2014-03-10 17:42:56 -0700404 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700405 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700406 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 deviceVector = &mAvailableInputDevices;
408 } else {
409 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
410 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700411 }
412
Eric Laurent3a4311c2014-03-17 12:00:47 -0700413 index = deviceVector->indexOf(devDesc);
414 if (index >= 0) {
415 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
416 } else {
417 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
418 }
Eric Laurente552edb2014-03-10 17:42:56 -0700419}
420
Eric Laurentc2730ba2014-07-20 15:47:07 -0700421void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
422{
423 bool createTxPatch = false;
424 struct audio_patch patch;
425 patch.num_sources = 1;
426 patch.num_sinks = 1;
427 status_t status;
428 audio_patch_handle_t afPatchHandle;
429 DeviceVector deviceList;
430
431 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
432 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
433
434 // release existing RX patch if any
435 if (mCallRxPatch != 0) {
436 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
437 mCallRxPatch.clear();
438 }
439 // release TX patch if any
440 if (mCallTxPatch != 0) {
441 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
442 mCallTxPatch.clear();
443 }
444
445 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
446 // via setOutputDevice() on primary output.
447 // Otherwise, create two audio patches for TX and RX path.
448 if (availablePrimaryOutputDevices() & rxDevice) {
449 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
450 // If the TX device is also on the primary HW module, setOutputDevice() will take care
451 // of it due to legacy implementation. If not, create a patch.
452 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
453 == AUDIO_DEVICE_NONE) {
454 createTxPatch = true;
455 }
456 } else {
457 // create RX path audio patch
458 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
459 ALOG_ASSERT(!deviceList.isEmpty(),
460 "updateCallRouting() selected device not in output device list");
461 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
462 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
463 ALOG_ASSERT(!deviceList.isEmpty(),
464 "updateCallRouting() no telephony RX device");
465 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
466
467 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
468 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
469
470 // request to reuse existing output stream if one is already opened to reach the RX device
471 SortedVector<audio_io_handle_t> outputs =
472 getOutputsForDevice(rxDevice, mOutputs);
473 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
474 if (output != AUDIO_IO_HANDLE_NONE) {
475 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
476 ALOG_ASSERT(!outputDesc->isDuplicated(),
477 "updateCallRouting() RX device output is duplicated");
478 outputDesc->toAudioPortConfig(&patch.sources[1]);
479 patch.num_sources = 2;
480 }
481
482 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
483 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
484 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
485 status);
486 if (status == NO_ERROR) {
487 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
488 &patch, mUidCached);
489 mCallRxPatch->mAfPatchHandle = afPatchHandle;
490 mCallRxPatch->mUid = mUidCached;
491 }
492 createTxPatch = true;
493 }
494 if (createTxPatch) {
495
496 struct audio_patch patch;
497 patch.num_sources = 1;
498 patch.num_sinks = 1;
499 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
500 ALOG_ASSERT(!deviceList.isEmpty(),
501 "updateCallRouting() selected device not in input device list");
502 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
503 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
504 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
505 ALOG_ASSERT(!deviceList.isEmpty(),
506 "updateCallRouting() no telephony TX device");
507 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
508 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
509
510 SortedVector<audio_io_handle_t> outputs =
511 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
512 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
513 // request to reuse existing output stream if one is already opened to reach the TX
514 // path output device
515 if (output != AUDIO_IO_HANDLE_NONE) {
516 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
517 ALOG_ASSERT(!outputDesc->isDuplicated(),
518 "updateCallRouting() RX device output is duplicated");
519 outputDesc->toAudioPortConfig(&patch.sources[1]);
520 patch.num_sources = 2;
521 }
522
523 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
524 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
525 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
526 status);
527 if (status == NO_ERROR) {
528 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
529 &patch, mUidCached);
530 mCallTxPatch->mAfPatchHandle = afPatchHandle;
531 mCallTxPatch->mUid = mUidCached;
532 }
533 }
534}
535
Eric Laurente0720872014-03-11 09:30:41 -0700536void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700537{
538 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGW("setPhoneState() invalid state %d", state);
541 return;
542 }
543
544 if (state == mPhoneState ) {
545 ALOGW("setPhoneState() setting same state %d", state);
546 return;
547 }
548
549 // if leaving call state, handle special case of active streams
550 // pertaining to sonification strategy see handleIncallSonification()
551 if (isInCall()) {
552 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700553 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
554 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700555 }
556 }
557
558 // store previous phone state for management of sonification strategy below
559 int oldState = mPhoneState;
560 mPhoneState = state;
561 bool force = false;
562
563 // are we entering or starting a call
564 if (!isStateInCall(oldState) && isStateInCall(state)) {
565 ALOGV(" Entering call in setPhoneState()");
566 // force routing command to audio hardware when starting a call
567 // even if no device change is needed
568 force = true;
569 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
570 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
571 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
572 }
573 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
574 ALOGV(" Exiting call in setPhoneState()");
575 // force routing command to audio hardware when exiting a call
576 // even if no device change is needed
577 force = true;
578 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
579 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
580 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
581 }
582 } else if (isStateInCall(state) && (state != oldState)) {
583 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
584 // force routing command to audio hardware when switching between telephony and VoIP
585 // even if no device change is needed
586 force = true;
587 }
588
589 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700590 checkA2dpSuspend();
591 checkOutputForAllStrategies();
592 updateDevicesAndOutputs();
593
Eric Laurent1f2f2232014-06-02 12:01:23 -0700594 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700595
Eric Laurente552edb2014-03-10 17:42:56 -0700596 int delayMs = 0;
597 if (isStateInCall(state)) {
598 nsecs_t sysTime = systemTime();
599 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700600 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700601 // mute media and sonification strategies and delay device switch by the largest
602 // latency of any output where either strategy is active.
603 // This avoid sending the ring tone or music tail into the earpiece or headset.
604 if ((desc->isStrategyActive(STRATEGY_MEDIA,
605 SONIFICATION_HEADSET_MUSIC_DELAY,
606 sysTime) ||
607 desc->isStrategyActive(STRATEGY_SONIFICATION,
608 SONIFICATION_HEADSET_MUSIC_DELAY,
609 sysTime)) &&
610 (delayMs < (int)desc->mLatency*2)) {
611 delayMs = desc->mLatency*2;
612 }
613 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
614 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
615 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
616 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
617 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
618 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
619 }
620 }
621
Eric Laurentc2730ba2014-07-20 15:47:07 -0700622 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
623 // the device returned is not necessarily reachable via this output
624 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
625 // force routing command to audio hardware when ending call
626 // even if no device change is needed
627 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
628 rxDevice = hwOutputDesc->device();
629 }
Eric Laurente552edb2014-03-10 17:42:56 -0700630
Eric Laurentc2730ba2014-07-20 15:47:07 -0700631 if (state == AUDIO_MODE_IN_CALL) {
632 updateCallRouting(rxDevice, delayMs);
633 } else if (oldState == AUDIO_MODE_IN_CALL) {
634 if (mCallRxPatch != 0) {
635 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
636 mCallRxPatch.clear();
637 }
638 if (mCallTxPatch != 0) {
639 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
640 mCallTxPatch.clear();
641 }
642 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
643 } else {
644 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
645 }
Eric Laurente552edb2014-03-10 17:42:56 -0700646 // if entering in call state, handle special case of active streams
647 // pertaining to sonification strategy see handleIncallSonification()
648 if (isStateInCall(state)) {
649 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
651 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700652 }
653 }
654
655 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 if (state == AUDIO_MODE_RINGTONE &&
657 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700658 mLimitRingtoneVolume = true;
659 } else {
660 mLimitRingtoneVolume = false;
661 }
662}
663
Eric Laurente0720872014-03-11 09:30:41 -0700664void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700665 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700666{
667 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
668
669 bool forceVolumeReeval = false;
670 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700671 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
672 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
673 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700674 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
675 return;
676 }
677 forceVolumeReeval = true;
678 mForceUse[usage] = config;
679 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700680 case AUDIO_POLICY_FORCE_FOR_MEDIA:
681 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
682 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
683 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
684 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900685 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700686 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
687 return;
688 }
689 mForceUse[usage] = config;
690 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 case AUDIO_POLICY_FORCE_FOR_RECORD:
692 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
693 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700694 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
695 return;
696 }
697 mForceUse[usage] = config;
698 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700699 case AUDIO_POLICY_FORCE_FOR_DOCK:
700 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
701 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
702 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
703 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
704 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700705 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
706 }
707 forceVolumeReeval = true;
708 mForceUse[usage] = config;
709 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700710 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
711 if (config != AUDIO_POLICY_FORCE_NONE &&
712 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
714 }
715 forceVolumeReeval = true;
716 mForceUse[usage] = config;
717 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900718 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
719 if (config != AUDIO_POLICY_FORCE_NONE &&
720 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
721 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
722 }
723 mForceUse[usage] = config;
724 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700725 default:
726 ALOGW("setForceUse() invalid usage %d", usage);
727 break;
728 }
729
730 // check for device and output changes triggered by new force usage
731 checkA2dpSuspend();
732 checkOutputForAllStrategies();
733 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700734 if (mPhoneState == AUDIO_MODE_IN_CALL) {
735 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
736 updateCallRouting(newDevice);
737 }
Eric Laurente552edb2014-03-10 17:42:56 -0700738 for (size_t i = 0; i < mOutputs.size(); i++) {
739 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700740 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
742 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
743 }
Eric Laurente552edb2014-03-10 17:42:56 -0700744 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
745 applyStreamVolumes(output, newDevice, 0, true);
746 }
747 }
748
749 audio_io_handle_t activeInput = getActiveInput();
750 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700751 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700752 }
753
754}
755
Eric Laurente0720872014-03-11 09:30:41 -0700756audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700757{
758 return mForceUse[usage];
759}
760
Eric Laurente0720872014-03-11 09:30:41 -0700761void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700762{
763 ALOGV("setSystemProperty() property %s, value %s", property, value);
764}
765
766// Find a direct output profile compatible with the parameters passed, even if the input flags do
767// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700768sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700769 audio_devices_t device,
770 uint32_t samplingRate,
771 audio_format_t format,
772 audio_channel_mask_t channelMask,
773 audio_output_flags_t flags)
774{
775 for (size_t i = 0; i < mHwModules.size(); i++) {
776 if (mHwModules[i]->mHandle == 0) {
777 continue;
778 }
779 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700780 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700781 bool found = profile->isCompatibleProfile(device, samplingRate,
782 NULL /*updatedSamplingRate*/, format, channelMask,
783 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
784 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700785 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
786 return profile;
787 }
Eric Laurente552edb2014-03-10 17:42:56 -0700788 }
789 }
790 return 0;
791}
792
Eric Laurente0720872014-03-11 09:30:41 -0700793audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700794 uint32_t samplingRate,
795 audio_format_t format,
796 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700797 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700798 const audio_offload_info_t *offloadInfo)
799{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700800
Eric Laurent3b73df72014-03-11 09:06:29 -0700801 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700802 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
803 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
804 device, stream, samplingRate, format, channelMask, flags);
805
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700806 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
807 offloadInfo);
808}
809
810audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
811 uint32_t samplingRate,
812 audio_format_t format,
813 audio_channel_mask_t channelMask,
814 audio_output_flags_t flags,
815 const audio_offload_info_t *offloadInfo)
816{
817 if (attr == NULL) {
818 ALOGE("getOutputForAttr() called with NULL audio attributes");
819 return 0;
820 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700821 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
822 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700823
824 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
825 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
826 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700827
828 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
829 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
830 }
831
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700832 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
833 device, samplingRate, format, channelMask, flags);
834
835 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
836 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
837 offloadInfo);
838}
839
840audio_io_handle_t AudioPolicyManager::getOutputForDevice(
841 audio_devices_t device,
842 audio_stream_type_t stream,
843 uint32_t samplingRate,
844 audio_format_t format,
845 audio_channel_mask_t channelMask,
846 audio_output_flags_t flags,
847 const audio_offload_info_t *offloadInfo)
848{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700849 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700850 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700851 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700852
Eric Laurente552edb2014-03-10 17:42:56 -0700853#ifdef AUDIO_POLICY_TEST
854 if (mCurOutput != 0) {
855 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
856 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
857
858 if (mTestOutputs[mCurOutput] == 0) {
859 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700860 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700861 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700862 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700863 outputDesc->mFlags =
864 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700865 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700866 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
867 config.sample_rate = mTestSamplingRate;
868 config.channel_mask = mTestChannels;
869 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700870 if (offloadInfo != NULL) {
871 config.offload_info = *offloadInfo;
872 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700873 status = mpClientInterface->openOutput(0,
874 &mTestOutputs[mCurOutput],
875 &config,
876 &outputDesc->mDevice,
877 String8(""),
878 &outputDesc->mLatency,
879 outputDesc->mFlags);
880 if (status == NO_ERROR) {
881 outputDesc->mSamplingRate = config.sample_rate;
882 outputDesc->mFormat = config.format;
883 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700884 AudioParameter outputCmd = AudioParameter();
885 outputCmd.addInt(String8("set_id"),mCurOutput);
886 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
887 addOutput(mTestOutputs[mCurOutput], outputDesc);
888 }
889 }
890 return mTestOutputs[mCurOutput];
891 }
892#endif //AUDIO_POLICY_TEST
893
894 // open a direct output if required by specified parameters
895 //force direct flag if offload flag is set: offloading implies a direct output stream
896 // and all common behaviors are driven by checking only the direct flag
897 // this should normally be set appropriately in the policy configuration file
898 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700899 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700900 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700901 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
902 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
905 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
906 // creating an offloaded track and tearing it down immediately after start when audioflinger
907 // detects there is an active non offloadable effect.
908 // FIXME: We should check the audio session here but we do not have it in this context.
909 // This may prevent offloading in rare situations where effects are left active by apps
910 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700911 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700912 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
913 !isNonOffloadableEffectEnabled()) {
914 profile = getProfileForDirectOutput(device,
915 samplingRate,
916 format,
917 channelMask,
918 (audio_output_flags_t)flags);
919 }
920
Eric Laurent1c333e22014-05-20 10:48:17 -0700921 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700922 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700923
924 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700925 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
927 outputDesc = desc;
928 // reuse direct output if currently open and configured with same parameters
929 if ((samplingRate == outputDesc->mSamplingRate) &&
930 (format == outputDesc->mFormat) &&
931 (channelMask == outputDesc->mChannelMask)) {
932 outputDesc->mDirectOpenCount++;
933 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
934 return mOutputs.keyAt(i);
935 }
936 }
937 }
938 // close direct output if currently open and configured with different parameters
939 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700940 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942 outputDesc = new AudioOutputDescriptor(profile);
943 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700944 outputDesc->mLatency = 0;
945 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700946 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
947 config.sample_rate = samplingRate;
948 config.channel_mask = channelMask;
949 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700950 if (offloadInfo != NULL) {
951 config.offload_info = *offloadInfo;
952 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700953 status = mpClientInterface->openOutput(profile->mModule->mHandle,
954 &output,
955 &config,
956 &outputDesc->mDevice,
957 String8(""),
958 &outputDesc->mLatency,
959 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700960
961 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 if (status != NO_ERROR ||
963 (samplingRate != 0 && samplingRate != config.sample_rate) ||
964 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
965 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
967 "format %d %d, channelMask %04x %04x", output, samplingRate,
968 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
969 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700970 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700971 mpClientInterface->closeOutput(output);
972 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700973 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700975 outputDesc->mSamplingRate = config.sample_rate;
976 outputDesc->mChannelMask = config.channel_mask;
977 outputDesc->mFormat = config.format;
978 outputDesc->mRefCount[stream] = 0;
979 outputDesc->mStopTime[stream] = 0;
980 outputDesc->mDirectOpenCount = 1;
981
Eric Laurente552edb2014-03-10 17:42:56 -0700982 audio_io_handle_t srcOutput = getOutputForEffect();
983 addOutput(output, outputDesc);
984 audio_io_handle_t dstOutput = getOutputForEffect();
985 if (dstOutput == output) {
986 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
987 }
988 mPreviousOutputs = mOutputs;
989 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700990 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700991 return output;
992 }
993
994 // ignoring channel mask due to downmix capability in mixer
995
996 // open a non direct output
997
998 // for non direct outputs, only PCM is supported
999 if (audio_is_linear_pcm(format)) {
1000 // get which output is suitable for the specified stream. The actual
1001 // routing change will happen when startOutput() will be called
1002 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1003
1004 output = selectOutput(outputs, flags);
1005 }
1006 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1007 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1008
1009 ALOGV("getOutput() returns output %d", output);
1010
1011 return output;
1012}
1013
Eric Laurente0720872014-03-11 09:30:41 -07001014audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -07001015 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
1017 // select one output among several that provide a path to a particular device or set of
1018 // devices (the list was previously build by getOutputsForDevice()).
1019 // The priority is as follows:
1020 // 1: the output with the highest number of requested policy flags
1021 // 2: the primary output
1022 // 3: the first output in the list
1023
1024 if (outputs.size() == 0) {
1025 return 0;
1026 }
1027 if (outputs.size() == 1) {
1028 return outputs[0];
1029 }
1030
1031 int maxCommonFlags = 0;
1032 audio_io_handle_t outputFlags = 0;
1033 audio_io_handle_t outputPrimary = 0;
1034
1035 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001036 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001038 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001039 if (commonFlags > maxCommonFlags) {
1040 outputFlags = outputs[i];
1041 maxCommonFlags = commonFlags;
1042 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1043 }
1044 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1045 outputPrimary = outputs[i];
1046 }
1047 }
1048 }
1049
1050 if (outputFlags != 0) {
1051 return outputFlags;
1052 }
1053 if (outputPrimary != 0) {
1054 return outputPrimary;
1055 }
1056
1057 return outputs[0];
1058}
1059
Eric Laurente0720872014-03-11 09:30:41 -07001060status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001061 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001062 int session)
1063{
1064 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1065 ssize_t index = mOutputs.indexOfKey(output);
1066 if (index < 0) {
1067 ALOGW("startOutput() unknown output %d", output);
1068 return BAD_VALUE;
1069 }
1070
Eric Laurent1f2f2232014-06-02 12:01:23 -07001071 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
1073 // increment usage count for this stream on the requested output:
1074 // NOTE that the usage count is the same for duplicated output and hardware output which is
1075 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1076 outputDesc->changeRefCount(stream, 1);
1077
1078 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001079 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001080 routing_strategy strategy = getStrategy(stream);
1081 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1082 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1083 uint32_t waitMs = 0;
1084 bool force = false;
1085 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001086 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001087 if (desc != outputDesc) {
1088 // force a device change if any other output is managed by the same hw
1089 // module and has a current device selection that differs from selected device.
1090 // In this case, the audio HAL must receive the new device selection so that it can
1091 // change the device currently selected by the other active output.
1092 if (outputDesc->sharesHwModuleWith(desc) &&
1093 desc->device() != newDevice) {
1094 force = true;
1095 }
1096 // wait for audio on other active outputs to be presented when starting
1097 // a notification so that audio focus effect can propagate.
1098 uint32_t latency = desc->latency();
1099 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1100 waitMs = latency;
1101 }
1102 }
1103 }
1104 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1105
1106 // handle special case for sonification while in call
1107 if (isInCall()) {
1108 handleIncallSonification(stream, true, false);
1109 }
1110
1111 // apply volume rules for current stream and device if necessary
1112 checkAndSetVolume(stream,
1113 mStreams[stream].getVolumeIndex(newDevice),
1114 output,
1115 newDevice);
1116
1117 // update the outputs if starting an output with a stream that can affect notification
1118 // routing
1119 handleNotificationRoutingForStream(stream);
1120 if (waitMs > muteWaitMs) {
1121 usleep((waitMs - muteWaitMs) * 2 * 1000);
1122 }
1123 }
1124 return NO_ERROR;
1125}
1126
1127
Eric Laurente0720872014-03-11 09:30:41 -07001128status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001129 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001130 int session)
1131{
1132 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1133 ssize_t index = mOutputs.indexOfKey(output);
1134 if (index < 0) {
1135 ALOGW("stopOutput() unknown output %d", output);
1136 return BAD_VALUE;
1137 }
1138
Eric Laurent1f2f2232014-06-02 12:01:23 -07001139 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001140
1141 // handle special case for sonification while in call
1142 if (isInCall()) {
1143 handleIncallSonification(stream, false, false);
1144 }
1145
1146 if (outputDesc->mRefCount[stream] > 0) {
1147 // decrement usage count of this stream on the output
1148 outputDesc->changeRefCount(stream, -1);
1149 // store time at which the stream was stopped - see isStreamActive()
1150 if (outputDesc->mRefCount[stream] == 0) {
1151 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001152 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001153 // delay the device switch by twice the latency because stopOutput() is executed when
1154 // the track stop() command is received and at that time the audio track buffer can
1155 // still contain data that needs to be drained. The latency only covers the audio HAL
1156 // and kernel buffers. Also the latency does not always include additional delay in the
1157 // audio path (audio DSP, CODEC ...)
1158 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1159
1160 // force restoring the device selection on other active outputs if it differs from the
1161 // one being selected for this output
1162 for (size_t i = 0; i < mOutputs.size(); i++) {
1163 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001164 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001165 if (curOutput != output &&
1166 desc->isActive() &&
1167 outputDesc->sharesHwModuleWith(desc) &&
1168 (newDevice != desc->device())) {
1169 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001170 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001171 true,
1172 outputDesc->mLatency*2);
1173 }
1174 }
1175 // update the outputs if stopping one with a stream that can affect notification routing
1176 handleNotificationRoutingForStream(stream);
1177 }
1178 return NO_ERROR;
1179 } else {
1180 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1181 return INVALID_OPERATION;
1182 }
1183}
1184
Eric Laurente0720872014-03-11 09:30:41 -07001185void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
1187 ALOGV("releaseOutput() %d", output);
1188 ssize_t index = mOutputs.indexOfKey(output);
1189 if (index < 0) {
1190 ALOGW("releaseOutput() releasing unknown output %d", output);
1191 return;
1192 }
1193
1194#ifdef AUDIO_POLICY_TEST
1195 int testIndex = testOutputIndex(output);
1196 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001197 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001198 if (outputDesc->isActive()) {
1199 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001200 mOutputs.removeItem(output);
1201 mTestOutputs[testIndex] = 0;
1202 }
1203 return;
1204 }
1205#endif //AUDIO_POLICY_TEST
1206
Eric Laurent1f2f2232014-06-02 12:01:23 -07001207 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001208 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001209 if (desc->mDirectOpenCount <= 0) {
1210 ALOGW("releaseOutput() invalid open count %d for output %d",
1211 desc->mDirectOpenCount, output);
1212 return;
1213 }
1214 if (--desc->mDirectOpenCount == 0) {
1215 closeOutput(output);
1216 // If effects where present on the output, audioflinger moved them to the primary
1217 // output by default: move them back to the appropriate output.
1218 audio_io_handle_t dstOutput = getOutputForEffect();
1219 if (dstOutput != mPrimaryOutput) {
1220 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1221 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001222 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001223 }
1224 }
1225}
1226
1227
Eric Laurente0720872014-03-11 09:30:41 -07001228audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001229 uint32_t samplingRate,
1230 audio_format_t format,
1231 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001232 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001233 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001234{
Eric Laurent4dc68062014-07-28 17:26:49 -07001235 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001236 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001237 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001238
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001239 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001240
1241 if (device == AUDIO_DEVICE_NONE) {
1242 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001243 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001244 }
1245
1246 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001247 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001248 case AUDIO_SOURCE_VOICE_UPLINK:
1249 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1250 break;
1251 case AUDIO_SOURCE_VOICE_DOWNLINK:
1252 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1253 break;
1254 case AUDIO_SOURCE_VOICE_CALL:
1255 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1256 break;
1257 default:
1258 break;
1259 }
1260
Eric Laurent1c333e22014-05-20 10:48:17 -07001261 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001262 samplingRate,
1263 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001264 channelMask,
1265 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001266 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001267 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1268 "channelMask 0x%X, flags %#x",
1269 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001270 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001271 }
1272
1273 if (profile->mModule->mHandle == 0) {
1274 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001275 return AUDIO_IO_HANDLE_NONE;
1276 }
1277
1278 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1279 config.sample_rate = samplingRate;
1280 config.channel_mask = channelMask;
1281 config.format = format;
1282 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001283
1284 bool isSoundTrigger = false;
1285 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1286 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1287 if (index >= 0) {
1288 input = mSoundTriggerSessions.valueFor(session);
1289 isSoundTrigger = true;
1290 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1291 }
1292 }
1293
Eric Laurentcf2c0212014-07-25 16:20:43 -07001294 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1295 &input,
1296 &config,
1297 &device,
1298 String8(""),
1299 inputSource,
1300 flags);
1301
1302 // only accept input with the exact requested set of parameters
1303 if (status != NO_ERROR ||
1304 (samplingRate != config.sample_rate) ||
1305 (format != config.format) ||
1306 (channelMask != config.channel_mask)) {
1307 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1308 samplingRate, format, channelMask);
1309 if (input != AUDIO_IO_HANDLE_NONE) {
1310 mpClientInterface->closeInput(input);
1311 }
1312 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001313 }
1314
Eric Laurent1f2f2232014-06-02 12:01:23 -07001315 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001316 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001317 inputDesc->mRefCount = 0;
1318 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001319 inputDesc->mSamplingRate = samplingRate;
1320 inputDesc->mFormat = format;
1321 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001322 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001323 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001324 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001325
Eric Laurentd4692962014-05-05 18:13:44 -07001326 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001327 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001328 return input;
1329}
1330
Eric Laurent4dc68062014-07-28 17:26:49 -07001331status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1332 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001333{
1334 ALOGV("startInput() input %d", input);
1335 ssize_t index = mInputs.indexOfKey(input);
1336 if (index < 0) {
1337 ALOGW("startInput() unknown input %d", input);
1338 return BAD_VALUE;
1339 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001340 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001341
Eric Laurent4dc68062014-07-28 17:26:49 -07001342 index = inputDesc->mSessions.indexOf(session);
1343 if (index < 0) {
1344 ALOGW("startInput() unknown session %d on input %d", session, input);
1345 return BAD_VALUE;
1346 }
1347
Glenn Kasten74a8e252014-07-24 14:09:55 -07001348 // virtual input devices are compatible with other input devices
1349 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1350
1351 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001352 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001353 if (activeInput != 0 && activeInput != input) {
1354
1355 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1356 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001357 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001358 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001359 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001360 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1361 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001362 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001363 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001364 return INVALID_OPERATION;
1365 }
1366 }
1367 }
1368
Glenn Kasten74a8e252014-07-24 14:09:55 -07001369 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001370 if (activeInputsCount() == 0) {
1371 SoundTrigger::setCaptureState(true);
1372 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001373 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001374
Glenn Kasten74a8e252014-07-24 14:09:55 -07001375 // Automatically enable the remote submix output when input is started.
1376 // For remote submix (a virtual device), we open only one input per capture request.
1377 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1378 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1379 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1380 }
Eric Laurente552edb2014-03-10 17:42:56 -07001381 }
1382
Eric Laurente552edb2014-03-10 17:42:56 -07001383 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1384
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001385 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001386 return NO_ERROR;
1387}
1388
Eric Laurent4dc68062014-07-28 17:26:49 -07001389status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1390 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001391{
1392 ALOGV("stopInput() input %d", input);
1393 ssize_t index = mInputs.indexOfKey(input);
1394 if (index < 0) {
1395 ALOGW("stopInput() unknown input %d", input);
1396 return BAD_VALUE;
1397 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001398 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001399
Eric Laurent4dc68062014-07-28 17:26:49 -07001400 index = inputDesc->mSessions.indexOf(session);
1401 if (index < 0) {
1402 ALOGW("stopInput() unknown session %d on input %d", session, input);
1403 return BAD_VALUE;
1404 }
1405
Eric Laurente552edb2014-03-10 17:42:56 -07001406 if (inputDesc->mRefCount == 0) {
1407 ALOGW("stopInput() input %d already stopped", input);
1408 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001409 }
1410
1411 inputDesc->mRefCount--;
1412 if (inputDesc->mRefCount == 0) {
1413
Eric Laurente552edb2014-03-10 17:42:56 -07001414 // automatically disable the remote submix output when input is stopped
1415 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1416 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001417 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001418 }
1419
Eric Laurent1c333e22014-05-20 10:48:17 -07001420 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001421
1422 if (activeInputsCount() == 0) {
1423 SoundTrigger::setCaptureState(false);
1424 }
Eric Laurente552edb2014-03-10 17:42:56 -07001425 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001426 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001427}
1428
Eric Laurent4dc68062014-07-28 17:26:49 -07001429void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1430 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001431{
1432 ALOGV("releaseInput() %d", input);
1433 ssize_t index = mInputs.indexOfKey(input);
1434 if (index < 0) {
1435 ALOGW("releaseInput() releasing unknown input %d", input);
1436 return;
1437 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001438 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1439 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001440
1441 index = inputDesc->mSessions.indexOf(session);
1442 if (index < 0) {
1443 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1444 return;
1445 }
1446 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001447 if (inputDesc->mOpenRefCount == 0) {
1448 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1449 return;
1450 }
1451 inputDesc->mOpenRefCount--;
1452 if (inputDesc->mOpenRefCount > 0) {
1453 ALOGV("releaseInput() exit > 0");
1454 return;
1455 }
1456
Eric Laurente552edb2014-03-10 17:42:56 -07001457 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001458 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001459 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001460 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001461 ALOGV("releaseInput() exit");
1462}
1463
Eric Laurentd4692962014-05-05 18:13:44 -07001464void AudioPolicyManager::closeAllInputs() {
1465 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1466 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1467 }
1468 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001469 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001470}
1471
Eric Laurente0720872014-03-11 09:30:41 -07001472void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001473 int indexMin,
1474 int indexMax)
1475{
1476 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1477 if (indexMin < 0 || indexMin >= indexMax) {
1478 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1479 return;
1480 }
1481 mStreams[stream].mIndexMin = indexMin;
1482 mStreams[stream].mIndexMax = indexMax;
1483}
1484
Eric Laurente0720872014-03-11 09:30:41 -07001485status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001486 int index,
1487 audio_devices_t device)
1488{
1489
1490 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1491 return BAD_VALUE;
1492 }
1493 if (!audio_is_output_device(device)) {
1494 return BAD_VALUE;
1495 }
1496
1497 // Force max volume if stream cannot be muted
1498 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1499
1500 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1501 stream, device, index);
1502
1503 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1504 // clear all device specific values
1505 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1506 mStreams[stream].mIndexCur.clear();
1507 }
1508 mStreams[stream].mIndexCur.add(device, index);
1509
1510 // compute and apply stream volume on all outputs according to connected device
1511 status_t status = NO_ERROR;
1512 for (size_t i = 0; i < mOutputs.size(); i++) {
1513 audio_devices_t curDevice =
1514 getDeviceForVolume(mOutputs.valueAt(i)->device());
1515 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1516 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1517 if (volStatus != NO_ERROR) {
1518 status = volStatus;
1519 }
1520 }
1521 }
1522 return status;
1523}
1524
Eric Laurente0720872014-03-11 09:30:41 -07001525status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001526 int *index,
1527 audio_devices_t device)
1528{
1529 if (index == NULL) {
1530 return BAD_VALUE;
1531 }
1532 if (!audio_is_output_device(device)) {
1533 return BAD_VALUE;
1534 }
1535 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1536 // the strategy the stream belongs to.
1537 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1538 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1539 }
1540 device = getDeviceForVolume(device);
1541
1542 *index = mStreams[stream].getVolumeIndex(device);
1543 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1544 return NO_ERROR;
1545}
1546
Eric Laurente0720872014-03-11 09:30:41 -07001547audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001548 const SortedVector<audio_io_handle_t>& outputs)
1549{
1550 // select one output among several suitable for global effects.
1551 // The priority is as follows:
1552 // 1: An offloaded output. If the effect ends up not being offloadable,
1553 // AudioFlinger will invalidate the track and the offloaded output
1554 // will be closed causing the effect to be moved to a PCM output.
1555 // 2: A deep buffer output
1556 // 3: the first output in the list
1557
1558 if (outputs.size() == 0) {
1559 return 0;
1560 }
1561
1562 audio_io_handle_t outputOffloaded = 0;
1563 audio_io_handle_t outputDeepBuffer = 0;
1564
1565 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001566 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001567 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001568 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1569 outputOffloaded = outputs[i];
1570 }
1571 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1572 outputDeepBuffer = outputs[i];
1573 }
1574 }
1575
1576 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1577 outputOffloaded, outputDeepBuffer);
1578 if (outputOffloaded != 0) {
1579 return outputOffloaded;
1580 }
1581 if (outputDeepBuffer != 0) {
1582 return outputDeepBuffer;
1583 }
1584
1585 return outputs[0];
1586}
1587
Eric Laurente0720872014-03-11 09:30:41 -07001588audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001589{
1590 // apply simple rule where global effects are attached to the same output as MUSIC streams
1591
Eric Laurent3b73df72014-03-11 09:06:29 -07001592 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001593 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1594 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1595
1596 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1597 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1598 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1599
1600 return output;
1601}
1602
Eric Laurente0720872014-03-11 09:30:41 -07001603status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001604 audio_io_handle_t io,
1605 uint32_t strategy,
1606 int session,
1607 int id)
1608{
1609 ssize_t index = mOutputs.indexOfKey(io);
1610 if (index < 0) {
1611 index = mInputs.indexOfKey(io);
1612 if (index < 0) {
1613 ALOGW("registerEffect() unknown io %d", io);
1614 return INVALID_OPERATION;
1615 }
1616 }
1617
1618 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1619 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1620 desc->name, desc->memoryUsage);
1621 return INVALID_OPERATION;
1622 }
1623 mTotalEffectsMemory += desc->memoryUsage;
1624 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1625 desc->name, io, strategy, session, id);
1626 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1627
Eric Laurent1f2f2232014-06-02 12:01:23 -07001628 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1629 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1630 effectDesc->mIo = io;
1631 effectDesc->mStrategy = (routing_strategy)strategy;
1632 effectDesc->mSession = session;
1633 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001634
Eric Laurent1f2f2232014-06-02 12:01:23 -07001635 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001636
1637 return NO_ERROR;
1638}
1639
Eric Laurente0720872014-03-11 09:30:41 -07001640status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001641{
1642 ssize_t index = mEffects.indexOfKey(id);
1643 if (index < 0) {
1644 ALOGW("unregisterEffect() unknown effect ID %d", id);
1645 return INVALID_OPERATION;
1646 }
1647
Eric Laurent1f2f2232014-06-02 12:01:23 -07001648 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurent1f2f2232014-06-02 12:01:23 -07001650 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001651
Eric Laurent1f2f2232014-06-02 12:01:23 -07001652 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001653 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001654 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1655 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001656 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001657 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001658 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001659 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001660
1661 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001662
1663 return NO_ERROR;
1664}
1665
Eric Laurente0720872014-03-11 09:30:41 -07001666status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001667{
1668 ssize_t index = mEffects.indexOfKey(id);
1669 if (index < 0) {
1670 ALOGW("unregisterEffect() unknown effect ID %d", id);
1671 return INVALID_OPERATION;
1672 }
1673
1674 return setEffectEnabled(mEffects.valueAt(index), enabled);
1675}
1676
Eric Laurent1f2f2232014-06-02 12:01:23 -07001677status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001678{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001679 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001680 ALOGV("setEffectEnabled(%s) effect already %s",
1681 enabled?"true":"false", enabled?"enabled":"disabled");
1682 return INVALID_OPERATION;
1683 }
1684
1685 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001686 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001687 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001688 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001689 return INVALID_OPERATION;
1690 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001691 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001692 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1693 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001694 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001695 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001696 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1697 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001698 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001699 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001700 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1701 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001702 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001703 return NO_ERROR;
1704}
1705
Eric Laurente0720872014-03-11 09:30:41 -07001706bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001707{
1708 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001709 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1710 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1711 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001712 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001713 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001714 return true;
1715 }
1716 }
1717 return false;
1718}
1719
Eric Laurente0720872014-03-11 09:30:41 -07001720bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001721{
1722 nsecs_t sysTime = systemTime();
1723 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001724 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001725 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001726 return true;
1727 }
1728 }
1729 return false;
1730}
1731
Eric Laurente0720872014-03-11 09:30:41 -07001732bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001733 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001734{
1735 nsecs_t sysTime = systemTime();
1736 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001737 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001738 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001739 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001740 return true;
1741 }
1742 }
1743 return false;
1744}
1745
Eric Laurente0720872014-03-11 09:30:41 -07001746bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001747{
1748 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001749 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001750 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001751 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001752 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1753 && (inputDescriptor->mRefCount > 0)) {
1754 return true;
1755 }
1756 }
1757 return false;
1758}
1759
1760
Eric Laurente0720872014-03-11 09:30:41 -07001761status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001762{
1763 const size_t SIZE = 256;
1764 char buffer[SIZE];
1765 String8 result;
1766
1767 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1768 result.append(buffer);
1769
1770 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1771 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001772 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1773 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001774 snprintf(buffer, SIZE, " Force use for communications %d\n",
1775 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001776 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001777 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001778 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001779 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001780 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001781 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001782 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001783 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001784 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001785 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1786 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1787 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001788
Eric Laurent3a4311c2014-03-17 12:00:47 -07001789 snprintf(buffer, SIZE, " Available output devices:\n");
1790 result.append(buffer);
1791 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001792 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001793 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001794 }
1795 snprintf(buffer, SIZE, "\n Available input devices:\n");
1796 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001797 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001798 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001799 }
Eric Laurente552edb2014-03-10 17:42:56 -07001800
1801 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1802 write(fd, buffer, strlen(buffer));
1803 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001804 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001805 write(fd, buffer, strlen(buffer));
1806 mHwModules[i]->dump(fd);
1807 }
1808
1809 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1810 write(fd, buffer, strlen(buffer));
1811 for (size_t i = 0; i < mOutputs.size(); i++) {
1812 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1813 write(fd, buffer, strlen(buffer));
1814 mOutputs.valueAt(i)->dump(fd);
1815 }
1816
1817 snprintf(buffer, SIZE, "\nInputs dump:\n");
1818 write(fd, buffer, strlen(buffer));
1819 for (size_t i = 0; i < mInputs.size(); i++) {
1820 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1821 write(fd, buffer, strlen(buffer));
1822 mInputs.valueAt(i)->dump(fd);
1823 }
1824
1825 snprintf(buffer, SIZE, "\nStreams dump:\n");
1826 write(fd, buffer, strlen(buffer));
1827 snprintf(buffer, SIZE,
1828 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1829 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001830 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001831 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001832 write(fd, buffer, strlen(buffer));
1833 mStreams[i].dump(fd);
1834 }
1835
1836 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1837 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1838 write(fd, buffer, strlen(buffer));
1839
1840 snprintf(buffer, SIZE, "Registered effects:\n");
1841 write(fd, buffer, strlen(buffer));
1842 for (size_t i = 0; i < mEffects.size(); i++) {
1843 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1844 write(fd, buffer, strlen(buffer));
1845 mEffects.valueAt(i)->dump(fd);
1846 }
1847
1848
1849 return NO_ERROR;
1850}
1851
1852// This function checks for the parameters which can be offloaded.
1853// This can be enhanced depending on the capability of the DSP and policy
1854// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001855bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001856{
1857 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001858 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001859 offloadInfo.sample_rate, offloadInfo.channel_mask,
1860 offloadInfo.format,
1861 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1862 offloadInfo.has_video);
1863
1864 // Check if offload has been disabled
1865 char propValue[PROPERTY_VALUE_MAX];
1866 if (property_get("audio.offload.disable", propValue, "0")) {
1867 if (atoi(propValue) != 0) {
1868 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1869 return false;
1870 }
1871 }
1872
1873 // Check if stream type is music, then only allow offload as of now.
1874 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1875 {
1876 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1877 return false;
1878 }
1879
1880 //TODO: enable audio offloading with video when ready
1881 if (offloadInfo.has_video)
1882 {
1883 ALOGV("isOffloadSupported: has_video == true, returning false");
1884 return false;
1885 }
1886
1887 //If duration is less than minimum value defined in property, return false
1888 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1889 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1890 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1891 return false;
1892 }
1893 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1894 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1895 return false;
1896 }
1897
1898 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1899 // creating an offloaded track and tearing it down immediately after start when audioflinger
1900 // detects there is an active non offloadable effect.
1901 // FIXME: We should check the audio session here but we do not have it in this context.
1902 // This may prevent offloading in rare situations where effects are left active by apps
1903 // in the background.
1904 if (isNonOffloadableEffectEnabled()) {
1905 return false;
1906 }
1907
1908 // See if there is a profile to support this.
1909 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001910 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001911 offloadInfo.sample_rate,
1912 offloadInfo.format,
1913 offloadInfo.channel_mask,
1914 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001915 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1916 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001917}
1918
Eric Laurent6a94d692014-05-20 11:18:06 -07001919status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1920 audio_port_type_t type,
1921 unsigned int *num_ports,
1922 struct audio_port *ports,
1923 unsigned int *generation)
1924{
1925 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1926 generation == NULL) {
1927 return BAD_VALUE;
1928 }
1929 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1930 if (ports == NULL) {
1931 *num_ports = 0;
1932 }
1933
1934 size_t portsWritten = 0;
1935 size_t portsMax = *num_ports;
1936 *num_ports = 0;
1937 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1938 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1939 for (size_t i = 0;
1940 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1941 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1942 }
1943 *num_ports += mAvailableOutputDevices.size();
1944 }
1945 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1946 for (size_t i = 0;
1947 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1948 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1949 }
1950 *num_ports += mAvailableInputDevices.size();
1951 }
1952 }
1953 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1954 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1955 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1956 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1957 }
1958 *num_ports += mInputs.size();
1959 }
1960 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001961 size_t numOutputs = 0;
1962 for (size_t i = 0; i < mOutputs.size(); i++) {
1963 if (!mOutputs[i]->isDuplicated()) {
1964 numOutputs++;
1965 if (portsWritten < portsMax) {
1966 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1967 }
1968 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001969 }
Eric Laurent84c70242014-06-23 08:46:27 -07001970 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001971 }
1972 }
1973 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001974 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001975 return NO_ERROR;
1976}
1977
1978status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1979{
1980 return NO_ERROR;
1981}
1982
Eric Laurent1f2f2232014-06-02 12:01:23 -07001983sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001984 audio_port_handle_t id) const
1985{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001986 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001987 for (size_t i = 0; i < mOutputs.size(); i++) {
1988 outputDesc = mOutputs.valueAt(i);
1989 if (outputDesc->mId == id) {
1990 break;
1991 }
1992 }
1993 return outputDesc;
1994}
1995
Eric Laurent1f2f2232014-06-02 12:01:23 -07001996sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001997 audio_port_handle_t id) const
1998{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001999 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002000 for (size_t i = 0; i < mInputs.size(); i++) {
2001 inputDesc = mInputs.valueAt(i);
2002 if (inputDesc->mId == id) {
2003 break;
2004 }
2005 }
2006 return inputDesc;
2007}
2008
Eric Laurent1f2f2232014-06-02 12:01:23 -07002009sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2010 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002011{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002012 sp <HwModule> module;
2013
Eric Laurent6a94d692014-05-20 11:18:06 -07002014 for (size_t i = 0; i < mHwModules.size(); i++) {
2015 if (mHwModules[i]->mHandle == 0) {
2016 continue;
2017 }
2018 if (audio_is_output_device(device)) {
2019 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2020 {
2021 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2022 return mHwModules[i];
2023 }
2024 }
2025 } else {
2026 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2027 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2028 device & ~AUDIO_DEVICE_BIT_IN) {
2029 return mHwModules[i];
2030 }
2031 }
2032 }
2033 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002034 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002035}
2036
Eric Laurent1f2f2232014-06-02 12:01:23 -07002037sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002038{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002039 sp <HwModule> module;
2040
Eric Laurent1afeecb2014-05-14 08:52:28 -07002041 for (size_t i = 0; i < mHwModules.size(); i++)
2042 {
2043 if (strcmp(mHwModules[i]->mName, name) == 0) {
2044 return mHwModules[i];
2045 }
2046 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002047 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002048}
2049
Eric Laurentc2730ba2014-07-20 15:47:07 -07002050audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2051{
2052 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2053 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2054 return devices & mAvailableOutputDevices.types();
2055}
2056
2057audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2058{
2059 audio_module_handle_t primaryHandle =
2060 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2061 audio_devices_t devices = AUDIO_DEVICE_NONE;
2062 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2063 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2064 devices |= mAvailableInputDevices[i]->mDeviceType;
2065 }
2066 }
2067 return devices;
2068}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002069
Eric Laurent6a94d692014-05-20 11:18:06 -07002070status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2071 audio_patch_handle_t *handle,
2072 uid_t uid)
2073{
2074 ALOGV("createAudioPatch()");
2075
2076 if (handle == NULL || patch == NULL) {
2077 return BAD_VALUE;
2078 }
2079 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2080
Eric Laurent874c42872014-08-08 15:13:39 -07002081 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2082 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2083 return BAD_VALUE;
2084 }
2085 // only one source per audio patch supported for now
2086 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002087 return INVALID_OPERATION;
2088 }
Eric Laurent874c42872014-08-08 15:13:39 -07002089
2090 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002091 return INVALID_OPERATION;
2092 }
Eric Laurent874c42872014-08-08 15:13:39 -07002093 for (size_t i = 0; i < patch->num_sinks; i++) {
2094 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2095 return INVALID_OPERATION;
2096 }
2097 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002098
2099 sp<AudioPatch> patchDesc;
2100 ssize_t index = mAudioPatches.indexOfKey(*handle);
2101
Eric Laurent6a94d692014-05-20 11:18:06 -07002102 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2103 patch->sources[0].role,
2104 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002105#if LOG_NDEBUG == 0
2106 for (size_t i = 0; i < patch->num_sinks; i++) {
2107 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2108 patch->sinks[i].role,
2109 patch->sinks[i].type);
2110 }
2111#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002112
2113 if (index >= 0) {
2114 patchDesc = mAudioPatches.valueAt(index);
2115 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2116 mUidCached, patchDesc->mUid, uid);
2117 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2118 return INVALID_OPERATION;
2119 }
2120 } else {
2121 *handle = 0;
2122 }
2123
2124 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002125 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002126 if (outputDesc == NULL) {
2127 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2128 return BAD_VALUE;
2129 }
Eric Laurent84c70242014-06-23 08:46:27 -07002130 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2131 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002132 if (patchDesc != 0) {
2133 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2134 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2135 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2136 return BAD_VALUE;
2137 }
2138 }
Eric Laurent874c42872014-08-08 15:13:39 -07002139 DeviceVector devices;
2140 for (size_t i = 0; i < patch->num_sinks; i++) {
2141 // Only support mix to devices connection
2142 // TODO add support for mix to mix connection
2143 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2144 ALOGV("createAudioPatch() source mix but sink is not a device");
2145 return INVALID_OPERATION;
2146 }
2147 sp<DeviceDescriptor> devDesc =
2148 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2149 if (devDesc == 0) {
2150 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2151 return BAD_VALUE;
2152 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002153
Eric Laurent874c42872014-08-08 15:13:39 -07002154 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2155 patch->sources[0].sample_rate,
2156 NULL, // updatedSamplingRate
2157 patch->sources[0].format,
2158 patch->sources[0].channel_mask,
2159 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2160 ALOGV("createAudioPatch() profile not supported for device %08x",
2161 devDesc->mDeviceType);
2162 return INVALID_OPERATION;
2163 }
2164 devices.add(devDesc);
2165 }
2166 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002167 return INVALID_OPERATION;
2168 }
Eric Laurent874c42872014-08-08 15:13:39 -07002169
Eric Laurent6a94d692014-05-20 11:18:06 -07002170 // TODO: reconfigure output format and channels here
2171 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002172 devices.types(), outputDesc->mIoHandle);
2173 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002174 index = mAudioPatches.indexOfKey(*handle);
2175 if (index >= 0) {
2176 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2177 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2178 }
2179 patchDesc = mAudioPatches.valueAt(index);
2180 patchDesc->mUid = uid;
2181 ALOGV("createAudioPatch() success");
2182 } else {
2183 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2184 return INVALID_OPERATION;
2185 }
2186 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2187 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2188 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002189 // only one sink supported when connecting an input device to a mix
2190 if (patch->num_sinks > 1) {
2191 return INVALID_OPERATION;
2192 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002193 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002194 if (inputDesc == NULL) {
2195 return BAD_VALUE;
2196 }
2197 if (patchDesc != 0) {
2198 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2199 return BAD_VALUE;
2200 }
2201 }
2202 sp<DeviceDescriptor> devDesc =
2203 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2204 if (devDesc == 0) {
2205 return BAD_VALUE;
2206 }
2207
Eric Laurent84c70242014-06-23 08:46:27 -07002208 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002209 patch->sinks[0].sample_rate,
2210 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002211 patch->sinks[0].format,
2212 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002213 // FIXME for the parameter type,
2214 // and the NONE
2215 (audio_output_flags_t)
2216 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002217 return INVALID_OPERATION;
2218 }
2219 // TODO: reconfigure output format and channels here
2220 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002221 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002222 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002223 index = mAudioPatches.indexOfKey(*handle);
2224 if (index >= 0) {
2225 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2226 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2227 }
2228 patchDesc = mAudioPatches.valueAt(index);
2229 patchDesc->mUid = uid;
2230 ALOGV("createAudioPatch() success");
2231 } else {
2232 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2233 return INVALID_OPERATION;
2234 }
2235 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2236 // device to device connection
2237 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002238 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002239 return BAD_VALUE;
2240 }
2241 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002242 sp<DeviceDescriptor> srcDeviceDesc =
2243 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent874c42872014-08-08 15:13:39 -07002244
Eric Laurent6a94d692014-05-20 11:18:06 -07002245 //update source and sink with our own data as the data passed in the patch may
2246 // be incomplete.
2247 struct audio_patch newPatch = *patch;
2248 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent874c42872014-08-08 15:13:39 -07002249 if (srcDeviceDesc == 0) {
2250 return BAD_VALUE;
2251 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002252
Eric Laurent874c42872014-08-08 15:13:39 -07002253 for (size_t i = 0; i < patch->num_sinks; i++) {
2254 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2255 ALOGV("createAudioPatch() source device but one sink is not a device");
2256 return INVALID_OPERATION;
2257 }
2258
2259 sp<DeviceDescriptor> sinkDeviceDesc =
2260 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2261 if (sinkDeviceDesc == 0) {
2262 return BAD_VALUE;
2263 }
2264 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2265
2266 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2267 // only one sink supported when connected devices across HW modules
2268 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002269 return INVALID_OPERATION;
2270 }
Eric Laurent874c42872014-08-08 15:13:39 -07002271 SortedVector<audio_io_handle_t> outputs =
2272 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2273 mOutputs);
2274 // if the sink device is reachable via an opened output stream, request to go via
2275 // this output stream by adding a second source to the patch description
2276 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2277 if (output != AUDIO_IO_HANDLE_NONE) {
2278 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2279 if (outputDesc->isDuplicated()) {
2280 return INVALID_OPERATION;
2281 }
2282 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2283 newPatch.num_sources = 2;
2284 }
Eric Laurent83b88082014-06-20 18:31:16 -07002285 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002286 }
2287 // TODO: check from routing capabilities in config file and other conflicting patches
2288
2289 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2290 if (index >= 0) {
2291 afPatchHandle = patchDesc->mAfPatchHandle;
2292 }
2293
2294 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2295 &afPatchHandle,
2296 0);
2297 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2298 status, afPatchHandle);
2299 if (status == NO_ERROR) {
2300 if (index < 0) {
2301 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2302 &newPatch, uid);
2303 addAudioPatch(patchDesc->mHandle, patchDesc);
2304 } else {
2305 patchDesc->mPatch = newPatch;
2306 }
2307 patchDesc->mAfPatchHandle = afPatchHandle;
2308 *handle = patchDesc->mHandle;
2309 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002310 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002311 } else {
2312 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2313 status);
2314 return INVALID_OPERATION;
2315 }
2316 } else {
2317 return BAD_VALUE;
2318 }
2319 } else {
2320 return BAD_VALUE;
2321 }
2322 return NO_ERROR;
2323}
2324
2325status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2326 uid_t uid)
2327{
2328 ALOGV("releaseAudioPatch() patch %d", handle);
2329
2330 ssize_t index = mAudioPatches.indexOfKey(handle);
2331
2332 if (index < 0) {
2333 return BAD_VALUE;
2334 }
2335 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2336 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2337 mUidCached, patchDesc->mUid, uid);
2338 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2339 return INVALID_OPERATION;
2340 }
2341
2342 struct audio_patch *patch = &patchDesc->mPatch;
2343 patchDesc->mUid = mUidCached;
2344 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002345 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002346 if (outputDesc == NULL) {
2347 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2348 return BAD_VALUE;
2349 }
2350
2351 setOutputDevice(outputDesc->mIoHandle,
2352 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2353 true,
2354 0,
2355 NULL);
2356 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2357 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002358 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002359 if (inputDesc == NULL) {
2360 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2361 return BAD_VALUE;
2362 }
2363 setInputDevice(inputDesc->mIoHandle,
2364 getNewInputDevice(inputDesc->mIoHandle),
2365 true,
2366 NULL);
2367 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2368 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2369 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2370 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2371 status, patchDesc->mAfPatchHandle);
2372 removeAudioPatch(patchDesc->mHandle);
2373 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002374 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002375 } else {
2376 return BAD_VALUE;
2377 }
2378 } else {
2379 return BAD_VALUE;
2380 }
2381 return NO_ERROR;
2382}
2383
2384status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2385 struct audio_patch *patches,
2386 unsigned int *generation)
2387{
2388 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2389 generation == NULL) {
2390 return BAD_VALUE;
2391 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002392 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 *num_patches, patches, mAudioPatches.size());
2394 if (patches == NULL) {
2395 *num_patches = 0;
2396 }
2397
2398 size_t patchesWritten = 0;
2399 size_t patchesMax = *num_patches;
2400 for (size_t i = 0;
2401 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2402 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2403 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002404 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2406 }
2407 *num_patches = mAudioPatches.size();
2408
2409 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002410 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002411 return NO_ERROR;
2412}
2413
Eric Laurente1715a42014-05-20 11:30:42 -07002414status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002415{
Eric Laurente1715a42014-05-20 11:30:42 -07002416 ALOGV("setAudioPortConfig()");
2417
2418 if (config == NULL) {
2419 return BAD_VALUE;
2420 }
2421 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2422 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002423 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2424 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002425 }
2426
Eric Laurenta121f902014-06-03 13:32:54 -07002427 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002428 if (config->type == AUDIO_PORT_TYPE_MIX) {
2429 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002430 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002431 if (outputDesc == NULL) {
2432 return BAD_VALUE;
2433 }
Eric Laurent84c70242014-06-23 08:46:27 -07002434 ALOG_ASSERT(!outputDesc->isDuplicated(),
2435 "setAudioPortConfig() called on duplicated output %d",
2436 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002437 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002438 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002439 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002440 if (inputDesc == NULL) {
2441 return BAD_VALUE;
2442 }
Eric Laurenta121f902014-06-03 13:32:54 -07002443 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002444 } else {
2445 return BAD_VALUE;
2446 }
2447 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2448 sp<DeviceDescriptor> deviceDesc;
2449 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2450 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2451 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2452 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2453 } else {
2454 return BAD_VALUE;
2455 }
2456 if (deviceDesc == NULL) {
2457 return BAD_VALUE;
2458 }
Eric Laurenta121f902014-06-03 13:32:54 -07002459 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002460 } else {
2461 return BAD_VALUE;
2462 }
2463
Eric Laurenta121f902014-06-03 13:32:54 -07002464 struct audio_port_config backupConfig;
2465 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2466 if (status == NO_ERROR) {
2467 struct audio_port_config newConfig;
2468 audioPortConfig->toAudioPortConfig(&newConfig, config);
2469 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002470 }
Eric Laurenta121f902014-06-03 13:32:54 -07002471 if (status != NO_ERROR) {
2472 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002473 }
Eric Laurente1715a42014-05-20 11:30:42 -07002474
2475 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002476}
2477
2478void AudioPolicyManager::clearAudioPatches(uid_t uid)
2479{
2480 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2481 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2482 if (patchDesc->mUid == uid) {
2483 // releaseAudioPatch() removes the patch from mAudioPatches
2484 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2485 i--;
2486 }
2487 }
2488 }
2489}
2490
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002491status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2492 audio_io_handle_t *ioHandle,
2493 audio_devices_t *device)
2494{
2495 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2496 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2497 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2498
2499 mSoundTriggerSessions.add(*session, *ioHandle);
2500
2501 return NO_ERROR;
2502}
2503
2504status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2505{
2506 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2507 if (index < 0) {
2508 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2509 return BAD_VALUE;
2510 }
2511
2512 mSoundTriggerSessions.removeItem(session);
2513 return NO_ERROR;
2514}
2515
Eric Laurent6a94d692014-05-20 11:18:06 -07002516status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2517 const sp<AudioPatch>& patch)
2518{
2519 ssize_t index = mAudioPatches.indexOfKey(handle);
2520
2521 if (index >= 0) {
2522 ALOGW("addAudioPatch() patch %d already in", handle);
2523 return ALREADY_EXISTS;
2524 }
2525 mAudioPatches.add(handle, patch);
2526 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2527 "sink handle %d",
2528 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2529 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2530 return NO_ERROR;
2531}
2532
2533status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2534{
2535 ssize_t index = mAudioPatches.indexOfKey(handle);
2536
2537 if (index < 0) {
2538 ALOGW("removeAudioPatch() patch %d not in", handle);
2539 return ALREADY_EXISTS;
2540 }
2541 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2542 mAudioPatches.valueAt(index)->mAfPatchHandle);
2543 mAudioPatches.removeItemsAt(index);
2544 return NO_ERROR;
2545}
2546
Eric Laurente552edb2014-03-10 17:42:56 -07002547// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002548// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002549// ----------------------------------------------------------------------------
2550
Eric Laurent3a4311c2014-03-17 12:00:47 -07002551uint32_t AudioPolicyManager::nextUniqueId()
2552{
2553 return android_atomic_inc(&mNextUniqueId);
2554}
2555
Eric Laurent6a94d692014-05-20 11:18:06 -07002556uint32_t AudioPolicyManager::nextAudioPortGeneration()
2557{
2558 return android_atomic_inc(&mAudioPortGeneration);
2559}
2560
Eric Laurente0720872014-03-11 09:30:41 -07002561AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002562 :
2563#ifdef AUDIO_POLICY_TEST
2564 Thread(false),
2565#endif //AUDIO_POLICY_TEST
2566 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002567 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002568 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2569 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002570 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002571 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2572 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002573{
Eric Laurent6a94d692014-05-20 11:18:06 -07002574 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002575 mpClientInterface = clientInterface;
2576
Eric Laurent3b73df72014-03-11 09:06:29 -07002577 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2578 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002579 }
2580
Eric Laurent1afeecb2014-05-14 08:52:28 -07002581 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002582 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2583 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2584 ALOGE("could not load audio policy configuration file, setting defaults");
2585 defaultAudioPolicyConfig();
2586 }
2587 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002588 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002589
2590 // must be done after reading the policy
2591 initializeVolumeCurves();
2592
2593 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002594 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2595 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002596 for (size_t i = 0; i < mHwModules.size(); i++) {
2597 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2598 if (mHwModules[i]->mHandle == 0) {
2599 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2600 continue;
2601 }
2602 // open all output streams needed to access attached devices
2603 // except for direct output streams that are only opened when they are actually
2604 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002605 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002606 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2607 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002608 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002609
Eric Laurent3a4311c2014-03-17 12:00:47 -07002610 if (outProfile->mSupportedDevices.isEmpty()) {
2611 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2612 continue;
2613 }
2614
Eric Laurent83b88082014-06-20 18:31:16 -07002615 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2616 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2617 profileType = mDefaultOutputDevice->mDeviceType;
2618 } else {
2619 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2620 }
2621 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002622 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002623 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002624
Eric Laurent83b88082014-06-20 18:31:16 -07002625 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002626 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2627 config.sample_rate = outputDesc->mSamplingRate;
2628 config.channel_mask = outputDesc->mChannelMask;
2629 config.format = outputDesc->mFormat;
2630 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2631 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2632 &output,
2633 &config,
2634 &outputDesc->mDevice,
2635 String8(""),
2636 &outputDesc->mLatency,
2637 outputDesc->mFlags);
2638
2639 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002640 ALOGW("Cannot open output stream for device %08x on hw module %s",
2641 outputDesc->mDevice,
2642 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002643 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002644 outputDesc->mSamplingRate = config.sample_rate;
2645 outputDesc->mChannelMask = config.channel_mask;
2646 outputDesc->mFormat = config.format;
2647
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002648 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002649 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002650 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002651 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002652 // give a valid ID to an attached device once confirmed it is reachable
2653 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2654 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002655 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002656 }
2657 }
Eric Laurente552edb2014-03-10 17:42:56 -07002658 if (mPrimaryOutput == 0 &&
2659 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2660 mPrimaryOutput = output;
2661 }
2662 addOutput(output, outputDesc);
2663 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002664 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002665 true);
2666 }
2667 }
2668 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002669 // open input streams needed to access attached devices to validate
2670 // mAvailableInputDevices list
2671 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2672 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002673 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002674
Eric Laurent3a4311c2014-03-17 12:00:47 -07002675 if (inProfile->mSupportedDevices.isEmpty()) {
2676 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2677 continue;
2678 }
2679
Eric Laurent83b88082014-06-20 18:31:16 -07002680 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2681 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002682 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002683
2684 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002685 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002686
Eric Laurentcf2c0212014-07-25 16:20:43 -07002687 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2688 config.sample_rate = inputDesc->mSamplingRate;
2689 config.channel_mask = inputDesc->mChannelMask;
2690 config.format = inputDesc->mFormat;
2691 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2692 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2693 &input,
2694 &config,
2695 &inputDesc->mDevice,
2696 String8(""),
2697 AUDIO_SOURCE_MIC,
2698 AUDIO_INPUT_FLAG_NONE);
2699
2700 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002701 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002702 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002703 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002704 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002705 // give a valid ID to an attached device once confirmed it is reachable
2706 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2707 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002708 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002709 }
2710 }
2711 mpClientInterface->closeInput(input);
2712 } else {
2713 ALOGW("Cannot open input stream for device %08x on hw module %s",
2714 inputDesc->mDevice,
2715 mHwModules[i]->mName);
2716 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002717 }
2718 }
2719 }
2720 // make sure all attached devices have been allocated a unique ID
2721 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2722 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002723 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002724 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2725 continue;
2726 }
2727 i++;
2728 }
2729 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2730 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002731 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002732 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2733 continue;
2734 }
2735 i++;
2736 }
2737 // make sure default device is reachable
2738 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002739 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002740 }
Eric Laurente552edb2014-03-10 17:42:56 -07002741
2742 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2743
2744 updateDevicesAndOutputs();
2745
2746#ifdef AUDIO_POLICY_TEST
2747 if (mPrimaryOutput != 0) {
2748 AudioParameter outputCmd = AudioParameter();
2749 outputCmd.addInt(String8("set_id"), 0);
2750 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2751
2752 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2753 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002754 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2755 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002756 mTestLatencyMs = 0;
2757 mCurOutput = 0;
2758 mDirectOutput = false;
2759 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2760 mTestOutputs[i] = 0;
2761 }
2762
2763 const size_t SIZE = 256;
2764 char buffer[SIZE];
2765 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2766 run(buffer, ANDROID_PRIORITY_AUDIO);
2767 }
2768#endif //AUDIO_POLICY_TEST
2769}
2770
Eric Laurente0720872014-03-11 09:30:41 -07002771AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002772{
2773#ifdef AUDIO_POLICY_TEST
2774 exit();
2775#endif //AUDIO_POLICY_TEST
2776 for (size_t i = 0; i < mOutputs.size(); i++) {
2777 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002778 }
2779 for (size_t i = 0; i < mInputs.size(); i++) {
2780 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002781 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002782 mAvailableOutputDevices.clear();
2783 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002784 mOutputs.clear();
2785 mInputs.clear();
2786 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002787}
2788
Eric Laurente0720872014-03-11 09:30:41 -07002789status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002790{
2791 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2792}
2793
2794#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002795bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002796{
2797 ALOGV("entering threadLoop()");
2798 while (!exitPending())
2799 {
2800 String8 command;
2801 int valueInt;
2802 String8 value;
2803
2804 Mutex::Autolock _l(mLock);
2805 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2806
2807 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2808 AudioParameter param = AudioParameter(command);
2809
2810 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2811 valueInt != 0) {
2812 ALOGV("Test command %s received", command.string());
2813 String8 target;
2814 if (param.get(String8("target"), target) != NO_ERROR) {
2815 target = "Manager";
2816 }
2817 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2818 param.remove(String8("test_cmd_policy_output"));
2819 mCurOutput = valueInt;
2820 }
2821 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2822 param.remove(String8("test_cmd_policy_direct"));
2823 if (value == "false") {
2824 mDirectOutput = false;
2825 } else if (value == "true") {
2826 mDirectOutput = true;
2827 }
2828 }
2829 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2830 param.remove(String8("test_cmd_policy_input"));
2831 mTestInput = valueInt;
2832 }
2833
2834 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2835 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002836 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002837 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002838 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002839 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002840 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002841 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002842 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002843 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002844 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002845 if (target == "Manager") {
2846 mTestFormat = format;
2847 } else if (mTestOutputs[mCurOutput] != 0) {
2848 AudioParameter outputParam = AudioParameter();
2849 outputParam.addInt(String8("format"), format);
2850 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2851 }
2852 }
2853 }
2854 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2855 param.remove(String8("test_cmd_policy_channels"));
2856 int channels = 0;
2857
2858 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002859 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002860 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002861 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002862 }
2863 if (channels != 0) {
2864 if (target == "Manager") {
2865 mTestChannels = channels;
2866 } else if (mTestOutputs[mCurOutput] != 0) {
2867 AudioParameter outputParam = AudioParameter();
2868 outputParam.addInt(String8("channels"), channels);
2869 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2870 }
2871 }
2872 }
2873 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2874 param.remove(String8("test_cmd_policy_sampleRate"));
2875 if (valueInt >= 0 && valueInt <= 96000) {
2876 int samplingRate = valueInt;
2877 if (target == "Manager") {
2878 mTestSamplingRate = samplingRate;
2879 } else if (mTestOutputs[mCurOutput] != 0) {
2880 AudioParameter outputParam = AudioParameter();
2881 outputParam.addInt(String8("sampling_rate"), samplingRate);
2882 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2883 }
2884 }
2885 }
2886
2887 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2888 param.remove(String8("test_cmd_policy_reopen"));
2889
Eric Laurent1f2f2232014-06-02 12:01:23 -07002890 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002891 mpClientInterface->closeOutput(mPrimaryOutput);
2892
2893 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2894
Eric Laurente552edb2014-03-10 17:42:56 -07002895 mOutputs.removeItem(mPrimaryOutput);
2896
Eric Laurent1f2f2232014-06-02 12:01:23 -07002897 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002898 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002899 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2900 config.sample_rate = outputDesc->mSamplingRate;
2901 config.channel_mask = outputDesc->mChannelMask;
2902 config.format = outputDesc->mFormat;
2903 status_t status = mpClientInterface->openOutput(moduleHandle,
2904 &mPrimaryOutput,
2905 &config,
2906 &outputDesc->mDevice,
2907 String8(""),
2908 &outputDesc->mLatency,
2909 outputDesc->mFlags);
2910 if (status != NO_ERROR) {
2911 ALOGE("Failed to reopen hardware output stream, "
2912 "samplingRate: %d, format %d, channels %d",
2913 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002914 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002915 outputDesc->mSamplingRate = config.sample_rate;
2916 outputDesc->mChannelMask = config.channel_mask;
2917 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002918 AudioParameter outputCmd = AudioParameter();
2919 outputCmd.addInt(String8("set_id"), 0);
2920 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2921 addOutput(mPrimaryOutput, outputDesc);
2922 }
2923 }
2924
2925
2926 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2927 }
2928 }
2929 return false;
2930}
2931
Eric Laurente0720872014-03-11 09:30:41 -07002932void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002933{
2934 {
2935 AutoMutex _l(mLock);
2936 requestExit();
2937 mWaitWorkCV.signal();
2938 }
2939 requestExitAndWait();
2940}
2941
Eric Laurente0720872014-03-11 09:30:41 -07002942int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002943{
2944 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2945 if (output == mTestOutputs[i]) return i;
2946 }
2947 return 0;
2948}
2949#endif //AUDIO_POLICY_TEST
2950
2951// ---
2952
Eric Laurent1f2f2232014-06-02 12:01:23 -07002953void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002954{
Eric Laurent1c333e22014-05-20 10:48:17 -07002955 outputDesc->mIoHandle = output;
2956 outputDesc->mId = nextUniqueId();
2957 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002958 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002959}
2960
Eric Laurent1f2f2232014-06-02 12:01:23 -07002961void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002962{
Eric Laurent1c333e22014-05-20 10:48:17 -07002963 inputDesc->mIoHandle = input;
2964 inputDesc->mId = nextUniqueId();
2965 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002966 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002967}
Eric Laurente552edb2014-03-10 17:42:56 -07002968
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002969void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2970 const String8 address /*in*/,
2971 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2972 // look for a match on the given address on the addresses of the outputs:
2973 // find the address by finding the patch that maps to this output
2974 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2975 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2976 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2977 if (patchIdx >= 0) {
2978 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2979 const int numSinks = patchDesc->mPatch.num_sinks;
2980 for (ssize_t j=0; j < numSinks; j++) {
2981 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2982 const char* patchAddr =
2983 patchDesc->mPatch.sinks[j].ext.device.address;
2984 if (strncmp(patchAddr,
2985 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2986 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2987 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2988 outputs.add(desc->mIoHandle);
2989 break;
2990 }
2991 }
2992 }
2993 }
2994}
2995
Eric Laurente0720872014-03-11 09:30:41 -07002996status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002997 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002998 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002999 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003000{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003001 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07003002
Eric Laurent3b73df72014-03-11 09:06:29 -07003003 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003004 // first list already open outputs that can be routed to this device
3005 for (size_t i = 0; i < mOutputs.size(); i++) {
3006 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003007 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003008 if (!deviceDistinguishesOnAddress(device)) {
3009 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3010 outputs.add(mOutputs.keyAt(i));
3011 } else {
3012 ALOGV(" checking address match due to device 0x%x", device);
3013 findIoHandlesByAddress(desc, address, outputs);
3014 }
Eric Laurente552edb2014-03-10 17:42:56 -07003015 }
3016 }
3017 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003018 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003019 for (size_t i = 0; i < mHwModules.size(); i++)
3020 {
3021 if (mHwModules[i]->mHandle == 0) {
3022 continue;
3023 }
3024 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3025 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003026 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003027 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003028 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3029 }
3030 }
3031 }
3032
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003033 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3034
Eric Laurente552edb2014-03-10 17:42:56 -07003035 if (profiles.isEmpty() && outputs.isEmpty()) {
3036 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3037 return BAD_VALUE;
3038 }
3039
3040 // open outputs for matching profiles if needed. Direct outputs are also opened to
3041 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3042 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003043 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003044
3045 // nothing to do if one output is already opened for this profile
3046 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003047 for (j = 0; j < outputs.size(); j++) {
3048 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003049 if (!desc->isDuplicated() && desc->mProfile == profile) {
3050 break;
3051 }
3052 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003053 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003054 continue;
3055 }
3056
Eric Laurent83b88082014-06-20 18:31:16 -07003057 ALOGV("opening output for device %08x with params %s profile %p",
3058 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003059 desc = new AudioOutputDescriptor(profile);
3060 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003061 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3062 config.sample_rate = desc->mSamplingRate;
3063 config.channel_mask = desc->mChannelMask;
3064 config.format = desc->mFormat;
3065 config.offload_info.sample_rate = desc->mSamplingRate;
3066 config.offload_info.channel_mask = desc->mChannelMask;
3067 config.offload_info.format = desc->mFormat;
3068 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3069 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3070 &output,
3071 &config,
3072 &desc->mDevice,
3073 address,
3074 &desc->mLatency,
3075 desc->mFlags);
3076 if (status == NO_ERROR) {
3077 desc->mSamplingRate = config.sample_rate;
3078 desc->mChannelMask = config.channel_mask;
3079 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003080
Eric Laurentd4692962014-05-05 18:13:44 -07003081 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003082 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003083 char *param = audio_device_address_to_parameter(device, address);
3084 mpClientInterface->setParameters(output, String8(param));
3085 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003086 }
3087
Eric Laurentd4692962014-05-05 18:13:44 -07003088 // Here is where we step through and resolve any "dynamic" fields
3089 String8 reply;
3090 char *value;
3091 if (profile->mSamplingRates[0] == 0) {
3092 reply = mpClientInterface->getParameters(output,
3093 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003094 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003095 reply.string());
3096 value = strpbrk((char *)reply.string(), "=");
3097 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003098 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003099 }
Eric Laurentd4692962014-05-05 18:13:44 -07003100 }
3101 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3102 reply = mpClientInterface->getParameters(output,
3103 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003104 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003105 reply.string());
3106 value = strpbrk((char *)reply.string(), "=");
3107 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003108 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003109 }
Eric Laurentd4692962014-05-05 18:13:44 -07003110 }
3111 if (profile->mChannelMasks[0] == 0) {
3112 reply = mpClientInterface->getParameters(output,
3113 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003114 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003115 reply.string());
3116 value = strpbrk((char *)reply.string(), "=");
3117 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003118 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003119 }
Eric Laurentd4692962014-05-05 18:13:44 -07003120 }
3121 if (((profile->mSamplingRates[0] == 0) &&
3122 (profile->mSamplingRates.size() < 2)) ||
3123 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3124 (profile->mFormats.size() < 2)) ||
3125 ((profile->mChannelMasks[0] == 0) &&
3126 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003127 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003128 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003129 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003130 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3131 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003132 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003133 config.sample_rate = profile->pickSamplingRate();
3134 config.channel_mask = profile->pickChannelMask();
3135 config.format = profile->pickFormat();
3136 config.offload_info.sample_rate = config.sample_rate;
3137 config.offload_info.channel_mask = config.channel_mask;
3138 config.offload_info.format = config.format;
3139 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3140 &output,
3141 &config,
3142 &desc->mDevice,
3143 address,
3144 &desc->mLatency,
3145 desc->mFlags);
3146 if (status == NO_ERROR) {
3147 desc->mSamplingRate = config.sample_rate;
3148 desc->mChannelMask = config.channel_mask;
3149 desc->mFormat = config.format;
3150 } else {
3151 output = AUDIO_IO_HANDLE_NONE;
3152 }
Eric Laurentd4692962014-05-05 18:13:44 -07003153 }
3154
Eric Laurentcf2c0212014-07-25 16:20:43 -07003155 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003156 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003157 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003158 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003159
Eric Laurentd4692962014-05-05 18:13:44 -07003160 // set initial stream volume for device
3161 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003162
Eric Laurentd4692962014-05-05 18:13:44 -07003163 //TODO: configure audio effect output stage here
3164
3165 // open a duplicating output thread for the new output and the primary output
3166 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3167 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003168 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003169 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003170 sp<AudioOutputDescriptor> dupOutputDesc =
3171 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003172 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3173 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3174 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3175 dupOutputDesc->mFormat = desc->mFormat;
3176 dupOutputDesc->mChannelMask = desc->mChannelMask;
3177 dupOutputDesc->mLatency = desc->mLatency;
3178 addOutput(duplicatedOutput, dupOutputDesc);
3179 applyStreamVolumes(duplicatedOutput, device, 0, true);
3180 } else {
3181 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3182 mPrimaryOutput, output);
3183 mpClientInterface->closeOutput(output);
3184 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003186 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003187 }
Eric Laurente552edb2014-03-10 17:42:56 -07003188 }
3189 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003190 } else {
3191 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003192 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003193 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003194 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003195 profiles.removeAt(profile_index);
3196 profile_index--;
3197 } else {
3198 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003199 if (deviceDistinguishesOnAddress(device)) {
3200 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3201 device, address.string());
3202 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3203 NULL/*patch handle*/, address.string());
3204 }
Eric Laurente552edb2014-03-10 17:42:56 -07003205 ALOGV("checkOutputsForDevice(): adding output %d", output);
3206 }
3207 }
3208
3209 if (profiles.isEmpty()) {
3210 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3211 return BAD_VALUE;
3212 }
Eric Laurentd4692962014-05-05 18:13:44 -07003213 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003214 // check if one opened output is not needed any more after disconnecting one device
3215 for (size_t i = 0; i < mOutputs.size(); i++) {
3216 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003217 if (!desc->isDuplicated()) {
3218 if (!(desc->mProfile->mSupportedDevices.types()
3219 & mAvailableOutputDevices.types())) {
3220 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3221 mOutputs.keyAt(i));
3222 outputs.add(mOutputs.keyAt(i));
3223 } else if (deviceDistinguishesOnAddress(device) &&
3224 // exact match on device
3225 (desc->mProfile->mSupportedDevices.types() == device)) {
3226 findIoHandlesByAddress(desc, address, outputs);
3227 }
Eric Laurente552edb2014-03-10 17:42:56 -07003228 }
3229 }
Eric Laurentd4692962014-05-05 18:13:44 -07003230 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003231 for (size_t i = 0; i < mHwModules.size(); i++)
3232 {
3233 if (mHwModules[i]->mHandle == 0) {
3234 continue;
3235 }
3236 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3237 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003238 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003239 if (profile->mSupportedDevices.types() & device) {
3240 ALOGV("checkOutputsForDevice(): "
3241 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003242 if (profile->mSamplingRates[0] == 0) {
3243 profile->mSamplingRates.clear();
3244 profile->mSamplingRates.add(0);
3245 }
3246 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3247 profile->mFormats.clear();
3248 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3249 }
3250 if (profile->mChannelMasks[0] == 0) {
3251 profile->mChannelMasks.clear();
3252 profile->mChannelMasks.add(0);
3253 }
3254 }
3255 }
3256 }
3257 }
3258 return NO_ERROR;
3259}
3260
Eric Laurentd4692962014-05-05 18:13:44 -07003261status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3262 audio_policy_dev_state_t state,
3263 SortedVector<audio_io_handle_t>& inputs,
3264 const String8 address)
3265{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003266 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003267 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3268 // first list already open inputs that can be routed to this device
3269 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3270 desc = mInputs.valueAt(input_index);
3271 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3272 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3273 inputs.add(mInputs.keyAt(input_index));
3274 }
3275 }
3276
3277 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003278 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003279 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3280 {
3281 if (mHwModules[module_idx]->mHandle == 0) {
3282 continue;
3283 }
3284 for (size_t profile_index = 0;
3285 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3286 profile_index++)
3287 {
3288 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3289 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003290 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003291 profile_index, module_idx);
3292 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3293 }
3294 }
3295 }
3296
3297 if (profiles.isEmpty() && inputs.isEmpty()) {
3298 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3299 return BAD_VALUE;
3300 }
3301
3302 // open inputs for matching profiles if needed. Direct inputs are also opened to
3303 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3304 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3305
Eric Laurent1c333e22014-05-20 10:48:17 -07003306 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003307 // nothing to do if one input is already opened for this profile
3308 size_t input_index;
3309 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3310 desc = mInputs.valueAt(input_index);
3311 if (desc->mProfile == profile) {
3312 break;
3313 }
3314 }
3315 if (input_index != mInputs.size()) {
3316 continue;
3317 }
3318
3319 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3320 desc = new AudioInputDescriptor(profile);
3321 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003322 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3323 config.sample_rate = desc->mSamplingRate;
3324 config.channel_mask = desc->mChannelMask;
3325 config.format = desc->mFormat;
3326 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3327 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3328 &input,
3329 &config,
3330 &desc->mDevice,
3331 address,
3332 AUDIO_SOURCE_MIC,
3333 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003334
Eric Laurentcf2c0212014-07-25 16:20:43 -07003335 if (status == NO_ERROR) {
3336 desc->mSamplingRate = config.sample_rate;
3337 desc->mChannelMask = config.channel_mask;
3338 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003339
Eric Laurentd4692962014-05-05 18:13:44 -07003340 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003341 char *param = audio_device_address_to_parameter(device, address);
3342 mpClientInterface->setParameters(input, String8(param));
3343 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003344 }
3345
3346 // Here is where we step through and resolve any "dynamic" fields
3347 String8 reply;
3348 char *value;
3349 if (profile->mSamplingRates[0] == 0) {
3350 reply = mpClientInterface->getParameters(input,
3351 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3352 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3353 reply.string());
3354 value = strpbrk((char *)reply.string(), "=");
3355 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003356 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003357 }
3358 }
3359 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3360 reply = mpClientInterface->getParameters(input,
3361 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3362 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3363 value = strpbrk((char *)reply.string(), "=");
3364 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003365 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003366 }
3367 }
3368 if (profile->mChannelMasks[0] == 0) {
3369 reply = mpClientInterface->getParameters(input,
3370 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3371 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3372 reply.string());
3373 value = strpbrk((char *)reply.string(), "=");
3374 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003375 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003376 }
3377 }
3378 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3379 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3380 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3381 ALOGW("checkInputsForDevice() direct input missing param");
3382 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003383 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003384 }
3385
3386 if (input != 0) {
3387 addInput(input, desc);
3388 }
3389 } // endif input != 0
3390
Eric Laurentcf2c0212014-07-25 16:20:43 -07003391 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003392 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003393 profiles.removeAt(profile_index);
3394 profile_index--;
3395 } else {
3396 inputs.add(input);
3397 ALOGV("checkInputsForDevice(): adding input %d", input);
3398 }
3399 } // end scan profiles
3400
3401 if (profiles.isEmpty()) {
3402 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3403 return BAD_VALUE;
3404 }
3405 } else {
3406 // Disconnect
3407 // check if one opened input is not needed any more after disconnecting one device
3408 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3409 desc = mInputs.valueAt(input_index);
3410 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3411 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3412 mInputs.keyAt(input_index));
3413 inputs.add(mInputs.keyAt(input_index));
3414 }
3415 }
3416 // Clear any profiles associated with the disconnected device.
3417 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3418 if (mHwModules[module_index]->mHandle == 0) {
3419 continue;
3420 }
3421 for (size_t profile_index = 0;
3422 profile_index < mHwModules[module_index]->mInputProfiles.size();
3423 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003424 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003425 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003426 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003427 profile_index, module_index);
3428 if (profile->mSamplingRates[0] == 0) {
3429 profile->mSamplingRates.clear();
3430 profile->mSamplingRates.add(0);
3431 }
3432 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3433 profile->mFormats.clear();
3434 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3435 }
3436 if (profile->mChannelMasks[0] == 0) {
3437 profile->mChannelMasks.clear();
3438 profile->mChannelMasks.add(0);
3439 }
3440 }
3441 }
3442 }
3443 } // end disconnect
3444
3445 return NO_ERROR;
3446}
3447
3448
Eric Laurente0720872014-03-11 09:30:41 -07003449void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003450{
3451 ALOGV("closeOutput(%d)", output);
3452
Eric Laurent1f2f2232014-06-02 12:01:23 -07003453 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003454 if (outputDesc == NULL) {
3455 ALOGW("closeOutput() unknown output %d", output);
3456 return;
3457 }
3458
3459 // look for duplicated outputs connected to the output being removed.
3460 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003461 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003462 if (dupOutputDesc->isDuplicated() &&
3463 (dupOutputDesc->mOutput1 == outputDesc ||
3464 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003465 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003466 if (dupOutputDesc->mOutput1 == outputDesc) {
3467 outputDesc2 = dupOutputDesc->mOutput2;
3468 } else {
3469 outputDesc2 = dupOutputDesc->mOutput1;
3470 }
3471 // As all active tracks on duplicated output will be deleted,
3472 // and as they were also referenced on the other output, the reference
3473 // count for their stream type must be adjusted accordingly on
3474 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003475 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003476 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003477 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003478 }
3479 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3480 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3481
3482 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003483 mOutputs.removeItem(duplicatedOutput);
3484 }
3485 }
3486
3487 AudioParameter param;
3488 param.add(String8("closing"), String8("true"));
3489 mpClientInterface->setParameters(output, param.toString());
3490
3491 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003492 mOutputs.removeItem(output);
3493 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003494 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003495}
3496
Eric Laurente0720872014-03-11 09:30:41 -07003497SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003498 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003499{
3500 SortedVector<audio_io_handle_t> outputs;
3501
3502 ALOGVV("getOutputsForDevice() device %04x", device);
3503 for (size_t i = 0; i < openOutputs.size(); i++) {
3504 ALOGVV("output %d isDuplicated=%d device=%04x",
3505 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3506 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3507 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3508 outputs.add(openOutputs.keyAt(i));
3509 }
3510 }
3511 return outputs;
3512}
3513
Eric Laurente0720872014-03-11 09:30:41 -07003514bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003515 SortedVector<audio_io_handle_t>& outputs2)
3516{
3517 if (outputs1.size() != outputs2.size()) {
3518 return false;
3519 }
3520 for (size_t i = 0; i < outputs1.size(); i++) {
3521 if (outputs1[i] != outputs2[i]) {
3522 return false;
3523 }
3524 }
3525 return true;
3526}
3527
Eric Laurente0720872014-03-11 09:30:41 -07003528void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003529{
3530 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3531 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3532 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3533 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3534
3535 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3536 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3537 strategy, srcOutputs[0], dstOutputs[0]);
3538 // mute strategy while moving tracks from one output to another
3539 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003540 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003541 if (desc->isStrategyActive(strategy)) {
3542 setStrategyMute(strategy, true, srcOutputs[i]);
3543 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3544 }
3545 }
3546
3547 // Move effects associated to this strategy from previous output to new output
3548 if (strategy == STRATEGY_MEDIA) {
3549 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3550 SortedVector<audio_io_handle_t> moved;
3551 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003552 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3553 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3554 effectDesc->mIo != fxOutput) {
3555 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003556 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3557 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003558 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003559 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003560 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003561 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003562 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003563 }
3564 }
3565 }
3566 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003567 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3568 if (getStrategy((audio_stream_type_t)i) == strategy) {
3569 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003570 }
3571 }
3572 }
3573}
3574
Eric Laurente0720872014-03-11 09:30:41 -07003575void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003576{
3577 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3578 checkOutputForStrategy(STRATEGY_PHONE);
3579 checkOutputForStrategy(STRATEGY_SONIFICATION);
3580 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3581 checkOutputForStrategy(STRATEGY_MEDIA);
3582 checkOutputForStrategy(STRATEGY_DTMF);
3583}
3584
Eric Laurente0720872014-03-11 09:30:41 -07003585audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003586{
Eric Laurente552edb2014-03-10 17:42:56 -07003587 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003588 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003589 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3590 return mOutputs.keyAt(i);
3591 }
3592 }
3593
3594 return 0;
3595}
3596
Eric Laurente0720872014-03-11 09:30:41 -07003597void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003598{
Eric Laurente552edb2014-03-10 17:42:56 -07003599 audio_io_handle_t a2dpOutput = getA2dpOutput();
3600 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003601 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003602 return;
3603 }
3604
Eric Laurent3a4311c2014-03-17 12:00:47 -07003605 bool isScoConnected =
3606 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003607 // suspend A2DP output if:
3608 // (NOT already suspended) &&
3609 // ((SCO device is connected &&
3610 // (forced usage for communication || for record is SCO))) ||
3611 // (phone state is ringing || in call)
3612 //
3613 // restore A2DP output if:
3614 // (Already suspended) &&
3615 // ((SCO device is NOT connected ||
3616 // (forced usage NOT for communication && NOT for record is SCO))) &&
3617 // (phone state is NOT ringing && NOT in call)
3618 //
3619 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003620 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003621 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3622 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3623 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3624 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003625
3626 mpClientInterface->restoreOutput(a2dpOutput);
3627 mA2dpSuspended = false;
3628 }
3629 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003630 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003631 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3632 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3633 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3634 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003635
3636 mpClientInterface->suspendOutput(a2dpOutput);
3637 mA2dpSuspended = true;
3638 }
3639 }
3640}
3641
Eric Laurent1c333e22014-05-20 10:48:17 -07003642audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003643{
3644 audio_devices_t device = AUDIO_DEVICE_NONE;
3645
Eric Laurent1f2f2232014-06-02 12:01:23 -07003646 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003647
3648 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3649 if (index >= 0) {
3650 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3651 if (patchDesc->mUid != mUidCached) {
3652 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3653 outputDesc->device(), outputDesc->mPatchHandle);
3654 return outputDesc->device();
3655 }
3656 }
3657
Eric Laurente552edb2014-03-10 17:42:56 -07003658 // check the following by order of priority to request a routing change if necessary:
3659 // 1: the strategy enforced audible is active on the output:
3660 // use device for strategy enforced audible
3661 // 2: we are in call or the strategy phone is active on the output:
3662 // use device for strategy phone
3663 // 3: the strategy sonification is active on the output:
3664 // use device for strategy sonification
3665 // 4: the strategy "respectful" sonification is active on the output:
3666 // use device for strategy "respectful" sonification
3667 // 5: the strategy media is active on the output:
3668 // use device for strategy media
3669 // 6: the strategy DTMF is active on the output:
3670 // use device for strategy DTMF
3671 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3672 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3673 } else if (isInCall() ||
3674 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3675 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3676 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3677 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3678 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3679 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3680 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3681 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3682 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3683 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3684 }
3685
Eric Laurent1c333e22014-05-20 10:48:17 -07003686 ALOGV("getNewOutputDevice() selected device %x", device);
3687 return device;
3688}
3689
3690audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3691{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003692 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003693
3694 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3695 if (index >= 0) {
3696 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3697 if (patchDesc->mUid != mUidCached) {
3698 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3699 inputDesc->mDevice, inputDesc->mPatchHandle);
3700 return inputDesc->mDevice;
3701 }
3702 }
3703
Eric Laurent1c333e22014-05-20 10:48:17 -07003704 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3705
3706 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003707 return device;
3708}
3709
Eric Laurente0720872014-03-11 09:30:41 -07003710uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003711 return (uint32_t)getStrategy(stream);
3712}
3713
Eric Laurente0720872014-03-11 09:30:41 -07003714audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003715 // By checking the range of stream before calling getStrategy, we avoid
3716 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3717 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003718 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003719 return AUDIO_DEVICE_NONE;
3720 }
3721 audio_devices_t devices;
3722 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3723 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3724 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3725 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003726 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003727 if (outputDesc->isStrategyActive(strategy)) {
3728 devices = outputDesc->device();
3729 break;
3730 }
Eric Laurente552edb2014-03-10 17:42:56 -07003731 }
3732 return devices;
3733}
3734
Eric Laurente0720872014-03-11 09:30:41 -07003735AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003736 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003737 // stream to strategy mapping
3738 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003739 case AUDIO_STREAM_VOICE_CALL:
3740 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003741 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003742 case AUDIO_STREAM_RING:
3743 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003744 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003745 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003746 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003747 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003748 return STRATEGY_DTMF;
3749 default:
3750 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003751 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003752 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3753 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003754 case AUDIO_STREAM_TTS:
3755 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003756 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003757 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003758 return STRATEGY_ENFORCED_AUDIBLE;
3759 }
3760}
3761
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003762uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3763 // flags to strategy mapping
3764 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3765 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3766 }
3767
3768 // usage to strategy mapping
3769 switch (attr->usage) {
3770 case AUDIO_USAGE_MEDIA:
3771 case AUDIO_USAGE_GAME:
3772 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3773 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3774 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3775 return (uint32_t) STRATEGY_MEDIA;
3776
3777 case AUDIO_USAGE_VOICE_COMMUNICATION:
3778 return (uint32_t) STRATEGY_PHONE;
3779
3780 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3781 return (uint32_t) STRATEGY_DTMF;
3782
3783 case AUDIO_USAGE_ALARM:
3784 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3785 return (uint32_t) STRATEGY_SONIFICATION;
3786
3787 case AUDIO_USAGE_NOTIFICATION:
3788 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3789 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3790 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3791 case AUDIO_USAGE_NOTIFICATION_EVENT:
3792 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3793
3794 case AUDIO_USAGE_UNKNOWN:
3795 default:
3796 return (uint32_t) STRATEGY_MEDIA;
3797 }
3798}
3799
Eric Laurente0720872014-03-11 09:30:41 -07003800void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003801 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003802 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003803 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3804 updateDevicesAndOutputs();
3805 break;
3806 default:
3807 break;
3808 }
3809}
3810
Eric Laurente0720872014-03-11 09:30:41 -07003811audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003812 bool fromCache)
3813{
3814 uint32_t device = AUDIO_DEVICE_NONE;
3815
3816 if (fromCache) {
3817 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3818 strategy, mDeviceForStrategy[strategy]);
3819 return mDeviceForStrategy[strategy];
3820 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003821 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003822 switch (strategy) {
3823
3824 case STRATEGY_SONIFICATION_RESPECTFUL:
3825 if (isInCall()) {
3826 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003827 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003828 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3829 // while media is playing on a remote device, use the the sonification behavior.
3830 // Note that we test this usecase before testing if media is playing because
3831 // the isStreamActive() method only informs about the activity of a stream, not
3832 // if it's for local playback. Note also that we use the same delay between both tests
3833 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003834 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003835 // while media is playing (or has recently played), use the same device
3836 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3837 } else {
3838 // when media is not playing anymore, fall back on the sonification behavior
3839 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3840 }
3841
3842 break;
3843
3844 case STRATEGY_DTMF:
3845 if (!isInCall()) {
3846 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3847 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3848 break;
3849 }
3850 // when in call, DTMF and PHONE strategies follow the same rules
3851 // FALL THROUGH
3852
3853 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003854 // Force use of only devices on primary output if:
3855 // - in call AND
3856 // - cannot route from voice call RX OR
3857 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3858 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3859 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3860 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3861 if (((mAvailableInputDevices.types() &
3862 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3863 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
3864 (hwOutputDesc->mAudioPort->mModule->mHalVersion <
3865 AUDIO_DEVICE_API_VERSION_3_0))) {
3866 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3867 }
3868 }
Eric Laurente552edb2014-03-10 17:42:56 -07003869 // for phone strategy, we first consider the forced use and then the available devices by order
3870 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003871 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3872 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003873 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003874 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003875 if (device) break;
3876 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003877 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003878 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003879 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003880 if (device) break;
3881 // if SCO device is requested but no SCO device is available, fall back to default case
3882 // FALL THROUGH
3883
3884 default: // FORCE_NONE
3885 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003886 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003887 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003888 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003889 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003890 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003891 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003892 if (device) break;
3893 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003894 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003895 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003896 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003897 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07003898 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3899 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003900 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003901 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003902 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003903 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003904 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003905 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003906 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003907 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003908 if (device) break;
3909 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003910 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003911 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003912 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003913 if (device == AUDIO_DEVICE_NONE) {
3914 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3915 }
3916 break;
3917
Eric Laurent3b73df72014-03-11 09:06:29 -07003918 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003919 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3920 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003923 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003924 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003925 if (device) break;
3926 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003927 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003928 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003929 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003930 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003931 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003932 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003933 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003934 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003935 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003937 if (device) break;
3938 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003939 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3940 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003941 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003942 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003943 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003944 if (device == AUDIO_DEVICE_NONE) {
3945 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3946 }
3947 break;
3948 }
3949 break;
3950
3951 case STRATEGY_SONIFICATION:
3952
3953 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3954 // handleIncallSonification().
3955 if (isInCall()) {
3956 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3957 break;
3958 }
3959 // FALL THROUGH
3960
3961 case STRATEGY_ENFORCED_AUDIBLE:
3962 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3963 // except:
3964 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3965 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3966
3967 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003968 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003969 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003970 if (device == AUDIO_DEVICE_NONE) {
3971 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3972 }
3973 }
3974 // The second device used for sonification is the same as the device used by media strategy
3975 // FALL THROUGH
3976
3977 case STRATEGY_MEDIA: {
3978 uint32_t device2 = AUDIO_DEVICE_NONE;
3979 if (strategy != STRATEGY_SONIFICATION) {
3980 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003981 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003982 }
3983 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003984 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003985 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003986 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003987 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003988 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003989 }
3990 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003991 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003992 }
3993 }
3994 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003995 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003996 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003997 if ((device2 == AUDIO_DEVICE_NONE)) {
3998 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3999 }
Eric Laurente552edb2014-03-10 17:42:56 -07004000 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004001 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004002 }
4003 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004004 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004005 }
4006 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004007 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004008 }
4009 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004010 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004011 }
4012 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4013 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004014 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004015 }
4016 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004017 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004018 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004019 }
4020 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004021 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004022 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004023 int device3 = AUDIO_DEVICE_NONE;
4024 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004025 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004026 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4027 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004028 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004029 }
Eric Laurente552edb2014-03-10 17:42:56 -07004030
Jungshik Jang839e4f32014-06-26 17:23:40 +09004031 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004032 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4033 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4034 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004035
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004036 // If hdmi system audio mode is on, remove speaker out of output list.
4037 if ((strategy == STRATEGY_MEDIA) &&
4038 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4039 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4040 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4041 }
4042
Eric Laurente552edb2014-03-10 17:42:56 -07004043 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004044 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device == AUDIO_DEVICE_NONE) {
4046 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4047 }
4048 } break;
4049
4050 default:
4051 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4052 break;
4053 }
4054
4055 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4056 return device;
4057}
4058
Eric Laurente0720872014-03-11 09:30:41 -07004059void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004060{
4061 for (int i = 0; i < NUM_STRATEGIES; i++) {
4062 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4063 }
4064 mPreviousOutputs = mOutputs;
4065}
4066
Eric Laurent1f2f2232014-06-02 12:01:23 -07004067uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004068 audio_devices_t prevDevice,
4069 uint32_t delayMs)
4070{
4071 // mute/unmute strategies using an incompatible device combination
4072 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4073 // if unmuting, unmute only after the specified delay
4074 if (outputDesc->isDuplicated()) {
4075 return 0;
4076 }
4077
4078 uint32_t muteWaitMs = 0;
4079 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004080 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004081
4082 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4083 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4084 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4085 bool doMute = false;
4086
4087 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4088 doMute = true;
4089 outputDesc->mStrategyMutedByDevice[i] = true;
4090 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4091 doMute = true;
4092 outputDesc->mStrategyMutedByDevice[i] = false;
4093 }
Eric Laurent99401132014-05-07 19:48:15 -07004094 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004095 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004096 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004097 // skip output if it does not share any device with current output
4098 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4099 == AUDIO_DEVICE_NONE) {
4100 continue;
4101 }
4102 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4103 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4104 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4105 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4106 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004107 if (mute) {
4108 // FIXME: should not need to double latency if volume could be applied
4109 // immediately by the audioflinger mixer. We must account for the delay
4110 // between now and the next time the audioflinger thread for this output
4111 // will process a buffer (which corresponds to one buffer size,
4112 // usually 1/2 or 1/4 of the latency).
4113 if (muteWaitMs < desc->latency() * 2) {
4114 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004115 }
4116 }
4117 }
4118 }
4119 }
4120 }
4121
Eric Laurent99401132014-05-07 19:48:15 -07004122 // temporary mute output if device selection changes to avoid volume bursts due to
4123 // different per device volumes
4124 if (outputDesc->isActive() && (device != prevDevice)) {
4125 if (muteWaitMs < outputDesc->latency() * 2) {
4126 muteWaitMs = outputDesc->latency() * 2;
4127 }
4128 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4129 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004130 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004131 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004132 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004133 muteWaitMs *2, device);
4134 }
4135 }
4136 }
4137
Eric Laurente552edb2014-03-10 17:42:56 -07004138 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4139 if (muteWaitMs > delayMs) {
4140 muteWaitMs -= delayMs;
4141 usleep(muteWaitMs * 1000);
4142 return muteWaitMs;
4143 }
4144 return 0;
4145}
4146
Eric Laurente0720872014-03-11 09:30:41 -07004147uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004148 audio_devices_t device,
4149 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004150 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004151 audio_patch_handle_t *patchHandle,
4152 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004153{
4154 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004155 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004156 AudioParameter param;
4157 uint32_t muteWaitMs;
4158
4159 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004160 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4161 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004162 return muteWaitMs;
4163 }
4164 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4165 // output profile
4166 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004167 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004168 return 0;
4169 }
4170
4171 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004173
4174 audio_devices_t prevDevice = outputDesc->mDevice;
4175
4176 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4177
4178 if (device != AUDIO_DEVICE_NONE) {
4179 outputDesc->mDevice = device;
4180 }
4181 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4182
4183 // Do not change the routing if:
4184 // - the requested device is AUDIO_DEVICE_NONE
4185 // - the requested device is the same as current device and force is not specified.
4186 // Doing this check here allows the caller to call setOutputDevice() without conditions
4187 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4188 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4189 return muteWaitMs;
4190 }
4191
4192 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004193
Eric Laurente552edb2014-03-10 17:42:56 -07004194 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004195 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004197 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004198 DeviceVector deviceList = (address == NULL) ?
4199 mAvailableOutputDevices.getDevicesFromType(device)
4200 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004201 if (!deviceList.isEmpty()) {
4202 struct audio_patch patch;
4203 outputDesc->toAudioPortConfig(&patch.sources[0]);
4204 patch.num_sources = 1;
4205 patch.num_sinks = 0;
4206 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4207 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004208 patch.num_sinks++;
4209 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 ssize_t index;
4211 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4212 index = mAudioPatches.indexOfKey(*patchHandle);
4213 } else {
4214 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4215 }
4216 sp< AudioPatch> patchDesc;
4217 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4218 if (index >= 0) {
4219 patchDesc = mAudioPatches.valueAt(index);
4220 afPatchHandle = patchDesc->mAfPatchHandle;
4221 }
4222
Eric Laurent1c333e22014-05-20 10:48:17 -07004223 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004224 &afPatchHandle,
4225 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004226 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4227 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004229 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004230 if (index < 0) {
4231 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4232 &patch, mUidCached);
4233 addAudioPatch(patchDesc->mHandle, patchDesc);
4234 } else {
4235 patchDesc->mPatch = patch;
4236 }
4237 patchDesc->mAfPatchHandle = afPatchHandle;
4238 patchDesc->mUid = mUidCached;
4239 if (patchHandle) {
4240 *patchHandle = patchDesc->mHandle;
4241 }
4242 outputDesc->mPatchHandle = patchDesc->mHandle;
4243 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004244 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004245 }
4246 }
4247 }
Eric Laurente552edb2014-03-10 17:42:56 -07004248
4249 // update stream volumes according to new device
4250 applyStreamVolumes(output, device, delayMs);
4251
4252 return muteWaitMs;
4253}
4254
Eric Laurent1c333e22014-05-20 10:48:17 -07004255status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004256 int delayMs,
4257 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004258{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004259 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004260 ssize_t index;
4261 if (patchHandle) {
4262 index = mAudioPatches.indexOfKey(*patchHandle);
4263 } else {
4264 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4265 }
4266 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004267 return INVALID_OPERATION;
4268 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004269 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4270 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004271 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4272 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004273 removeAudioPatch(patchDesc->mHandle);
4274 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004275 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004276 return status;
4277}
4278
4279status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4280 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004281 bool force,
4282 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004283{
4284 status_t status = NO_ERROR;
4285
Eric Laurent1f2f2232014-06-02 12:01:23 -07004286 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004287 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4288 inputDesc->mDevice = device;
4289
4290 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4291 if (!deviceList.isEmpty()) {
4292 struct audio_patch patch;
4293 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004294 // AUDIO_SOURCE_HOTWORD is for internal use only:
4295 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004296 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4297 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004298 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4299 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004300 patch.num_sinks = 1;
4301 //only one input device for now
4302 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004303 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004304 ssize_t index;
4305 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4306 index = mAudioPatches.indexOfKey(*patchHandle);
4307 } else {
4308 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4309 }
4310 sp< AudioPatch> patchDesc;
4311 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4312 if (index >= 0) {
4313 patchDesc = mAudioPatches.valueAt(index);
4314 afPatchHandle = patchDesc->mAfPatchHandle;
4315 }
4316
Eric Laurent1c333e22014-05-20 10:48:17 -07004317 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004318 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004319 0);
4320 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004321 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004322 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 if (index < 0) {
4324 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4325 &patch, mUidCached);
4326 addAudioPatch(patchDesc->mHandle, patchDesc);
4327 } else {
4328 patchDesc->mPatch = patch;
4329 }
4330 patchDesc->mAfPatchHandle = afPatchHandle;
4331 patchDesc->mUid = mUidCached;
4332 if (patchHandle) {
4333 *patchHandle = patchDesc->mHandle;
4334 }
4335 inputDesc->mPatchHandle = patchDesc->mHandle;
4336 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004337 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004338 }
4339 }
4340 }
4341 return status;
4342}
4343
Eric Laurent6a94d692014-05-20 11:18:06 -07004344status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4345 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004346{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004347 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004348 ssize_t index;
4349 if (patchHandle) {
4350 index = mAudioPatches.indexOfKey(*patchHandle);
4351 } else {
4352 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4353 }
4354 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004355 return INVALID_OPERATION;
4356 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004357 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4358 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004359 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4360 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004361 removeAudioPatch(patchDesc->mHandle);
4362 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004363 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004364 return status;
4365}
4366
4367sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004368 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004369 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004370 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004371 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004372{
4373 // Choose an input profile based on the requested capture parameters: select the first available
4374 // profile supporting all requested parameters.
4375
4376 for (size_t i = 0; i < mHwModules.size(); i++)
4377 {
4378 if (mHwModules[i]->mHandle == 0) {
4379 continue;
4380 }
4381 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4382 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004383 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004384 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004385 if (profile->isCompatibleProfile(device, samplingRate,
4386 &samplingRate /*updatedSamplingRate*/,
4387 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004388 return profile;
4389 }
4390 }
4391 }
4392 return NULL;
4393}
4394
Eric Laurente0720872014-03-11 09:30:41 -07004395audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004396{
4397 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004398 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4399 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004400 switch (inputSource) {
4401 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004402 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004403 device = AUDIO_DEVICE_IN_VOICE_CALL;
4404 break;
4405 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004406 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004407
4408 case AUDIO_SOURCE_DEFAULT:
4409 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004410 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4411 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004412 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4413 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4414 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4415 device = AUDIO_DEVICE_IN_USB_DEVICE;
4416 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4417 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004418 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004419 break;
4420
4421 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4422 // Allow only use of devices on primary input if in call and HAL does not support routing
4423 // to voice call path.
4424 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4425 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4426 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4427 }
4428
4429 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4430 case AUDIO_POLICY_FORCE_BT_SCO:
4431 // if SCO device is requested but no SCO device is available, fall back to default case
4432 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4433 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4434 break;
4435 }
4436 // FALL THROUGH
4437
4438 default: // FORCE_NONE
4439 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4440 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4441 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4442 device = AUDIO_DEVICE_IN_USB_DEVICE;
4443 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4444 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4445 }
4446 break;
4447
4448 case AUDIO_POLICY_FORCE_SPEAKER:
4449 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4450 device = AUDIO_DEVICE_IN_BACK_MIC;
4451 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4452 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4453 }
4454 break;
4455 }
4456 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004457
Eric Laurente552edb2014-03-10 17:42:56 -07004458 case AUDIO_SOURCE_VOICE_RECOGNITION:
4459 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004460 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004461 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004462 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004463 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004464 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004465 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4466 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004467 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004468 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4469 }
4470 break;
4471 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004472 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004473 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004474 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004475 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4476 }
4477 break;
4478 case AUDIO_SOURCE_VOICE_DOWNLINK:
4479 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004480 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004481 device = AUDIO_DEVICE_IN_VOICE_CALL;
4482 }
4483 break;
4484 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004485 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004486 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4487 }
4488 break;
4489 default:
4490 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4491 break;
4492 }
4493 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4494 return device;
4495}
4496
Eric Laurente0720872014-03-11 09:30:41 -07004497bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004498{
4499 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4500 device &= ~AUDIO_DEVICE_BIT_IN;
4501 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4502 return true;
4503 }
4504 return false;
4505}
4506
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004507bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4508 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4509}
4510
Eric Laurente0720872014-03-11 09:30:41 -07004511audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004512{
4513 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004514 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004515 if ((input_descriptor->mRefCount > 0)
4516 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4517 return mInputs.keyAt(i);
4518 }
4519 }
4520 return 0;
4521}
4522
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004523uint32_t AudioPolicyManager::activeInputsCount() const
4524{
4525 uint32_t count = 0;
4526 for (size_t i = 0; i < mInputs.size(); i++) {
4527 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4528 if (desc->mRefCount > 0) {
4529 return count++;
4530 }
4531 }
4532 return count;
4533}
4534
Eric Laurente552edb2014-03-10 17:42:56 -07004535
Eric Laurente0720872014-03-11 09:30:41 -07004536audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004537{
4538 if (device == AUDIO_DEVICE_NONE) {
4539 // this happens when forcing a route update and no track is active on an output.
4540 // In this case the returned category is not important.
4541 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004542 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004543 // Multiple device selection is either:
4544 // - speaker + one other device: give priority to speaker in this case.
4545 // - one A2DP device + another device: happens with duplicated output. In this case
4546 // retain the device on the A2DP output as the other must not correspond to an active
4547 // selection if not the speaker.
4548 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4549 device = AUDIO_DEVICE_OUT_SPEAKER;
4550 } else {
4551 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4552 }
4553 }
4554
Eric Laurent3b73df72014-03-11 09:06:29 -07004555 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004556 "getDeviceForVolume() invalid device combination: %08x",
4557 device);
4558
4559 return device;
4560}
4561
Eric Laurente0720872014-03-11 09:30:41 -07004562AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004563{
4564 switch(getDeviceForVolume(device)) {
4565 case AUDIO_DEVICE_OUT_EARPIECE:
4566 return DEVICE_CATEGORY_EARPIECE;
4567 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4568 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4569 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4570 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4571 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4572 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4573 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004574 case AUDIO_DEVICE_OUT_LINE:
4575 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4576 /*USB? Remote submix?*/
4577 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004578 case AUDIO_DEVICE_OUT_SPEAKER:
4579 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4580 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004581 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4582 case AUDIO_DEVICE_OUT_USB_DEVICE:
4583 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4584 default:
4585 return DEVICE_CATEGORY_SPEAKER;
4586 }
4587}
4588
Eric Laurente0720872014-03-11 09:30:41 -07004589float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004590 int indexInUi)
4591{
4592 device_category deviceCategory = getDeviceCategory(device);
4593 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4594
4595 // the volume index in the UI is relative to the min and max volume indices for this stream type
4596 int nbSteps = 1 + curve[VOLMAX].mIndex -
4597 curve[VOLMIN].mIndex;
4598 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4599 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4600
4601 // find what part of the curve this index volume belongs to, or if it's out of bounds
4602 int segment = 0;
4603 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4604 return 0.0f;
4605 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4606 segment = 0;
4607 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4608 segment = 1;
4609 } else if (volIdx <= curve[VOLMAX].mIndex) {
4610 segment = 2;
4611 } else { // out of bounds
4612 return 1.0f;
4613 }
4614
4615 // linear interpolation in the attenuation table in dB
4616 float decibels = curve[segment].mDBAttenuation +
4617 ((float)(volIdx - curve[segment].mIndex)) *
4618 ( (curve[segment+1].mDBAttenuation -
4619 curve[segment].mDBAttenuation) /
4620 ((float)(curve[segment+1].mIndex -
4621 curve[segment].mIndex)) );
4622
4623 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4624
4625 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4626 curve[segment].mIndex, volIdx,
4627 curve[segment+1].mIndex,
4628 curve[segment].mDBAttenuation,
4629 decibels,
4630 curve[segment+1].mDBAttenuation,
4631 amplification);
4632
4633 return amplification;
4634}
4635
Eric Laurente0720872014-03-11 09:30:41 -07004636const AudioPolicyManager::VolumeCurvePoint
4637 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004638 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4639};
4640
Eric Laurente0720872014-03-11 09:30:41 -07004641const AudioPolicyManager::VolumeCurvePoint
4642 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004643 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4644};
4645
Eric Laurente0720872014-03-11 09:30:41 -07004646const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004647 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4648 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4649};
4650
4651const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004652 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004653 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4654};
4655
Eric Laurente0720872014-03-11 09:30:41 -07004656const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004657 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004658 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004659};
4660
4661const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004662 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004663 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4664};
4665
Eric Laurente0720872014-03-11 09:30:41 -07004666const AudioPolicyManager::VolumeCurvePoint
4667 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004668 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4669};
4670
4671// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4672// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4673// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4674// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4675
Eric Laurente0720872014-03-11 09:30:41 -07004676const AudioPolicyManager::VolumeCurvePoint
4677 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004678 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4679};
4680
Eric Laurente0720872014-03-11 09:30:41 -07004681const AudioPolicyManager::VolumeCurvePoint
4682 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004683 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4684};
4685
Eric Laurente0720872014-03-11 09:30:41 -07004686const AudioPolicyManager::VolumeCurvePoint
4687 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004688 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4689};
4690
Eric Laurente0720872014-03-11 09:30:41 -07004691const AudioPolicyManager::VolumeCurvePoint
4692 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004693 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4694};
4695
Eric Laurente0720872014-03-11 09:30:41 -07004696const AudioPolicyManager::VolumeCurvePoint
4697 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004698 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4699};
4700
Eric Laurente0720872014-03-11 09:30:41 -07004701const AudioPolicyManager::VolumeCurvePoint
4702 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4703 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004704 { // AUDIO_STREAM_VOICE_CALL
4705 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4706 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004707 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4708 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004709 },
4710 { // AUDIO_STREAM_SYSTEM
4711 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4712 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004713 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4714 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004715 },
4716 { // AUDIO_STREAM_RING
4717 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4718 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004719 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4720 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004721 },
4722 { // AUDIO_STREAM_MUSIC
4723 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4724 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004725 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4726 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004727 },
4728 { // AUDIO_STREAM_ALARM
4729 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4730 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004731 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4732 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004733 },
4734 { // AUDIO_STREAM_NOTIFICATION
4735 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4736 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004737 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4738 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004739 },
4740 { // AUDIO_STREAM_BLUETOOTH_SCO
4741 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4742 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004743 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4744 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004745 },
4746 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4747 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4748 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004749 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4750 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004751 },
4752 { // AUDIO_STREAM_DTMF
4753 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4754 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004755 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4756 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004757 },
4758 { // AUDIO_STREAM_TTS
4759 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4760 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004761 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4762 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004763 },
4764};
4765
Eric Laurente0720872014-03-11 09:30:41 -07004766void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004767{
4768 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4769 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4770 mStreams[i].mVolumeCurve[j] =
4771 sVolumeProfiles[i][j];
4772 }
4773 }
4774
4775 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4776 if (mSpeakerDrcEnabled) {
4777 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4778 sDefaultSystemVolumeCurveDrc;
4779 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4780 sSpeakerSonificationVolumeCurveDrc;
4781 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4782 sSpeakerSonificationVolumeCurveDrc;
4783 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4784 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004785 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4786 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004787 }
4788}
4789
Eric Laurente0720872014-03-11 09:30:41 -07004790float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004791 int index,
4792 audio_io_handle_t output,
4793 audio_devices_t device)
4794{
4795 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004796 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004797 StreamDescriptor &streamDesc = mStreams[stream];
4798
4799 if (device == AUDIO_DEVICE_NONE) {
4800 device = outputDesc->device();
4801 }
4802
Eric Laurente552edb2014-03-10 17:42:56 -07004803 volume = volIndexToAmpl(device, streamDesc, index);
4804
4805 // if a headset is connected, apply the following rules to ring tones and notifications
4806 // to avoid sound level bursts in user's ears:
4807 // - always attenuate ring tones and notifications volume by 6dB
4808 // - if music is playing, always limit the volume to current music volume,
4809 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004810 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004811 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4812 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4813 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4814 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4815 ((stream_strategy == STRATEGY_SONIFICATION)
4816 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004817 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004818 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004819 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004820 streamDesc.mCanBeMuted) {
4821 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4822 // when the phone is ringing we must consider that music could have been paused just before
4823 // by the music application and behave as if music was active if the last music track was
4824 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004825 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004826 mLimitRingtoneVolume) {
4827 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004828 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4829 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004830 output,
4831 musicDevice);
4832 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4833 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4834 if (volume > minVol) {
4835 volume = minVol;
4836 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4837 }
4838 }
4839 }
4840
4841 return volume;
4842}
4843
Eric Laurente0720872014-03-11 09:30:41 -07004844status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004845 int index,
4846 audio_io_handle_t output,
4847 audio_devices_t device,
4848 int delayMs,
4849 bool force)
4850{
4851
4852 // do not change actual stream volume if the stream is muted
4853 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4854 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4855 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4856 return NO_ERROR;
4857 }
4858
4859 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004860 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4861 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4862 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4863 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004865 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004866 return INVALID_OPERATION;
4867 }
4868
4869 float volume = computeVolume(stream, index, output, device);
4870 // We actually change the volume if:
4871 // - the float value returned by computeVolume() changed
4872 // - the force flag is set
4873 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4874 force) {
4875 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4876 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4877 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4878 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004879 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4880 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004881 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004882 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004883 }
4884
Eric Laurent3b73df72014-03-11 09:06:29 -07004885 if (stream == AUDIO_STREAM_VOICE_CALL ||
4886 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004887 float voiceVolume;
4888 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004889 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004890 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4891 } else {
4892 voiceVolume = 1.0;
4893 }
4894
4895 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4896 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4897 mLastVoiceVolume = voiceVolume;
4898 }
4899 }
4900
4901 return NO_ERROR;
4902}
4903
Eric Laurente0720872014-03-11 09:30:41 -07004904void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004905 audio_devices_t device,
4906 int delayMs,
4907 bool force)
4908{
4909 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4910
Eric Laurent3b73df72014-03-11 09:06:29 -07004911 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4912 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004913 mStreams[stream].getVolumeIndex(device),
4914 output,
4915 device,
4916 delayMs,
4917 force);
4918 }
4919}
4920
Eric Laurente0720872014-03-11 09:30:41 -07004921void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004922 bool on,
4923 audio_io_handle_t output,
4924 int delayMs,
4925 audio_devices_t device)
4926{
4927 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004928 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4929 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4930 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004931 }
4932 }
4933}
4934
Eric Laurente0720872014-03-11 09:30:41 -07004935void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004936 bool on,
4937 audio_io_handle_t output,
4938 int delayMs,
4939 audio_devices_t device)
4940{
4941 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004942 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004943 if (device == AUDIO_DEVICE_NONE) {
4944 device = outputDesc->device();
4945 }
4946
4947 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4948 stream, on, output, outputDesc->mMuteCount[stream], device);
4949
4950 if (on) {
4951 if (outputDesc->mMuteCount[stream] == 0) {
4952 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004953 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4954 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004955 checkAndSetVolume(stream, 0, output, device, delayMs);
4956 }
4957 }
4958 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4959 outputDesc->mMuteCount[stream]++;
4960 } else {
4961 if (outputDesc->mMuteCount[stream] == 0) {
4962 ALOGV("setStreamMute() unmuting non muted stream!");
4963 return;
4964 }
4965 if (--outputDesc->mMuteCount[stream] == 0) {
4966 checkAndSetVolume(stream,
4967 streamDesc.getVolumeIndex(device),
4968 output,
4969 device,
4970 delayMs);
4971 }
4972 }
4973}
4974
Eric Laurente0720872014-03-11 09:30:41 -07004975void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004976 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004977{
4978 // if the stream pertains to sonification strategy and we are in call we must
4979 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4980 // in the device used for phone strategy and play the tone if the selected device does not
4981 // interfere with the device used for phone strategy
4982 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4983 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004984 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004985 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4986 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004987 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004988 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4989 stream, starting, outputDesc->mDevice, stateChange);
4990 if (outputDesc->mRefCount[stream]) {
4991 int muteCount = 1;
4992 if (stateChange) {
4993 muteCount = outputDesc->mRefCount[stream];
4994 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004995 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004996 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4997 for (int i = 0; i < muteCount; i++) {
4998 setStreamMute(stream, starting, mPrimaryOutput);
4999 }
5000 } else {
5001 ALOGV("handleIncallSonification() high visibility");
5002 if (outputDesc->device() &
5003 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5004 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5005 for (int i = 0; i < muteCount; i++) {
5006 setStreamMute(stream, starting, mPrimaryOutput);
5007 }
5008 }
5009 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005010 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5011 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005012 } else {
5013 mpClientInterface->stopTone();
5014 }
5015 }
5016 }
5017 }
5018}
5019
Eric Laurente0720872014-03-11 09:30:41 -07005020bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005021{
5022 return isStateInCall(mPhoneState);
5023}
5024
Eric Laurente0720872014-03-11 09:30:41 -07005025bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005026 return ((state == AUDIO_MODE_IN_CALL) ||
5027 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005028}
5029
Eric Laurente0720872014-03-11 09:30:41 -07005030uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005031{
5032 return MAX_EFFECTS_CPU_LOAD;
5033}
5034
Eric Laurente0720872014-03-11 09:30:41 -07005035uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005036{
5037 return MAX_EFFECTS_MEMORY;
5038}
5039
Eric Laurent6a94d692014-05-20 11:18:06 -07005040
Eric Laurente552edb2014-03-10 17:42:56 -07005041// --- AudioOutputDescriptor class implementation
5042
Eric Laurente0720872014-03-11 09:30:41 -07005043AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005044 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005045 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005046 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005047 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5048{
5049 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005050 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005051 mRefCount[i] = 0;
5052 mCurVolume[i] = -1.0;
5053 mMuteCount[i] = 0;
5054 mStopTime[i] = 0;
5055 }
5056 for (int i = 0; i < NUM_STRATEGIES; i++) {
5057 mStrategyMutedByDevice[i] = false;
5058 }
5059 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005060 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07005061 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005062 mSamplingRate = profile->pickSamplingRate();
5063 mFormat = profile->pickFormat();
5064 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005065 if (profile->mGains.size() > 0) {
5066 profile->mGains[0]->getDefaultConfig(&mGain);
5067 }
Eric Laurente552edb2014-03-10 17:42:56 -07005068 }
5069}
5070
Eric Laurente0720872014-03-11 09:30:41 -07005071audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005072{
5073 if (isDuplicated()) {
5074 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5075 } else {
5076 return mDevice;
5077 }
5078}
5079
Eric Laurente0720872014-03-11 09:30:41 -07005080uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005081{
5082 if (isDuplicated()) {
5083 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5084 } else {
5085 return mLatency;
5086 }
5087}
5088
Eric Laurente0720872014-03-11 09:30:41 -07005089bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005090 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005091{
5092 if (isDuplicated()) {
5093 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5094 } else if (outputDesc->isDuplicated()){
5095 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5096 } else {
5097 return (mProfile->mModule == outputDesc->mProfile->mModule);
5098 }
5099}
5100
Eric Laurente0720872014-03-11 09:30:41 -07005101void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005102 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005103{
5104 // forward usage count change to attached outputs
5105 if (isDuplicated()) {
5106 mOutput1->changeRefCount(stream, delta);
5107 mOutput2->changeRefCount(stream, delta);
5108 }
5109 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005110 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5111 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005112 mRefCount[stream] = 0;
5113 return;
5114 }
5115 mRefCount[stream] += delta;
5116 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5117}
5118
Eric Laurente0720872014-03-11 09:30:41 -07005119audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005120{
5121 if (isDuplicated()) {
5122 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5123 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005124 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005125 }
5126}
5127
Eric Laurente0720872014-03-11 09:30:41 -07005128bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005129{
5130 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5131}
5132
Eric Laurente0720872014-03-11 09:30:41 -07005133bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005134 uint32_t inPastMs,
5135 nsecs_t sysTime) const
5136{
5137 if ((sysTime == 0) && (inPastMs != 0)) {
5138 sysTime = systemTime();
5139 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005140 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5141 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005142 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005143 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005144 return true;
5145 }
5146 }
5147 return false;
5148}
5149
Eric Laurente0720872014-03-11 09:30:41 -07005150bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005151 uint32_t inPastMs,
5152 nsecs_t sysTime) const
5153{
5154 if (mRefCount[stream] != 0) {
5155 return true;
5156 }
5157 if (inPastMs == 0) {
5158 return false;
5159 }
5160 if (sysTime == 0) {
5161 sysTime = systemTime();
5162 }
5163 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5164 return true;
5165 }
5166 return false;
5167}
5168
Eric Laurent1c333e22014-05-20 10:48:17 -07005169void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 struct audio_port_config *dstConfig,
5171 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005172{
Eric Laurent84c70242014-06-23 08:46:27 -07005173 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5174
Eric Laurent1f2f2232014-06-02 12:01:23 -07005175 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5176 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5177 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005178 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005179 }
5180 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5181
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 dstConfig->id = mId;
5183 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5184 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5186 dstConfig->ext.mix.handle = mIoHandle;
5187 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005188}
5189
5190void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5191 struct audio_port *port) const
5192{
Eric Laurent84c70242014-06-23 08:46:27 -07005193 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005194 mProfile->toAudioPort(port);
5195 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 toAudioPortConfig(&port->active_config);
5197 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005198 port->ext.mix.handle = mIoHandle;
5199 port->ext.mix.latency_class =
5200 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5201}
Eric Laurente552edb2014-03-10 17:42:56 -07005202
Eric Laurente0720872014-03-11 09:30:41 -07005203status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005204{
5205 const size_t SIZE = 256;
5206 char buffer[SIZE];
5207 String8 result;
5208
5209 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5210 result.append(buffer);
5211 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5212 result.append(buffer);
5213 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5214 result.append(buffer);
5215 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5216 result.append(buffer);
5217 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5218 result.append(buffer);
5219 snprintf(buffer, SIZE, " Devices %08x\n", device());
5220 result.append(buffer);
5221 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5222 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005223 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5224 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5225 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005226 result.append(buffer);
5227 }
5228 write(fd, result.string(), result.size());
5229
5230 return NO_ERROR;
5231}
5232
5233// --- AudioInputDescriptor class implementation
5234
Eric Laurent1c333e22014-05-20 10:48:17 -07005235AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005236 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005237 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005238 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005239{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005240 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005241 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07005242 mSamplingRate = profile->pickSamplingRate();
5243 mFormat = profile->pickFormat();
5244 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005245 if (profile->mGains.size() > 0) {
5246 profile->mGains[0]->getDefaultConfig(&mGain);
5247 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005248 }
Eric Laurente552edb2014-03-10 17:42:56 -07005249}
5250
Eric Laurent1c333e22014-05-20 10:48:17 -07005251void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 struct audio_port_config *dstConfig,
5253 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005254{
Eric Laurent84c70242014-06-23 08:46:27 -07005255 ALOG_ASSERT(mProfile != 0,
5256 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005257 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5258 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5259 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005260 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005261 }
5262
5263 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5264
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 dstConfig->id = mId;
5266 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5267 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005268 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5269 dstConfig->ext.mix.handle = mIoHandle;
5270 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005271}
5272
5273void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5274 struct audio_port *port) const
5275{
Eric Laurent84c70242014-06-23 08:46:27 -07005276 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5277
Eric Laurent1c333e22014-05-20 10:48:17 -07005278 mProfile->toAudioPort(port);
5279 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 toAudioPortConfig(&port->active_config);
5281 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005282 port->ext.mix.handle = mIoHandle;
5283 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5284}
5285
Eric Laurente0720872014-03-11 09:30:41 -07005286status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005287{
5288 const size_t SIZE = 256;
5289 char buffer[SIZE];
5290 String8 result;
5291
5292 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5293 result.append(buffer);
5294 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5295 result.append(buffer);
5296 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5297 result.append(buffer);
5298 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5299 result.append(buffer);
5300 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5301 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005302 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5303 result.append(buffer);
5304
Eric Laurente552edb2014-03-10 17:42:56 -07005305 write(fd, result.string(), result.size());
5306
5307 return NO_ERROR;
5308}
5309
5310// --- StreamDescriptor class implementation
5311
Eric Laurente0720872014-03-11 09:30:41 -07005312AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005313 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5314{
5315 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5316}
5317
Eric Laurente0720872014-03-11 09:30:41 -07005318int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005319{
Eric Laurente0720872014-03-11 09:30:41 -07005320 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005321 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5322 if (mIndexCur.indexOfKey(device) < 0) {
5323 device = AUDIO_DEVICE_OUT_DEFAULT;
5324 }
5325 return mIndexCur.valueFor(device);
5326}
5327
Eric Laurente0720872014-03-11 09:30:41 -07005328void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005329{
5330 const size_t SIZE = 256;
5331 char buffer[SIZE];
5332 String8 result;
5333
5334 snprintf(buffer, SIZE, "%s %02d %02d ",
5335 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5336 result.append(buffer);
5337 for (size_t i = 0; i < mIndexCur.size(); i++) {
5338 snprintf(buffer, SIZE, "%04x : %02d, ",
5339 mIndexCur.keyAt(i),
5340 mIndexCur.valueAt(i));
5341 result.append(buffer);
5342 }
5343 result.append("\n");
5344
5345 write(fd, result.string(), result.size());
5346}
5347
5348// --- EffectDescriptor class implementation
5349
Eric Laurente0720872014-03-11 09:30:41 -07005350status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005351{
5352 const size_t SIZE = 256;
5353 char buffer[SIZE];
5354 String8 result;
5355
5356 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5357 result.append(buffer);
5358 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5359 result.append(buffer);
5360 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5361 result.append(buffer);
5362 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5363 result.append(buffer);
5364 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5365 result.append(buffer);
5366 write(fd, result.string(), result.size());
5367
5368 return NO_ERROR;
5369}
5370
Eric Laurent1c333e22014-05-20 10:48:17 -07005371// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005372
Eric Laurente0720872014-03-11 09:30:41 -07005373AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005374 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5375 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005376{
5377}
5378
Eric Laurente0720872014-03-11 09:30:41 -07005379AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005380{
5381 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005382 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005383 }
5384 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005385 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005386 }
5387 free((void *)mName);
5388}
5389
Eric Laurent1afeecb2014-05-14 08:52:28 -07005390status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5391{
5392 cnode *node = root->first_child;
5393
5394 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5395
5396 while (node) {
5397 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5398 profile->loadSamplingRates((char *)node->value);
5399 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5400 profile->loadFormats((char *)node->value);
5401 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5402 profile->loadInChannels((char *)node->value);
5403 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5404 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5405 mDeclaredDevices);
5406 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5407 profile->loadGains(node);
5408 }
5409 node = node->next;
5410 }
5411 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5412 "loadInput() invalid supported devices");
5413 ALOGW_IF(profile->mChannelMasks.size() == 0,
5414 "loadInput() invalid supported channel masks");
5415 ALOGW_IF(profile->mSamplingRates.size() == 0,
5416 "loadInput() invalid supported sampling rates");
5417 ALOGW_IF(profile->mFormats.size() == 0,
5418 "loadInput() invalid supported formats");
5419 if (!profile->mSupportedDevices.isEmpty() &&
5420 (profile->mChannelMasks.size() != 0) &&
5421 (profile->mSamplingRates.size() != 0) &&
5422 (profile->mFormats.size() != 0)) {
5423
5424 ALOGV("loadInput() adding input Supported Devices %04x",
5425 profile->mSupportedDevices.types());
5426
5427 mInputProfiles.add(profile);
5428 return NO_ERROR;
5429 } else {
5430 return BAD_VALUE;
5431 }
5432}
5433
5434status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5435{
5436 cnode *node = root->first_child;
5437
5438 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5439
5440 while (node) {
5441 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5442 profile->loadSamplingRates((char *)node->value);
5443 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5444 profile->loadFormats((char *)node->value);
5445 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5446 profile->loadOutChannels((char *)node->value);
5447 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5448 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5449 mDeclaredDevices);
5450 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5451 profile->mFlags = parseFlagNames((char *)node->value);
5452 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5453 profile->loadGains(node);
5454 }
5455 node = node->next;
5456 }
5457 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5458 "loadOutput() invalid supported devices");
5459 ALOGW_IF(profile->mChannelMasks.size() == 0,
5460 "loadOutput() invalid supported channel masks");
5461 ALOGW_IF(profile->mSamplingRates.size() == 0,
5462 "loadOutput() invalid supported sampling rates");
5463 ALOGW_IF(profile->mFormats.size() == 0,
5464 "loadOutput() invalid supported formats");
5465 if (!profile->mSupportedDevices.isEmpty() &&
5466 (profile->mChannelMasks.size() != 0) &&
5467 (profile->mSamplingRates.size() != 0) &&
5468 (profile->mFormats.size() != 0)) {
5469
5470 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5471 profile->mSupportedDevices.types(), profile->mFlags);
5472
5473 mOutputProfiles.add(profile);
5474 return NO_ERROR;
5475 } else {
5476 return BAD_VALUE;
5477 }
5478}
5479
5480status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5481{
5482 cnode *node = root->first_child;
5483
5484 audio_devices_t type = AUDIO_DEVICE_NONE;
5485 while (node) {
5486 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5487 type = parseDeviceNames((char *)node->value);
5488 break;
5489 }
5490 node = node->next;
5491 }
5492 if (type == AUDIO_DEVICE_NONE ||
5493 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5494 ALOGW("loadDevice() bad type %08x", type);
5495 return BAD_VALUE;
5496 }
5497 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5498 deviceDesc->mModule = this;
5499
5500 node = root->first_child;
5501 while (node) {
5502 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5503 deviceDesc->mAddress = String8((char *)node->value);
5504 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5505 if (audio_is_input_device(type)) {
5506 deviceDesc->loadInChannels((char *)node->value);
5507 } else {
5508 deviceDesc->loadOutChannels((char *)node->value);
5509 }
5510 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5511 deviceDesc->loadGains(node);
5512 }
5513 node = node->next;
5514 }
5515
5516 ALOGV("loadDevice() adding device name %s type %08x address %s",
5517 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5518
5519 mDeclaredDevices.add(deviceDesc);
5520
5521 return NO_ERROR;
5522}
5523
Eric Laurente0720872014-03-11 09:30:41 -07005524void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005525{
5526 const size_t SIZE = 256;
5527 char buffer[SIZE];
5528 String8 result;
5529
5530 snprintf(buffer, SIZE, " - name: %s\n", mName);
5531 result.append(buffer);
5532 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5533 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005534 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5535 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005536 write(fd, result.string(), result.size());
5537 if (mOutputProfiles.size()) {
5538 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5539 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005540 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005541 write(fd, buffer, strlen(buffer));
5542 mOutputProfiles[i]->dump(fd);
5543 }
5544 }
5545 if (mInputProfiles.size()) {
5546 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5547 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005548 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005549 write(fd, buffer, strlen(buffer));
5550 mInputProfiles[i]->dump(fd);
5551 }
5552 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005553 if (mDeclaredDevices.size()) {
5554 write(fd, " - devices:\n", strlen(" - devices:\n"));
5555 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5556 mDeclaredDevices[i]->dump(fd, 4, i);
5557 }
5558 }
Eric Laurente552edb2014-03-10 17:42:56 -07005559}
5560
Eric Laurent1c333e22014-05-20 10:48:17 -07005561// --- AudioPort class implementation
5562
Eric Laurenta121f902014-06-03 13:32:54 -07005563
5564AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5565 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005566 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005567{
5568 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5569 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5570}
5571
Eric Laurent1c333e22014-05-20 10:48:17 -07005572void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5573{
5574 port->role = mRole;
5575 port->type = mType;
5576 unsigned int i;
5577 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5578 port->sample_rates[i] = mSamplingRates[i];
5579 }
5580 port->num_sample_rates = i;
5581 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5582 port->channel_masks[i] = mChannelMasks[i];
5583 }
5584 port->num_channel_masks = i;
5585 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5586 port->formats[i] = mFormats[i];
5587 }
5588 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005589
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005590 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005591
5592 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5593 port->gains[i] = mGains[i]->mGain;
5594 }
5595 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005596}
5597
5598
5599void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5600{
5601 char *str = strtok(name, "|");
5602
5603 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5604 // rates should be read from the output stream after it is opened for the first time
5605 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5606 mSamplingRates.add(0);
5607 return;
5608 }
5609
5610 while (str != NULL) {
5611 uint32_t rate = atoi(str);
5612 if (rate != 0) {
5613 ALOGV("loadSamplingRates() adding rate %d", rate);
5614 mSamplingRates.add(rate);
5615 }
5616 str = strtok(NULL, "|");
5617 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005618}
5619
5620void AudioPolicyManager::AudioPort::loadFormats(char *name)
5621{
5622 char *str = strtok(name, "|");
5623
5624 // by convention, "0' in the first entry in mFormats indicates the supported formats
5625 // should be read from the output stream after it is opened for the first time
5626 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5627 mFormats.add(AUDIO_FORMAT_DEFAULT);
5628 return;
5629 }
5630
5631 while (str != NULL) {
5632 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5633 ARRAY_SIZE(sFormatNameToEnumTable),
5634 str);
5635 if (format != AUDIO_FORMAT_DEFAULT) {
5636 mFormats.add(format);
5637 }
5638 str = strtok(NULL, "|");
5639 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005640}
5641
5642void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5643{
5644 const char *str = strtok(name, "|");
5645
5646 ALOGV("loadInChannels() %s", name);
5647
5648 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5649 mChannelMasks.add(0);
5650 return;
5651 }
5652
5653 while (str != NULL) {
5654 audio_channel_mask_t channelMask =
5655 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5656 ARRAY_SIZE(sInChannelsNameToEnumTable),
5657 str);
5658 if (channelMask != 0) {
5659 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5660 mChannelMasks.add(channelMask);
5661 }
5662 str = strtok(NULL, "|");
5663 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005664}
5665
5666void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5667{
5668 const char *str = strtok(name, "|");
5669
5670 ALOGV("loadOutChannels() %s", name);
5671
5672 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5673 // masks should be read from the output stream after it is opened for the first time
5674 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5675 mChannelMasks.add(0);
5676 return;
5677 }
5678
5679 while (str != NULL) {
5680 audio_channel_mask_t channelMask =
5681 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5682 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5683 str);
5684 if (channelMask != 0) {
5685 mChannelMasks.add(channelMask);
5686 }
5687 str = strtok(NULL, "|");
5688 }
5689 return;
5690}
5691
Eric Laurent1afeecb2014-05-14 08:52:28 -07005692audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5693{
5694 const char *str = strtok(name, "|");
5695
5696 ALOGV("loadGainMode() %s", name);
5697 audio_gain_mode_t mode = 0;
5698 while (str != NULL) {
5699 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5700 ARRAY_SIZE(sGainModeNameToEnumTable),
5701 str);
5702 str = strtok(NULL, "|");
5703 }
5704 return mode;
5705}
5706
Eric Laurenta121f902014-06-03 13:32:54 -07005707void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005708{
5709 cnode *node = root->first_child;
5710
Eric Laurenta121f902014-06-03 13:32:54 -07005711 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005712
5713 while (node) {
5714 if (strcmp(node->name, GAIN_MODE) == 0) {
5715 gain->mGain.mode = loadGainMode((char *)node->value);
5716 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005717 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005718 gain->mGain.channel_mask =
5719 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5720 ARRAY_SIZE(sInChannelsNameToEnumTable),
5721 (char *)node->value);
5722 } else {
5723 gain->mGain.channel_mask =
5724 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5725 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5726 (char *)node->value);
5727 }
5728 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5729 gain->mGain.min_value = atoi((char *)node->value);
5730 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5731 gain->mGain.max_value = atoi((char *)node->value);
5732 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5733 gain->mGain.default_value = atoi((char *)node->value);
5734 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5735 gain->mGain.step_value = atoi((char *)node->value);
5736 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5737 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5738 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5739 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5740 }
5741 node = node->next;
5742 }
5743
5744 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5745 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5746
5747 if (gain->mGain.mode == 0) {
5748 return;
5749 }
5750 mGains.add(gain);
5751}
5752
5753void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5754{
5755 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005756 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005757 while (node) {
5758 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005759 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005760 node = node->next;
5761 }
5762}
5763
Glenn Kastencbd48022014-07-24 13:46:44 -07005764status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005765{
5766 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5767 if (mSamplingRates[i] == samplingRate) {
5768 return NO_ERROR;
5769 }
5770 }
5771 return BAD_VALUE;
5772}
5773
Glenn Kastencbd48022014-07-24 13:46:44 -07005774status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5775 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005776{
Glenn Kastencbd48022014-07-24 13:46:44 -07005777 // Search for the closest supported sampling rate that is above (preferred)
5778 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5779 // The sampling rates do not need to be sorted in ascending order.
5780 ssize_t maxBelow = -1;
5781 ssize_t minAbove = -1;
5782 uint32_t candidate;
5783 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5784 candidate = mSamplingRates[i];
5785 if (candidate == samplingRate) {
5786 if (updatedSamplingRate != NULL) {
5787 *updatedSamplingRate = candidate;
5788 }
5789 return NO_ERROR;
5790 }
5791 // candidate < desired
5792 if (candidate < samplingRate) {
5793 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5794 maxBelow = i;
5795 }
5796 // candidate > desired
5797 } else {
5798 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5799 minAbove = i;
5800 }
5801 }
5802 }
5803 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5804 // TODO Move these assumptions out.
5805 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5806 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5807 // due to approximation by an int32_t of the
5808 // phase increments
5809 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5810 if (minAbove >= 0) {
5811 candidate = mSamplingRates[minAbove];
5812 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5813 if (updatedSamplingRate != NULL) {
5814 *updatedSamplingRate = candidate;
5815 }
5816 return NO_ERROR;
5817 }
5818 }
5819 // But if we have to up-sample from a lower sampling rate, that's OK.
5820 if (maxBelow >= 0) {
5821 candidate = mSamplingRates[maxBelow];
5822 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5823 if (updatedSamplingRate != NULL) {
5824 *updatedSamplingRate = candidate;
5825 }
5826 return NO_ERROR;
5827 }
5828 }
5829 // leave updatedSamplingRate unmodified
5830 return BAD_VALUE;
5831}
5832
5833status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5834{
5835 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005836 if (mChannelMasks[i] == channelMask) {
5837 return NO_ERROR;
5838 }
5839 }
5840 return BAD_VALUE;
5841}
5842
Glenn Kastencbd48022014-07-24 13:46:44 -07005843status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5844 const
5845{
5846 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5847 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5848 // FIXME Does not handle multi-channel automatic conversions yet
5849 audio_channel_mask_t supported = mChannelMasks[i];
5850 if (supported == channelMask) {
5851 return NO_ERROR;
5852 }
5853 if (isRecordThread) {
5854 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5855 // FIXME Abstract this out to a table.
5856 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5857 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5858 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5859 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5860 return NO_ERROR;
5861 }
5862 }
5863 }
5864 return BAD_VALUE;
5865}
5866
Eric Laurenta121f902014-06-03 13:32:54 -07005867status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5868{
5869 for (size_t i = 0; i < mFormats.size(); i ++) {
5870 if (mFormats[i] == format) {
5871 return NO_ERROR;
5872 }
5873 }
5874 return BAD_VALUE;
5875}
5876
Eric Laurent1e693b52014-07-09 15:03:28 -07005877
5878uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5879{
5880 // special case for uninitialized dynamic profile
5881 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5882 return 0;
5883 }
5884
5885 uint32_t samplingRate = 0;
5886 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5887
5888 // For mixed output and inputs, use max mixer sampling rates. Do not
5889 // limit sampling rate otherwise
5890 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5891 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5892 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5893 maxRate = UINT_MAX;
5894 }
5895 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5896 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5897 samplingRate = mSamplingRates[i];
5898 }
5899 }
5900 return samplingRate;
5901}
5902
5903audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5904{
5905 // special case for uninitialized dynamic profile
5906 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5907 return AUDIO_CHANNEL_NONE;
5908 }
5909
5910 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5911 uint32_t channelCount = 0;
5912 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5913
5914 // For mixed output and inputs, use max mixer channel count. Do not
5915 // limit channel count otherwise
5916 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5917 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5918 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5919 maxCount = UINT_MAX;
5920 }
5921 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5922 uint32_t cnlCount;
5923 if (mUseInChannelMask) {
5924 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5925 } else {
5926 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5927 }
5928 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5929 channelMask = mChannelMasks[i];
5930 }
5931 }
5932 return channelMask;
5933}
5934
Andy Hung9a605382014-07-28 16:16:31 -07005935/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005936const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5937 AUDIO_FORMAT_DEFAULT,
5938 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005939 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005940 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005941 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005942 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005943};
5944
5945int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5946 audio_format_t format2)
5947{
5948 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5949 // compressed format and better than any PCM format. This is by design of pickFormat()
5950 if (!audio_is_linear_pcm(format1)) {
5951 if (!audio_is_linear_pcm(format2)) {
5952 return 0;
5953 }
5954 return 1;
5955 }
5956 if (!audio_is_linear_pcm(format2)) {
5957 return -1;
5958 }
5959
5960 int index1 = -1, index2 = -1;
5961 for (size_t i = 0;
5962 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5963 i ++) {
5964 if (sPcmFormatCompareTable[i] == format1) {
5965 index1 = i;
5966 }
5967 if (sPcmFormatCompareTable[i] == format2) {
5968 index2 = i;
5969 }
5970 }
5971 // format1 not found => index1 < 0 => format2 > format1
5972 // format2 not found => index2 < 0 => format2 < format1
5973 return index1 - index2;
5974}
5975
5976audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5977{
5978 // special case for uninitialized dynamic profile
5979 if (mFormats.size() == 1 && mFormats[0] == 0) {
5980 return AUDIO_FORMAT_DEFAULT;
5981 }
5982
5983 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005984 audio_format_t bestFormat =
5985 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5986 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005987 // For mixed output and inputs, use best mixer output format. Do not
5988 // limit format otherwise
5989 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5990 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005991 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005992 bestFormat = AUDIO_FORMAT_INVALID;
5993 }
5994
5995 for (size_t i = 0; i < mFormats.size(); i ++) {
5996 if ((compareFormats(mFormats[i], format) > 0) &&
5997 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5998 format = mFormats[i];
5999 }
6000 }
6001 return format;
6002}
6003
Eric Laurenta121f902014-06-03 13:32:54 -07006004status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6005 int index) const
6006{
6007 if (index < 0 || (size_t)index >= mGains.size()) {
6008 return BAD_VALUE;
6009 }
6010 return mGains[index]->checkConfig(gainConfig);
6011}
6012
Eric Laurent1afeecb2014-05-14 08:52:28 -07006013void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6014{
6015 const size_t SIZE = 256;
6016 char buffer[SIZE];
6017 String8 result;
6018
6019 if (mName.size() != 0) {
6020 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6021 result.append(buffer);
6022 }
6023
6024 if (mSamplingRates.size() != 0) {
6025 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6026 result.append(buffer);
6027 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006028 if (i == 0 && mSamplingRates[i] == 0) {
6029 snprintf(buffer, SIZE, "Dynamic");
6030 } else {
6031 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6032 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006033 result.append(buffer);
6034 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6035 }
6036 result.append("\n");
6037 }
6038
6039 if (mChannelMasks.size() != 0) {
6040 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6041 result.append(buffer);
6042 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006043 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6044
6045 if (i == 0 && mChannelMasks[i] == 0) {
6046 snprintf(buffer, SIZE, "Dynamic");
6047 } else {
6048 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6049 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006050 result.append(buffer);
6051 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6052 }
6053 result.append("\n");
6054 }
6055
6056 if (mFormats.size() != 0) {
6057 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6058 result.append(buffer);
6059 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006060 const char *formatStr = enumToString(sFormatNameToEnumTable,
6061 ARRAY_SIZE(sFormatNameToEnumTable),
6062 mFormats[i]);
6063 if (i == 0 && strcmp(formatStr, "") == 0) {
6064 snprintf(buffer, SIZE, "Dynamic");
6065 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006066 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006067 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006068 result.append(buffer);
6069 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6070 }
6071 result.append("\n");
6072 }
6073 write(fd, result.string(), result.size());
6074 if (mGains.size() != 0) {
6075 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6076 write(fd, buffer, strlen(buffer) + 1);
6077 result.append(buffer);
6078 for (size_t i = 0; i < mGains.size(); i++) {
6079 mGains[i]->dump(fd, spaces + 2, i);
6080 }
6081 }
6082}
6083
6084// --- AudioGain class implementation
6085
Eric Laurenta121f902014-06-03 13:32:54 -07006086AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006087{
Eric Laurenta121f902014-06-03 13:32:54 -07006088 mIndex = index;
6089 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006090 memset(&mGain, 0, sizeof(struct audio_gain));
6091}
6092
Eric Laurenta121f902014-06-03 13:32:54 -07006093void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6094{
6095 config->index = mIndex;
6096 config->mode = mGain.mode;
6097 config->channel_mask = mGain.channel_mask;
6098 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6099 config->values[0] = mGain.default_value;
6100 } else {
6101 uint32_t numValues;
6102 if (mUseInChannelMask) {
6103 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6104 } else {
6105 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6106 }
6107 for (size_t i = 0; i < numValues; i++) {
6108 config->values[i] = mGain.default_value;
6109 }
6110 }
6111 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6112 config->ramp_duration_ms = mGain.min_ramp_ms;
6113 }
6114}
6115
6116status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6117{
6118 if ((config->mode & ~mGain.mode) != 0) {
6119 return BAD_VALUE;
6120 }
6121 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6122 if ((config->values[0] < mGain.min_value) ||
6123 (config->values[0] > mGain.max_value)) {
6124 return BAD_VALUE;
6125 }
6126 } else {
6127 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6128 return BAD_VALUE;
6129 }
6130 uint32_t numValues;
6131 if (mUseInChannelMask) {
6132 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6133 } else {
6134 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6135 }
6136 for (size_t i = 0; i < numValues; i++) {
6137 if ((config->values[i] < mGain.min_value) ||
6138 (config->values[i] > mGain.max_value)) {
6139 return BAD_VALUE;
6140 }
6141 }
6142 }
6143 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6144 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6145 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6146 return BAD_VALUE;
6147 }
6148 }
6149 return NO_ERROR;
6150}
6151
Eric Laurent1afeecb2014-05-14 08:52:28 -07006152void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6153{
6154 const size_t SIZE = 256;
6155 char buffer[SIZE];
6156 String8 result;
6157
6158 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6159 result.append(buffer);
6160 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6161 result.append(buffer);
6162 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6163 result.append(buffer);
6164 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6165 result.append(buffer);
6166 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6167 result.append(buffer);
6168 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6169 result.append(buffer);
6170 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6171 result.append(buffer);
6172 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6173 result.append(buffer);
6174 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6175 result.append(buffer);
6176
6177 write(fd, result.string(), result.size());
6178}
6179
Eric Laurent1f2f2232014-06-02 12:01:23 -07006180// --- AudioPortConfig class implementation
6181
6182AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6183{
6184 mSamplingRate = 0;
6185 mChannelMask = AUDIO_CHANNEL_NONE;
6186 mFormat = AUDIO_FORMAT_INVALID;
6187 mGain.index = -1;
6188}
6189
Eric Laurenta121f902014-06-03 13:32:54 -07006190status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6191 const struct audio_port_config *config,
6192 struct audio_port_config *backupConfig)
6193{
6194 struct audio_port_config localBackupConfig;
6195 status_t status = NO_ERROR;
6196
6197 localBackupConfig.config_mask = config->config_mask;
6198 toAudioPortConfig(&localBackupConfig);
6199
6200 if (mAudioPort == 0) {
6201 status = NO_INIT;
6202 goto exit;
6203 }
6204 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07006205 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006206 if (status != NO_ERROR) {
6207 goto exit;
6208 }
6209 mSamplingRate = config->sample_rate;
6210 }
6211 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07006212 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006213 if (status != NO_ERROR) {
6214 goto exit;
6215 }
6216 mChannelMask = config->channel_mask;
6217 }
6218 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6219 status = mAudioPort->checkFormat(config->format);
6220 if (status != NO_ERROR) {
6221 goto exit;
6222 }
6223 mFormat = config->format;
6224 }
6225 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6226 status = mAudioPort->checkGain(&config->gain, config->gain.index);
6227 if (status != NO_ERROR) {
6228 goto exit;
6229 }
6230 mGain = config->gain;
6231 }
6232
6233exit:
6234 if (status != NO_ERROR) {
6235 applyAudioPortConfig(&localBackupConfig);
6236 }
6237 if (backupConfig != NULL) {
6238 *backupConfig = localBackupConfig;
6239 }
6240 return status;
6241}
6242
Eric Laurent1f2f2232014-06-02 12:01:23 -07006243void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6244 struct audio_port_config *dstConfig,
6245 const struct audio_port_config *srcConfig) const
6246{
6247 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6248 dstConfig->sample_rate = mSamplingRate;
6249 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6250 dstConfig->sample_rate = srcConfig->sample_rate;
6251 }
6252 } else {
6253 dstConfig->sample_rate = 0;
6254 }
6255 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6256 dstConfig->channel_mask = mChannelMask;
6257 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6258 dstConfig->channel_mask = srcConfig->channel_mask;
6259 }
6260 } else {
6261 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6262 }
6263 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6264 dstConfig->format = mFormat;
6265 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6266 dstConfig->format = srcConfig->format;
6267 }
6268 } else {
6269 dstConfig->format = AUDIO_FORMAT_INVALID;
6270 }
6271 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6272 dstConfig->gain = mGain;
6273 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6274 dstConfig->gain = srcConfig->gain;
6275 }
6276 } else {
6277 dstConfig->gain.index = -1;
6278 }
6279 if (dstConfig->gain.index != -1) {
6280 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6281 } else {
6282 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6283 }
6284}
6285
Eric Laurent1c333e22014-05-20 10:48:17 -07006286// --- IOProfile class implementation
6287
Eric Laurent1afeecb2014-05-14 08:52:28 -07006288AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006289 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006290 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006291{
6292}
6293
Eric Laurente0720872014-03-11 09:30:41 -07006294AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006295{
6296}
6297
6298// checks if the IO profile is compatible with specified parameters.
6299// Sampling rate, format and channel mask must be specified in order to
6300// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006301bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006302 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006303 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006304 audio_format_t format,
6305 audio_channel_mask_t channelMask,
6306 audio_output_flags_t flags) const
6307{
Glenn Kastencbd48022014-07-24 13:46:44 -07006308 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6309 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6310 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006311
Glenn Kastencbd48022014-07-24 13:46:44 -07006312 if ((mSupportedDevices.types() & device) != device) {
6313 return false;
6314 }
6315
6316 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006317 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006318 }
6319 uint32_t myUpdatedSamplingRate = samplingRate;
6320 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006321 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006322 }
6323 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6324 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006325 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006326 }
6327
6328 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6329 return false;
6330 }
6331
6332 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6333 checkExactChannelMask(channelMask) != NO_ERROR)) {
6334 return false;
6335 }
6336 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6337 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6338 return false;
6339 }
6340
6341 if (isPlaybackThread && (mFlags & flags) != flags) {
6342 return false;
6343 }
6344 // The only input flag that is allowed to be different is the fast flag.
6345 // An existing fast stream is compatible with a normal track request.
6346 // An existing normal stream is compatible with a fast track request,
6347 // but the fast request will be denied by AudioFlinger and converted to normal track.
6348 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6349 ~AUDIO_INPUT_FLAG_FAST)) {
6350 return false;
6351 }
6352
6353 if (updatedSamplingRate != NULL) {
6354 *updatedSamplingRate = myUpdatedSamplingRate;
6355 }
6356 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006357}
6358
Eric Laurente0720872014-03-11 09:30:41 -07006359void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006360{
6361 const size_t SIZE = 256;
6362 char buffer[SIZE];
6363 String8 result;
6364
Eric Laurent1afeecb2014-05-14 08:52:28 -07006365 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006366
Eric Laurente552edb2014-03-10 17:42:56 -07006367 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6368 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006369 snprintf(buffer, SIZE, " - devices:\n");
6370 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006371 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006372 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6373 mSupportedDevices[i]->dump(fd, 6, i);
6374 }
Eric Laurente552edb2014-03-10 17:42:56 -07006375}
6376
Eric Laurentd4692962014-05-05 18:13:44 -07006377void AudioPolicyManager::IOProfile::log()
6378{
6379 const size_t SIZE = 256;
6380 char buffer[SIZE];
6381 String8 result;
6382
6383 ALOGV(" - sampling rates: ");
6384 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6385 ALOGV(" %d", mSamplingRates[i]);
6386 }
6387
6388 ALOGV(" - channel masks: ");
6389 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6390 ALOGV(" 0x%04x", mChannelMasks[i]);
6391 }
6392
6393 ALOGV(" - formats: ");
6394 for (size_t i = 0; i < mFormats.size(); i++) {
6395 ALOGV(" 0x%08x", mFormats[i]);
6396 }
6397
6398 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6399 ALOGV(" - flags: 0x%04x\n", mFlags);
6400}
6401
6402
Eric Laurent3a4311c2014-03-17 12:00:47 -07006403// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006404
Eric Laurent1f2f2232014-06-02 12:01:23 -07006405
6406AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6407 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6408 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6409 AUDIO_PORT_ROLE_SOURCE,
6410 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006411 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006412{
6413 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006414 if (mGains.size() > 0) {
6415 mGains[0]->getDefaultConfig(&mGain);
6416 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006417}
6418
Eric Laurent3a4311c2014-03-17 12:00:47 -07006419bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006420{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006421 // Devices are considered equal if they:
6422 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6423 // - have the same address or one device does not specify the address
6424 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006425 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006426 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006427 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006428 mChannelMask == other->mChannelMask);
6429}
6430
6431void AudioPolicyManager::DeviceVector::refreshTypes()
6432{
Eric Laurent1c333e22014-05-20 10:48:17 -07006433 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006434 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006435 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006436 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006437 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006438}
6439
6440ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6441{
6442 for(size_t i = 0; i < size(); i++) {
6443 if (item->equals(itemAt(i))) {
6444 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006445 }
6446 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006447 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006448}
6449
Eric Laurent3a4311c2014-03-17 12:00:47 -07006450ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006451{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006452 ssize_t ret = indexOf(item);
6453
6454 if (ret < 0) {
6455 ret = SortedVector::add(item);
6456 if (ret >= 0) {
6457 refreshTypes();
6458 }
6459 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006460 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006461 ret = -1;
6462 }
6463 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006464}
6465
Eric Laurent3a4311c2014-03-17 12:00:47 -07006466ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6467{
6468 size_t i;
6469 ssize_t ret = indexOf(item);
6470
6471 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006472 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006473 } else {
6474 ret = SortedVector::removeAt(ret);
6475 if (ret >= 0) {
6476 refreshTypes();
6477 }
6478 }
6479 return ret;
6480}
6481
6482void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6483{
6484 DeviceVector deviceList;
6485
6486 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6487 types &= ~role_bit;
6488
6489 while (types) {
6490 uint32_t i = 31 - __builtin_clz(types);
6491 uint32_t type = 1 << i;
6492 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006493 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006494 }
6495}
6496
Eric Laurent1afeecb2014-05-14 08:52:28 -07006497void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6498 const DeviceVector& declaredDevices)
6499{
6500 char *devName = strtok(name, "|");
6501 while (devName != NULL) {
6502 if (strlen(devName) != 0) {
6503 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6504 ARRAY_SIZE(sDeviceNameToEnumTable),
6505 devName);
6506 if (type != AUDIO_DEVICE_NONE) {
6507 add(new DeviceDescriptor(String8(""), type));
6508 } else {
6509 sp<DeviceDescriptor> deviceDesc =
6510 declaredDevices.getDeviceFromName(String8(devName));
6511 if (deviceDesc != 0) {
6512 add(deviceDesc);
6513 }
6514 }
6515 }
6516 devName = strtok(NULL, "|");
6517 }
6518}
6519
Eric Laurent1c333e22014-05-20 10:48:17 -07006520sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6521 audio_devices_t type, String8 address) const
6522{
6523 sp<DeviceDescriptor> device;
6524 for (size_t i = 0; i < size(); i++) {
6525 if (itemAt(i)->mDeviceType == type) {
6526 device = itemAt(i);
6527 if (itemAt(i)->mAddress = address) {
6528 break;
6529 }
6530 }
6531 }
6532 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6533 type, address.string(), device.get());
6534 return device;
6535}
6536
Eric Laurent6a94d692014-05-20 11:18:06 -07006537sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6538 audio_port_handle_t id) const
6539{
6540 sp<DeviceDescriptor> device;
6541 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006542 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006543 if (itemAt(i)->mId == id) {
6544 device = itemAt(i);
6545 break;
6546 }
6547 }
6548 return device;
6549}
6550
Eric Laurent1c333e22014-05-20 10:48:17 -07006551AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6552 audio_devices_t type) const
6553{
6554 DeviceVector devices;
6555 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6556 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6557 devices.add(itemAt(i));
6558 type &= ~itemAt(i)->mDeviceType;
6559 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6560 itemAt(i)->mDeviceType, itemAt(i).get());
6561 }
6562 }
6563 return devices;
6564}
6565
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006566AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6567 audio_devices_t type, String8 address) const
6568{
6569 DeviceVector devices;
6570 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6571 for (size_t i = 0; i < size(); i++) {
6572 //ALOGV(" at i=%d: device=%x, addr=%s",
6573 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6574 if (itemAt(i)->mDeviceType == type) {
6575 if (itemAt(i)->mAddress == address) {
6576 //ALOGV(" found matching address %s", address.string());
6577 devices.add(itemAt(i));
6578 }
6579 }
6580 }
6581 return devices;
6582}
6583
Eric Laurent1afeecb2014-05-14 08:52:28 -07006584sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6585 const String8& name) const
6586{
6587 sp<DeviceDescriptor> device;
6588 for (size_t i = 0; i < size(); i++) {
6589 if (itemAt(i)->mName == name) {
6590 device = itemAt(i);
6591 break;
6592 }
6593 }
6594 return device;
6595}
6596
Eric Laurent6a94d692014-05-20 11:18:06 -07006597void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6598 struct audio_port_config *dstConfig,
6599 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006600{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006601 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6602 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006603 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006604 }
6605
6606 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6607
Eric Laurent6a94d692014-05-20 11:18:06 -07006608 dstConfig->id = mId;
6609 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006610 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006611 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006612 dstConfig->ext.device.type = mDeviceType;
6613 dstConfig->ext.device.hw_module = mModule->mHandle;
6614 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006615}
6616
6617void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6618{
Eric Laurent83b88082014-06-20 18:31:16 -07006619 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006620 AudioPort::toAudioPort(port);
6621 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006622 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006623 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006624 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006625 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6626}
6627
Eric Laurent1afeecb2014-05-14 08:52:28 -07006628status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006629{
6630 const size_t SIZE = 256;
6631 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006632 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006633
Eric Laurent1afeecb2014-05-14 08:52:28 -07006634 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6635 result.append(buffer);
6636 if (mId != 0) {
6637 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6638 result.append(buffer);
6639 }
6640 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6641 enumToString(sDeviceNameToEnumTable,
6642 ARRAY_SIZE(sDeviceNameToEnumTable),
6643 mDeviceType));
6644 result.append(buffer);
6645 if (mAddress.size() != 0) {
6646 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6647 result.append(buffer);
6648 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006649 write(fd, result.string(), result.size());
6650 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006651
6652 return NO_ERROR;
6653}
6654
6655
6656// --- audio_policy.conf file parsing
6657
Eric Laurente0720872014-03-11 09:30:41 -07006658audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006659{
6660 uint32_t flag = 0;
6661
6662 // it is OK to cast name to non const here as we are not going to use it after
6663 // strtok() modifies it
6664 char *flagName = strtok(name, "|");
6665 while (flagName != NULL) {
6666 if (strlen(flagName) != 0) {
6667 flag |= stringToEnum(sFlagNameToEnumTable,
6668 ARRAY_SIZE(sFlagNameToEnumTable),
6669 flagName);
6670 }
6671 flagName = strtok(NULL, "|");
6672 }
6673 //force direct flag if offload flag is set: offloading implies a direct output stream
6674 // and all common behaviors are driven by checking only the direct flag
6675 // this should normally be set appropriately in the policy configuration file
6676 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6677 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6678 }
6679
6680 return (audio_output_flags_t)flag;
6681}
6682
Eric Laurente0720872014-03-11 09:30:41 -07006683audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006684{
6685 uint32_t device = 0;
6686
6687 char *devName = strtok(name, "|");
6688 while (devName != NULL) {
6689 if (strlen(devName) != 0) {
6690 device |= stringToEnum(sDeviceNameToEnumTable,
6691 ARRAY_SIZE(sDeviceNameToEnumTable),
6692 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006693 }
Eric Laurente552edb2014-03-10 17:42:56 -07006694 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006695 }
Eric Laurente552edb2014-03-10 17:42:56 -07006696 return device;
6697}
6698
Eric Laurente0720872014-03-11 09:30:41 -07006699void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006700{
Eric Laurente552edb2014-03-10 17:42:56 -07006701 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006702 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006703 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006704
Eric Laurent1afeecb2014-05-14 08:52:28 -07006705 node = config_find(root, DEVICES_TAG);
6706 if (node != NULL) {
6707 node = node->first_child;
6708 while (node) {
6709 ALOGV("loadHwModule() loading device %s", node->name);
6710 status_t tmpStatus = module->loadDevice(node);
6711 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6712 status = tmpStatus;
6713 }
6714 node = node->next;
6715 }
6716 }
6717 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006718 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006719 node = node->first_child;
6720 while (node) {
6721 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006722 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006723 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6724 status = tmpStatus;
6725 }
6726 node = node->next;
6727 }
6728 }
6729 node = config_find(root, INPUTS_TAG);
6730 if (node != NULL) {
6731 node = node->first_child;
6732 while (node) {
6733 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006734 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006735 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6736 status = tmpStatus;
6737 }
6738 node = node->next;
6739 }
6740 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006741 loadGlobalConfig(root, module);
6742
Eric Laurente552edb2014-03-10 17:42:56 -07006743 if (status == NO_ERROR) {
6744 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006745 }
6746}
6747
Eric Laurente0720872014-03-11 09:30:41 -07006748void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006749{
6750 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6751 if (node == NULL) {
6752 return;
6753 }
6754
6755 node = node->first_child;
6756 while (node) {
6757 ALOGV("loadHwModules() loading module %s", node->name);
6758 loadHwModule(node);
6759 node = node->next;
6760 }
6761}
6762
Eric Laurent1f2f2232014-06-02 12:01:23 -07006763void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006764{
6765 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006766
Eric Laurente552edb2014-03-10 17:42:56 -07006767 if (node == NULL) {
6768 return;
6769 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006770 DeviceVector declaredDevices;
6771 if (module != NULL) {
6772 declaredDevices = module->mDeclaredDevices;
6773 }
6774
Eric Laurente552edb2014-03-10 17:42:56 -07006775 node = node->first_child;
6776 while (node) {
6777 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006778 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6779 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006780 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6781 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006782 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006783 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006784 ARRAY_SIZE(sDeviceNameToEnumTable),
6785 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006786 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006787 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006788 } else {
6789 ALOGW("loadGlobalConfig() default device not specified");
6790 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006791 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006792 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006793 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6794 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006795 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006796 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6797 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6798 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006799 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6800 uint32_t major, minor;
6801 sscanf((char *)node->value, "%u.%u", &major, &minor);
6802 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6803 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6804 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006805 }
6806 node = node->next;
6807 }
6808}
6809
Eric Laurente0720872014-03-11 09:30:41 -07006810status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006811{
6812 cnode *root;
6813 char *data;
6814
6815 data = (char *)load_file(path, NULL);
6816 if (data == NULL) {
6817 return -ENODEV;
6818 }
6819 root = config_node("", "");
6820 config_load(root, data);
6821
Eric Laurente552edb2014-03-10 17:42:56 -07006822 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006823 // legacy audio_policy.conf files have one global_configuration section
6824 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006825 config_free(root);
6826 free(root);
6827 free(data);
6828
6829 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6830
6831 return NO_ERROR;
6832}
6833
Eric Laurente0720872014-03-11 09:30:41 -07006834void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006835{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006836 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006837 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006838 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6839 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006840 mAvailableOutputDevices.add(mDefaultOutputDevice);
6841 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006842
6843 module = new HwModule("primary");
6844
Eric Laurent1afeecb2014-05-14 08:52:28 -07006845 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006846 profile->mSamplingRates.add(44100);
6847 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6848 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006849 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006850 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6851 module->mOutputProfiles.add(profile);
6852
Eric Laurent1afeecb2014-05-14 08:52:28 -07006853 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006854 profile->mSamplingRates.add(8000);
6855 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6856 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006857 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006858 module->mInputProfiles.add(profile);
6859
6860 mHwModules.add(module);
6861}
6862
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006863audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6864{
6865 // flags to stream type mapping
6866 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6867 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6868 }
6869 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6870 return AUDIO_STREAM_BLUETOOTH_SCO;
6871 }
6872
6873 // usage to stream type mapping
6874 switch (attr->usage) {
6875 case AUDIO_USAGE_MEDIA:
6876 case AUDIO_USAGE_GAME:
6877 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6878 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6879 return AUDIO_STREAM_MUSIC;
6880 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6881 return AUDIO_STREAM_SYSTEM;
6882 case AUDIO_USAGE_VOICE_COMMUNICATION:
6883 return AUDIO_STREAM_VOICE_CALL;
6884
6885 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6886 return AUDIO_STREAM_DTMF;
6887
6888 case AUDIO_USAGE_ALARM:
6889 return AUDIO_STREAM_ALARM;
6890 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6891 return AUDIO_STREAM_RING;
6892
6893 case AUDIO_USAGE_NOTIFICATION:
6894 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6895 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6896 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6897 case AUDIO_USAGE_NOTIFICATION_EVENT:
6898 return AUDIO_STREAM_NOTIFICATION;
6899
6900 case AUDIO_USAGE_UNKNOWN:
6901 default:
6902 return AUDIO_STREAM_MUSIC;
6903 }
6904}
Eric Laurente552edb2014-03-10 17:42:56 -07006905}; // namespace android