blob: 06dd22ca18404195593907ff1221863cae5bc041 [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 Trivif17026d2014-08-10 14:30:48 -0700257 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700258 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
Paul McLean5c477aa2014-08-20 16:47:57 -0700274 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
275
276 // Set Disconnect to HALs
277 AudioParameter param = AudioParameter(address);
278 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
279 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
280
Eric Laurente552edb2014-03-10 17:42:56 -0700281 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700283
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700284 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700285 } break;
286
287 default:
288 ALOGE("setDeviceConnectionState() invalid state: %x", state);
289 return BAD_VALUE;
290 }
291
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
293 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700294 checkA2dpSuspend();
295 checkOutputForAllStrategies();
296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700299 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700300 // close unused outputs after device disconnection or direct outputs that have been
301 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700302 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700303 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
304 (desc->mDirectOpenCount == 0))) {
305 closeOutput(outputs[i]);
306 }
307 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700308 // check again after closing A2DP output to reset mA2dpSuspended if needed
309 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700310 }
311
312 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700313 if (mPhoneState == AUDIO_MODE_IN_CALL) {
314 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
315 updateCallRouting(newDevice);
316 }
Eric Laurente552edb2014-03-10 17:42:56 -0700317 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 audio_io_handle_t output = mOutputs.keyAt(i);
319 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
320 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
321 true /*fromCache*/);
322 // do not force device change on duplicated output because if device is 0, it will
323 // also force a device 0 for the two outputs it is duplicated to which may override
324 // a valid device selection on those outputs.
325 bool force = !mOutputs.valueAt(i)->isDuplicated()
326 && (!deviceDistinguishesOnAddress(device)
327 // always force when disconnecting (a non-duplicated device)
328 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
329 setOutputDevice(output, newDevice, force, 0);
330 }
Eric Laurente552edb2014-03-10 17:42:56 -0700331 }
332
Eric Laurent72aa32f2014-05-30 18:51:48 -0700333 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700334 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700335 } // end if is output device
336
Eric Laurente552edb2014-03-10 17:42:56 -0700337 // handle input devices
338 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700339 SortedVector <audio_io_handle_t> inputs;
340
Eric Laurent1afeecb2014-05-14 08:52:28 -0700341 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
342 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700344 switch (state)
345 {
346 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700347 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700349 ALOGW("setDeviceConnectionState() device already connected: %d", device);
350 return INVALID_OPERATION;
351 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700352 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700353 if (module == NULL) {
354 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
355 device);
356 return INVALID_OPERATION;
357 }
Eric Laurentd4692962014-05-05 18:13:44 -0700358 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
359 return INVALID_OPERATION;
360 }
361
Eric Laurent3a4311c2014-03-17 12:00:47 -0700362 index = mAvailableInputDevices.add(devDesc);
363 if (index >= 0) {
364 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700365 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 } else {
367 return NO_MEMORY;
368 }
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700372 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700373 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700374 ALOGW("setDeviceConnectionState() device not connected: %d", device);
375 return INVALID_OPERATION;
376 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700377
378 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
379
380 // Set Disconnect to HALs
381 AudioParameter param = AudioParameter(address);
382 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
383 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
384
Eric Laurentd4692962014-05-05 18:13:44 -0700385 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700387
Eric Laurentd4692962014-05-05 18:13:44 -0700388 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700389
390 default:
391 ALOGE("setDeviceConnectionState() invalid state: %x", state);
392 return BAD_VALUE;
393 }
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700396
Eric Laurentc2730ba2014-07-20 15:47:07 -0700397 if (mPhoneState == AUDIO_MODE_IN_CALL) {
398 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
399 updateCallRouting(newDevice);
400 }
401
Eric Laurentb52c1522014-05-20 11:27:36 -0700402 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700403 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700404 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700405
406 ALOGW("setDeviceConnectionState() invalid device: %x", device);
407 return BAD_VALUE;
408}
409
Eric Laurente0720872014-03-11 09:30:41 -0700410audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700411 const char *device_address)
412{
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700414 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700415 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700416 ssize_t index;
417 DeviceVector *deviceVector;
418
Eric Laurente552edb2014-03-10 17:42:56 -0700419 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700420 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700421 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 deviceVector = &mAvailableInputDevices;
423 } else {
424 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
425 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700426 }
427
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 index = deviceVector->indexOf(devDesc);
429 if (index >= 0) {
430 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
431 } else {
432 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
433 }
Eric Laurente552edb2014-03-10 17:42:56 -0700434}
435
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
437{
438 bool createTxPatch = false;
439 struct audio_patch patch;
440 patch.num_sources = 1;
441 patch.num_sinks = 1;
442 status_t status;
443 audio_patch_handle_t afPatchHandle;
444 DeviceVector deviceList;
445
446 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
447 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
448
449 // release existing RX patch if any
450 if (mCallRxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
452 mCallRxPatch.clear();
453 }
454 // release TX patch if any
455 if (mCallTxPatch != 0) {
456 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
457 mCallTxPatch.clear();
458 }
459
460 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
461 // via setOutputDevice() on primary output.
462 // Otherwise, create two audio patches for TX and RX path.
463 if (availablePrimaryOutputDevices() & rxDevice) {
464 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
465 // If the TX device is also on the primary HW module, setOutputDevice() will take care
466 // of it due to legacy implementation. If not, create a patch.
467 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
468 == AUDIO_DEVICE_NONE) {
469 createTxPatch = true;
470 }
471 } else {
472 // create RX path audio patch
473 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
474 ALOG_ASSERT(!deviceList.isEmpty(),
475 "updateCallRouting() selected device not in output device list");
476 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
477 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
478 ALOG_ASSERT(!deviceList.isEmpty(),
479 "updateCallRouting() no telephony RX device");
480 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
481
482 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
483 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
484
485 // request to reuse existing output stream if one is already opened to reach the RX device
486 SortedVector<audio_io_handle_t> outputs =
487 getOutputsForDevice(rxDevice, mOutputs);
488 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "updateCallRouting() RX device output is duplicated");
493 outputDesc->toAudioPortConfig(&patch.sources[1]);
494 patch.num_sources = 2;
495 }
496
497 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
498 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
499 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
500 status);
501 if (status == NO_ERROR) {
502 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
503 &patch, mUidCached);
504 mCallRxPatch->mAfPatchHandle = afPatchHandle;
505 mCallRxPatch->mUid = mUidCached;
506 }
507 createTxPatch = true;
508 }
509 if (createTxPatch) {
510
511 struct audio_patch patch;
512 patch.num_sources = 1;
513 patch.num_sinks = 1;
514 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
515 ALOG_ASSERT(!deviceList.isEmpty(),
516 "updateCallRouting() selected device not in input device list");
517 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
518 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
519 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
520 ALOG_ASSERT(!deviceList.isEmpty(),
521 "updateCallRouting() no telephony TX device");
522 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
523 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
524
525 SortedVector<audio_io_handle_t> outputs =
526 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
527 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
528 // request to reuse existing output stream if one is already opened to reach the TX
529 // path output device
530 if (output != AUDIO_IO_HANDLE_NONE) {
531 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
532 ALOG_ASSERT(!outputDesc->isDuplicated(),
533 "updateCallRouting() RX device output is duplicated");
534 outputDesc->toAudioPortConfig(&patch.sources[1]);
535 patch.num_sources = 2;
536 }
537
538 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
539 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
540 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
541 status);
542 if (status == NO_ERROR) {
543 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
544 &patch, mUidCached);
545 mCallTxPatch->mAfPatchHandle = afPatchHandle;
546 mCallTxPatch->mUid = mUidCached;
547 }
548 }
549}
550
Eric Laurente0720872014-03-11 09:30:41 -0700551void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700552{
553 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700554 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700555 ALOGW("setPhoneState() invalid state %d", state);
556 return;
557 }
558
559 if (state == mPhoneState ) {
560 ALOGW("setPhoneState() setting same state %d", state);
561 return;
562 }
563
564 // if leaving call state, handle special case of active streams
565 // pertaining to sonification strategy see handleIncallSonification()
566 if (isInCall()) {
567 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700568 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
569 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700570 }
571 }
572
573 // store previous phone state for management of sonification strategy below
574 int oldState = mPhoneState;
575 mPhoneState = state;
576 bool force = false;
577
578 // are we entering or starting a call
579 if (!isStateInCall(oldState) && isStateInCall(state)) {
580 ALOGV(" Entering call in setPhoneState()");
581 // force routing command to audio hardware when starting a call
582 // even if no device change is needed
583 force = true;
584 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
585 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
586 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
587 }
588 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
589 ALOGV(" Exiting call in setPhoneState()");
590 // force routing command to audio hardware when exiting a call
591 // even if no device change is needed
592 force = true;
593 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
594 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
595 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
596 }
597 } else if (isStateInCall(state) && (state != oldState)) {
598 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
599 // force routing command to audio hardware when switching between telephony and VoIP
600 // even if no device change is needed
601 force = true;
602 }
603
604 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700605 checkA2dpSuspend();
606 checkOutputForAllStrategies();
607 updateDevicesAndOutputs();
608
Eric Laurent1f2f2232014-06-02 12:01:23 -0700609 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700610
Eric Laurente552edb2014-03-10 17:42:56 -0700611 int delayMs = 0;
612 if (isStateInCall(state)) {
613 nsecs_t sysTime = systemTime();
614 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700615 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700616 // mute media and sonification strategies and delay device switch by the largest
617 // latency of any output where either strategy is active.
618 // This avoid sending the ring tone or music tail into the earpiece or headset.
619 if ((desc->isStrategyActive(STRATEGY_MEDIA,
620 SONIFICATION_HEADSET_MUSIC_DELAY,
621 sysTime) ||
622 desc->isStrategyActive(STRATEGY_SONIFICATION,
623 SONIFICATION_HEADSET_MUSIC_DELAY,
624 sysTime)) &&
625 (delayMs < (int)desc->mLatency*2)) {
626 delayMs = desc->mLatency*2;
627 }
628 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
629 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
630 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
631 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
632 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
633 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
634 }
635 }
636
Eric Laurentc2730ba2014-07-20 15:47:07 -0700637 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
638 // the device returned is not necessarily reachable via this output
639 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
640 // force routing command to audio hardware when ending call
641 // even if no device change is needed
642 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
643 rxDevice = hwOutputDesc->device();
644 }
Eric Laurente552edb2014-03-10 17:42:56 -0700645
Eric Laurentc2730ba2014-07-20 15:47:07 -0700646 if (state == AUDIO_MODE_IN_CALL) {
647 updateCallRouting(rxDevice, delayMs);
648 } else if (oldState == AUDIO_MODE_IN_CALL) {
649 if (mCallRxPatch != 0) {
650 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
651 mCallRxPatch.clear();
652 }
653 if (mCallTxPatch != 0) {
654 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
655 mCallTxPatch.clear();
656 }
657 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
658 } else {
659 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
660 }
Eric Laurente552edb2014-03-10 17:42:56 -0700661 // if entering in call state, handle special case of active streams
662 // pertaining to sonification strategy see handleIncallSonification()
663 if (isStateInCall(state)) {
664 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700665 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
666 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700667 }
668 }
669
670 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700671 if (state == AUDIO_MODE_RINGTONE &&
672 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700673 mLimitRingtoneVolume = true;
674 } else {
675 mLimitRingtoneVolume = false;
676 }
677}
678
Eric Laurente0720872014-03-11 09:30:41 -0700679void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700680 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700681{
682 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
683
684 bool forceVolumeReeval = false;
685 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700686 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
687 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
688 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700689 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
690 return;
691 }
692 forceVolumeReeval = true;
693 mForceUse[usage] = config;
694 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700695 case AUDIO_POLICY_FORCE_FOR_MEDIA:
696 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
697 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
698 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
699 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900700 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700701 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
702 return;
703 }
704 mForceUse[usage] = config;
705 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700706 case AUDIO_POLICY_FORCE_FOR_RECORD:
707 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
708 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700709 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
710 return;
711 }
712 mForceUse[usage] = config;
713 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700714 case AUDIO_POLICY_FORCE_FOR_DOCK:
715 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
716 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
717 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
718 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
719 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700720 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
721 }
722 forceVolumeReeval = true;
723 mForceUse[usage] = config;
724 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700725 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
726 if (config != AUDIO_POLICY_FORCE_NONE &&
727 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700728 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
729 }
730 forceVolumeReeval = true;
731 mForceUse[usage] = config;
732 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900733 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
734 if (config != AUDIO_POLICY_FORCE_NONE &&
735 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
736 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
737 }
738 mForceUse[usage] = config;
739 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700740 default:
741 ALOGW("setForceUse() invalid usage %d", usage);
742 break;
743 }
744
745 // check for device and output changes triggered by new force usage
746 checkA2dpSuspend();
747 checkOutputForAllStrategies();
748 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700749 if (mPhoneState == AUDIO_MODE_IN_CALL) {
750 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
751 updateCallRouting(newDevice);
752 }
Eric Laurente552edb2014-03-10 17:42:56 -0700753 for (size_t i = 0; i < mOutputs.size(); i++) {
754 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700755 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700756 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
757 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
758 }
Eric Laurente552edb2014-03-10 17:42:56 -0700759 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
760 applyStreamVolumes(output, newDevice, 0, true);
761 }
762 }
763
764 audio_io_handle_t activeInput = getActiveInput();
765 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700766 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700767 }
768
769}
770
Eric Laurente0720872014-03-11 09:30:41 -0700771audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700772{
773 return mForceUse[usage];
774}
775
Eric Laurente0720872014-03-11 09:30:41 -0700776void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700777{
778 ALOGV("setSystemProperty() property %s, value %s", property, value);
779}
780
781// Find a direct output profile compatible with the parameters passed, even if the input flags do
782// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700783sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700784 audio_devices_t device,
785 uint32_t samplingRate,
786 audio_format_t format,
787 audio_channel_mask_t channelMask,
788 audio_output_flags_t flags)
789{
790 for (size_t i = 0; i < mHwModules.size(); i++) {
791 if (mHwModules[i]->mHandle == 0) {
792 continue;
793 }
794 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700795 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700796 bool found = profile->isCompatibleProfile(device, samplingRate,
797 NULL /*updatedSamplingRate*/, format, channelMask,
798 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
799 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700800 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
801 return profile;
802 }
Eric Laurente552edb2014-03-10 17:42:56 -0700803 }
804 }
805 return 0;
806}
807
Eric Laurente0720872014-03-11 09:30:41 -0700808audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700809 uint32_t samplingRate,
810 audio_format_t format,
811 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700812 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700813 const audio_offload_info_t *offloadInfo)
814{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700815
Eric Laurent3b73df72014-03-11 09:06:29 -0700816 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
818 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
819 device, stream, samplingRate, format, channelMask, flags);
820
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700821 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
822 offloadInfo);
823}
824
825audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
826 uint32_t samplingRate,
827 audio_format_t format,
828 audio_channel_mask_t channelMask,
829 audio_output_flags_t flags,
830 const audio_offload_info_t *offloadInfo)
831{
832 if (attr == NULL) {
833 ALOGE("getOutputForAttr() called with NULL audio attributes");
834 return 0;
835 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700836 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
837 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700838
839 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
840 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
841 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700842
843 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
844 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
845 }
846
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700847 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
848 device, samplingRate, format, channelMask, flags);
849
850 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
851 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
852 offloadInfo);
853}
854
855audio_io_handle_t AudioPolicyManager::getOutputForDevice(
856 audio_devices_t device,
857 audio_stream_type_t stream,
858 uint32_t samplingRate,
859 audio_format_t format,
860 audio_channel_mask_t channelMask,
861 audio_output_flags_t flags,
862 const audio_offload_info_t *offloadInfo)
863{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700864 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700866 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700867
Eric Laurente552edb2014-03-10 17:42:56 -0700868#ifdef AUDIO_POLICY_TEST
869 if (mCurOutput != 0) {
870 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
871 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
872
873 if (mTestOutputs[mCurOutput] == 0) {
874 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700875 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700876 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700877 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700878 outputDesc->mFlags =
879 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700880 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700881 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
882 config.sample_rate = mTestSamplingRate;
883 config.channel_mask = mTestChannels;
884 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700885 if (offloadInfo != NULL) {
886 config.offload_info = *offloadInfo;
887 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700888 status = mpClientInterface->openOutput(0,
889 &mTestOutputs[mCurOutput],
890 &config,
891 &outputDesc->mDevice,
892 String8(""),
893 &outputDesc->mLatency,
894 outputDesc->mFlags);
895 if (status == NO_ERROR) {
896 outputDesc->mSamplingRate = config.sample_rate;
897 outputDesc->mFormat = config.format;
898 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700899 AudioParameter outputCmd = AudioParameter();
900 outputCmd.addInt(String8("set_id"),mCurOutput);
901 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
902 addOutput(mTestOutputs[mCurOutput], outputDesc);
903 }
904 }
905 return mTestOutputs[mCurOutput];
906 }
907#endif //AUDIO_POLICY_TEST
908
909 // open a direct output if required by specified parameters
910 //force direct flag if offload flag is set: offloading implies a direct output stream
911 // and all common behaviors are driven by checking only the direct flag
912 // this should normally be set appropriately in the policy configuration file
913 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700914 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700915 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700916 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
917 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
918 }
Eric Laurente552edb2014-03-10 17:42:56 -0700919
920 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
921 // creating an offloaded track and tearing it down immediately after start when audioflinger
922 // detects there is an active non offloadable effect.
923 // FIXME: We should check the audio session here but we do not have it in this context.
924 // This may prevent offloading in rare situations where effects are left active by apps
925 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700926 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700927 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
928 !isNonOffloadableEffectEnabled()) {
929 profile = getProfileForDirectOutput(device,
930 samplingRate,
931 format,
932 channelMask,
933 (audio_output_flags_t)flags);
934 }
935
Eric Laurent1c333e22014-05-20 10:48:17 -0700936 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700937 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700938
939 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700940 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700941 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
942 outputDesc = desc;
943 // reuse direct output if currently open and configured with same parameters
944 if ((samplingRate == outputDesc->mSamplingRate) &&
945 (format == outputDesc->mFormat) &&
946 (channelMask == outputDesc->mChannelMask)) {
947 outputDesc->mDirectOpenCount++;
948 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
949 return mOutputs.keyAt(i);
950 }
951 }
952 }
953 // close direct output if currently open and configured with different parameters
954 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700955 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700956 }
957 outputDesc = new AudioOutputDescriptor(profile);
958 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700959 outputDesc->mLatency = 0;
960 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700961 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
962 config.sample_rate = samplingRate;
963 config.channel_mask = channelMask;
964 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700965 if (offloadInfo != NULL) {
966 config.offload_info = *offloadInfo;
967 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700968 status = mpClientInterface->openOutput(profile->mModule->mHandle,
969 &output,
970 &config,
971 &outputDesc->mDevice,
972 String8(""),
973 &outputDesc->mLatency,
974 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700977 if (status != NO_ERROR ||
978 (samplingRate != 0 && samplingRate != config.sample_rate) ||
979 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
980 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700981 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
982 "format %d %d, channelMask %04x %04x", output, samplingRate,
983 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
984 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700985 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700986 mpClientInterface->closeOutput(output);
987 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700988 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700990 outputDesc->mSamplingRate = config.sample_rate;
991 outputDesc->mChannelMask = config.channel_mask;
992 outputDesc->mFormat = config.format;
993 outputDesc->mRefCount[stream] = 0;
994 outputDesc->mStopTime[stream] = 0;
995 outputDesc->mDirectOpenCount = 1;
996
Eric Laurente552edb2014-03-10 17:42:56 -0700997 audio_io_handle_t srcOutput = getOutputForEffect();
998 addOutput(output, outputDesc);
999 audio_io_handle_t dstOutput = getOutputForEffect();
1000 if (dstOutput == output) {
1001 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1002 }
1003 mPreviousOutputs = mOutputs;
1004 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001005 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001006 return output;
1007 }
1008
1009 // ignoring channel mask due to downmix capability in mixer
1010
1011 // open a non direct output
1012
1013 // for non direct outputs, only PCM is supported
1014 if (audio_is_linear_pcm(format)) {
1015 // get which output is suitable for the specified stream. The actual
1016 // routing change will happen when startOutput() will be called
1017 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1018
1019 output = selectOutput(outputs, flags);
1020 }
1021 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1022 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1023
1024 ALOGV("getOutput() returns output %d", output);
1025
1026 return output;
1027}
1028
Eric Laurente0720872014-03-11 09:30:41 -07001029audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -07001030 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001031{
1032 // select one output among several that provide a path to a particular device or set of
1033 // devices (the list was previously build by getOutputsForDevice()).
1034 // The priority is as follows:
1035 // 1: the output with the highest number of requested policy flags
1036 // 2: the primary output
1037 // 3: the first output in the list
1038
1039 if (outputs.size() == 0) {
1040 return 0;
1041 }
1042 if (outputs.size() == 1) {
1043 return outputs[0];
1044 }
1045
1046 int maxCommonFlags = 0;
1047 audio_io_handle_t outputFlags = 0;
1048 audio_io_handle_t outputPrimary = 0;
1049
1050 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001051 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001052 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001053 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 if (commonFlags > maxCommonFlags) {
1055 outputFlags = outputs[i];
1056 maxCommonFlags = commonFlags;
1057 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1058 }
1059 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1060 outputPrimary = outputs[i];
1061 }
1062 }
1063 }
1064
1065 if (outputFlags != 0) {
1066 return outputFlags;
1067 }
1068 if (outputPrimary != 0) {
1069 return outputPrimary;
1070 }
1071
1072 return outputs[0];
1073}
1074
Eric Laurente0720872014-03-11 09:30:41 -07001075status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001076 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001077 int session)
1078{
1079 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1080 ssize_t index = mOutputs.indexOfKey(output);
1081 if (index < 0) {
1082 ALOGW("startOutput() unknown output %d", output);
1083 return BAD_VALUE;
1084 }
1085
Eric Laurent1f2f2232014-06-02 12:01:23 -07001086 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001087
1088 // increment usage count for this stream on the requested output:
1089 // NOTE that the usage count is the same for duplicated output and hardware output which is
1090 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1091 outputDesc->changeRefCount(stream, 1);
1092
1093 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001094 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001095 routing_strategy strategy = getStrategy(stream);
1096 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1097 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1098 uint32_t waitMs = 0;
1099 bool force = false;
1100 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001101 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001102 if (desc != outputDesc) {
1103 // force a device change if any other output is managed by the same hw
1104 // module and has a current device selection that differs from selected device.
1105 // In this case, the audio HAL must receive the new device selection so that it can
1106 // change the device currently selected by the other active output.
1107 if (outputDesc->sharesHwModuleWith(desc) &&
1108 desc->device() != newDevice) {
1109 force = true;
1110 }
1111 // wait for audio on other active outputs to be presented when starting
1112 // a notification so that audio focus effect can propagate.
1113 uint32_t latency = desc->latency();
1114 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1115 waitMs = latency;
1116 }
1117 }
1118 }
1119 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1120
1121 // handle special case for sonification while in call
1122 if (isInCall()) {
1123 handleIncallSonification(stream, true, false);
1124 }
1125
1126 // apply volume rules for current stream and device if necessary
1127 checkAndSetVolume(stream,
1128 mStreams[stream].getVolumeIndex(newDevice),
1129 output,
1130 newDevice);
1131
1132 // update the outputs if starting an output with a stream that can affect notification
1133 // routing
1134 handleNotificationRoutingForStream(stream);
1135 if (waitMs > muteWaitMs) {
1136 usleep((waitMs - muteWaitMs) * 2 * 1000);
1137 }
1138 }
1139 return NO_ERROR;
1140}
1141
1142
Eric Laurente0720872014-03-11 09:30:41 -07001143status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001144 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001145 int session)
1146{
1147 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1148 ssize_t index = mOutputs.indexOfKey(output);
1149 if (index < 0) {
1150 ALOGW("stopOutput() unknown output %d", output);
1151 return BAD_VALUE;
1152 }
1153
Eric Laurent1f2f2232014-06-02 12:01:23 -07001154 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001155
1156 // handle special case for sonification while in call
1157 if (isInCall()) {
1158 handleIncallSonification(stream, false, false);
1159 }
1160
1161 if (outputDesc->mRefCount[stream] > 0) {
1162 // decrement usage count of this stream on the output
1163 outputDesc->changeRefCount(stream, -1);
1164 // store time at which the stream was stopped - see isStreamActive()
1165 if (outputDesc->mRefCount[stream] == 0) {
1166 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001167 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001168 // delay the device switch by twice the latency because stopOutput() is executed when
1169 // the track stop() command is received and at that time the audio track buffer can
1170 // still contain data that needs to be drained. The latency only covers the audio HAL
1171 // and kernel buffers. Also the latency does not always include additional delay in the
1172 // audio path (audio DSP, CODEC ...)
1173 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1174
1175 // force restoring the device selection on other active outputs if it differs from the
1176 // one being selected for this output
1177 for (size_t i = 0; i < mOutputs.size(); i++) {
1178 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001179 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 if (curOutput != output &&
1181 desc->isActive() &&
1182 outputDesc->sharesHwModuleWith(desc) &&
1183 (newDevice != desc->device())) {
1184 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001185 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001186 true,
1187 outputDesc->mLatency*2);
1188 }
1189 }
1190 // update the outputs if stopping one with a stream that can affect notification routing
1191 handleNotificationRoutingForStream(stream);
1192 }
1193 return NO_ERROR;
1194 } else {
1195 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1196 return INVALID_OPERATION;
1197 }
1198}
1199
Eric Laurente0720872014-03-11 09:30:41 -07001200void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001201{
1202 ALOGV("releaseOutput() %d", output);
1203 ssize_t index = mOutputs.indexOfKey(output);
1204 if (index < 0) {
1205 ALOGW("releaseOutput() releasing unknown output %d", output);
1206 return;
1207 }
1208
1209#ifdef AUDIO_POLICY_TEST
1210 int testIndex = testOutputIndex(output);
1211 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001212 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001213 if (outputDesc->isActive()) {
1214 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001215 mOutputs.removeItem(output);
1216 mTestOutputs[testIndex] = 0;
1217 }
1218 return;
1219 }
1220#endif //AUDIO_POLICY_TEST
1221
Eric Laurent1f2f2232014-06-02 12:01:23 -07001222 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001223 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001224 if (desc->mDirectOpenCount <= 0) {
1225 ALOGW("releaseOutput() invalid open count %d for output %d",
1226 desc->mDirectOpenCount, output);
1227 return;
1228 }
1229 if (--desc->mDirectOpenCount == 0) {
1230 closeOutput(output);
1231 // If effects where present on the output, audioflinger moved them to the primary
1232 // output by default: move them back to the appropriate output.
1233 audio_io_handle_t dstOutput = getOutputForEffect();
1234 if (dstOutput != mPrimaryOutput) {
1235 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1236 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001237 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001238 }
1239 }
1240}
1241
1242
Eric Laurente0720872014-03-11 09:30:41 -07001243audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001244 uint32_t samplingRate,
1245 audio_format_t format,
1246 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001247 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001248 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001249{
Eric Laurent4dc68062014-07-28 17:26:49 -07001250 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001251 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001252 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001253
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001254 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001255
1256 if (device == AUDIO_DEVICE_NONE) {
1257 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001258 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001259 }
1260
1261 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001262 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001263 case AUDIO_SOURCE_VOICE_UPLINK:
1264 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1265 break;
1266 case AUDIO_SOURCE_VOICE_DOWNLINK:
1267 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1268 break;
1269 case AUDIO_SOURCE_VOICE_CALL:
1270 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1271 break;
1272 default:
1273 break;
1274 }
1275
Eric Laurent1c333e22014-05-20 10:48:17 -07001276 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001277 samplingRate,
1278 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001279 channelMask,
1280 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001281 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001282 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1283 "channelMask 0x%X, flags %#x",
1284 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001285 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001286 }
1287
1288 if (profile->mModule->mHandle == 0) {
1289 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001290 return AUDIO_IO_HANDLE_NONE;
1291 }
1292
1293 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1294 config.sample_rate = samplingRate;
1295 config.channel_mask = channelMask;
1296 config.format = format;
1297 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001298
1299 bool isSoundTrigger = false;
1300 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1301 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1302 if (index >= 0) {
1303 input = mSoundTriggerSessions.valueFor(session);
1304 isSoundTrigger = true;
1305 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1306 }
1307 }
1308
Eric Laurentcf2c0212014-07-25 16:20:43 -07001309 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1310 &input,
1311 &config,
1312 &device,
1313 String8(""),
1314 inputSource,
1315 flags);
1316
1317 // only accept input with the exact requested set of parameters
1318 if (status != NO_ERROR ||
1319 (samplingRate != config.sample_rate) ||
1320 (format != config.format) ||
1321 (channelMask != config.channel_mask)) {
1322 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1323 samplingRate, format, channelMask);
1324 if (input != AUDIO_IO_HANDLE_NONE) {
1325 mpClientInterface->closeInput(input);
1326 }
1327 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001328 }
1329
Eric Laurent1f2f2232014-06-02 12:01:23 -07001330 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001331 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001332 inputDesc->mRefCount = 0;
1333 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001334 inputDesc->mSamplingRate = samplingRate;
1335 inputDesc->mFormat = format;
1336 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001337 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001338 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001339 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001340
Eric Laurentd4692962014-05-05 18:13:44 -07001341 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001342 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001343 return input;
1344}
1345
Eric Laurent4dc68062014-07-28 17:26:49 -07001346status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1347 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001348{
1349 ALOGV("startInput() input %d", input);
1350 ssize_t index = mInputs.indexOfKey(input);
1351 if (index < 0) {
1352 ALOGW("startInput() unknown input %d", input);
1353 return BAD_VALUE;
1354 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001355 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001356
Eric Laurent4dc68062014-07-28 17:26:49 -07001357 index = inputDesc->mSessions.indexOf(session);
1358 if (index < 0) {
1359 ALOGW("startInput() unknown session %d on input %d", session, input);
1360 return BAD_VALUE;
1361 }
1362
Glenn Kasten74a8e252014-07-24 14:09:55 -07001363 // virtual input devices are compatible with other input devices
1364 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1365
1366 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001367 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001368 if (activeInput != 0 && activeInput != input) {
1369
1370 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1371 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001372 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001373 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001374 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001375 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1376 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001377 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001378 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001379 return INVALID_OPERATION;
1380 }
1381 }
1382 }
1383
Glenn Kasten74a8e252014-07-24 14:09:55 -07001384 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001385 if (activeInputsCount() == 0) {
1386 SoundTrigger::setCaptureState(true);
1387 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001388 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001389
Glenn Kasten74a8e252014-07-24 14:09:55 -07001390 // Automatically enable the remote submix output when input is started.
1391 // For remote submix (a virtual device), we open only one input per capture request.
1392 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1393 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1394 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1395 }
Eric Laurente552edb2014-03-10 17:42:56 -07001396 }
1397
Eric Laurente552edb2014-03-10 17:42:56 -07001398 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1399
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001400 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001401 return NO_ERROR;
1402}
1403
Eric Laurent4dc68062014-07-28 17:26:49 -07001404status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1405 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001406{
1407 ALOGV("stopInput() input %d", input);
1408 ssize_t index = mInputs.indexOfKey(input);
1409 if (index < 0) {
1410 ALOGW("stopInput() unknown input %d", input);
1411 return BAD_VALUE;
1412 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001413 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001414
Eric Laurent4dc68062014-07-28 17:26:49 -07001415 index = inputDesc->mSessions.indexOf(session);
1416 if (index < 0) {
1417 ALOGW("stopInput() unknown session %d on input %d", session, input);
1418 return BAD_VALUE;
1419 }
1420
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (inputDesc->mRefCount == 0) {
1422 ALOGW("stopInput() input %d already stopped", input);
1423 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001424 }
1425
1426 inputDesc->mRefCount--;
1427 if (inputDesc->mRefCount == 0) {
1428
Eric Laurente552edb2014-03-10 17:42:56 -07001429 // automatically disable the remote submix output when input is stopped
1430 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1431 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001432 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001433 }
1434
Eric Laurent1c333e22014-05-20 10:48:17 -07001435 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001436
1437 if (activeInputsCount() == 0) {
1438 SoundTrigger::setCaptureState(false);
1439 }
Eric Laurente552edb2014-03-10 17:42:56 -07001440 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001441 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001442}
1443
Eric Laurent4dc68062014-07-28 17:26:49 -07001444void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1445 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001446{
1447 ALOGV("releaseInput() %d", input);
1448 ssize_t index = mInputs.indexOfKey(input);
1449 if (index < 0) {
1450 ALOGW("releaseInput() releasing unknown input %d", input);
1451 return;
1452 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001453 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1454 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001455
1456 index = inputDesc->mSessions.indexOf(session);
1457 if (index < 0) {
1458 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1459 return;
1460 }
1461 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001462 if (inputDesc->mOpenRefCount == 0) {
1463 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1464 return;
1465 }
1466 inputDesc->mOpenRefCount--;
1467 if (inputDesc->mOpenRefCount > 0) {
1468 ALOGV("releaseInput() exit > 0");
1469 return;
1470 }
1471
Eric Laurent05b90f82014-08-27 15:32:29 -07001472 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001473 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001474 ALOGV("releaseInput() exit");
1475}
1476
Eric Laurentd4692962014-05-05 18:13:44 -07001477void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001478 bool patchRemoved = false;
1479
Eric Laurentd4692962014-05-05 18:13:44 -07001480 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001481 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1482 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1483 if (patch_index >= 0) {
1484 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1485 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1486 mAudioPatches.removeItemsAt(patch_index);
1487 patchRemoved = true;
1488 }
Eric Laurentd4692962014-05-05 18:13:44 -07001489 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1490 }
1491 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001492 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001493
1494 if (patchRemoved) {
1495 mpClientInterface->onAudioPatchListUpdate();
1496 }
Eric Laurentd4692962014-05-05 18:13:44 -07001497}
1498
Eric Laurente0720872014-03-11 09:30:41 -07001499void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001500 int indexMin,
1501 int indexMax)
1502{
1503 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1504 if (indexMin < 0 || indexMin >= indexMax) {
1505 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1506 return;
1507 }
1508 mStreams[stream].mIndexMin = indexMin;
1509 mStreams[stream].mIndexMax = indexMax;
1510}
1511
Eric Laurente0720872014-03-11 09:30:41 -07001512status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001513 int index,
1514 audio_devices_t device)
1515{
1516
1517 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1518 return BAD_VALUE;
1519 }
1520 if (!audio_is_output_device(device)) {
1521 return BAD_VALUE;
1522 }
1523
1524 // Force max volume if stream cannot be muted
1525 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1526
1527 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1528 stream, device, index);
1529
1530 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1531 // clear all device specific values
1532 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1533 mStreams[stream].mIndexCur.clear();
1534 }
1535 mStreams[stream].mIndexCur.add(device, index);
1536
1537 // compute and apply stream volume on all outputs according to connected device
1538 status_t status = NO_ERROR;
1539 for (size_t i = 0; i < mOutputs.size(); i++) {
1540 audio_devices_t curDevice =
1541 getDeviceForVolume(mOutputs.valueAt(i)->device());
1542 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1543 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1544 if (volStatus != NO_ERROR) {
1545 status = volStatus;
1546 }
1547 }
1548 }
1549 return status;
1550}
1551
Eric Laurente0720872014-03-11 09:30:41 -07001552status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001553 int *index,
1554 audio_devices_t device)
1555{
1556 if (index == NULL) {
1557 return BAD_VALUE;
1558 }
1559 if (!audio_is_output_device(device)) {
1560 return BAD_VALUE;
1561 }
1562 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1563 // the strategy the stream belongs to.
1564 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1565 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1566 }
1567 device = getDeviceForVolume(device);
1568
1569 *index = mStreams[stream].getVolumeIndex(device);
1570 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1571 return NO_ERROR;
1572}
1573
Eric Laurente0720872014-03-11 09:30:41 -07001574audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001575 const SortedVector<audio_io_handle_t>& outputs)
1576{
1577 // select one output among several suitable for global effects.
1578 // The priority is as follows:
1579 // 1: An offloaded output. If the effect ends up not being offloadable,
1580 // AudioFlinger will invalidate the track and the offloaded output
1581 // will be closed causing the effect to be moved to a PCM output.
1582 // 2: A deep buffer output
1583 // 3: the first output in the list
1584
1585 if (outputs.size() == 0) {
1586 return 0;
1587 }
1588
1589 audio_io_handle_t outputOffloaded = 0;
1590 audio_io_handle_t outputDeepBuffer = 0;
1591
1592 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001593 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001594 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001595 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1596 outputOffloaded = outputs[i];
1597 }
1598 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1599 outputDeepBuffer = outputs[i];
1600 }
1601 }
1602
1603 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1604 outputOffloaded, outputDeepBuffer);
1605 if (outputOffloaded != 0) {
1606 return outputOffloaded;
1607 }
1608 if (outputDeepBuffer != 0) {
1609 return outputDeepBuffer;
1610 }
1611
1612 return outputs[0];
1613}
1614
Eric Laurente0720872014-03-11 09:30:41 -07001615audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001616{
1617 // apply simple rule where global effects are attached to the same output as MUSIC streams
1618
Eric Laurent3b73df72014-03-11 09:06:29 -07001619 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001620 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1621 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1622
1623 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1624 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1625 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1626
1627 return output;
1628}
1629
Eric Laurente0720872014-03-11 09:30:41 -07001630status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001631 audio_io_handle_t io,
1632 uint32_t strategy,
1633 int session,
1634 int id)
1635{
1636 ssize_t index = mOutputs.indexOfKey(io);
1637 if (index < 0) {
1638 index = mInputs.indexOfKey(io);
1639 if (index < 0) {
1640 ALOGW("registerEffect() unknown io %d", io);
1641 return INVALID_OPERATION;
1642 }
1643 }
1644
1645 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1646 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1647 desc->name, desc->memoryUsage);
1648 return INVALID_OPERATION;
1649 }
1650 mTotalEffectsMemory += desc->memoryUsage;
1651 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1652 desc->name, io, strategy, session, id);
1653 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1654
Eric Laurent1f2f2232014-06-02 12:01:23 -07001655 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1656 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1657 effectDesc->mIo = io;
1658 effectDesc->mStrategy = (routing_strategy)strategy;
1659 effectDesc->mSession = session;
1660 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001661
Eric Laurent1f2f2232014-06-02 12:01:23 -07001662 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001663
1664 return NO_ERROR;
1665}
1666
Eric Laurente0720872014-03-11 09:30:41 -07001667status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001668{
1669 ssize_t index = mEffects.indexOfKey(id);
1670 if (index < 0) {
1671 ALOGW("unregisterEffect() unknown effect ID %d", id);
1672 return INVALID_OPERATION;
1673 }
1674
Eric Laurent1f2f2232014-06-02 12:01:23 -07001675 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001676
Eric Laurent1f2f2232014-06-02 12:01:23 -07001677 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001678
Eric Laurent1f2f2232014-06-02 12:01:23 -07001679 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001680 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001681 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1682 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001683 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001684 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001685 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001686 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001687
1688 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001689
1690 return NO_ERROR;
1691}
1692
Eric Laurente0720872014-03-11 09:30:41 -07001693status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001694{
1695 ssize_t index = mEffects.indexOfKey(id);
1696 if (index < 0) {
1697 ALOGW("unregisterEffect() unknown effect ID %d", id);
1698 return INVALID_OPERATION;
1699 }
1700
1701 return setEffectEnabled(mEffects.valueAt(index), enabled);
1702}
1703
Eric Laurent1f2f2232014-06-02 12:01:23 -07001704status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001705{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001706 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001707 ALOGV("setEffectEnabled(%s) effect already %s",
1708 enabled?"true":"false", enabled?"enabled":"disabled");
1709 return INVALID_OPERATION;
1710 }
1711
1712 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001713 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001714 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001715 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001716 return INVALID_OPERATION;
1717 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001718 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001719 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1720 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001721 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001722 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1724 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001725 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001726 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001727 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1728 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001729 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001730 return NO_ERROR;
1731}
1732
Eric Laurente0720872014-03-11 09:30:41 -07001733bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001734{
1735 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1737 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1738 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001739 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001740 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001741 return true;
1742 }
1743 }
1744 return false;
1745}
1746
Eric Laurente0720872014-03-11 09:30:41 -07001747bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001748{
1749 nsecs_t sysTime = systemTime();
1750 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001751 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001752 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001753 return true;
1754 }
1755 }
1756 return false;
1757}
1758
Eric Laurente0720872014-03-11 09:30:41 -07001759bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001760 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001761{
1762 nsecs_t sysTime = systemTime();
1763 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001764 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001765 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001766 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001767 return true;
1768 }
1769 }
1770 return false;
1771}
1772
Eric Laurente0720872014-03-11 09:30:41 -07001773bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001774{
1775 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001776 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001777 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001778 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001779 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1780 && (inputDescriptor->mRefCount > 0)) {
1781 return true;
1782 }
1783 }
1784 return false;
1785}
1786
1787
Eric Laurente0720872014-03-11 09:30:41 -07001788status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001789{
1790 const size_t SIZE = 256;
1791 char buffer[SIZE];
1792 String8 result;
1793
1794 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1795 result.append(buffer);
1796
1797 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1798 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001799 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1800 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001801 snprintf(buffer, SIZE, " Force use for communications %d\n",
1802 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001803 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001804 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001805 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001806 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001807 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001808 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001809 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001810 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001811 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001812 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1813 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1814 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
Eric Laurent3a4311c2014-03-17 12:00:47 -07001816 snprintf(buffer, SIZE, " Available output devices:\n");
1817 result.append(buffer);
1818 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001819 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001820 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001821 }
1822 snprintf(buffer, SIZE, "\n Available input devices:\n");
1823 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001824 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001825 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001826 }
Eric Laurente552edb2014-03-10 17:42:56 -07001827
1828 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1829 write(fd, buffer, strlen(buffer));
1830 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001831 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001832 write(fd, buffer, strlen(buffer));
1833 mHwModules[i]->dump(fd);
1834 }
1835
1836 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1837 write(fd, buffer, strlen(buffer));
1838 for (size_t i = 0; i < mOutputs.size(); i++) {
1839 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1840 write(fd, buffer, strlen(buffer));
1841 mOutputs.valueAt(i)->dump(fd);
1842 }
1843
1844 snprintf(buffer, SIZE, "\nInputs dump:\n");
1845 write(fd, buffer, strlen(buffer));
1846 for (size_t i = 0; i < mInputs.size(); i++) {
1847 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1848 write(fd, buffer, strlen(buffer));
1849 mInputs.valueAt(i)->dump(fd);
1850 }
1851
1852 snprintf(buffer, SIZE, "\nStreams dump:\n");
1853 write(fd, buffer, strlen(buffer));
1854 snprintf(buffer, SIZE,
1855 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1856 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001857 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001858 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001859 write(fd, buffer, strlen(buffer));
1860 mStreams[i].dump(fd);
1861 }
1862
1863 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1864 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1865 write(fd, buffer, strlen(buffer));
1866
1867 snprintf(buffer, SIZE, "Registered effects:\n");
1868 write(fd, buffer, strlen(buffer));
1869 for (size_t i = 0; i < mEffects.size(); i++) {
1870 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1871 write(fd, buffer, strlen(buffer));
1872 mEffects.valueAt(i)->dump(fd);
1873 }
1874
Eric Laurent4d416952014-08-10 14:07:09 -07001875 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1876 write(fd, buffer, strlen(buffer));
1877 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1878 mAudioPatches[i]->dump(fd, 2, i);
1879 }
Eric Laurente552edb2014-03-10 17:42:56 -07001880
1881 return NO_ERROR;
1882}
1883
1884// This function checks for the parameters which can be offloaded.
1885// This can be enhanced depending on the capability of the DSP and policy
1886// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001887bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001888{
1889 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001890 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001891 offloadInfo.sample_rate, offloadInfo.channel_mask,
1892 offloadInfo.format,
1893 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1894 offloadInfo.has_video);
1895
1896 // Check if offload has been disabled
1897 char propValue[PROPERTY_VALUE_MAX];
1898 if (property_get("audio.offload.disable", propValue, "0")) {
1899 if (atoi(propValue) != 0) {
1900 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1901 return false;
1902 }
1903 }
1904
1905 // Check if stream type is music, then only allow offload as of now.
1906 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1907 {
1908 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1909 return false;
1910 }
1911
1912 //TODO: enable audio offloading with video when ready
1913 if (offloadInfo.has_video)
1914 {
1915 ALOGV("isOffloadSupported: has_video == true, returning false");
1916 return false;
1917 }
1918
1919 //If duration is less than minimum value defined in property, return false
1920 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1921 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1922 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1923 return false;
1924 }
1925 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1926 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1927 return false;
1928 }
1929
1930 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1931 // creating an offloaded track and tearing it down immediately after start when audioflinger
1932 // detects there is an active non offloadable effect.
1933 // FIXME: We should check the audio session here but we do not have it in this context.
1934 // This may prevent offloading in rare situations where effects are left active by apps
1935 // in the background.
1936 if (isNonOffloadableEffectEnabled()) {
1937 return false;
1938 }
1939
1940 // See if there is a profile to support this.
1941 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001942 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001943 offloadInfo.sample_rate,
1944 offloadInfo.format,
1945 offloadInfo.channel_mask,
1946 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001947 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1948 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001949}
1950
Eric Laurent6a94d692014-05-20 11:18:06 -07001951status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1952 audio_port_type_t type,
1953 unsigned int *num_ports,
1954 struct audio_port *ports,
1955 unsigned int *generation)
1956{
1957 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1958 generation == NULL) {
1959 return BAD_VALUE;
1960 }
1961 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1962 if (ports == NULL) {
1963 *num_ports = 0;
1964 }
1965
1966 size_t portsWritten = 0;
1967 size_t portsMax = *num_ports;
1968 *num_ports = 0;
1969 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1970 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1971 for (size_t i = 0;
1972 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1973 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1974 }
1975 *num_ports += mAvailableOutputDevices.size();
1976 }
1977 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1978 for (size_t i = 0;
1979 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1980 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1981 }
1982 *num_ports += mAvailableInputDevices.size();
1983 }
1984 }
1985 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1986 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1987 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1988 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1989 }
1990 *num_ports += mInputs.size();
1991 }
1992 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001993 size_t numOutputs = 0;
1994 for (size_t i = 0; i < mOutputs.size(); i++) {
1995 if (!mOutputs[i]->isDuplicated()) {
1996 numOutputs++;
1997 if (portsWritten < portsMax) {
1998 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1999 }
2000 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002001 }
Eric Laurent84c70242014-06-23 08:46:27 -07002002 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002003 }
2004 }
2005 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002006 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002007 return NO_ERROR;
2008}
2009
2010status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2011{
2012 return NO_ERROR;
2013}
2014
Eric Laurent1f2f2232014-06-02 12:01:23 -07002015sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002016 audio_port_handle_t id) const
2017{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002018 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002019 for (size_t i = 0; i < mOutputs.size(); i++) {
2020 outputDesc = mOutputs.valueAt(i);
2021 if (outputDesc->mId == id) {
2022 break;
2023 }
2024 }
2025 return outputDesc;
2026}
2027
Eric Laurent1f2f2232014-06-02 12:01:23 -07002028sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002029 audio_port_handle_t id) const
2030{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002031 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002032 for (size_t i = 0; i < mInputs.size(); i++) {
2033 inputDesc = mInputs.valueAt(i);
2034 if (inputDesc->mId == id) {
2035 break;
2036 }
2037 }
2038 return inputDesc;
2039}
2040
Eric Laurent1f2f2232014-06-02 12:01:23 -07002041sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2042 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002043{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002044 sp <HwModule> module;
2045
Eric Laurent6a94d692014-05-20 11:18:06 -07002046 for (size_t i = 0; i < mHwModules.size(); i++) {
2047 if (mHwModules[i]->mHandle == 0) {
2048 continue;
2049 }
2050 if (audio_is_output_device(device)) {
2051 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2052 {
2053 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2054 return mHwModules[i];
2055 }
2056 }
2057 } else {
2058 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2059 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2060 device & ~AUDIO_DEVICE_BIT_IN) {
2061 return mHwModules[i];
2062 }
2063 }
2064 }
2065 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002066 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002067}
2068
Eric Laurent1f2f2232014-06-02 12:01:23 -07002069sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002070{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002071 sp <HwModule> module;
2072
Eric Laurent1afeecb2014-05-14 08:52:28 -07002073 for (size_t i = 0; i < mHwModules.size(); i++)
2074 {
2075 if (strcmp(mHwModules[i]->mName, name) == 0) {
2076 return mHwModules[i];
2077 }
2078 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002079 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002080}
2081
Eric Laurentc2730ba2014-07-20 15:47:07 -07002082audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2083{
2084 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2085 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2086 return devices & mAvailableOutputDevices.types();
2087}
2088
2089audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2090{
2091 audio_module_handle_t primaryHandle =
2092 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2093 audio_devices_t devices = AUDIO_DEVICE_NONE;
2094 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2095 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2096 devices |= mAvailableInputDevices[i]->mDeviceType;
2097 }
2098 }
2099 return devices;
2100}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002101
Eric Laurent6a94d692014-05-20 11:18:06 -07002102status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2103 audio_patch_handle_t *handle,
2104 uid_t uid)
2105{
2106 ALOGV("createAudioPatch()");
2107
2108 if (handle == NULL || patch == NULL) {
2109 return BAD_VALUE;
2110 }
2111 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2112
Eric Laurent874c42872014-08-08 15:13:39 -07002113 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2114 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2115 return BAD_VALUE;
2116 }
2117 // only one source per audio patch supported for now
2118 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002119 return INVALID_OPERATION;
2120 }
Eric Laurent874c42872014-08-08 15:13:39 -07002121
2122 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002123 return INVALID_OPERATION;
2124 }
Eric Laurent874c42872014-08-08 15:13:39 -07002125 for (size_t i = 0; i < patch->num_sinks; i++) {
2126 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2127 return INVALID_OPERATION;
2128 }
2129 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002130
2131 sp<AudioPatch> patchDesc;
2132 ssize_t index = mAudioPatches.indexOfKey(*handle);
2133
Eric Laurent6a94d692014-05-20 11:18:06 -07002134 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2135 patch->sources[0].role,
2136 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002137#if LOG_NDEBUG == 0
2138 for (size_t i = 0; i < patch->num_sinks; i++) {
2139 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2140 patch->sinks[i].role,
2141 patch->sinks[i].type);
2142 }
2143#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002144
2145 if (index >= 0) {
2146 patchDesc = mAudioPatches.valueAt(index);
2147 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2148 mUidCached, patchDesc->mUid, uid);
2149 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2150 return INVALID_OPERATION;
2151 }
2152 } else {
2153 *handle = 0;
2154 }
2155
2156 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002157 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002158 if (outputDesc == NULL) {
2159 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2160 return BAD_VALUE;
2161 }
Eric Laurent84c70242014-06-23 08:46:27 -07002162 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2163 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002164 if (patchDesc != 0) {
2165 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2166 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2167 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2168 return BAD_VALUE;
2169 }
2170 }
Eric Laurent874c42872014-08-08 15:13:39 -07002171 DeviceVector devices;
2172 for (size_t i = 0; i < patch->num_sinks; i++) {
2173 // Only support mix to devices connection
2174 // TODO add support for mix to mix connection
2175 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2176 ALOGV("createAudioPatch() source mix but sink is not a device");
2177 return INVALID_OPERATION;
2178 }
2179 sp<DeviceDescriptor> devDesc =
2180 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2181 if (devDesc == 0) {
2182 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2183 return BAD_VALUE;
2184 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002185
Eric Laurent874c42872014-08-08 15:13:39 -07002186 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2187 patch->sources[0].sample_rate,
2188 NULL, // updatedSamplingRate
2189 patch->sources[0].format,
2190 patch->sources[0].channel_mask,
2191 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2192 ALOGV("createAudioPatch() profile not supported for device %08x",
2193 devDesc->mDeviceType);
2194 return INVALID_OPERATION;
2195 }
2196 devices.add(devDesc);
2197 }
2198 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002199 return INVALID_OPERATION;
2200 }
Eric Laurent874c42872014-08-08 15:13:39 -07002201
Eric Laurent6a94d692014-05-20 11:18:06 -07002202 // TODO: reconfigure output format and channels here
2203 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002204 devices.types(), outputDesc->mIoHandle);
2205 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002206 index = mAudioPatches.indexOfKey(*handle);
2207 if (index >= 0) {
2208 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2209 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2210 }
2211 patchDesc = mAudioPatches.valueAt(index);
2212 patchDesc->mUid = uid;
2213 ALOGV("createAudioPatch() success");
2214 } else {
2215 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2216 return INVALID_OPERATION;
2217 }
2218 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2219 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2220 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002221 // only one sink supported when connecting an input device to a mix
2222 if (patch->num_sinks > 1) {
2223 return INVALID_OPERATION;
2224 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002225 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002226 if (inputDesc == NULL) {
2227 return BAD_VALUE;
2228 }
2229 if (patchDesc != 0) {
2230 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2231 return BAD_VALUE;
2232 }
2233 }
2234 sp<DeviceDescriptor> devDesc =
2235 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2236 if (devDesc == 0) {
2237 return BAD_VALUE;
2238 }
2239
Eric Laurent84c70242014-06-23 08:46:27 -07002240 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002241 patch->sinks[0].sample_rate,
2242 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002243 patch->sinks[0].format,
2244 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002245 // FIXME for the parameter type,
2246 // and the NONE
2247 (audio_output_flags_t)
2248 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002249 return INVALID_OPERATION;
2250 }
2251 // TODO: reconfigure output format and channels here
2252 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002253 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002254 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002255 index = mAudioPatches.indexOfKey(*handle);
2256 if (index >= 0) {
2257 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2258 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2259 }
2260 patchDesc = mAudioPatches.valueAt(index);
2261 patchDesc->mUid = uid;
2262 ALOGV("createAudioPatch() success");
2263 } else {
2264 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2265 return INVALID_OPERATION;
2266 }
2267 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2268 // device to device connection
2269 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002270 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002271 return BAD_VALUE;
2272 }
2273 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002274 sp<DeviceDescriptor> srcDeviceDesc =
2275 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent874c42872014-08-08 15:13:39 -07002276
Eric Laurent6a94d692014-05-20 11:18:06 -07002277 //update source and sink with our own data as the data passed in the patch may
2278 // be incomplete.
2279 struct audio_patch newPatch = *patch;
2280 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent874c42872014-08-08 15:13:39 -07002281 if (srcDeviceDesc == 0) {
2282 return BAD_VALUE;
2283 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002284
Eric Laurent874c42872014-08-08 15:13:39 -07002285 for (size_t i = 0; i < patch->num_sinks; i++) {
2286 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2287 ALOGV("createAudioPatch() source device but one sink is not a device");
2288 return INVALID_OPERATION;
2289 }
2290
2291 sp<DeviceDescriptor> sinkDeviceDesc =
2292 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2293 if (sinkDeviceDesc == 0) {
2294 return BAD_VALUE;
2295 }
2296 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2297
2298 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2299 // only one sink supported when connected devices across HW modules
2300 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002301 return INVALID_OPERATION;
2302 }
Eric Laurent874c42872014-08-08 15:13:39 -07002303 SortedVector<audio_io_handle_t> outputs =
2304 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2305 mOutputs);
2306 // if the sink device is reachable via an opened output stream, request to go via
2307 // this output stream by adding a second source to the patch description
2308 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2309 if (output != AUDIO_IO_HANDLE_NONE) {
2310 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2311 if (outputDesc->isDuplicated()) {
2312 return INVALID_OPERATION;
2313 }
2314 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2315 newPatch.num_sources = 2;
2316 }
Eric Laurent83b88082014-06-20 18:31:16 -07002317 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002318 }
2319 // TODO: check from routing capabilities in config file and other conflicting patches
2320
2321 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2322 if (index >= 0) {
2323 afPatchHandle = patchDesc->mAfPatchHandle;
2324 }
2325
2326 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2327 &afPatchHandle,
2328 0);
2329 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2330 status, afPatchHandle);
2331 if (status == NO_ERROR) {
2332 if (index < 0) {
2333 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2334 &newPatch, uid);
2335 addAudioPatch(patchDesc->mHandle, patchDesc);
2336 } else {
2337 patchDesc->mPatch = newPatch;
2338 }
2339 patchDesc->mAfPatchHandle = afPatchHandle;
2340 *handle = patchDesc->mHandle;
2341 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002342 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002343 } else {
2344 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2345 status);
2346 return INVALID_OPERATION;
2347 }
2348 } else {
2349 return BAD_VALUE;
2350 }
2351 } else {
2352 return BAD_VALUE;
2353 }
2354 return NO_ERROR;
2355}
2356
2357status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2358 uid_t uid)
2359{
2360 ALOGV("releaseAudioPatch() patch %d", handle);
2361
2362 ssize_t index = mAudioPatches.indexOfKey(handle);
2363
2364 if (index < 0) {
2365 return BAD_VALUE;
2366 }
2367 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2368 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2369 mUidCached, patchDesc->mUid, uid);
2370 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2371 return INVALID_OPERATION;
2372 }
2373
2374 struct audio_patch *patch = &patchDesc->mPatch;
2375 patchDesc->mUid = mUidCached;
2376 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002377 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002378 if (outputDesc == NULL) {
2379 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2380 return BAD_VALUE;
2381 }
2382
2383 setOutputDevice(outputDesc->mIoHandle,
2384 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2385 true,
2386 0,
2387 NULL);
2388 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2389 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002390 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002391 if (inputDesc == NULL) {
2392 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2393 return BAD_VALUE;
2394 }
2395 setInputDevice(inputDesc->mIoHandle,
2396 getNewInputDevice(inputDesc->mIoHandle),
2397 true,
2398 NULL);
2399 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2400 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2401 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2402 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2403 status, patchDesc->mAfPatchHandle);
2404 removeAudioPatch(patchDesc->mHandle);
2405 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002406 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002407 } else {
2408 return BAD_VALUE;
2409 }
2410 } else {
2411 return BAD_VALUE;
2412 }
2413 return NO_ERROR;
2414}
2415
2416status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2417 struct audio_patch *patches,
2418 unsigned int *generation)
2419{
2420 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2421 generation == NULL) {
2422 return BAD_VALUE;
2423 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002424 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002425 *num_patches, patches, mAudioPatches.size());
2426 if (patches == NULL) {
2427 *num_patches = 0;
2428 }
2429
2430 size_t patchesWritten = 0;
2431 size_t patchesMax = *num_patches;
2432 for (size_t i = 0;
2433 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2434 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2435 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002436 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002437 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2438 }
2439 *num_patches = mAudioPatches.size();
2440
2441 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002442 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002443 return NO_ERROR;
2444}
2445
Eric Laurente1715a42014-05-20 11:30:42 -07002446status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002447{
Eric Laurente1715a42014-05-20 11:30:42 -07002448 ALOGV("setAudioPortConfig()");
2449
2450 if (config == NULL) {
2451 return BAD_VALUE;
2452 }
2453 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2454 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002455 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2456 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002457 }
2458
Eric Laurenta121f902014-06-03 13:32:54 -07002459 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002460 if (config->type == AUDIO_PORT_TYPE_MIX) {
2461 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002462 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002463 if (outputDesc == NULL) {
2464 return BAD_VALUE;
2465 }
Eric Laurent84c70242014-06-23 08:46:27 -07002466 ALOG_ASSERT(!outputDesc->isDuplicated(),
2467 "setAudioPortConfig() called on duplicated output %d",
2468 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002469 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002470 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002471 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002472 if (inputDesc == NULL) {
2473 return BAD_VALUE;
2474 }
Eric Laurenta121f902014-06-03 13:32:54 -07002475 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002476 } else {
2477 return BAD_VALUE;
2478 }
2479 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2480 sp<DeviceDescriptor> deviceDesc;
2481 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2482 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2483 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2484 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2485 } else {
2486 return BAD_VALUE;
2487 }
2488 if (deviceDesc == NULL) {
2489 return BAD_VALUE;
2490 }
Eric Laurenta121f902014-06-03 13:32:54 -07002491 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002492 } else {
2493 return BAD_VALUE;
2494 }
2495
Eric Laurenta121f902014-06-03 13:32:54 -07002496 struct audio_port_config backupConfig;
2497 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2498 if (status == NO_ERROR) {
2499 struct audio_port_config newConfig;
2500 audioPortConfig->toAudioPortConfig(&newConfig, config);
2501 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002502 }
Eric Laurenta121f902014-06-03 13:32:54 -07002503 if (status != NO_ERROR) {
2504 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002505 }
Eric Laurente1715a42014-05-20 11:30:42 -07002506
2507 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002508}
2509
2510void AudioPolicyManager::clearAudioPatches(uid_t uid)
2511{
2512 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2513 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2514 if (patchDesc->mUid == uid) {
2515 // releaseAudioPatch() removes the patch from mAudioPatches
2516 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2517 i--;
2518 }
2519 }
2520 }
2521}
2522
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002523status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2524 audio_io_handle_t *ioHandle,
2525 audio_devices_t *device)
2526{
2527 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2528 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2529 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2530
2531 mSoundTriggerSessions.add(*session, *ioHandle);
2532
2533 return NO_ERROR;
2534}
2535
2536status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2537{
2538 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2539 if (index < 0) {
2540 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2541 return BAD_VALUE;
2542 }
2543
2544 mSoundTriggerSessions.removeItem(session);
2545 return NO_ERROR;
2546}
2547
Eric Laurent6a94d692014-05-20 11:18:06 -07002548status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2549 const sp<AudioPatch>& patch)
2550{
2551 ssize_t index = mAudioPatches.indexOfKey(handle);
2552
2553 if (index >= 0) {
2554 ALOGW("addAudioPatch() patch %d already in", handle);
2555 return ALREADY_EXISTS;
2556 }
2557 mAudioPatches.add(handle, patch);
2558 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2559 "sink handle %d",
2560 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2561 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2562 return NO_ERROR;
2563}
2564
2565status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2566{
2567 ssize_t index = mAudioPatches.indexOfKey(handle);
2568
2569 if (index < 0) {
2570 ALOGW("removeAudioPatch() patch %d not in", handle);
2571 return ALREADY_EXISTS;
2572 }
2573 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2574 mAudioPatches.valueAt(index)->mAfPatchHandle);
2575 mAudioPatches.removeItemsAt(index);
2576 return NO_ERROR;
2577}
2578
Eric Laurente552edb2014-03-10 17:42:56 -07002579// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002580// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002581// ----------------------------------------------------------------------------
2582
Eric Laurent3a4311c2014-03-17 12:00:47 -07002583uint32_t AudioPolicyManager::nextUniqueId()
2584{
2585 return android_atomic_inc(&mNextUniqueId);
2586}
2587
Eric Laurent6a94d692014-05-20 11:18:06 -07002588uint32_t AudioPolicyManager::nextAudioPortGeneration()
2589{
2590 return android_atomic_inc(&mAudioPortGeneration);
2591}
2592
Eric Laurente0720872014-03-11 09:30:41 -07002593AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002594 :
2595#ifdef AUDIO_POLICY_TEST
2596 Thread(false),
2597#endif //AUDIO_POLICY_TEST
2598 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002599 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002600 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2601 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002602 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002603 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2604 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002605{
Eric Laurent6a94d692014-05-20 11:18:06 -07002606 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002607 mpClientInterface = clientInterface;
2608
Eric Laurent3b73df72014-03-11 09:06:29 -07002609 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2610 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002611 }
2612
Eric Laurent1afeecb2014-05-14 08:52:28 -07002613 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002614 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2615 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2616 ALOGE("could not load audio policy configuration file, setting defaults");
2617 defaultAudioPolicyConfig();
2618 }
2619 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002620 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002621
2622 // must be done after reading the policy
2623 initializeVolumeCurves();
2624
2625 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002626 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2627 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002628 for (size_t i = 0; i < mHwModules.size(); i++) {
2629 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2630 if (mHwModules[i]->mHandle == 0) {
2631 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2632 continue;
2633 }
2634 // open all output streams needed to access attached devices
2635 // except for direct output streams that are only opened when they are actually
2636 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002637 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002638 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2639 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002640 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002641
Eric Laurent3a4311c2014-03-17 12:00:47 -07002642 if (outProfile->mSupportedDevices.isEmpty()) {
2643 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2644 continue;
2645 }
2646
Eric Laurent83b88082014-06-20 18:31:16 -07002647 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2648 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2649 profileType = mDefaultOutputDevice->mDeviceType;
2650 } else {
2651 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2652 }
2653 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002654 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002655 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002656
Eric Laurent83b88082014-06-20 18:31:16 -07002657 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002658 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2659 config.sample_rate = outputDesc->mSamplingRate;
2660 config.channel_mask = outputDesc->mChannelMask;
2661 config.format = outputDesc->mFormat;
2662 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2663 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2664 &output,
2665 &config,
2666 &outputDesc->mDevice,
2667 String8(""),
2668 &outputDesc->mLatency,
2669 outputDesc->mFlags);
2670
2671 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002672 ALOGW("Cannot open output stream for device %08x on hw module %s",
2673 outputDesc->mDevice,
2674 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002675 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002676 outputDesc->mSamplingRate = config.sample_rate;
2677 outputDesc->mChannelMask = config.channel_mask;
2678 outputDesc->mFormat = config.format;
2679
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002680 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002681 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002682 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002683 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002684 // give a valid ID to an attached device once confirmed it is reachable
2685 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2686 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002687 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688 }
2689 }
Eric Laurente552edb2014-03-10 17:42:56 -07002690 if (mPrimaryOutput == 0 &&
2691 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2692 mPrimaryOutput = output;
2693 }
2694 addOutput(output, outputDesc);
2695 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002696 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002697 true);
2698 }
2699 }
2700 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002701 // open input streams needed to access attached devices to validate
2702 // mAvailableInputDevices list
2703 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2704 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002705 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002706
Eric Laurent3a4311c2014-03-17 12:00:47 -07002707 if (inProfile->mSupportedDevices.isEmpty()) {
2708 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2709 continue;
2710 }
2711
Eric Laurent83b88082014-06-20 18:31:16 -07002712 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2713 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002714 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002715
2716 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002717 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002718
Eric Laurentcf2c0212014-07-25 16:20:43 -07002719 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2720 config.sample_rate = inputDesc->mSamplingRate;
2721 config.channel_mask = inputDesc->mChannelMask;
2722 config.format = inputDesc->mFormat;
2723 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2724 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2725 &input,
2726 &config,
2727 &inputDesc->mDevice,
2728 String8(""),
2729 AUDIO_SOURCE_MIC,
2730 AUDIO_INPUT_FLAG_NONE);
2731
2732 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002733 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002734 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002735 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002736 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002737 // give a valid ID to an attached device once confirmed it is reachable
2738 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2739 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002740 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002741 }
2742 }
2743 mpClientInterface->closeInput(input);
2744 } else {
2745 ALOGW("Cannot open input stream for device %08x on hw module %s",
2746 inputDesc->mDevice,
2747 mHwModules[i]->mName);
2748 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002749 }
2750 }
2751 }
2752 // make sure all attached devices have been allocated a unique ID
2753 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2754 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002755 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002756 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2757 continue;
2758 }
2759 i++;
2760 }
2761 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2762 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002763 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002764 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2765 continue;
2766 }
2767 i++;
2768 }
2769 // make sure default device is reachable
2770 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002771 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002772 }
Eric Laurente552edb2014-03-10 17:42:56 -07002773
2774 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2775
2776 updateDevicesAndOutputs();
2777
2778#ifdef AUDIO_POLICY_TEST
2779 if (mPrimaryOutput != 0) {
2780 AudioParameter outputCmd = AudioParameter();
2781 outputCmd.addInt(String8("set_id"), 0);
2782 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2783
2784 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2785 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002786 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2787 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002788 mTestLatencyMs = 0;
2789 mCurOutput = 0;
2790 mDirectOutput = false;
2791 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2792 mTestOutputs[i] = 0;
2793 }
2794
2795 const size_t SIZE = 256;
2796 char buffer[SIZE];
2797 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2798 run(buffer, ANDROID_PRIORITY_AUDIO);
2799 }
2800#endif //AUDIO_POLICY_TEST
2801}
2802
Eric Laurente0720872014-03-11 09:30:41 -07002803AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002804{
2805#ifdef AUDIO_POLICY_TEST
2806 exit();
2807#endif //AUDIO_POLICY_TEST
2808 for (size_t i = 0; i < mOutputs.size(); i++) {
2809 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002810 }
2811 for (size_t i = 0; i < mInputs.size(); i++) {
2812 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002813 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002814 mAvailableOutputDevices.clear();
2815 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002816 mOutputs.clear();
2817 mInputs.clear();
2818 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002819}
2820
Eric Laurente0720872014-03-11 09:30:41 -07002821status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002822{
2823 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2824}
2825
2826#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002827bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002828{
2829 ALOGV("entering threadLoop()");
2830 while (!exitPending())
2831 {
2832 String8 command;
2833 int valueInt;
2834 String8 value;
2835
2836 Mutex::Autolock _l(mLock);
2837 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2838
2839 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2840 AudioParameter param = AudioParameter(command);
2841
2842 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2843 valueInt != 0) {
2844 ALOGV("Test command %s received", command.string());
2845 String8 target;
2846 if (param.get(String8("target"), target) != NO_ERROR) {
2847 target = "Manager";
2848 }
2849 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2850 param.remove(String8("test_cmd_policy_output"));
2851 mCurOutput = valueInt;
2852 }
2853 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2854 param.remove(String8("test_cmd_policy_direct"));
2855 if (value == "false") {
2856 mDirectOutput = false;
2857 } else if (value == "true") {
2858 mDirectOutput = true;
2859 }
2860 }
2861 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2862 param.remove(String8("test_cmd_policy_input"));
2863 mTestInput = valueInt;
2864 }
2865
2866 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2867 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002868 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002869 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002870 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002871 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002872 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002873 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002874 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002875 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002876 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002877 if (target == "Manager") {
2878 mTestFormat = format;
2879 } else if (mTestOutputs[mCurOutput] != 0) {
2880 AudioParameter outputParam = AudioParameter();
2881 outputParam.addInt(String8("format"), format);
2882 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2883 }
2884 }
2885 }
2886 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2887 param.remove(String8("test_cmd_policy_channels"));
2888 int channels = 0;
2889
2890 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002891 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002892 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002893 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002894 }
2895 if (channels != 0) {
2896 if (target == "Manager") {
2897 mTestChannels = channels;
2898 } else if (mTestOutputs[mCurOutput] != 0) {
2899 AudioParameter outputParam = AudioParameter();
2900 outputParam.addInt(String8("channels"), channels);
2901 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2902 }
2903 }
2904 }
2905 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2906 param.remove(String8("test_cmd_policy_sampleRate"));
2907 if (valueInt >= 0 && valueInt <= 96000) {
2908 int samplingRate = valueInt;
2909 if (target == "Manager") {
2910 mTestSamplingRate = samplingRate;
2911 } else if (mTestOutputs[mCurOutput] != 0) {
2912 AudioParameter outputParam = AudioParameter();
2913 outputParam.addInt(String8("sampling_rate"), samplingRate);
2914 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2915 }
2916 }
2917 }
2918
2919 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2920 param.remove(String8("test_cmd_policy_reopen"));
2921
Eric Laurent1f2f2232014-06-02 12:01:23 -07002922 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002923 mpClientInterface->closeOutput(mPrimaryOutput);
2924
2925 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2926
Eric Laurente552edb2014-03-10 17:42:56 -07002927 mOutputs.removeItem(mPrimaryOutput);
2928
Eric Laurent1f2f2232014-06-02 12:01:23 -07002929 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002930 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002931 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2932 config.sample_rate = outputDesc->mSamplingRate;
2933 config.channel_mask = outputDesc->mChannelMask;
2934 config.format = outputDesc->mFormat;
2935 status_t status = mpClientInterface->openOutput(moduleHandle,
2936 &mPrimaryOutput,
2937 &config,
2938 &outputDesc->mDevice,
2939 String8(""),
2940 &outputDesc->mLatency,
2941 outputDesc->mFlags);
2942 if (status != NO_ERROR) {
2943 ALOGE("Failed to reopen hardware output stream, "
2944 "samplingRate: %d, format %d, channels %d",
2945 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002946 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002947 outputDesc->mSamplingRate = config.sample_rate;
2948 outputDesc->mChannelMask = config.channel_mask;
2949 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002950 AudioParameter outputCmd = AudioParameter();
2951 outputCmd.addInt(String8("set_id"), 0);
2952 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2953 addOutput(mPrimaryOutput, outputDesc);
2954 }
2955 }
2956
2957
2958 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2959 }
2960 }
2961 return false;
2962}
2963
Eric Laurente0720872014-03-11 09:30:41 -07002964void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002965{
2966 {
2967 AutoMutex _l(mLock);
2968 requestExit();
2969 mWaitWorkCV.signal();
2970 }
2971 requestExitAndWait();
2972}
2973
Eric Laurente0720872014-03-11 09:30:41 -07002974int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002975{
2976 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2977 if (output == mTestOutputs[i]) return i;
2978 }
2979 return 0;
2980}
2981#endif //AUDIO_POLICY_TEST
2982
2983// ---
2984
Eric Laurent1f2f2232014-06-02 12:01:23 -07002985void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002986{
Eric Laurent1c333e22014-05-20 10:48:17 -07002987 outputDesc->mIoHandle = output;
2988 outputDesc->mId = nextUniqueId();
2989 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002991}
2992
Eric Laurent1f2f2232014-06-02 12:01:23 -07002993void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002994{
Eric Laurent1c333e22014-05-20 10:48:17 -07002995 inputDesc->mIoHandle = input;
2996 inputDesc->mId = nextUniqueId();
2997 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002998 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002999}
Eric Laurente552edb2014-03-10 17:42:56 -07003000
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003001void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3002 const String8 address /*in*/,
3003 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3004 // look for a match on the given address on the addresses of the outputs:
3005 // find the address by finding the patch that maps to this output
3006 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3007 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3008 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3009 if (patchIdx >= 0) {
3010 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3011 const int numSinks = patchDesc->mPatch.num_sinks;
3012 for (ssize_t j=0; j < numSinks; j++) {
3013 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3014 const char* patchAddr =
3015 patchDesc->mPatch.sinks[j].ext.device.address;
3016 if (strncmp(patchAddr,
3017 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003018 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003019 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3020 outputs.add(desc->mIoHandle);
3021 break;
3022 }
3023 }
3024 }
3025 }
3026}
3027
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003028status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003029 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003030 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003031 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003032{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003033 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003034 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003035 // erase all current sample rates, formats and channel masks
3036 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003037
Eric Laurent3b73df72014-03-11 09:06:29 -07003038 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003039 // first list already open outputs that can be routed to this device
3040 for (size_t i = 0; i < mOutputs.size(); i++) {
3041 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003042 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003043 if (!deviceDistinguishesOnAddress(device)) {
3044 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3045 outputs.add(mOutputs.keyAt(i));
3046 } else {
3047 ALOGV(" checking address match due to device 0x%x", device);
3048 findIoHandlesByAddress(desc, address, outputs);
3049 }
Eric Laurente552edb2014-03-10 17:42:56 -07003050 }
3051 }
3052 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003053 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003054 for (size_t i = 0; i < mHwModules.size(); i++)
3055 {
3056 if (mHwModules[i]->mHandle == 0) {
3057 continue;
3058 }
3059 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3060 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003061 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003062 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003063 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3064 }
3065 }
3066 }
3067
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003068 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3069
Eric Laurente552edb2014-03-10 17:42:56 -07003070 if (profiles.isEmpty() && outputs.isEmpty()) {
3071 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3072 return BAD_VALUE;
3073 }
3074
3075 // open outputs for matching profiles if needed. Direct outputs are also opened to
3076 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3077 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003078 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003079
3080 // nothing to do if one output is already opened for this profile
3081 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003082 for (j = 0; j < outputs.size(); j++) {
3083 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003084 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003085 // matching profile: save the sample rates, format and channel masks supported
3086 // by the profile in our device descriptor
3087 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003088 break;
3089 }
3090 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003091 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003092 continue;
3093 }
3094
Eric Laurent83b88082014-06-20 18:31:16 -07003095 ALOGV("opening output for device %08x with params %s profile %p",
3096 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003097 desc = new AudioOutputDescriptor(profile);
3098 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003099 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3100 config.sample_rate = desc->mSamplingRate;
3101 config.channel_mask = desc->mChannelMask;
3102 config.format = desc->mFormat;
3103 config.offload_info.sample_rate = desc->mSamplingRate;
3104 config.offload_info.channel_mask = desc->mChannelMask;
3105 config.offload_info.format = desc->mFormat;
3106 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3107 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3108 &output,
3109 &config,
3110 &desc->mDevice,
3111 address,
3112 &desc->mLatency,
3113 desc->mFlags);
3114 if (status == NO_ERROR) {
3115 desc->mSamplingRate = config.sample_rate;
3116 desc->mChannelMask = config.channel_mask;
3117 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003118
Eric Laurentd4692962014-05-05 18:13:44 -07003119 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003120 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003121 char *param = audio_device_address_to_parameter(device, address);
3122 mpClientInterface->setParameters(output, String8(param));
3123 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003124 }
3125
Eric Laurentd4692962014-05-05 18:13:44 -07003126 // Here is where we step through and resolve any "dynamic" fields
3127 String8 reply;
3128 char *value;
3129 if (profile->mSamplingRates[0] == 0) {
3130 reply = mpClientInterface->getParameters(output,
3131 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003132 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003133 reply.string());
3134 value = strpbrk((char *)reply.string(), "=");
3135 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003136 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003137 }
Eric Laurentd4692962014-05-05 18:13:44 -07003138 }
3139 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3140 reply = mpClientInterface->getParameters(output,
3141 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003142 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003143 reply.string());
3144 value = strpbrk((char *)reply.string(), "=");
3145 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003146 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003147 }
Eric Laurentd4692962014-05-05 18:13:44 -07003148 }
3149 if (profile->mChannelMasks[0] == 0) {
3150 reply = mpClientInterface->getParameters(output,
3151 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003152 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003153 reply.string());
3154 value = strpbrk((char *)reply.string(), "=");
3155 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003156 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003157 }
Eric Laurentd4692962014-05-05 18:13:44 -07003158 }
3159 if (((profile->mSamplingRates[0] == 0) &&
3160 (profile->mSamplingRates.size() < 2)) ||
3161 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3162 (profile->mFormats.size() < 2)) ||
3163 ((profile->mChannelMasks[0] == 0) &&
3164 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003165 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003166 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003167 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003168 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3169 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003170 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003171 config.sample_rate = profile->pickSamplingRate();
3172 config.channel_mask = profile->pickChannelMask();
3173 config.format = profile->pickFormat();
3174 config.offload_info.sample_rate = config.sample_rate;
3175 config.offload_info.channel_mask = config.channel_mask;
3176 config.offload_info.format = config.format;
3177 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3178 &output,
3179 &config,
3180 &desc->mDevice,
3181 address,
3182 &desc->mLatency,
3183 desc->mFlags);
3184 if (status == NO_ERROR) {
3185 desc->mSamplingRate = config.sample_rate;
3186 desc->mChannelMask = config.channel_mask;
3187 desc->mFormat = config.format;
3188 } else {
3189 output = AUDIO_IO_HANDLE_NONE;
3190 }
Eric Laurentd4692962014-05-05 18:13:44 -07003191 }
3192
Eric Laurentcf2c0212014-07-25 16:20:43 -07003193 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003194 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003195 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003196 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003197
Eric Laurentd4692962014-05-05 18:13:44 -07003198 // set initial stream volume for device
3199 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003200
Eric Laurentd4692962014-05-05 18:13:44 -07003201 //TODO: configure audio effect output stage here
3202
3203 // open a duplicating output thread for the new output and the primary output
3204 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3205 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003206 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003207 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003208 sp<AudioOutputDescriptor> dupOutputDesc =
3209 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003210 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3211 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3212 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3213 dupOutputDesc->mFormat = desc->mFormat;
3214 dupOutputDesc->mChannelMask = desc->mChannelMask;
3215 dupOutputDesc->mLatency = desc->mLatency;
3216 addOutput(duplicatedOutput, dupOutputDesc);
3217 applyStreamVolumes(duplicatedOutput, device, 0, true);
3218 } else {
3219 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3220 mPrimaryOutput, output);
3221 mpClientInterface->closeOutput(output);
3222 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003223 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003224 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003225 }
Eric Laurente552edb2014-03-10 17:42:56 -07003226 }
3227 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003228 } else {
3229 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003230 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003231 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003232 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003233 profiles.removeAt(profile_index);
3234 profile_index--;
3235 } else {
3236 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003237 devDesc->importAudioPort(profile);
3238
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003239 if (deviceDistinguishesOnAddress(device)) {
3240 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3241 device, address.string());
3242 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3243 NULL/*patch handle*/, address.string());
3244 }
Eric Laurente552edb2014-03-10 17:42:56 -07003245 ALOGV("checkOutputsForDevice(): adding output %d", output);
3246 }
3247 }
3248
3249 if (profiles.isEmpty()) {
3250 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3251 return BAD_VALUE;
3252 }
Eric Laurentd4692962014-05-05 18:13:44 -07003253 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003254 // check if one opened output is not needed any more after disconnecting one device
3255 for (size_t i = 0; i < mOutputs.size(); i++) {
3256 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003257 if (!desc->isDuplicated()) {
3258 if (!(desc->mProfile->mSupportedDevices.types()
3259 & mAvailableOutputDevices.types())) {
3260 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3261 mOutputs.keyAt(i));
3262 outputs.add(mOutputs.keyAt(i));
3263 } else if (deviceDistinguishesOnAddress(device) &&
3264 // exact match on device
3265 (desc->mProfile->mSupportedDevices.types() == device)) {
3266 findIoHandlesByAddress(desc, address, outputs);
3267 }
Eric Laurente552edb2014-03-10 17:42:56 -07003268 }
3269 }
Eric Laurentd4692962014-05-05 18:13:44 -07003270 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003271 for (size_t i = 0; i < mHwModules.size(); i++)
3272 {
3273 if (mHwModules[i]->mHandle == 0) {
3274 continue;
3275 }
3276 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3277 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003278 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003279 if (profile->mSupportedDevices.types() & device) {
3280 ALOGV("checkOutputsForDevice(): "
3281 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003282 if (profile->mSamplingRates[0] == 0) {
3283 profile->mSamplingRates.clear();
3284 profile->mSamplingRates.add(0);
3285 }
3286 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3287 profile->mFormats.clear();
3288 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3289 }
3290 if (profile->mChannelMasks[0] == 0) {
3291 profile->mChannelMasks.clear();
3292 profile->mChannelMasks.add(0);
3293 }
3294 }
3295 }
3296 }
3297 }
3298 return NO_ERROR;
3299}
3300
Eric Laurentd4692962014-05-05 18:13:44 -07003301status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3302 audio_policy_dev_state_t state,
3303 SortedVector<audio_io_handle_t>& inputs,
3304 const String8 address)
3305{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003306 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003307 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3308 // first list already open inputs that can be routed to this device
3309 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3310 desc = mInputs.valueAt(input_index);
3311 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3312 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3313 inputs.add(mInputs.keyAt(input_index));
3314 }
3315 }
3316
3317 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003318 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003319 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3320 {
3321 if (mHwModules[module_idx]->mHandle == 0) {
3322 continue;
3323 }
3324 for (size_t profile_index = 0;
3325 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3326 profile_index++)
3327 {
3328 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3329 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003330 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003331 profile_index, module_idx);
3332 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3333 }
3334 }
3335 }
3336
3337 if (profiles.isEmpty() && inputs.isEmpty()) {
3338 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3339 return BAD_VALUE;
3340 }
3341
3342 // open inputs for matching profiles if needed. Direct inputs are also opened to
3343 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3344 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3345
Eric Laurent1c333e22014-05-20 10:48:17 -07003346 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003347 // nothing to do if one input is already opened for this profile
3348 size_t input_index;
3349 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3350 desc = mInputs.valueAt(input_index);
3351 if (desc->mProfile == profile) {
3352 break;
3353 }
3354 }
3355 if (input_index != mInputs.size()) {
3356 continue;
3357 }
3358
3359 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3360 desc = new AudioInputDescriptor(profile);
3361 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003362 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3363 config.sample_rate = desc->mSamplingRate;
3364 config.channel_mask = desc->mChannelMask;
3365 config.format = desc->mFormat;
3366 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3367 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3368 &input,
3369 &config,
3370 &desc->mDevice,
3371 address,
3372 AUDIO_SOURCE_MIC,
3373 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003374
Eric Laurentcf2c0212014-07-25 16:20:43 -07003375 if (status == NO_ERROR) {
3376 desc->mSamplingRate = config.sample_rate;
3377 desc->mChannelMask = config.channel_mask;
3378 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003379
Eric Laurentd4692962014-05-05 18:13:44 -07003380 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003381 char *param = audio_device_address_to_parameter(device, address);
3382 mpClientInterface->setParameters(input, String8(param));
3383 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003384 }
3385
3386 // Here is where we step through and resolve any "dynamic" fields
3387 String8 reply;
3388 char *value;
3389 if (profile->mSamplingRates[0] == 0) {
3390 reply = mpClientInterface->getParameters(input,
3391 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3392 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3393 reply.string());
3394 value = strpbrk((char *)reply.string(), "=");
3395 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003396 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003397 }
3398 }
3399 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3400 reply = mpClientInterface->getParameters(input,
3401 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3402 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3403 value = strpbrk((char *)reply.string(), "=");
3404 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003405 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003406 }
3407 }
3408 if (profile->mChannelMasks[0] == 0) {
3409 reply = mpClientInterface->getParameters(input,
3410 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3411 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3412 reply.string());
3413 value = strpbrk((char *)reply.string(), "=");
3414 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003415 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003416 }
3417 }
3418 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3419 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3420 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3421 ALOGW("checkInputsForDevice() direct input missing param");
3422 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003423 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003424 }
3425
3426 if (input != 0) {
3427 addInput(input, desc);
3428 }
3429 } // endif input != 0
3430
Eric Laurentcf2c0212014-07-25 16:20:43 -07003431 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003432 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003433 profiles.removeAt(profile_index);
3434 profile_index--;
3435 } else {
3436 inputs.add(input);
3437 ALOGV("checkInputsForDevice(): adding input %d", input);
3438 }
3439 } // end scan profiles
3440
3441 if (profiles.isEmpty()) {
3442 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3443 return BAD_VALUE;
3444 }
3445 } else {
3446 // Disconnect
3447 // check if one opened input is not needed any more after disconnecting one device
3448 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3449 desc = mInputs.valueAt(input_index);
3450 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3451 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3452 mInputs.keyAt(input_index));
3453 inputs.add(mInputs.keyAt(input_index));
3454 }
3455 }
3456 // Clear any profiles associated with the disconnected device.
3457 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3458 if (mHwModules[module_index]->mHandle == 0) {
3459 continue;
3460 }
3461 for (size_t profile_index = 0;
3462 profile_index < mHwModules[module_index]->mInputProfiles.size();
3463 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003464 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003465 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003466 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003467 profile_index, module_index);
3468 if (profile->mSamplingRates[0] == 0) {
3469 profile->mSamplingRates.clear();
3470 profile->mSamplingRates.add(0);
3471 }
3472 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3473 profile->mFormats.clear();
3474 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3475 }
3476 if (profile->mChannelMasks[0] == 0) {
3477 profile->mChannelMasks.clear();
3478 profile->mChannelMasks.add(0);
3479 }
3480 }
3481 }
3482 }
3483 } // end disconnect
3484
3485 return NO_ERROR;
3486}
3487
3488
Eric Laurente0720872014-03-11 09:30:41 -07003489void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003490{
3491 ALOGV("closeOutput(%d)", output);
3492
Eric Laurent1f2f2232014-06-02 12:01:23 -07003493 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003494 if (outputDesc == NULL) {
3495 ALOGW("closeOutput() unknown output %d", output);
3496 return;
3497 }
3498
3499 // look for duplicated outputs connected to the output being removed.
3500 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003501 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003502 if (dupOutputDesc->isDuplicated() &&
3503 (dupOutputDesc->mOutput1 == outputDesc ||
3504 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003505 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003506 if (dupOutputDesc->mOutput1 == outputDesc) {
3507 outputDesc2 = dupOutputDesc->mOutput2;
3508 } else {
3509 outputDesc2 = dupOutputDesc->mOutput1;
3510 }
3511 // As all active tracks on duplicated output will be deleted,
3512 // and as they were also referenced on the other output, the reference
3513 // count for their stream type must be adjusted accordingly on
3514 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003515 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003516 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003517 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
3519 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3520 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3521
3522 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003523 mOutputs.removeItem(duplicatedOutput);
3524 }
3525 }
3526
Eric Laurent05b90f82014-08-27 15:32:29 -07003527 nextAudioPortGeneration();
3528
3529 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3530 if (index >= 0) {
3531 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3532 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3533 mAudioPatches.removeItemsAt(index);
3534 mpClientInterface->onAudioPatchListUpdate();
3535 }
3536
Eric Laurente552edb2014-03-10 17:42:56 -07003537 AudioParameter param;
3538 param.add(String8("closing"), String8("true"));
3539 mpClientInterface->setParameters(output, param.toString());
3540
3541 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003542 mOutputs.removeItem(output);
3543 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003544}
3545
3546void AudioPolicyManager::closeInput(audio_io_handle_t input)
3547{
3548 ALOGV("closeInput(%d)", input);
3549
3550 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3551 if (inputDesc == NULL) {
3552 ALOGW("closeInput() unknown input %d", input);
3553 return;
3554 }
3555
Eric Laurent6a94d692014-05-20 11:18:06 -07003556 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003557
3558 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3559 if (index >= 0) {
3560 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3561 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3562 mAudioPatches.removeItemsAt(index);
3563 mpClientInterface->onAudioPatchListUpdate();
3564 }
3565
3566 mpClientInterface->closeInput(input);
3567 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003568}
3569
Eric Laurente0720872014-03-11 09:30:41 -07003570SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003571 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003572{
3573 SortedVector<audio_io_handle_t> outputs;
3574
3575 ALOGVV("getOutputsForDevice() device %04x", device);
3576 for (size_t i = 0; i < openOutputs.size(); i++) {
3577 ALOGVV("output %d isDuplicated=%d device=%04x",
3578 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3579 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3580 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3581 outputs.add(openOutputs.keyAt(i));
3582 }
3583 }
3584 return outputs;
3585}
3586
Eric Laurente0720872014-03-11 09:30:41 -07003587bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003588 SortedVector<audio_io_handle_t>& outputs2)
3589{
3590 if (outputs1.size() != outputs2.size()) {
3591 return false;
3592 }
3593 for (size_t i = 0; i < outputs1.size(); i++) {
3594 if (outputs1[i] != outputs2[i]) {
3595 return false;
3596 }
3597 }
3598 return true;
3599}
3600
Eric Laurente0720872014-03-11 09:30:41 -07003601void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003602{
3603 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3604 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3605 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3606 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3607
3608 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3609 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3610 strategy, srcOutputs[0], dstOutputs[0]);
3611 // mute strategy while moving tracks from one output to another
3612 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003613 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003614 if (desc->isStrategyActive(strategy)) {
3615 setStrategyMute(strategy, true, srcOutputs[i]);
3616 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3617 }
3618 }
3619
3620 // Move effects associated to this strategy from previous output to new output
3621 if (strategy == STRATEGY_MEDIA) {
3622 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3623 SortedVector<audio_io_handle_t> moved;
3624 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003625 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3626 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3627 effectDesc->mIo != fxOutput) {
3628 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003629 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3630 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003631 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003632 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003633 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003634 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003635 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003636 }
3637 }
3638 }
3639 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003640 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3641 if (getStrategy((audio_stream_type_t)i) == strategy) {
3642 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003643 }
3644 }
3645 }
3646}
3647
Eric Laurente0720872014-03-11 09:30:41 -07003648void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003649{
3650 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3651 checkOutputForStrategy(STRATEGY_PHONE);
3652 checkOutputForStrategy(STRATEGY_SONIFICATION);
3653 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3654 checkOutputForStrategy(STRATEGY_MEDIA);
3655 checkOutputForStrategy(STRATEGY_DTMF);
3656}
3657
Eric Laurente0720872014-03-11 09:30:41 -07003658audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003659{
Eric Laurente552edb2014-03-10 17:42:56 -07003660 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003661 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003662 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3663 return mOutputs.keyAt(i);
3664 }
3665 }
3666
3667 return 0;
3668}
3669
Eric Laurente0720872014-03-11 09:30:41 -07003670void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003671{
Eric Laurente552edb2014-03-10 17:42:56 -07003672 audio_io_handle_t a2dpOutput = getA2dpOutput();
3673 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003674 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003675 return;
3676 }
3677
Eric Laurent3a4311c2014-03-17 12:00:47 -07003678 bool isScoConnected =
3679 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003680 // suspend A2DP output if:
3681 // (NOT already suspended) &&
3682 // ((SCO device is connected &&
3683 // (forced usage for communication || for record is SCO))) ||
3684 // (phone state is ringing || in call)
3685 //
3686 // restore A2DP output if:
3687 // (Already suspended) &&
3688 // ((SCO device is NOT connected ||
3689 // (forced usage NOT for communication && NOT for record is SCO))) &&
3690 // (phone state is NOT ringing && NOT in call)
3691 //
3692 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003693 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003694 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3695 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3696 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3697 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003698
3699 mpClientInterface->restoreOutput(a2dpOutput);
3700 mA2dpSuspended = false;
3701 }
3702 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003703 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003704 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3705 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3706 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3707 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003708
3709 mpClientInterface->suspendOutput(a2dpOutput);
3710 mA2dpSuspended = true;
3711 }
3712 }
3713}
3714
Eric Laurent1c333e22014-05-20 10:48:17 -07003715audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003716{
3717 audio_devices_t device = AUDIO_DEVICE_NONE;
3718
Eric Laurent1f2f2232014-06-02 12:01:23 -07003719 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003720
3721 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3722 if (index >= 0) {
3723 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3724 if (patchDesc->mUid != mUidCached) {
3725 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3726 outputDesc->device(), outputDesc->mPatchHandle);
3727 return outputDesc->device();
3728 }
3729 }
3730
Eric Laurente552edb2014-03-10 17:42:56 -07003731 // check the following by order of priority to request a routing change if necessary:
3732 // 1: the strategy enforced audible is active on the output:
3733 // use device for strategy enforced audible
3734 // 2: we are in call or the strategy phone is active on the output:
3735 // use device for strategy phone
3736 // 3: the strategy sonification is active on the output:
3737 // use device for strategy sonification
3738 // 4: the strategy "respectful" sonification is active on the output:
3739 // use device for strategy "respectful" sonification
3740 // 5: the strategy media is active on the output:
3741 // use device for strategy media
3742 // 6: the strategy DTMF is active on the output:
3743 // use device for strategy DTMF
3744 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3745 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3746 } else if (isInCall() ||
3747 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3748 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3749 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3750 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3751 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3752 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3753 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3754 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3755 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3756 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3757 }
3758
Eric Laurent1c333e22014-05-20 10:48:17 -07003759 ALOGV("getNewOutputDevice() selected device %x", device);
3760 return device;
3761}
3762
3763audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3764{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003765 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003766
3767 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3768 if (index >= 0) {
3769 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3770 if (patchDesc->mUid != mUidCached) {
3771 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3772 inputDesc->mDevice, inputDesc->mPatchHandle);
3773 return inputDesc->mDevice;
3774 }
3775 }
3776
Eric Laurent1c333e22014-05-20 10:48:17 -07003777 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3778
3779 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003780 return device;
3781}
3782
Eric Laurente0720872014-03-11 09:30:41 -07003783uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003784 return (uint32_t)getStrategy(stream);
3785}
3786
Eric Laurente0720872014-03-11 09:30:41 -07003787audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003788 // By checking the range of stream before calling getStrategy, we avoid
3789 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3790 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003791 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003792 return AUDIO_DEVICE_NONE;
3793 }
3794 audio_devices_t devices;
3795 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3796 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3797 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3798 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003799 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003800 if (outputDesc->isStrategyActive(strategy)) {
3801 devices = outputDesc->device();
3802 break;
3803 }
Eric Laurente552edb2014-03-10 17:42:56 -07003804 }
3805 return devices;
3806}
3807
Eric Laurente0720872014-03-11 09:30:41 -07003808AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003809 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003810 // stream to strategy mapping
3811 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003812 case AUDIO_STREAM_VOICE_CALL:
3813 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003814 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003815 case AUDIO_STREAM_RING:
3816 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003817 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003818 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003819 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003820 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003821 return STRATEGY_DTMF;
3822 default:
3823 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003824 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003825 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3826 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003827 case AUDIO_STREAM_TTS:
3828 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003829 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003830 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003831 return STRATEGY_ENFORCED_AUDIBLE;
3832 }
3833}
3834
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003835uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3836 // flags to strategy mapping
3837 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3838 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3839 }
3840
3841 // usage to strategy mapping
3842 switch (attr->usage) {
3843 case AUDIO_USAGE_MEDIA:
3844 case AUDIO_USAGE_GAME:
3845 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3846 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3847 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3848 return (uint32_t) STRATEGY_MEDIA;
3849
3850 case AUDIO_USAGE_VOICE_COMMUNICATION:
3851 return (uint32_t) STRATEGY_PHONE;
3852
3853 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3854 return (uint32_t) STRATEGY_DTMF;
3855
3856 case AUDIO_USAGE_ALARM:
3857 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3858 return (uint32_t) STRATEGY_SONIFICATION;
3859
3860 case AUDIO_USAGE_NOTIFICATION:
3861 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3862 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3863 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3864 case AUDIO_USAGE_NOTIFICATION_EVENT:
3865 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3866
3867 case AUDIO_USAGE_UNKNOWN:
3868 default:
3869 return (uint32_t) STRATEGY_MEDIA;
3870 }
3871}
3872
Eric Laurente0720872014-03-11 09:30:41 -07003873void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003874 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003875 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003876 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3877 updateDevicesAndOutputs();
3878 break;
3879 default:
3880 break;
3881 }
3882}
3883
Eric Laurente0720872014-03-11 09:30:41 -07003884audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003885 bool fromCache)
3886{
3887 uint32_t device = AUDIO_DEVICE_NONE;
3888
3889 if (fromCache) {
3890 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3891 strategy, mDeviceForStrategy[strategy]);
3892 return mDeviceForStrategy[strategy];
3893 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003894 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003895 switch (strategy) {
3896
3897 case STRATEGY_SONIFICATION_RESPECTFUL:
3898 if (isInCall()) {
3899 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003900 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003901 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3902 // while media is playing on a remote device, use the the sonification behavior.
3903 // Note that we test this usecase before testing if media is playing because
3904 // the isStreamActive() method only informs about the activity of a stream, not
3905 // if it's for local playback. Note also that we use the same delay between both tests
3906 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003907 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003908 // while media is playing (or has recently played), use the same device
3909 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3910 } else {
3911 // when media is not playing anymore, fall back on the sonification behavior
3912 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3913 }
3914
3915 break;
3916
3917 case STRATEGY_DTMF:
3918 if (!isInCall()) {
3919 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3920 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3921 break;
3922 }
3923 // when in call, DTMF and PHONE strategies follow the same rules
3924 // FALL THROUGH
3925
3926 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003927 // Force use of only devices on primary output if:
3928 // - in call AND
3929 // - cannot route from voice call RX OR
3930 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3931 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3932 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3933 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3934 if (((mAvailableInputDevices.types() &
3935 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3936 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07003937 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07003938 AUDIO_DEVICE_API_VERSION_3_0))) {
3939 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3940 }
3941 }
Eric Laurente552edb2014-03-10 17:42:56 -07003942 // for phone strategy, we first consider the forced use and then the available devices by order
3943 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003944 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3945 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003946 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003947 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003948 if (device) break;
3949 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003950 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003951 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003953 if (device) break;
3954 // if SCO device is requested but no SCO device is available, fall back to default case
3955 // FALL THROUGH
3956
3957 default: // FORCE_NONE
3958 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003959 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003960 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003961 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003962 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003963 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003964 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003965 if (device) break;
3966 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003967 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003968 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003969 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003970 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07003971 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3972 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003973 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003974 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003975 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003976 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003977 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003978 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003979 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003980 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003981 if (device) break;
3982 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003983 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003984 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003985 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003986 if (device == AUDIO_DEVICE_NONE) {
3987 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3988 }
3989 break;
3990
Eric Laurent3b73df72014-03-11 09:06:29 -07003991 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003992 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3993 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003994 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003995 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003996 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003997 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003998 if (device) break;
3999 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004000 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004001 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004002 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004003 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004004 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004005 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004006 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004007 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004008 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004009 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004010 if (device) break;
4011 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004012 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4013 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004014 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004015 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004016 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004017 if (device == AUDIO_DEVICE_NONE) {
4018 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4019 }
4020 break;
4021 }
4022 break;
4023
4024 case STRATEGY_SONIFICATION:
4025
4026 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4027 // handleIncallSonification().
4028 if (isInCall()) {
4029 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4030 break;
4031 }
4032 // FALL THROUGH
4033
4034 case STRATEGY_ENFORCED_AUDIBLE:
4035 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4036 // except:
4037 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4038 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4039
4040 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004041 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004042 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004043 if (device == AUDIO_DEVICE_NONE) {
4044 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4045 }
4046 }
4047 // The second device used for sonification is the same as the device used by media strategy
4048 // FALL THROUGH
4049
4050 case STRATEGY_MEDIA: {
4051 uint32_t device2 = AUDIO_DEVICE_NONE;
4052 if (strategy != STRATEGY_SONIFICATION) {
4053 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004055 }
4056 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004057 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004058 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004060 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004062 }
4063 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004065 }
4066 }
4067 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004070 if ((device2 == AUDIO_DEVICE_NONE)) {
4071 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4072 }
Eric Laurente552edb2014-03-10 17:42:56 -07004073 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004074 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004075 }
4076 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004078 }
4079 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004081 }
4082 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004083 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
4085 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4086 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004087 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004088 }
4089 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004090 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004092 }
4093 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004095 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004096 int device3 = AUDIO_DEVICE_NONE;
4097 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004098 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004099 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4100 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004101 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004102 }
Eric Laurente552edb2014-03-10 17:42:56 -07004103
Jungshik Jang839e4f32014-06-26 17:23:40 +09004104 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004105 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4106 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4107 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004108
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004109 // If hdmi system audio mode is on, remove speaker out of output list.
4110 if ((strategy == STRATEGY_MEDIA) &&
4111 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4112 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4113 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4114 }
4115
Eric Laurente552edb2014-03-10 17:42:56 -07004116 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004117 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004118 if (device == AUDIO_DEVICE_NONE) {
4119 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4120 }
4121 } break;
4122
4123 default:
4124 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4125 break;
4126 }
4127
4128 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4129 return device;
4130}
4131
Eric Laurente0720872014-03-11 09:30:41 -07004132void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004133{
4134 for (int i = 0; i < NUM_STRATEGIES; i++) {
4135 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4136 }
4137 mPreviousOutputs = mOutputs;
4138}
4139
Eric Laurent1f2f2232014-06-02 12:01:23 -07004140uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004141 audio_devices_t prevDevice,
4142 uint32_t delayMs)
4143{
4144 // mute/unmute strategies using an incompatible device combination
4145 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4146 // if unmuting, unmute only after the specified delay
4147 if (outputDesc->isDuplicated()) {
4148 return 0;
4149 }
4150
4151 uint32_t muteWaitMs = 0;
4152 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004153 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004154
4155 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4156 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4157 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4158 bool doMute = false;
4159
4160 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4161 doMute = true;
4162 outputDesc->mStrategyMutedByDevice[i] = true;
4163 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4164 doMute = true;
4165 outputDesc->mStrategyMutedByDevice[i] = false;
4166 }
Eric Laurent99401132014-05-07 19:48:15 -07004167 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004168 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004169 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004170 // skip output if it does not share any device with current output
4171 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4172 == AUDIO_DEVICE_NONE) {
4173 continue;
4174 }
4175 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4176 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4177 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4178 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4179 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004180 if (mute) {
4181 // FIXME: should not need to double latency if volume could be applied
4182 // immediately by the audioflinger mixer. We must account for the delay
4183 // between now and the next time the audioflinger thread for this output
4184 // will process a buffer (which corresponds to one buffer size,
4185 // usually 1/2 or 1/4 of the latency).
4186 if (muteWaitMs < desc->latency() * 2) {
4187 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004188 }
4189 }
4190 }
4191 }
4192 }
4193 }
4194
Eric Laurent99401132014-05-07 19:48:15 -07004195 // temporary mute output if device selection changes to avoid volume bursts due to
4196 // different per device volumes
4197 if (outputDesc->isActive() && (device != prevDevice)) {
4198 if (muteWaitMs < outputDesc->latency() * 2) {
4199 muteWaitMs = outputDesc->latency() * 2;
4200 }
4201 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4202 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004203 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004204 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004205 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004206 muteWaitMs *2, device);
4207 }
4208 }
4209 }
4210
Eric Laurente552edb2014-03-10 17:42:56 -07004211 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4212 if (muteWaitMs > delayMs) {
4213 muteWaitMs -= delayMs;
4214 usleep(muteWaitMs * 1000);
4215 return muteWaitMs;
4216 }
4217 return 0;
4218}
4219
Eric Laurente0720872014-03-11 09:30:41 -07004220uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004221 audio_devices_t device,
4222 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004223 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004224 audio_patch_handle_t *patchHandle,
4225 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004226{
4227 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004228 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004229 AudioParameter param;
4230 uint32_t muteWaitMs;
4231
4232 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004233 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4234 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004235 return muteWaitMs;
4236 }
4237 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4238 // output profile
4239 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004240 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004241 return 0;
4242 }
4243
4244 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004245 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004246
4247 audio_devices_t prevDevice = outputDesc->mDevice;
4248
4249 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4250
4251 if (device != AUDIO_DEVICE_NONE) {
4252 outputDesc->mDevice = device;
4253 }
4254 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4255
4256 // Do not change the routing if:
4257 // - the requested device is AUDIO_DEVICE_NONE
4258 // - the requested device is the same as current device and force is not specified.
4259 // Doing this check here allows the caller to call setOutputDevice() without conditions
4260 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4261 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4262 return muteWaitMs;
4263 }
4264
4265 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004266
Eric Laurente552edb2014-03-10 17:42:56 -07004267 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004268 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004269 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004270 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004271 DeviceVector deviceList = (address == NULL) ?
4272 mAvailableOutputDevices.getDevicesFromType(device)
4273 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004274 if (!deviceList.isEmpty()) {
4275 struct audio_patch patch;
4276 outputDesc->toAudioPortConfig(&patch.sources[0]);
4277 patch.num_sources = 1;
4278 patch.num_sinks = 0;
4279 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4280 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004281 patch.num_sinks++;
4282 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004283 ssize_t index;
4284 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4285 index = mAudioPatches.indexOfKey(*patchHandle);
4286 } else {
4287 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4288 }
4289 sp< AudioPatch> patchDesc;
4290 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4291 if (index >= 0) {
4292 patchDesc = mAudioPatches.valueAt(index);
4293 afPatchHandle = patchDesc->mAfPatchHandle;
4294 }
4295
Eric Laurent1c333e22014-05-20 10:48:17 -07004296 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004297 &afPatchHandle,
4298 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004299 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4300 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004301 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004302 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004303 if (index < 0) {
4304 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4305 &patch, mUidCached);
4306 addAudioPatch(patchDesc->mHandle, patchDesc);
4307 } else {
4308 patchDesc->mPatch = patch;
4309 }
4310 patchDesc->mAfPatchHandle = afPatchHandle;
4311 patchDesc->mUid = mUidCached;
4312 if (patchHandle) {
4313 *patchHandle = patchDesc->mHandle;
4314 }
4315 outputDesc->mPatchHandle = patchDesc->mHandle;
4316 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004317 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004318 }
4319 }
4320 }
Eric Laurente552edb2014-03-10 17:42:56 -07004321
4322 // update stream volumes according to new device
4323 applyStreamVolumes(output, device, delayMs);
4324
4325 return muteWaitMs;
4326}
4327
Eric Laurent1c333e22014-05-20 10:48:17 -07004328status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004329 int delayMs,
4330 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004331{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004332 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004333 ssize_t index;
4334 if (patchHandle) {
4335 index = mAudioPatches.indexOfKey(*patchHandle);
4336 } else {
4337 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4338 }
4339 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004340 return INVALID_OPERATION;
4341 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004342 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4343 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004344 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4345 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004346 removeAudioPatch(patchDesc->mHandle);
4347 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004348 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004349 return status;
4350}
4351
4352status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4353 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004354 bool force,
4355 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004356{
4357 status_t status = NO_ERROR;
4358
Eric Laurent1f2f2232014-06-02 12:01:23 -07004359 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004360 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4361 inputDesc->mDevice = device;
4362
4363 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4364 if (!deviceList.isEmpty()) {
4365 struct audio_patch patch;
4366 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004367 // AUDIO_SOURCE_HOTWORD is for internal use only:
4368 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004369 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4370 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004371 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4372 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004373 patch.num_sinks = 1;
4374 //only one input device for now
4375 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004376 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004377 ssize_t index;
4378 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4379 index = mAudioPatches.indexOfKey(*patchHandle);
4380 } else {
4381 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4382 }
4383 sp< AudioPatch> patchDesc;
4384 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4385 if (index >= 0) {
4386 patchDesc = mAudioPatches.valueAt(index);
4387 afPatchHandle = patchDesc->mAfPatchHandle;
4388 }
4389
Eric Laurent1c333e22014-05-20 10:48:17 -07004390 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004391 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004392 0);
4393 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004394 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004395 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004396 if (index < 0) {
4397 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4398 &patch, mUidCached);
4399 addAudioPatch(patchDesc->mHandle, patchDesc);
4400 } else {
4401 patchDesc->mPatch = patch;
4402 }
4403 patchDesc->mAfPatchHandle = afPatchHandle;
4404 patchDesc->mUid = mUidCached;
4405 if (patchHandle) {
4406 *patchHandle = patchDesc->mHandle;
4407 }
4408 inputDesc->mPatchHandle = patchDesc->mHandle;
4409 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004410 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004411 }
4412 }
4413 }
4414 return status;
4415}
4416
Eric Laurent6a94d692014-05-20 11:18:06 -07004417status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4418 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004419{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004420 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004421 ssize_t index;
4422 if (patchHandle) {
4423 index = mAudioPatches.indexOfKey(*patchHandle);
4424 } else {
4425 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4426 }
4427 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004428 return INVALID_OPERATION;
4429 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004430 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4431 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004432 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4433 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 removeAudioPatch(patchDesc->mHandle);
4435 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004436 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004437 return status;
4438}
4439
4440sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004441 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004442 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004443 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004444 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004445{
4446 // Choose an input profile based on the requested capture parameters: select the first available
4447 // profile supporting all requested parameters.
4448
4449 for (size_t i = 0; i < mHwModules.size(); i++)
4450 {
4451 if (mHwModules[i]->mHandle == 0) {
4452 continue;
4453 }
4454 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4455 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004456 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004457 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004458 if (profile->isCompatibleProfile(device, samplingRate,
4459 &samplingRate /*updatedSamplingRate*/,
4460 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004461 return profile;
4462 }
4463 }
4464 }
4465 return NULL;
4466}
4467
Eric Laurente0720872014-03-11 09:30:41 -07004468audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004469{
4470 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004471 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4472 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004473 switch (inputSource) {
4474 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004475 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004476 device = AUDIO_DEVICE_IN_VOICE_CALL;
4477 break;
4478 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004479 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004480
4481 case AUDIO_SOURCE_DEFAULT:
4482 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004483 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4484 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004485 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4486 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4487 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4488 device = AUDIO_DEVICE_IN_USB_DEVICE;
4489 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4490 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004491 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004492 break;
4493
4494 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4495 // Allow only use of devices on primary input if in call and HAL does not support routing
4496 // to voice call path.
4497 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4498 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4499 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4500 }
4501
4502 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4503 case AUDIO_POLICY_FORCE_BT_SCO:
4504 // if SCO device is requested but no SCO device is available, fall back to default case
4505 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4506 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4507 break;
4508 }
4509 // FALL THROUGH
4510
4511 default: // FORCE_NONE
4512 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4513 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4514 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4515 device = AUDIO_DEVICE_IN_USB_DEVICE;
4516 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4517 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4518 }
4519 break;
4520
4521 case AUDIO_POLICY_FORCE_SPEAKER:
4522 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4523 device = AUDIO_DEVICE_IN_BACK_MIC;
4524 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4525 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4526 }
4527 break;
4528 }
4529 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004530
Eric Laurente552edb2014-03-10 17:42:56 -07004531 case AUDIO_SOURCE_VOICE_RECOGNITION:
4532 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004533 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004534 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004535 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004536 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004537 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004538 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4539 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004540 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004541 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4542 }
4543 break;
4544 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004545 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004546 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004547 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004548 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4549 }
4550 break;
4551 case AUDIO_SOURCE_VOICE_DOWNLINK:
4552 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004553 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004554 device = AUDIO_DEVICE_IN_VOICE_CALL;
4555 }
4556 break;
4557 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004558 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004559 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4560 }
4561 break;
4562 default:
4563 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4564 break;
4565 }
4566 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4567 return device;
4568}
4569
Eric Laurente0720872014-03-11 09:30:41 -07004570bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004571{
4572 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4573 device &= ~AUDIO_DEVICE_BIT_IN;
4574 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4575 return true;
4576 }
4577 return false;
4578}
4579
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004580bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4581 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4582}
4583
Eric Laurente0720872014-03-11 09:30:41 -07004584audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004585{
4586 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004587 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004588 if ((input_descriptor->mRefCount > 0)
4589 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4590 return mInputs.keyAt(i);
4591 }
4592 }
4593 return 0;
4594}
4595
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004596uint32_t AudioPolicyManager::activeInputsCount() const
4597{
4598 uint32_t count = 0;
4599 for (size_t i = 0; i < mInputs.size(); i++) {
4600 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4601 if (desc->mRefCount > 0) {
4602 return count++;
4603 }
4604 }
4605 return count;
4606}
4607
Eric Laurente552edb2014-03-10 17:42:56 -07004608
Eric Laurente0720872014-03-11 09:30:41 -07004609audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004610{
4611 if (device == AUDIO_DEVICE_NONE) {
4612 // this happens when forcing a route update and no track is active on an output.
4613 // In this case the returned category is not important.
4614 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004615 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004616 // Multiple device selection is either:
4617 // - speaker + one other device: give priority to speaker in this case.
4618 // - one A2DP device + another device: happens with duplicated output. In this case
4619 // retain the device on the A2DP output as the other must not correspond to an active
4620 // selection if not the speaker.
4621 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4622 device = AUDIO_DEVICE_OUT_SPEAKER;
4623 } else {
4624 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4625 }
4626 }
4627
Eric Laurent3b73df72014-03-11 09:06:29 -07004628 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004629 "getDeviceForVolume() invalid device combination: %08x",
4630 device);
4631
4632 return device;
4633}
4634
Eric Laurente0720872014-03-11 09:30:41 -07004635AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004636{
4637 switch(getDeviceForVolume(device)) {
4638 case AUDIO_DEVICE_OUT_EARPIECE:
4639 return DEVICE_CATEGORY_EARPIECE;
4640 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4641 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4642 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4643 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4644 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4645 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4646 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004647 case AUDIO_DEVICE_OUT_LINE:
4648 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4649 /*USB? Remote submix?*/
4650 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004651 case AUDIO_DEVICE_OUT_SPEAKER:
4652 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4653 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004654 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4655 case AUDIO_DEVICE_OUT_USB_DEVICE:
4656 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4657 default:
4658 return DEVICE_CATEGORY_SPEAKER;
4659 }
4660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004663 int indexInUi)
4664{
4665 device_category deviceCategory = getDeviceCategory(device);
4666 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4667
4668 // the volume index in the UI is relative to the min and max volume indices for this stream type
4669 int nbSteps = 1 + curve[VOLMAX].mIndex -
4670 curve[VOLMIN].mIndex;
4671 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4672 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4673
4674 // find what part of the curve this index volume belongs to, or if it's out of bounds
4675 int segment = 0;
4676 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4677 return 0.0f;
4678 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4679 segment = 0;
4680 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4681 segment = 1;
4682 } else if (volIdx <= curve[VOLMAX].mIndex) {
4683 segment = 2;
4684 } else { // out of bounds
4685 return 1.0f;
4686 }
4687
4688 // linear interpolation in the attenuation table in dB
4689 float decibels = curve[segment].mDBAttenuation +
4690 ((float)(volIdx - curve[segment].mIndex)) *
4691 ( (curve[segment+1].mDBAttenuation -
4692 curve[segment].mDBAttenuation) /
4693 ((float)(curve[segment+1].mIndex -
4694 curve[segment].mIndex)) );
4695
4696 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4697
4698 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4699 curve[segment].mIndex, volIdx,
4700 curve[segment+1].mIndex,
4701 curve[segment].mDBAttenuation,
4702 decibels,
4703 curve[segment+1].mDBAttenuation,
4704 amplification);
4705
4706 return amplification;
4707}
4708
Eric Laurente0720872014-03-11 09:30:41 -07004709const AudioPolicyManager::VolumeCurvePoint
4710 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004711 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4712};
4713
Eric Laurente0720872014-03-11 09:30:41 -07004714const AudioPolicyManager::VolumeCurvePoint
4715 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004716 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4717};
4718
Eric Laurente0720872014-03-11 09:30:41 -07004719const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004720 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4721 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4722};
4723
4724const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004725 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004726 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4727};
4728
Eric Laurente0720872014-03-11 09:30:41 -07004729const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004730 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004731 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004732};
4733
4734const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004735 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004736 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4737};
4738
Eric Laurente0720872014-03-11 09:30:41 -07004739const AudioPolicyManager::VolumeCurvePoint
4740 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004741 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4742};
4743
4744// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4745// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4746// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4747// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4748
Eric Laurente0720872014-03-11 09:30:41 -07004749const AudioPolicyManager::VolumeCurvePoint
4750 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004751 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4752};
4753
Eric Laurente0720872014-03-11 09:30:41 -07004754const AudioPolicyManager::VolumeCurvePoint
4755 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004756 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4757};
4758
Eric Laurente0720872014-03-11 09:30:41 -07004759const AudioPolicyManager::VolumeCurvePoint
4760 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004761 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4762};
4763
Eric Laurente0720872014-03-11 09:30:41 -07004764const AudioPolicyManager::VolumeCurvePoint
4765 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004766 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4767};
4768
Eric Laurente0720872014-03-11 09:30:41 -07004769const AudioPolicyManager::VolumeCurvePoint
4770 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004771 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4772};
4773
Eric Laurente0720872014-03-11 09:30:41 -07004774const AudioPolicyManager::VolumeCurvePoint
4775 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4776 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004777 { // AUDIO_STREAM_VOICE_CALL
4778 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4779 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004780 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4781 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004782 },
4783 { // AUDIO_STREAM_SYSTEM
4784 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4785 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004786 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4787 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004788 },
4789 { // AUDIO_STREAM_RING
4790 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4791 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004792 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4793 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004794 },
4795 { // AUDIO_STREAM_MUSIC
4796 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4797 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004798 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4799 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004800 },
4801 { // AUDIO_STREAM_ALARM
4802 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4803 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004804 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4805 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004806 },
4807 { // AUDIO_STREAM_NOTIFICATION
4808 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4809 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004810 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4811 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004812 },
4813 { // AUDIO_STREAM_BLUETOOTH_SCO
4814 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4815 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004816 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4817 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004818 },
4819 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4820 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4821 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004822 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4823 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004824 },
4825 { // AUDIO_STREAM_DTMF
4826 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4827 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004828 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4829 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004830 },
4831 { // AUDIO_STREAM_TTS
4832 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4833 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004834 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4835 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004836 },
4837};
4838
Eric Laurente0720872014-03-11 09:30:41 -07004839void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004840{
4841 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4842 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4843 mStreams[i].mVolumeCurve[j] =
4844 sVolumeProfiles[i][j];
4845 }
4846 }
4847
4848 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4849 if (mSpeakerDrcEnabled) {
4850 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4851 sDefaultSystemVolumeCurveDrc;
4852 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4853 sSpeakerSonificationVolumeCurveDrc;
4854 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4855 sSpeakerSonificationVolumeCurveDrc;
4856 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4857 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004858 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4859 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004860 }
4861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004864 int index,
4865 audio_io_handle_t output,
4866 audio_devices_t device)
4867{
4868 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004869 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004870 StreamDescriptor &streamDesc = mStreams[stream];
4871
4872 if (device == AUDIO_DEVICE_NONE) {
4873 device = outputDesc->device();
4874 }
4875
Eric Laurente552edb2014-03-10 17:42:56 -07004876 volume = volIndexToAmpl(device, streamDesc, index);
4877
4878 // if a headset is connected, apply the following rules to ring tones and notifications
4879 // to avoid sound level bursts in user's ears:
4880 // - always attenuate ring tones and notifications volume by 6dB
4881 // - if music is playing, always limit the volume to current music volume,
4882 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004883 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004884 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4885 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4886 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4887 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4888 ((stream_strategy == STRATEGY_SONIFICATION)
4889 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004890 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004891 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004892 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004893 streamDesc.mCanBeMuted) {
4894 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4895 // when the phone is ringing we must consider that music could have been paused just before
4896 // by the music application and behave as if music was active if the last music track was
4897 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004898 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004899 mLimitRingtoneVolume) {
4900 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004901 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4902 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004903 output,
4904 musicDevice);
4905 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4906 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4907 if (volume > minVol) {
4908 volume = minVol;
4909 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4910 }
4911 }
4912 }
4913
4914 return volume;
4915}
4916
Eric Laurente0720872014-03-11 09:30:41 -07004917status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004918 int index,
4919 audio_io_handle_t output,
4920 audio_devices_t device,
4921 int delayMs,
4922 bool force)
4923{
4924
4925 // do not change actual stream volume if the stream is muted
4926 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4927 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4928 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4929 return NO_ERROR;
4930 }
4931
4932 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004933 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4934 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4935 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4936 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004937 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004938 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004939 return INVALID_OPERATION;
4940 }
4941
4942 float volume = computeVolume(stream, index, output, device);
4943 // We actually change the volume if:
4944 // - the float value returned by computeVolume() changed
4945 // - the force flag is set
4946 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4947 force) {
4948 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4949 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4950 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4951 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004952 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4953 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004954 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004955 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004956 }
4957
Eric Laurent3b73df72014-03-11 09:06:29 -07004958 if (stream == AUDIO_STREAM_VOICE_CALL ||
4959 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004960 float voiceVolume;
4961 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004962 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004963 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4964 } else {
4965 voiceVolume = 1.0;
4966 }
4967
4968 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4969 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4970 mLastVoiceVolume = voiceVolume;
4971 }
4972 }
4973
4974 return NO_ERROR;
4975}
4976
Eric Laurente0720872014-03-11 09:30:41 -07004977void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004978 audio_devices_t device,
4979 int delayMs,
4980 bool force)
4981{
4982 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4983
Eric Laurent3b73df72014-03-11 09:06:29 -07004984 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4985 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004986 mStreams[stream].getVolumeIndex(device),
4987 output,
4988 device,
4989 delayMs,
4990 force);
4991 }
4992}
4993
Eric Laurente0720872014-03-11 09:30:41 -07004994void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004995 bool on,
4996 audio_io_handle_t output,
4997 int delayMs,
4998 audio_devices_t device)
4999{
5000 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005001 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5002 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5003 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005004 }
5005 }
5006}
5007
Eric Laurente0720872014-03-11 09:30:41 -07005008void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005009 bool on,
5010 audio_io_handle_t output,
5011 int delayMs,
5012 audio_devices_t device)
5013{
5014 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005015 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005016 if (device == AUDIO_DEVICE_NONE) {
5017 device = outputDesc->device();
5018 }
5019
5020 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5021 stream, on, output, outputDesc->mMuteCount[stream], device);
5022
5023 if (on) {
5024 if (outputDesc->mMuteCount[stream] == 0) {
5025 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005026 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5027 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005028 checkAndSetVolume(stream, 0, output, device, delayMs);
5029 }
5030 }
5031 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5032 outputDesc->mMuteCount[stream]++;
5033 } else {
5034 if (outputDesc->mMuteCount[stream] == 0) {
5035 ALOGV("setStreamMute() unmuting non muted stream!");
5036 return;
5037 }
5038 if (--outputDesc->mMuteCount[stream] == 0) {
5039 checkAndSetVolume(stream,
5040 streamDesc.getVolumeIndex(device),
5041 output,
5042 device,
5043 delayMs);
5044 }
5045 }
5046}
5047
Eric Laurente0720872014-03-11 09:30:41 -07005048void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005049 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005050{
5051 // if the stream pertains to sonification strategy and we are in call we must
5052 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5053 // in the device used for phone strategy and play the tone if the selected device does not
5054 // interfere with the device used for phone strategy
5055 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5056 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005057 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005058 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5059 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005060 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005061 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5062 stream, starting, outputDesc->mDevice, stateChange);
5063 if (outputDesc->mRefCount[stream]) {
5064 int muteCount = 1;
5065 if (stateChange) {
5066 muteCount = outputDesc->mRefCount[stream];
5067 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005068 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005069 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5070 for (int i = 0; i < muteCount; i++) {
5071 setStreamMute(stream, starting, mPrimaryOutput);
5072 }
5073 } else {
5074 ALOGV("handleIncallSonification() high visibility");
5075 if (outputDesc->device() &
5076 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5077 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5078 for (int i = 0; i < muteCount; i++) {
5079 setStreamMute(stream, starting, mPrimaryOutput);
5080 }
5081 }
5082 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005083 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5084 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005085 } else {
5086 mpClientInterface->stopTone();
5087 }
5088 }
5089 }
5090 }
5091}
5092
Eric Laurente0720872014-03-11 09:30:41 -07005093bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005094{
5095 return isStateInCall(mPhoneState);
5096}
5097
Eric Laurente0720872014-03-11 09:30:41 -07005098bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005099 return ((state == AUDIO_MODE_IN_CALL) ||
5100 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005101}
5102
Eric Laurente0720872014-03-11 09:30:41 -07005103uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005104{
5105 return MAX_EFFECTS_CPU_LOAD;
5106}
5107
Eric Laurente0720872014-03-11 09:30:41 -07005108uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005109{
5110 return MAX_EFFECTS_MEMORY;
5111}
5112
Eric Laurent6a94d692014-05-20 11:18:06 -07005113
Eric Laurente552edb2014-03-10 17:42:56 -07005114// --- AudioOutputDescriptor class implementation
5115
Eric Laurente0720872014-03-11 09:30:41 -07005116AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005117 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005118 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005119 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005120 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5121{
5122 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005123 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005124 mRefCount[i] = 0;
5125 mCurVolume[i] = -1.0;
5126 mMuteCount[i] = 0;
5127 mStopTime[i] = 0;
5128 }
5129 for (int i = 0; i < NUM_STRATEGIES; i++) {
5130 mStrategyMutedByDevice[i] = false;
5131 }
5132 if (profile != NULL) {
Eric Laurentd8622372014-07-27 13:47:31 -07005133 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005134 mSamplingRate = profile->pickSamplingRate();
5135 mFormat = profile->pickFormat();
5136 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005137 if (profile->mGains.size() > 0) {
5138 profile->mGains[0]->getDefaultConfig(&mGain);
5139 }
Eric Laurente552edb2014-03-10 17:42:56 -07005140 }
5141}
5142
Eric Laurente0720872014-03-11 09:30:41 -07005143audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005144{
5145 if (isDuplicated()) {
5146 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5147 } else {
5148 return mDevice;
5149 }
5150}
5151
Eric Laurente0720872014-03-11 09:30:41 -07005152uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005153{
5154 if (isDuplicated()) {
5155 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5156 } else {
5157 return mLatency;
5158 }
5159}
5160
Eric Laurente0720872014-03-11 09:30:41 -07005161bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005162 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005163{
5164 if (isDuplicated()) {
5165 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5166 } else if (outputDesc->isDuplicated()){
5167 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5168 } else {
5169 return (mProfile->mModule == outputDesc->mProfile->mModule);
5170 }
5171}
5172
Eric Laurente0720872014-03-11 09:30:41 -07005173void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005174 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005175{
5176 // forward usage count change to attached outputs
5177 if (isDuplicated()) {
5178 mOutput1->changeRefCount(stream, delta);
5179 mOutput2->changeRefCount(stream, delta);
5180 }
5181 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005182 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5183 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005184 mRefCount[stream] = 0;
5185 return;
5186 }
5187 mRefCount[stream] += delta;
5188 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5189}
5190
Eric Laurente0720872014-03-11 09:30:41 -07005191audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005192{
5193 if (isDuplicated()) {
5194 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5195 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005196 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005197 }
5198}
5199
Eric Laurente0720872014-03-11 09:30:41 -07005200bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005201{
5202 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5203}
5204
Eric Laurente0720872014-03-11 09:30:41 -07005205bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005206 uint32_t inPastMs,
5207 nsecs_t sysTime) const
5208{
5209 if ((sysTime == 0) && (inPastMs != 0)) {
5210 sysTime = systemTime();
5211 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005212 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5213 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005214 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005215 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005216 return true;
5217 }
5218 }
5219 return false;
5220}
5221
Eric Laurente0720872014-03-11 09:30:41 -07005222bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005223 uint32_t inPastMs,
5224 nsecs_t sysTime) const
5225{
5226 if (mRefCount[stream] != 0) {
5227 return true;
5228 }
5229 if (inPastMs == 0) {
5230 return false;
5231 }
5232 if (sysTime == 0) {
5233 sysTime = systemTime();
5234 }
5235 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5236 return true;
5237 }
5238 return false;
5239}
5240
Eric Laurent1c333e22014-05-20 10:48:17 -07005241void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 struct audio_port_config *dstConfig,
5243 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005244{
Eric Laurent84c70242014-06-23 08:46:27 -07005245 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5246
Eric Laurent1f2f2232014-06-02 12:01:23 -07005247 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5248 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5249 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005250 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005251 }
5252 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5253
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 dstConfig->id = mId;
5255 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5256 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5258 dstConfig->ext.mix.handle = mIoHandle;
5259 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005260}
5261
5262void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5263 struct audio_port *port) const
5264{
Eric Laurent84c70242014-06-23 08:46:27 -07005265 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005266 mProfile->toAudioPort(port);
5267 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 toAudioPortConfig(&port->active_config);
5269 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005270 port->ext.mix.handle = mIoHandle;
5271 port->ext.mix.latency_class =
5272 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5273}
Eric Laurente552edb2014-03-10 17:42:56 -07005274
Eric Laurente0720872014-03-11 09:30:41 -07005275status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005276{
5277 const size_t SIZE = 256;
5278 char buffer[SIZE];
5279 String8 result;
5280
Eric Laurent4d416952014-08-10 14:07:09 -07005281 snprintf(buffer, SIZE, " ID: %d\n", mId);
5282 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005283 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5284 result.append(buffer);
5285 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5286 result.append(buffer);
5287 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5288 result.append(buffer);
5289 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5290 result.append(buffer);
5291 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5292 result.append(buffer);
5293 snprintf(buffer, SIZE, " Devices %08x\n", device());
5294 result.append(buffer);
5295 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5296 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005297 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5298 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5299 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005300 result.append(buffer);
5301 }
5302 write(fd, result.string(), result.size());
5303
5304 return NO_ERROR;
5305}
5306
5307// --- AudioInputDescriptor class implementation
5308
Eric Laurent1c333e22014-05-20 10:48:17 -07005309AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005310 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005311 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005312 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005313{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005314 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005315 mSamplingRate = profile->pickSamplingRate();
5316 mFormat = profile->pickFormat();
5317 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005318 if (profile->mGains.size() > 0) {
5319 profile->mGains[0]->getDefaultConfig(&mGain);
5320 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005321 }
Eric Laurente552edb2014-03-10 17:42:56 -07005322}
5323
Eric Laurent1c333e22014-05-20 10:48:17 -07005324void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005325 struct audio_port_config *dstConfig,
5326 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005327{
Eric Laurent84c70242014-06-23 08:46:27 -07005328 ALOG_ASSERT(mProfile != 0,
5329 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005330 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5331 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5332 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005333 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005334 }
5335
5336 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5337
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 dstConfig->id = mId;
5339 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5340 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005341 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5342 dstConfig->ext.mix.handle = mIoHandle;
5343 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005344}
5345
5346void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5347 struct audio_port *port) const
5348{
Eric Laurent84c70242014-06-23 08:46:27 -07005349 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5350
Eric Laurent1c333e22014-05-20 10:48:17 -07005351 mProfile->toAudioPort(port);
5352 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005353 toAudioPortConfig(&port->active_config);
5354 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005355 port->ext.mix.handle = mIoHandle;
5356 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5357}
5358
Eric Laurente0720872014-03-11 09:30:41 -07005359status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005360{
5361 const size_t SIZE = 256;
5362 char buffer[SIZE];
5363 String8 result;
5364
Eric Laurent4d416952014-08-10 14:07:09 -07005365 snprintf(buffer, SIZE, " ID: %d\n", mId);
5366 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005367 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5368 result.append(buffer);
5369 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5370 result.append(buffer);
5371 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5372 result.append(buffer);
5373 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5374 result.append(buffer);
5375 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5376 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005377 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5378 result.append(buffer);
5379
Eric Laurente552edb2014-03-10 17:42:56 -07005380 write(fd, result.string(), result.size());
5381
5382 return NO_ERROR;
5383}
5384
5385// --- StreamDescriptor class implementation
5386
Eric Laurente0720872014-03-11 09:30:41 -07005387AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005388 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5389{
5390 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5391}
5392
Eric Laurente0720872014-03-11 09:30:41 -07005393int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005394{
Eric Laurente0720872014-03-11 09:30:41 -07005395 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005396 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5397 if (mIndexCur.indexOfKey(device) < 0) {
5398 device = AUDIO_DEVICE_OUT_DEFAULT;
5399 }
5400 return mIndexCur.valueFor(device);
5401}
5402
Eric Laurente0720872014-03-11 09:30:41 -07005403void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005404{
5405 const size_t SIZE = 256;
5406 char buffer[SIZE];
5407 String8 result;
5408
5409 snprintf(buffer, SIZE, "%s %02d %02d ",
5410 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5411 result.append(buffer);
5412 for (size_t i = 0; i < mIndexCur.size(); i++) {
5413 snprintf(buffer, SIZE, "%04x : %02d, ",
5414 mIndexCur.keyAt(i),
5415 mIndexCur.valueAt(i));
5416 result.append(buffer);
5417 }
5418 result.append("\n");
5419
5420 write(fd, result.string(), result.size());
5421}
5422
5423// --- EffectDescriptor class implementation
5424
Eric Laurente0720872014-03-11 09:30:41 -07005425status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005426{
5427 const size_t SIZE = 256;
5428 char buffer[SIZE];
5429 String8 result;
5430
5431 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5432 result.append(buffer);
5433 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5434 result.append(buffer);
5435 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5436 result.append(buffer);
5437 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5438 result.append(buffer);
5439 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5440 result.append(buffer);
5441 write(fd, result.string(), result.size());
5442
5443 return NO_ERROR;
5444}
5445
Eric Laurent1c333e22014-05-20 10:48:17 -07005446// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005447
Eric Laurente0720872014-03-11 09:30:41 -07005448AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005449 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5450 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005451{
5452}
5453
Eric Laurente0720872014-03-11 09:30:41 -07005454AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005455{
5456 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005457 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005458 }
5459 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005460 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005461 }
5462 free((void *)mName);
5463}
5464
Eric Laurent1afeecb2014-05-14 08:52:28 -07005465status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5466{
5467 cnode *node = root->first_child;
5468
5469 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5470
5471 while (node) {
5472 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5473 profile->loadSamplingRates((char *)node->value);
5474 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5475 profile->loadFormats((char *)node->value);
5476 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5477 profile->loadInChannels((char *)node->value);
5478 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5479 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5480 mDeclaredDevices);
5481 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5482 profile->loadGains(node);
5483 }
5484 node = node->next;
5485 }
5486 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5487 "loadInput() invalid supported devices");
5488 ALOGW_IF(profile->mChannelMasks.size() == 0,
5489 "loadInput() invalid supported channel masks");
5490 ALOGW_IF(profile->mSamplingRates.size() == 0,
5491 "loadInput() invalid supported sampling rates");
5492 ALOGW_IF(profile->mFormats.size() == 0,
5493 "loadInput() invalid supported formats");
5494 if (!profile->mSupportedDevices.isEmpty() &&
5495 (profile->mChannelMasks.size() != 0) &&
5496 (profile->mSamplingRates.size() != 0) &&
5497 (profile->mFormats.size() != 0)) {
5498
5499 ALOGV("loadInput() adding input Supported Devices %04x",
5500 profile->mSupportedDevices.types());
5501
5502 mInputProfiles.add(profile);
5503 return NO_ERROR;
5504 } else {
5505 return BAD_VALUE;
5506 }
5507}
5508
5509status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5510{
5511 cnode *node = root->first_child;
5512
5513 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5514
5515 while (node) {
5516 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5517 profile->loadSamplingRates((char *)node->value);
5518 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5519 profile->loadFormats((char *)node->value);
5520 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5521 profile->loadOutChannels((char *)node->value);
5522 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5523 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5524 mDeclaredDevices);
5525 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5526 profile->mFlags = parseFlagNames((char *)node->value);
5527 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5528 profile->loadGains(node);
5529 }
5530 node = node->next;
5531 }
5532 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5533 "loadOutput() invalid supported devices");
5534 ALOGW_IF(profile->mChannelMasks.size() == 0,
5535 "loadOutput() invalid supported channel masks");
5536 ALOGW_IF(profile->mSamplingRates.size() == 0,
5537 "loadOutput() invalid supported sampling rates");
5538 ALOGW_IF(profile->mFormats.size() == 0,
5539 "loadOutput() invalid supported formats");
5540 if (!profile->mSupportedDevices.isEmpty() &&
5541 (profile->mChannelMasks.size() != 0) &&
5542 (profile->mSamplingRates.size() != 0) &&
5543 (profile->mFormats.size() != 0)) {
5544
5545 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5546 profile->mSupportedDevices.types(), profile->mFlags);
5547
5548 mOutputProfiles.add(profile);
5549 return NO_ERROR;
5550 } else {
5551 return BAD_VALUE;
5552 }
5553}
5554
5555status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5556{
5557 cnode *node = root->first_child;
5558
5559 audio_devices_t type = AUDIO_DEVICE_NONE;
5560 while (node) {
5561 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5562 type = parseDeviceNames((char *)node->value);
5563 break;
5564 }
5565 node = node->next;
5566 }
5567 if (type == AUDIO_DEVICE_NONE ||
5568 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5569 ALOGW("loadDevice() bad type %08x", type);
5570 return BAD_VALUE;
5571 }
5572 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5573 deviceDesc->mModule = this;
5574
5575 node = root->first_child;
5576 while (node) {
5577 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5578 deviceDesc->mAddress = String8((char *)node->value);
5579 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5580 if (audio_is_input_device(type)) {
5581 deviceDesc->loadInChannels((char *)node->value);
5582 } else {
5583 deviceDesc->loadOutChannels((char *)node->value);
5584 }
5585 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5586 deviceDesc->loadGains(node);
5587 }
5588 node = node->next;
5589 }
5590
5591 ALOGV("loadDevice() adding device name %s type %08x address %s",
5592 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5593
5594 mDeclaredDevices.add(deviceDesc);
5595
5596 return NO_ERROR;
5597}
5598
Eric Laurente0720872014-03-11 09:30:41 -07005599void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005600{
5601 const size_t SIZE = 256;
5602 char buffer[SIZE];
5603 String8 result;
5604
5605 snprintf(buffer, SIZE, " - name: %s\n", mName);
5606 result.append(buffer);
5607 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5608 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005609 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5610 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005611 write(fd, result.string(), result.size());
5612 if (mOutputProfiles.size()) {
5613 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5614 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005615 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005616 write(fd, buffer, strlen(buffer));
5617 mOutputProfiles[i]->dump(fd);
5618 }
5619 }
5620 if (mInputProfiles.size()) {
5621 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5622 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005623 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005624 write(fd, buffer, strlen(buffer));
5625 mInputProfiles[i]->dump(fd);
5626 }
5627 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005628 if (mDeclaredDevices.size()) {
5629 write(fd, " - devices:\n", strlen(" - devices:\n"));
5630 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5631 mDeclaredDevices[i]->dump(fd, 4, i);
5632 }
5633 }
Eric Laurente552edb2014-03-10 17:42:56 -07005634}
5635
Eric Laurent1c333e22014-05-20 10:48:17 -07005636// --- AudioPort class implementation
5637
Eric Laurenta121f902014-06-03 13:32:54 -07005638
5639AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5640 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005641 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005642{
5643 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5644 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5645}
5646
Eric Laurent1c333e22014-05-20 10:48:17 -07005647void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5648{
5649 port->role = mRole;
5650 port->type = mType;
5651 unsigned int i;
5652 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005653 if (mSamplingRates[i] != 0) {
5654 port->sample_rates[i] = mSamplingRates[i];
5655 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005656 }
5657 port->num_sample_rates = i;
5658 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005659 if (mChannelMasks[i] != 0) {
5660 port->channel_masks[i] = mChannelMasks[i];
5661 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005662 }
5663 port->num_channel_masks = i;
5664 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005665 if (mFormats[i] != 0) {
5666 port->formats[i] = mFormats[i];
5667 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005668 }
5669 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005670
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005671 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005672
5673 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5674 port->gains[i] = mGains[i]->mGain;
5675 }
5676 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005677}
5678
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005679void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5680 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5681 const uint32_t rate = port->mSamplingRates.itemAt(k);
5682 if (rate != 0) { // skip "dynamic" rates
5683 bool hasRate = false;
5684 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5685 if (rate == mSamplingRates.itemAt(l)) {
5686 hasRate = true;
5687 break;
5688 }
5689 }
5690 if (!hasRate) { // never import a sampling rate twice
5691 mSamplingRates.add(rate);
5692 }
5693 }
5694 }
5695 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5696 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5697 if (mask != 0) { // skip "dynamic" masks
5698 bool hasMask = false;
5699 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5700 if (mask == mChannelMasks.itemAt(l)) {
5701 hasMask = true;
5702 break;
5703 }
5704 }
5705 if (!hasMask) { // never import a channel mask twice
5706 mChannelMasks.add(mask);
5707 }
5708 }
5709 }
5710 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5711 const audio_format_t format = port->mFormats.itemAt(k);
5712 if (format != 0) { // skip "dynamic" formats
5713 bool hasFormat = false;
5714 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5715 if (format == mFormats.itemAt(l)) {
5716 hasFormat = true;
5717 break;
5718 }
5719 }
5720 if (!hasFormat) { // never import a channel mask twice
5721 mFormats.add(format);
5722 }
5723 }
5724 }
5725}
5726
5727void AudioPolicyManager::AudioPort::clearCapabilities() {
5728 mChannelMasks.clear();
5729 mFormats.clear();
5730 mSamplingRates.clear();
5731}
Eric Laurent1c333e22014-05-20 10:48:17 -07005732
5733void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5734{
5735 char *str = strtok(name, "|");
5736
5737 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5738 // rates should be read from the output stream after it is opened for the first time
5739 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5740 mSamplingRates.add(0);
5741 return;
5742 }
5743
5744 while (str != NULL) {
5745 uint32_t rate = atoi(str);
5746 if (rate != 0) {
5747 ALOGV("loadSamplingRates() adding rate %d", rate);
5748 mSamplingRates.add(rate);
5749 }
5750 str = strtok(NULL, "|");
5751 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005752}
5753
5754void AudioPolicyManager::AudioPort::loadFormats(char *name)
5755{
5756 char *str = strtok(name, "|");
5757
5758 // by convention, "0' in the first entry in mFormats indicates the supported formats
5759 // should be read from the output stream after it is opened for the first time
5760 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5761 mFormats.add(AUDIO_FORMAT_DEFAULT);
5762 return;
5763 }
5764
5765 while (str != NULL) {
5766 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5767 ARRAY_SIZE(sFormatNameToEnumTable),
5768 str);
5769 if (format != AUDIO_FORMAT_DEFAULT) {
5770 mFormats.add(format);
5771 }
5772 str = strtok(NULL, "|");
5773 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005774}
5775
5776void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5777{
5778 const char *str = strtok(name, "|");
5779
5780 ALOGV("loadInChannels() %s", name);
5781
5782 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5783 mChannelMasks.add(0);
5784 return;
5785 }
5786
5787 while (str != NULL) {
5788 audio_channel_mask_t channelMask =
5789 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5790 ARRAY_SIZE(sInChannelsNameToEnumTable),
5791 str);
5792 if (channelMask != 0) {
5793 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5794 mChannelMasks.add(channelMask);
5795 }
5796 str = strtok(NULL, "|");
5797 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005798}
5799
5800void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5801{
5802 const char *str = strtok(name, "|");
5803
5804 ALOGV("loadOutChannels() %s", name);
5805
5806 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5807 // masks should be read from the output stream after it is opened for the first time
5808 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5809 mChannelMasks.add(0);
5810 return;
5811 }
5812
5813 while (str != NULL) {
5814 audio_channel_mask_t channelMask =
5815 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5816 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5817 str);
5818 if (channelMask != 0) {
5819 mChannelMasks.add(channelMask);
5820 }
5821 str = strtok(NULL, "|");
5822 }
5823 return;
5824}
5825
Eric Laurent1afeecb2014-05-14 08:52:28 -07005826audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5827{
5828 const char *str = strtok(name, "|");
5829
5830 ALOGV("loadGainMode() %s", name);
5831 audio_gain_mode_t mode = 0;
5832 while (str != NULL) {
5833 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5834 ARRAY_SIZE(sGainModeNameToEnumTable),
5835 str);
5836 str = strtok(NULL, "|");
5837 }
5838 return mode;
5839}
5840
Eric Laurenta121f902014-06-03 13:32:54 -07005841void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005842{
5843 cnode *node = root->first_child;
5844
Eric Laurenta121f902014-06-03 13:32:54 -07005845 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005846
5847 while (node) {
5848 if (strcmp(node->name, GAIN_MODE) == 0) {
5849 gain->mGain.mode = loadGainMode((char *)node->value);
5850 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005851 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005852 gain->mGain.channel_mask =
5853 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5854 ARRAY_SIZE(sInChannelsNameToEnumTable),
5855 (char *)node->value);
5856 } else {
5857 gain->mGain.channel_mask =
5858 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5859 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5860 (char *)node->value);
5861 }
5862 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5863 gain->mGain.min_value = atoi((char *)node->value);
5864 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5865 gain->mGain.max_value = atoi((char *)node->value);
5866 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5867 gain->mGain.default_value = atoi((char *)node->value);
5868 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5869 gain->mGain.step_value = atoi((char *)node->value);
5870 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5871 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5872 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5873 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5874 }
5875 node = node->next;
5876 }
5877
5878 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5879 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5880
5881 if (gain->mGain.mode == 0) {
5882 return;
5883 }
5884 mGains.add(gain);
5885}
5886
5887void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5888{
5889 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005890 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005891 while (node) {
5892 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005893 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005894 node = node->next;
5895 }
5896}
5897
Glenn Kastencbd48022014-07-24 13:46:44 -07005898status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005899{
5900 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5901 if (mSamplingRates[i] == samplingRate) {
5902 return NO_ERROR;
5903 }
5904 }
5905 return BAD_VALUE;
5906}
5907
Glenn Kastencbd48022014-07-24 13:46:44 -07005908status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5909 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005910{
Glenn Kastencbd48022014-07-24 13:46:44 -07005911 // Search for the closest supported sampling rate that is above (preferred)
5912 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5913 // The sampling rates do not need to be sorted in ascending order.
5914 ssize_t maxBelow = -1;
5915 ssize_t minAbove = -1;
5916 uint32_t candidate;
5917 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5918 candidate = mSamplingRates[i];
5919 if (candidate == samplingRate) {
5920 if (updatedSamplingRate != NULL) {
5921 *updatedSamplingRate = candidate;
5922 }
5923 return NO_ERROR;
5924 }
5925 // candidate < desired
5926 if (candidate < samplingRate) {
5927 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5928 maxBelow = i;
5929 }
5930 // candidate > desired
5931 } else {
5932 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5933 minAbove = i;
5934 }
5935 }
5936 }
5937 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5938 // TODO Move these assumptions out.
5939 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5940 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5941 // due to approximation by an int32_t of the
5942 // phase increments
5943 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5944 if (minAbove >= 0) {
5945 candidate = mSamplingRates[minAbove];
5946 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5947 if (updatedSamplingRate != NULL) {
5948 *updatedSamplingRate = candidate;
5949 }
5950 return NO_ERROR;
5951 }
5952 }
5953 // But if we have to up-sample from a lower sampling rate, that's OK.
5954 if (maxBelow >= 0) {
5955 candidate = mSamplingRates[maxBelow];
5956 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5957 if (updatedSamplingRate != NULL) {
5958 *updatedSamplingRate = candidate;
5959 }
5960 return NO_ERROR;
5961 }
5962 }
5963 // leave updatedSamplingRate unmodified
5964 return BAD_VALUE;
5965}
5966
5967status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5968{
5969 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005970 if (mChannelMasks[i] == channelMask) {
5971 return NO_ERROR;
5972 }
5973 }
5974 return BAD_VALUE;
5975}
5976
Glenn Kastencbd48022014-07-24 13:46:44 -07005977status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5978 const
5979{
5980 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5981 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5982 // FIXME Does not handle multi-channel automatic conversions yet
5983 audio_channel_mask_t supported = mChannelMasks[i];
5984 if (supported == channelMask) {
5985 return NO_ERROR;
5986 }
5987 if (isRecordThread) {
5988 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5989 // FIXME Abstract this out to a table.
5990 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5991 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5992 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5993 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5994 return NO_ERROR;
5995 }
5996 }
5997 }
5998 return BAD_VALUE;
5999}
6000
Eric Laurenta121f902014-06-03 13:32:54 -07006001status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6002{
6003 for (size_t i = 0; i < mFormats.size(); i ++) {
6004 if (mFormats[i] == format) {
6005 return NO_ERROR;
6006 }
6007 }
6008 return BAD_VALUE;
6009}
6010
Eric Laurent1e693b52014-07-09 15:03:28 -07006011
6012uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6013{
6014 // special case for uninitialized dynamic profile
6015 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6016 return 0;
6017 }
6018
6019 uint32_t samplingRate = 0;
6020 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6021
6022 // For mixed output and inputs, use max mixer sampling rates. Do not
6023 // limit sampling rate otherwise
6024 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6025 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
6026 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
6027 maxRate = UINT_MAX;
6028 }
6029 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6030 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6031 samplingRate = mSamplingRates[i];
6032 }
6033 }
6034 return samplingRate;
6035}
6036
6037audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6038{
6039 // special case for uninitialized dynamic profile
6040 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6041 return AUDIO_CHANNEL_NONE;
6042 }
6043
6044 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
6045 uint32_t channelCount = 0;
6046 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6047
6048 // For mixed output and inputs, use max mixer channel count. Do not
6049 // limit channel count otherwise
6050 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6051 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
6052 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
6053 maxCount = UINT_MAX;
6054 }
6055 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6056 uint32_t cnlCount;
6057 if (mUseInChannelMask) {
6058 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6059 } else {
6060 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6061 }
6062 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6063 channelMask = mChannelMasks[i];
6064 }
6065 }
6066 return channelMask;
6067}
6068
Andy Hung9a605382014-07-28 16:16:31 -07006069/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006070const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6071 AUDIO_FORMAT_DEFAULT,
6072 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006073 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006074 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006075 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006076 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006077};
6078
6079int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6080 audio_format_t format2)
6081{
6082 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6083 // compressed format and better than any PCM format. This is by design of pickFormat()
6084 if (!audio_is_linear_pcm(format1)) {
6085 if (!audio_is_linear_pcm(format2)) {
6086 return 0;
6087 }
6088 return 1;
6089 }
6090 if (!audio_is_linear_pcm(format2)) {
6091 return -1;
6092 }
6093
6094 int index1 = -1, index2 = -1;
6095 for (size_t i = 0;
6096 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6097 i ++) {
6098 if (sPcmFormatCompareTable[i] == format1) {
6099 index1 = i;
6100 }
6101 if (sPcmFormatCompareTable[i] == format2) {
6102 index2 = i;
6103 }
6104 }
6105 // format1 not found => index1 < 0 => format2 > format1
6106 // format2 not found => index2 < 0 => format2 < format1
6107 return index1 - index2;
6108}
6109
6110audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6111{
6112 // special case for uninitialized dynamic profile
6113 if (mFormats.size() == 1 && mFormats[0] == 0) {
6114 return AUDIO_FORMAT_DEFAULT;
6115 }
6116
6117 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006118 audio_format_t bestFormat =
6119 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6120 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006121 // For mixed output and inputs, use best mixer output format. Do not
6122 // limit format otherwise
6123 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6124 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006125 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006126 bestFormat = AUDIO_FORMAT_INVALID;
6127 }
6128
6129 for (size_t i = 0; i < mFormats.size(); i ++) {
6130 if ((compareFormats(mFormats[i], format) > 0) &&
6131 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6132 format = mFormats[i];
6133 }
6134 }
6135 return format;
6136}
6137
Eric Laurenta121f902014-06-03 13:32:54 -07006138status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6139 int index) const
6140{
6141 if (index < 0 || (size_t)index >= mGains.size()) {
6142 return BAD_VALUE;
6143 }
6144 return mGains[index]->checkConfig(gainConfig);
6145}
6146
Eric Laurent1afeecb2014-05-14 08:52:28 -07006147void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6148{
6149 const size_t SIZE = 256;
6150 char buffer[SIZE];
6151 String8 result;
6152
6153 if (mName.size() != 0) {
6154 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6155 result.append(buffer);
6156 }
6157
6158 if (mSamplingRates.size() != 0) {
6159 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6160 result.append(buffer);
6161 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006162 if (i == 0 && mSamplingRates[i] == 0) {
6163 snprintf(buffer, SIZE, "Dynamic");
6164 } else {
6165 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6166 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006167 result.append(buffer);
6168 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6169 }
6170 result.append("\n");
6171 }
6172
6173 if (mChannelMasks.size() != 0) {
6174 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6175 result.append(buffer);
6176 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006177 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6178
6179 if (i == 0 && mChannelMasks[i] == 0) {
6180 snprintf(buffer, SIZE, "Dynamic");
6181 } else {
6182 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6183 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006184 result.append(buffer);
6185 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6186 }
6187 result.append("\n");
6188 }
6189
6190 if (mFormats.size() != 0) {
6191 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6192 result.append(buffer);
6193 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006194 const char *formatStr = enumToString(sFormatNameToEnumTable,
6195 ARRAY_SIZE(sFormatNameToEnumTable),
6196 mFormats[i]);
6197 if (i == 0 && strcmp(formatStr, "") == 0) {
6198 snprintf(buffer, SIZE, "Dynamic");
6199 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006200 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006201 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006202 result.append(buffer);
6203 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6204 }
6205 result.append("\n");
6206 }
6207 write(fd, result.string(), result.size());
6208 if (mGains.size() != 0) {
6209 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6210 write(fd, buffer, strlen(buffer) + 1);
6211 result.append(buffer);
6212 for (size_t i = 0; i < mGains.size(); i++) {
6213 mGains[i]->dump(fd, spaces + 2, i);
6214 }
6215 }
6216}
6217
6218// --- AudioGain class implementation
6219
Eric Laurenta121f902014-06-03 13:32:54 -07006220AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006221{
Eric Laurenta121f902014-06-03 13:32:54 -07006222 mIndex = index;
6223 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006224 memset(&mGain, 0, sizeof(struct audio_gain));
6225}
6226
Eric Laurenta121f902014-06-03 13:32:54 -07006227void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6228{
6229 config->index = mIndex;
6230 config->mode = mGain.mode;
6231 config->channel_mask = mGain.channel_mask;
6232 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6233 config->values[0] = mGain.default_value;
6234 } else {
6235 uint32_t numValues;
6236 if (mUseInChannelMask) {
6237 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6238 } else {
6239 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6240 }
6241 for (size_t i = 0; i < numValues; i++) {
6242 config->values[i] = mGain.default_value;
6243 }
6244 }
6245 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6246 config->ramp_duration_ms = mGain.min_ramp_ms;
6247 }
6248}
6249
6250status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6251{
6252 if ((config->mode & ~mGain.mode) != 0) {
6253 return BAD_VALUE;
6254 }
6255 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6256 if ((config->values[0] < mGain.min_value) ||
6257 (config->values[0] > mGain.max_value)) {
6258 return BAD_VALUE;
6259 }
6260 } else {
6261 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6262 return BAD_VALUE;
6263 }
6264 uint32_t numValues;
6265 if (mUseInChannelMask) {
6266 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6267 } else {
6268 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6269 }
6270 for (size_t i = 0; i < numValues; i++) {
6271 if ((config->values[i] < mGain.min_value) ||
6272 (config->values[i] > mGain.max_value)) {
6273 return BAD_VALUE;
6274 }
6275 }
6276 }
6277 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6278 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6279 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6280 return BAD_VALUE;
6281 }
6282 }
6283 return NO_ERROR;
6284}
6285
Eric Laurent1afeecb2014-05-14 08:52:28 -07006286void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6287{
6288 const size_t SIZE = 256;
6289 char buffer[SIZE];
6290 String8 result;
6291
6292 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6293 result.append(buffer);
6294 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6295 result.append(buffer);
6296 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6297 result.append(buffer);
6298 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6299 result.append(buffer);
6300 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6301 result.append(buffer);
6302 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6303 result.append(buffer);
6304 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6305 result.append(buffer);
6306 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6307 result.append(buffer);
6308 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6309 result.append(buffer);
6310
6311 write(fd, result.string(), result.size());
6312}
6313
Eric Laurent1f2f2232014-06-02 12:01:23 -07006314// --- AudioPortConfig class implementation
6315
6316AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6317{
6318 mSamplingRate = 0;
6319 mChannelMask = AUDIO_CHANNEL_NONE;
6320 mFormat = AUDIO_FORMAT_INVALID;
6321 mGain.index = -1;
6322}
6323
Eric Laurenta121f902014-06-03 13:32:54 -07006324status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6325 const struct audio_port_config *config,
6326 struct audio_port_config *backupConfig)
6327{
6328 struct audio_port_config localBackupConfig;
6329 status_t status = NO_ERROR;
6330
6331 localBackupConfig.config_mask = config->config_mask;
6332 toAudioPortConfig(&localBackupConfig);
6333
Marco Nelissen961ec212014-08-25 15:58:39 -07006334 sp<AudioPort> audioport = getAudioPort();
6335 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006336 status = NO_INIT;
6337 goto exit;
6338 }
6339 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006340 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006341 if (status != NO_ERROR) {
6342 goto exit;
6343 }
6344 mSamplingRate = config->sample_rate;
6345 }
6346 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006347 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006348 if (status != NO_ERROR) {
6349 goto exit;
6350 }
6351 mChannelMask = config->channel_mask;
6352 }
6353 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006354 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006355 if (status != NO_ERROR) {
6356 goto exit;
6357 }
6358 mFormat = config->format;
6359 }
6360 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006361 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006362 if (status != NO_ERROR) {
6363 goto exit;
6364 }
6365 mGain = config->gain;
6366 }
6367
6368exit:
6369 if (status != NO_ERROR) {
6370 applyAudioPortConfig(&localBackupConfig);
6371 }
6372 if (backupConfig != NULL) {
6373 *backupConfig = localBackupConfig;
6374 }
6375 return status;
6376}
6377
Eric Laurent1f2f2232014-06-02 12:01:23 -07006378void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6379 struct audio_port_config *dstConfig,
6380 const struct audio_port_config *srcConfig) const
6381{
6382 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6383 dstConfig->sample_rate = mSamplingRate;
6384 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6385 dstConfig->sample_rate = srcConfig->sample_rate;
6386 }
6387 } else {
6388 dstConfig->sample_rate = 0;
6389 }
6390 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6391 dstConfig->channel_mask = mChannelMask;
6392 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6393 dstConfig->channel_mask = srcConfig->channel_mask;
6394 }
6395 } else {
6396 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6397 }
6398 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6399 dstConfig->format = mFormat;
6400 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6401 dstConfig->format = srcConfig->format;
6402 }
6403 } else {
6404 dstConfig->format = AUDIO_FORMAT_INVALID;
6405 }
6406 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6407 dstConfig->gain = mGain;
6408 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6409 dstConfig->gain = srcConfig->gain;
6410 }
6411 } else {
6412 dstConfig->gain.index = -1;
6413 }
6414 if (dstConfig->gain.index != -1) {
6415 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6416 } else {
6417 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6418 }
6419}
6420
Eric Laurent1c333e22014-05-20 10:48:17 -07006421// --- IOProfile class implementation
6422
Eric Laurent1afeecb2014-05-14 08:52:28 -07006423AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006424 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006425 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006426{
6427}
6428
Eric Laurente0720872014-03-11 09:30:41 -07006429AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006430{
6431}
6432
6433// checks if the IO profile is compatible with specified parameters.
6434// Sampling rate, format and channel mask must be specified in order to
6435// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006436bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006437 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006438 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006439 audio_format_t format,
6440 audio_channel_mask_t channelMask,
6441 audio_output_flags_t flags) const
6442{
Glenn Kastencbd48022014-07-24 13:46:44 -07006443 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6444 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6445 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006446
Glenn Kastencbd48022014-07-24 13:46:44 -07006447 if ((mSupportedDevices.types() & device) != device) {
6448 return false;
6449 }
6450
6451 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006452 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006453 }
6454 uint32_t myUpdatedSamplingRate = samplingRate;
6455 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006456 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006457 }
6458 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6459 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006460 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006461 }
6462
6463 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6464 return false;
6465 }
6466
6467 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6468 checkExactChannelMask(channelMask) != NO_ERROR)) {
6469 return false;
6470 }
6471 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6472 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6473 return false;
6474 }
6475
6476 if (isPlaybackThread && (mFlags & flags) != flags) {
6477 return false;
6478 }
6479 // The only input flag that is allowed to be different is the fast flag.
6480 // An existing fast stream is compatible with a normal track request.
6481 // An existing normal stream is compatible with a fast track request,
6482 // but the fast request will be denied by AudioFlinger and converted to normal track.
6483 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6484 ~AUDIO_INPUT_FLAG_FAST)) {
6485 return false;
6486 }
6487
6488 if (updatedSamplingRate != NULL) {
6489 *updatedSamplingRate = myUpdatedSamplingRate;
6490 }
6491 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006492}
6493
Eric Laurente0720872014-03-11 09:30:41 -07006494void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006495{
6496 const size_t SIZE = 256;
6497 char buffer[SIZE];
6498 String8 result;
6499
Eric Laurent1afeecb2014-05-14 08:52:28 -07006500 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006501
Eric Laurente552edb2014-03-10 17:42:56 -07006502 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6503 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006504 snprintf(buffer, SIZE, " - devices:\n");
6505 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006506 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006507 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6508 mSupportedDevices[i]->dump(fd, 6, i);
6509 }
Eric Laurente552edb2014-03-10 17:42:56 -07006510}
6511
Eric Laurentd4692962014-05-05 18:13:44 -07006512void AudioPolicyManager::IOProfile::log()
6513{
6514 const size_t SIZE = 256;
6515 char buffer[SIZE];
6516 String8 result;
6517
6518 ALOGV(" - sampling rates: ");
6519 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6520 ALOGV(" %d", mSamplingRates[i]);
6521 }
6522
6523 ALOGV(" - channel masks: ");
6524 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6525 ALOGV(" 0x%04x", mChannelMasks[i]);
6526 }
6527
6528 ALOGV(" - formats: ");
6529 for (size_t i = 0; i < mFormats.size(); i++) {
6530 ALOGV(" 0x%08x", mFormats[i]);
6531 }
6532
6533 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6534 ALOGV(" - flags: 0x%04x\n", mFlags);
6535}
6536
6537
Eric Laurent3a4311c2014-03-17 12:00:47 -07006538// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006539
Eric Laurent1f2f2232014-06-02 12:01:23 -07006540
6541AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6542 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6543 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6544 AUDIO_PORT_ROLE_SOURCE,
6545 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006546 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006547{
Eric Laurenta121f902014-06-03 13:32:54 -07006548 if (mGains.size() > 0) {
6549 mGains[0]->getDefaultConfig(&mGain);
6550 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006551}
6552
Eric Laurent3a4311c2014-03-17 12:00:47 -07006553bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006554{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006555 // Devices are considered equal if they:
6556 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6557 // - have the same address or one device does not specify the address
6558 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006559 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006560 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006561 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006562 mChannelMask == other->mChannelMask);
6563}
6564
6565void AudioPolicyManager::DeviceVector::refreshTypes()
6566{
Eric Laurent1c333e22014-05-20 10:48:17 -07006567 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006568 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006569 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006570 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006571 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006572}
6573
6574ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6575{
6576 for(size_t i = 0; i < size(); i++) {
6577 if (item->equals(itemAt(i))) {
6578 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006579 }
6580 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006581 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006582}
6583
Eric Laurent3a4311c2014-03-17 12:00:47 -07006584ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006585{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006586 ssize_t ret = indexOf(item);
6587
6588 if (ret < 0) {
6589 ret = SortedVector::add(item);
6590 if (ret >= 0) {
6591 refreshTypes();
6592 }
6593 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006594 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006595 ret = -1;
6596 }
6597 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006598}
6599
Eric Laurent3a4311c2014-03-17 12:00:47 -07006600ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6601{
6602 size_t i;
6603 ssize_t ret = indexOf(item);
6604
6605 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006606 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006607 } else {
6608 ret = SortedVector::removeAt(ret);
6609 if (ret >= 0) {
6610 refreshTypes();
6611 }
6612 }
6613 return ret;
6614}
6615
6616void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6617{
6618 DeviceVector deviceList;
6619
6620 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6621 types &= ~role_bit;
6622
6623 while (types) {
6624 uint32_t i = 31 - __builtin_clz(types);
6625 uint32_t type = 1 << i;
6626 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006627 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006628 }
6629}
6630
Eric Laurent1afeecb2014-05-14 08:52:28 -07006631void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6632 const DeviceVector& declaredDevices)
6633{
6634 char *devName = strtok(name, "|");
6635 while (devName != NULL) {
6636 if (strlen(devName) != 0) {
6637 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6638 ARRAY_SIZE(sDeviceNameToEnumTable),
6639 devName);
6640 if (type != AUDIO_DEVICE_NONE) {
6641 add(new DeviceDescriptor(String8(""), type));
6642 } else {
6643 sp<DeviceDescriptor> deviceDesc =
6644 declaredDevices.getDeviceFromName(String8(devName));
6645 if (deviceDesc != 0) {
6646 add(deviceDesc);
6647 }
6648 }
6649 }
6650 devName = strtok(NULL, "|");
6651 }
6652}
6653
Eric Laurent1c333e22014-05-20 10:48:17 -07006654sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6655 audio_devices_t type, String8 address) const
6656{
6657 sp<DeviceDescriptor> device;
6658 for (size_t i = 0; i < size(); i++) {
6659 if (itemAt(i)->mDeviceType == type) {
6660 device = itemAt(i);
6661 if (itemAt(i)->mAddress = address) {
6662 break;
6663 }
6664 }
6665 }
6666 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6667 type, address.string(), device.get());
6668 return device;
6669}
6670
Eric Laurent6a94d692014-05-20 11:18:06 -07006671sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6672 audio_port_handle_t id) const
6673{
6674 sp<DeviceDescriptor> device;
6675 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006676 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006677 if (itemAt(i)->mId == id) {
6678 device = itemAt(i);
6679 break;
6680 }
6681 }
6682 return device;
6683}
6684
Eric Laurent1c333e22014-05-20 10:48:17 -07006685AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6686 audio_devices_t type) const
6687{
6688 DeviceVector devices;
6689 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6690 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6691 devices.add(itemAt(i));
6692 type &= ~itemAt(i)->mDeviceType;
6693 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6694 itemAt(i)->mDeviceType, itemAt(i).get());
6695 }
6696 }
6697 return devices;
6698}
6699
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006700AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6701 audio_devices_t type, String8 address) const
6702{
6703 DeviceVector devices;
6704 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6705 for (size_t i = 0; i < size(); i++) {
6706 //ALOGV(" at i=%d: device=%x, addr=%s",
6707 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6708 if (itemAt(i)->mDeviceType == type) {
6709 if (itemAt(i)->mAddress == address) {
6710 //ALOGV(" found matching address %s", address.string());
6711 devices.add(itemAt(i));
6712 }
6713 }
6714 }
6715 return devices;
6716}
6717
Eric Laurent1afeecb2014-05-14 08:52:28 -07006718sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6719 const String8& name) const
6720{
6721 sp<DeviceDescriptor> device;
6722 for (size_t i = 0; i < size(); i++) {
6723 if (itemAt(i)->mName == name) {
6724 device = itemAt(i);
6725 break;
6726 }
6727 }
6728 return device;
6729}
6730
Eric Laurent6a94d692014-05-20 11:18:06 -07006731void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6732 struct audio_port_config *dstConfig,
6733 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006734{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006735 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6736 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006737 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006738 }
6739
6740 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6741
Eric Laurent6a94d692014-05-20 11:18:06 -07006742 dstConfig->id = mId;
6743 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006744 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006745 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006746 dstConfig->ext.device.type = mDeviceType;
6747 dstConfig->ext.device.hw_module = mModule->mHandle;
6748 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006749}
6750
6751void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6752{
Eric Laurent83b88082014-06-20 18:31:16 -07006753 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006754 AudioPort::toAudioPort(port);
6755 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006756 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006757 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006758 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006759 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6760}
6761
Eric Laurent1afeecb2014-05-14 08:52:28 -07006762status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006763{
6764 const size_t SIZE = 256;
6765 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006766 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006767
Eric Laurent1afeecb2014-05-14 08:52:28 -07006768 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6769 result.append(buffer);
6770 if (mId != 0) {
6771 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6772 result.append(buffer);
6773 }
6774 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6775 enumToString(sDeviceNameToEnumTable,
6776 ARRAY_SIZE(sDeviceNameToEnumTable),
6777 mDeviceType));
6778 result.append(buffer);
6779 if (mAddress.size() != 0) {
6780 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6781 result.append(buffer);
6782 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006783 write(fd, result.string(), result.size());
6784 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006785
6786 return NO_ERROR;
6787}
6788
Eric Laurent4d416952014-08-10 14:07:09 -07006789status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6790{
6791 const size_t SIZE = 256;
6792 char buffer[SIZE];
6793 String8 result;
6794
6795
6796 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6797 result.append(buffer);
6798 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6799 result.append(buffer);
6800 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6801 result.append(buffer);
6802 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6803 result.append(buffer);
6804 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6805 result.append(buffer);
6806 for (size_t i = 0; i < mPatch.num_sources; i++) {
6807 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6808 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6809 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6810 ARRAY_SIZE(sDeviceNameToEnumTable),
6811 mPatch.sources[i].ext.device.type));
6812 } else {
6813 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6814 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6815 }
6816 result.append(buffer);
6817 }
6818 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6819 result.append(buffer);
6820 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6821 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6822 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6823 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6824 ARRAY_SIZE(sDeviceNameToEnumTable),
6825 mPatch.sinks[i].ext.device.type));
6826 } else {
6827 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6828 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6829 }
6830 result.append(buffer);
6831 }
6832
6833 write(fd, result.string(), result.size());
6834 return NO_ERROR;
6835}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006836
6837// --- audio_policy.conf file parsing
6838
Eric Laurente0720872014-03-11 09:30:41 -07006839audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006840{
6841 uint32_t flag = 0;
6842
6843 // it is OK to cast name to non const here as we are not going to use it after
6844 // strtok() modifies it
6845 char *flagName = strtok(name, "|");
6846 while (flagName != NULL) {
6847 if (strlen(flagName) != 0) {
6848 flag |= stringToEnum(sFlagNameToEnumTable,
6849 ARRAY_SIZE(sFlagNameToEnumTable),
6850 flagName);
6851 }
6852 flagName = strtok(NULL, "|");
6853 }
6854 //force direct flag if offload flag is set: offloading implies a direct output stream
6855 // and all common behaviors are driven by checking only the direct flag
6856 // this should normally be set appropriately in the policy configuration file
6857 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6858 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6859 }
6860
6861 return (audio_output_flags_t)flag;
6862}
6863
Eric Laurente0720872014-03-11 09:30:41 -07006864audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006865{
6866 uint32_t device = 0;
6867
6868 char *devName = strtok(name, "|");
6869 while (devName != NULL) {
6870 if (strlen(devName) != 0) {
6871 device |= stringToEnum(sDeviceNameToEnumTable,
6872 ARRAY_SIZE(sDeviceNameToEnumTable),
6873 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006874 }
Eric Laurente552edb2014-03-10 17:42:56 -07006875 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006876 }
Eric Laurente552edb2014-03-10 17:42:56 -07006877 return device;
6878}
6879
Eric Laurente0720872014-03-11 09:30:41 -07006880void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006881{
Eric Laurente552edb2014-03-10 17:42:56 -07006882 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006883 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006884 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006885
Eric Laurent1afeecb2014-05-14 08:52:28 -07006886 node = config_find(root, DEVICES_TAG);
6887 if (node != NULL) {
6888 node = node->first_child;
6889 while (node) {
6890 ALOGV("loadHwModule() loading device %s", node->name);
6891 status_t tmpStatus = module->loadDevice(node);
6892 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6893 status = tmpStatus;
6894 }
6895 node = node->next;
6896 }
6897 }
6898 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006899 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006900 node = node->first_child;
6901 while (node) {
6902 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006903 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006904 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6905 status = tmpStatus;
6906 }
6907 node = node->next;
6908 }
6909 }
6910 node = config_find(root, INPUTS_TAG);
6911 if (node != NULL) {
6912 node = node->first_child;
6913 while (node) {
6914 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006915 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006916 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6917 status = tmpStatus;
6918 }
6919 node = node->next;
6920 }
6921 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006922 loadGlobalConfig(root, module);
6923
Eric Laurente552edb2014-03-10 17:42:56 -07006924 if (status == NO_ERROR) {
6925 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006926 }
6927}
6928
Eric Laurente0720872014-03-11 09:30:41 -07006929void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006930{
6931 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6932 if (node == NULL) {
6933 return;
6934 }
6935
6936 node = node->first_child;
6937 while (node) {
6938 ALOGV("loadHwModules() loading module %s", node->name);
6939 loadHwModule(node);
6940 node = node->next;
6941 }
6942}
6943
Eric Laurent1f2f2232014-06-02 12:01:23 -07006944void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006945{
6946 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006947
Eric Laurente552edb2014-03-10 17:42:56 -07006948 if (node == NULL) {
6949 return;
6950 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006951 DeviceVector declaredDevices;
6952 if (module != NULL) {
6953 declaredDevices = module->mDeclaredDevices;
6954 }
6955
Eric Laurente552edb2014-03-10 17:42:56 -07006956 node = node->first_child;
6957 while (node) {
6958 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006959 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6960 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006961 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6962 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006963 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006964 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006965 ARRAY_SIZE(sDeviceNameToEnumTable),
6966 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006967 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006968 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006969 } else {
6970 ALOGW("loadGlobalConfig() default device not specified");
6971 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006972 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006973 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006974 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6975 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006976 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006977 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6978 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6979 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006980 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6981 uint32_t major, minor;
6982 sscanf((char *)node->value, "%u.%u", &major, &minor);
6983 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6984 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6985 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006986 }
6987 node = node->next;
6988 }
6989}
6990
Eric Laurente0720872014-03-11 09:30:41 -07006991status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006992{
6993 cnode *root;
6994 char *data;
6995
6996 data = (char *)load_file(path, NULL);
6997 if (data == NULL) {
6998 return -ENODEV;
6999 }
7000 root = config_node("", "");
7001 config_load(root, data);
7002
Eric Laurente552edb2014-03-10 17:42:56 -07007003 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007004 // legacy audio_policy.conf files have one global_configuration section
7005 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007006 config_free(root);
7007 free(root);
7008 free(data);
7009
7010 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7011
7012 return NO_ERROR;
7013}
7014
Eric Laurente0720872014-03-11 09:30:41 -07007015void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007016{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007017 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007018 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007019 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7020 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007021 mAvailableOutputDevices.add(mDefaultOutputDevice);
7022 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007023
7024 module = new HwModule("primary");
7025
Eric Laurent1afeecb2014-05-14 08:52:28 -07007026 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007027 profile->mSamplingRates.add(44100);
7028 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7029 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007030 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007031 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7032 module->mOutputProfiles.add(profile);
7033
Eric Laurent1afeecb2014-05-14 08:52:28 -07007034 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007035 profile->mSamplingRates.add(8000);
7036 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7037 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007038 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007039 module->mInputProfiles.add(profile);
7040
7041 mHwModules.add(module);
7042}
7043
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007044audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7045{
7046 // flags to stream type mapping
7047 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7048 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7049 }
7050 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7051 return AUDIO_STREAM_BLUETOOTH_SCO;
7052 }
7053
7054 // usage to stream type mapping
7055 switch (attr->usage) {
7056 case AUDIO_USAGE_MEDIA:
7057 case AUDIO_USAGE_GAME:
7058 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7059 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7060 return AUDIO_STREAM_MUSIC;
7061 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7062 return AUDIO_STREAM_SYSTEM;
7063 case AUDIO_USAGE_VOICE_COMMUNICATION:
7064 return AUDIO_STREAM_VOICE_CALL;
7065
7066 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7067 return AUDIO_STREAM_DTMF;
7068
7069 case AUDIO_USAGE_ALARM:
7070 return AUDIO_STREAM_ALARM;
7071 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7072 return AUDIO_STREAM_RING;
7073
7074 case AUDIO_USAGE_NOTIFICATION:
7075 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7076 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7077 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7078 case AUDIO_USAGE_NOTIFICATION_EVENT:
7079 return AUDIO_STREAM_NOTIFICATION;
7080
7081 case AUDIO_USAGE_UNKNOWN:
7082 default:
7083 return AUDIO_STREAM_MUSIC;
7084 }
7085}
Eric Laurente552edb2014-03-10 17:42:56 -07007086}; // namespace android