blob: f65e13664284e646637d42c100cec63773cbe76c [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 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004320
4321 // inform all input as well
4322 for (size_t i = 0; i < mInputs.size(); i++) {
4323 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4324 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4325 AudioParameter inputCmd = AudioParameter();
4326 ALOGV("%s: inform input %d of device:%d", __func__,
4327 inputDescriptor->mIoHandle, device);
4328 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4329 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4330 inputCmd.toString(),
4331 delayMs);
4332 }
4333 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004334 }
Eric Laurente552edb2014-03-10 17:42:56 -07004335
4336 // update stream volumes according to new device
4337 applyStreamVolumes(output, device, delayMs);
4338
4339 return muteWaitMs;
4340}
4341
Eric Laurent1c333e22014-05-20 10:48:17 -07004342status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004343 int delayMs,
4344 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004345{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004346 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004347 ssize_t index;
4348 if (patchHandle) {
4349 index = mAudioPatches.indexOfKey(*patchHandle);
4350 } else {
4351 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4352 }
4353 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004354 return INVALID_OPERATION;
4355 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004356 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4357 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004358 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4359 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004360 removeAudioPatch(patchDesc->mHandle);
4361 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004362 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004363 return status;
4364}
4365
4366status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4367 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004368 bool force,
4369 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004370{
4371 status_t status = NO_ERROR;
4372
Eric Laurent1f2f2232014-06-02 12:01:23 -07004373 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004374 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4375 inputDesc->mDevice = device;
4376
4377 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4378 if (!deviceList.isEmpty()) {
4379 struct audio_patch patch;
4380 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004381 // AUDIO_SOURCE_HOTWORD is for internal use only:
4382 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004383 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4384 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004385 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4386 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004387 patch.num_sinks = 1;
4388 //only one input device for now
4389 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004390 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004391 ssize_t index;
4392 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4393 index = mAudioPatches.indexOfKey(*patchHandle);
4394 } else {
4395 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4396 }
4397 sp< AudioPatch> patchDesc;
4398 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4399 if (index >= 0) {
4400 patchDesc = mAudioPatches.valueAt(index);
4401 afPatchHandle = patchDesc->mAfPatchHandle;
4402 }
4403
Eric Laurent1c333e22014-05-20 10:48:17 -07004404 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004406 0);
4407 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004408 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004409 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004410 if (index < 0) {
4411 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4412 &patch, mUidCached);
4413 addAudioPatch(patchDesc->mHandle, patchDesc);
4414 } else {
4415 patchDesc->mPatch = patch;
4416 }
4417 patchDesc->mAfPatchHandle = afPatchHandle;
4418 patchDesc->mUid = mUidCached;
4419 if (patchHandle) {
4420 *patchHandle = patchDesc->mHandle;
4421 }
4422 inputDesc->mPatchHandle = patchDesc->mHandle;
4423 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004424 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004425 }
4426 }
4427 }
4428 return status;
4429}
4430
Eric Laurent6a94d692014-05-20 11:18:06 -07004431status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4432 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004433{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004434 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 ssize_t index;
4436 if (patchHandle) {
4437 index = mAudioPatches.indexOfKey(*patchHandle);
4438 } else {
4439 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4440 }
4441 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004442 return INVALID_OPERATION;
4443 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4445 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004446 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4447 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004448 removeAudioPatch(patchDesc->mHandle);
4449 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004450 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004451 return status;
4452}
4453
4454sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004455 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004456 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004457 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004458 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004459{
4460 // Choose an input profile based on the requested capture parameters: select the first available
4461 // profile supporting all requested parameters.
4462
4463 for (size_t i = 0; i < mHwModules.size(); i++)
4464 {
4465 if (mHwModules[i]->mHandle == 0) {
4466 continue;
4467 }
4468 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4469 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004470 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004471 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004472 if (profile->isCompatibleProfile(device, samplingRate,
4473 &samplingRate /*updatedSamplingRate*/,
4474 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004475 return profile;
4476 }
4477 }
4478 }
4479 return NULL;
4480}
4481
Eric Laurente0720872014-03-11 09:30:41 -07004482audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004483{
4484 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004485 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4486 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004487 switch (inputSource) {
4488 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004489 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004490 device = AUDIO_DEVICE_IN_VOICE_CALL;
4491 break;
4492 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004493 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004494
4495 case AUDIO_SOURCE_DEFAULT:
4496 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004497 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4498 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004499 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4500 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4501 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4502 device = AUDIO_DEVICE_IN_USB_DEVICE;
4503 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4504 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004505 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004506 break;
4507
4508 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4509 // Allow only use of devices on primary input if in call and HAL does not support routing
4510 // to voice call path.
4511 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4512 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4513 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4514 }
4515
4516 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4517 case AUDIO_POLICY_FORCE_BT_SCO:
4518 // if SCO device is requested but no SCO device is available, fall back to default case
4519 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4520 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4521 break;
4522 }
4523 // FALL THROUGH
4524
4525 default: // FORCE_NONE
4526 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4527 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4528 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4529 device = AUDIO_DEVICE_IN_USB_DEVICE;
4530 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4531 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4532 }
4533 break;
4534
4535 case AUDIO_POLICY_FORCE_SPEAKER:
4536 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4537 device = AUDIO_DEVICE_IN_BACK_MIC;
4538 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4539 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4540 }
4541 break;
4542 }
4543 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004544
Eric Laurente552edb2014-03-10 17:42:56 -07004545 case AUDIO_SOURCE_VOICE_RECOGNITION:
4546 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004547 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004548 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004549 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004550 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004551 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004552 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4553 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004554 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004555 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4556 }
4557 break;
4558 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004559 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004560 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004561 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004562 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4563 }
4564 break;
4565 case AUDIO_SOURCE_VOICE_DOWNLINK:
4566 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004567 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004568 device = AUDIO_DEVICE_IN_VOICE_CALL;
4569 }
4570 break;
4571 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004573 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4574 }
4575 break;
4576 default:
4577 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4578 break;
4579 }
4580 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4581 return device;
4582}
4583
Eric Laurente0720872014-03-11 09:30:41 -07004584bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004585{
4586 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4587 device &= ~AUDIO_DEVICE_BIT_IN;
4588 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4589 return true;
4590 }
4591 return false;
4592}
4593
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004594bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4595 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4596}
4597
Eric Laurente0720872014-03-11 09:30:41 -07004598audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004599{
4600 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004601 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004602 if ((input_descriptor->mRefCount > 0)
4603 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4604 return mInputs.keyAt(i);
4605 }
4606 }
4607 return 0;
4608}
4609
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004610uint32_t AudioPolicyManager::activeInputsCount() const
4611{
4612 uint32_t count = 0;
4613 for (size_t i = 0; i < mInputs.size(); i++) {
4614 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4615 if (desc->mRefCount > 0) {
4616 return count++;
4617 }
4618 }
4619 return count;
4620}
4621
Eric Laurente552edb2014-03-10 17:42:56 -07004622
Eric Laurente0720872014-03-11 09:30:41 -07004623audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004624{
4625 if (device == AUDIO_DEVICE_NONE) {
4626 // this happens when forcing a route update and no track is active on an output.
4627 // In this case the returned category is not important.
4628 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004629 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004630 // Multiple device selection is either:
4631 // - speaker + one other device: give priority to speaker in this case.
4632 // - one A2DP device + another device: happens with duplicated output. In this case
4633 // retain the device on the A2DP output as the other must not correspond to an active
4634 // selection if not the speaker.
4635 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4636 device = AUDIO_DEVICE_OUT_SPEAKER;
4637 } else {
4638 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4639 }
4640 }
4641
Eric Laurent3b73df72014-03-11 09:06:29 -07004642 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004643 "getDeviceForVolume() invalid device combination: %08x",
4644 device);
4645
4646 return device;
4647}
4648
Eric Laurente0720872014-03-11 09:30:41 -07004649AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004650{
4651 switch(getDeviceForVolume(device)) {
4652 case AUDIO_DEVICE_OUT_EARPIECE:
4653 return DEVICE_CATEGORY_EARPIECE;
4654 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4655 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4656 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4657 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4658 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4659 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4660 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004661 case AUDIO_DEVICE_OUT_LINE:
4662 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4663 /*USB? Remote submix?*/
4664 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004665 case AUDIO_DEVICE_OUT_SPEAKER:
4666 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4667 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004668 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4669 case AUDIO_DEVICE_OUT_USB_DEVICE:
4670 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4671 default:
4672 return DEVICE_CATEGORY_SPEAKER;
4673 }
4674}
4675
Eric Laurente0720872014-03-11 09:30:41 -07004676float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004677 int indexInUi)
4678{
4679 device_category deviceCategory = getDeviceCategory(device);
4680 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4681
4682 // the volume index in the UI is relative to the min and max volume indices for this stream type
4683 int nbSteps = 1 + curve[VOLMAX].mIndex -
4684 curve[VOLMIN].mIndex;
4685 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4686 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4687
4688 // find what part of the curve this index volume belongs to, or if it's out of bounds
4689 int segment = 0;
4690 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4691 return 0.0f;
4692 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4693 segment = 0;
4694 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4695 segment = 1;
4696 } else if (volIdx <= curve[VOLMAX].mIndex) {
4697 segment = 2;
4698 } else { // out of bounds
4699 return 1.0f;
4700 }
4701
4702 // linear interpolation in the attenuation table in dB
4703 float decibels = curve[segment].mDBAttenuation +
4704 ((float)(volIdx - curve[segment].mIndex)) *
4705 ( (curve[segment+1].mDBAttenuation -
4706 curve[segment].mDBAttenuation) /
4707 ((float)(curve[segment+1].mIndex -
4708 curve[segment].mIndex)) );
4709
4710 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4711
4712 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4713 curve[segment].mIndex, volIdx,
4714 curve[segment+1].mIndex,
4715 curve[segment].mDBAttenuation,
4716 decibels,
4717 curve[segment+1].mDBAttenuation,
4718 amplification);
4719
4720 return amplification;
4721}
4722
Eric Laurente0720872014-03-11 09:30:41 -07004723const AudioPolicyManager::VolumeCurvePoint
4724 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004725 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4726};
4727
Eric Laurente0720872014-03-11 09:30:41 -07004728const AudioPolicyManager::VolumeCurvePoint
4729 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004730 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4731};
4732
Eric Laurente0720872014-03-11 09:30:41 -07004733const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004734 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4735 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4736};
4737
4738const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004739 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004740 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4741};
4742
Eric Laurente0720872014-03-11 09:30:41 -07004743const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004744 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004745 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004746};
4747
4748const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004749 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004750 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4751};
4752
Eric Laurente0720872014-03-11 09:30:41 -07004753const AudioPolicyManager::VolumeCurvePoint
4754 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004755 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4756};
4757
4758// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4759// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4760// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4761// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4762
Eric Laurente0720872014-03-11 09:30:41 -07004763const AudioPolicyManager::VolumeCurvePoint
4764 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004765 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4766};
4767
Eric Laurente0720872014-03-11 09:30:41 -07004768const AudioPolicyManager::VolumeCurvePoint
4769 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004770 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4771};
4772
Eric Laurente0720872014-03-11 09:30:41 -07004773const AudioPolicyManager::VolumeCurvePoint
4774 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004775 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4776};
4777
Eric Laurente0720872014-03-11 09:30:41 -07004778const AudioPolicyManager::VolumeCurvePoint
4779 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004780 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4781};
4782
Eric Laurente0720872014-03-11 09:30:41 -07004783const AudioPolicyManager::VolumeCurvePoint
4784 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004785 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4786};
4787
Eric Laurente0720872014-03-11 09:30:41 -07004788const AudioPolicyManager::VolumeCurvePoint
4789 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4790 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004791 { // AUDIO_STREAM_VOICE_CALL
4792 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4793 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004794 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4795 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004796 },
4797 { // AUDIO_STREAM_SYSTEM
4798 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4799 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004800 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4801 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004802 },
4803 { // AUDIO_STREAM_RING
4804 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4805 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004806 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4807 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004808 },
4809 { // AUDIO_STREAM_MUSIC
4810 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4811 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004812 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4813 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004814 },
4815 { // AUDIO_STREAM_ALARM
4816 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4817 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004818 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4819 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004820 },
4821 { // AUDIO_STREAM_NOTIFICATION
4822 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4823 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004824 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4825 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004826 },
4827 { // AUDIO_STREAM_BLUETOOTH_SCO
4828 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4829 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004830 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4831 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004832 },
4833 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4834 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4835 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004836 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4837 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004838 },
4839 { // AUDIO_STREAM_DTMF
4840 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4841 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004842 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4843 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004844 },
4845 { // AUDIO_STREAM_TTS
4846 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4847 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004848 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4849 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004850 },
4851};
4852
Eric Laurente0720872014-03-11 09:30:41 -07004853void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004854{
4855 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4856 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4857 mStreams[i].mVolumeCurve[j] =
4858 sVolumeProfiles[i][j];
4859 }
4860 }
4861
4862 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4863 if (mSpeakerDrcEnabled) {
4864 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4865 sDefaultSystemVolumeCurveDrc;
4866 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4867 sSpeakerSonificationVolumeCurveDrc;
4868 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4869 sSpeakerSonificationVolumeCurveDrc;
4870 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4871 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004872 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4873 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004874 }
4875}
4876
Eric Laurente0720872014-03-11 09:30:41 -07004877float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004878 int index,
4879 audio_io_handle_t output,
4880 audio_devices_t device)
4881{
4882 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004883 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004884 StreamDescriptor &streamDesc = mStreams[stream];
4885
4886 if (device == AUDIO_DEVICE_NONE) {
4887 device = outputDesc->device();
4888 }
4889
Eric Laurente552edb2014-03-10 17:42:56 -07004890 volume = volIndexToAmpl(device, streamDesc, index);
4891
4892 // if a headset is connected, apply the following rules to ring tones and notifications
4893 // to avoid sound level bursts in user's ears:
4894 // - always attenuate ring tones and notifications volume by 6dB
4895 // - if music is playing, always limit the volume to current music volume,
4896 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004897 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004898 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4899 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4900 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4901 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4902 ((stream_strategy == STRATEGY_SONIFICATION)
4903 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004904 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004905 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004906 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004907 streamDesc.mCanBeMuted) {
4908 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4909 // when the phone is ringing we must consider that music could have been paused just before
4910 // by the music application and behave as if music was active if the last music track was
4911 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004912 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004913 mLimitRingtoneVolume) {
4914 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004915 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4916 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004917 output,
4918 musicDevice);
4919 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4920 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4921 if (volume > minVol) {
4922 volume = minVol;
4923 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4924 }
4925 }
4926 }
4927
4928 return volume;
4929}
4930
Eric Laurente0720872014-03-11 09:30:41 -07004931status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004932 int index,
4933 audio_io_handle_t output,
4934 audio_devices_t device,
4935 int delayMs,
4936 bool force)
4937{
4938
4939 // do not change actual stream volume if the stream is muted
4940 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4941 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4942 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4943 return NO_ERROR;
4944 }
4945
4946 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004947 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4948 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4949 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4950 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004951 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004952 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004953 return INVALID_OPERATION;
4954 }
4955
4956 float volume = computeVolume(stream, index, output, device);
4957 // We actually change the volume if:
4958 // - the float value returned by computeVolume() changed
4959 // - the force flag is set
4960 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4961 force) {
4962 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4963 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4964 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4965 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004966 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4967 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004968 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004969 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004970 }
4971
Eric Laurent3b73df72014-03-11 09:06:29 -07004972 if (stream == AUDIO_STREAM_VOICE_CALL ||
4973 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004974 float voiceVolume;
4975 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004976 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004977 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4978 } else {
4979 voiceVolume = 1.0;
4980 }
4981
4982 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4983 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4984 mLastVoiceVolume = voiceVolume;
4985 }
4986 }
4987
4988 return NO_ERROR;
4989}
4990
Eric Laurente0720872014-03-11 09:30:41 -07004991void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004992 audio_devices_t device,
4993 int delayMs,
4994 bool force)
4995{
4996 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4997
Eric Laurent3b73df72014-03-11 09:06:29 -07004998 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4999 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005000 mStreams[stream].getVolumeIndex(device),
5001 output,
5002 device,
5003 delayMs,
5004 force);
5005 }
5006}
5007
Eric Laurente0720872014-03-11 09:30:41 -07005008void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
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 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005015 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5016 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5017 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005018 }
5019 }
5020}
5021
Eric Laurente0720872014-03-11 09:30:41 -07005022void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005023 bool on,
5024 audio_io_handle_t output,
5025 int delayMs,
5026 audio_devices_t device)
5027{
5028 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005029 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005030 if (device == AUDIO_DEVICE_NONE) {
5031 device = outputDesc->device();
5032 }
5033
5034 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5035 stream, on, output, outputDesc->mMuteCount[stream], device);
5036
5037 if (on) {
5038 if (outputDesc->mMuteCount[stream] == 0) {
5039 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005040 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5041 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005042 checkAndSetVolume(stream, 0, output, device, delayMs);
5043 }
5044 }
5045 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5046 outputDesc->mMuteCount[stream]++;
5047 } else {
5048 if (outputDesc->mMuteCount[stream] == 0) {
5049 ALOGV("setStreamMute() unmuting non muted stream!");
5050 return;
5051 }
5052 if (--outputDesc->mMuteCount[stream] == 0) {
5053 checkAndSetVolume(stream,
5054 streamDesc.getVolumeIndex(device),
5055 output,
5056 device,
5057 delayMs);
5058 }
5059 }
5060}
5061
Eric Laurente0720872014-03-11 09:30:41 -07005062void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005063 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005064{
5065 // if the stream pertains to sonification strategy and we are in call we must
5066 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5067 // in the device used for phone strategy and play the tone if the selected device does not
5068 // interfere with the device used for phone strategy
5069 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5070 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005071 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005072 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5073 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005074 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005075 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5076 stream, starting, outputDesc->mDevice, stateChange);
5077 if (outputDesc->mRefCount[stream]) {
5078 int muteCount = 1;
5079 if (stateChange) {
5080 muteCount = outputDesc->mRefCount[stream];
5081 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005082 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005083 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5084 for (int i = 0; i < muteCount; i++) {
5085 setStreamMute(stream, starting, mPrimaryOutput);
5086 }
5087 } else {
5088 ALOGV("handleIncallSonification() high visibility");
5089 if (outputDesc->device() &
5090 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5091 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5092 for (int i = 0; i < muteCount; i++) {
5093 setStreamMute(stream, starting, mPrimaryOutput);
5094 }
5095 }
5096 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005097 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5098 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005099 } else {
5100 mpClientInterface->stopTone();
5101 }
5102 }
5103 }
5104 }
5105}
5106
Eric Laurente0720872014-03-11 09:30:41 -07005107bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005108{
5109 return isStateInCall(mPhoneState);
5110}
5111
Eric Laurente0720872014-03-11 09:30:41 -07005112bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005113 return ((state == AUDIO_MODE_IN_CALL) ||
5114 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005115}
5116
Eric Laurente0720872014-03-11 09:30:41 -07005117uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005118{
5119 return MAX_EFFECTS_CPU_LOAD;
5120}
5121
Eric Laurente0720872014-03-11 09:30:41 -07005122uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005123{
5124 return MAX_EFFECTS_MEMORY;
5125}
5126
Eric Laurent6a94d692014-05-20 11:18:06 -07005127
Eric Laurente552edb2014-03-10 17:42:56 -07005128// --- AudioOutputDescriptor class implementation
5129
Eric Laurente0720872014-03-11 09:30:41 -07005130AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005131 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005132 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005133 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005134 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5135{
5136 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005137 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005138 mRefCount[i] = 0;
5139 mCurVolume[i] = -1.0;
5140 mMuteCount[i] = 0;
5141 mStopTime[i] = 0;
5142 }
5143 for (int i = 0; i < NUM_STRATEGIES; i++) {
5144 mStrategyMutedByDevice[i] = false;
5145 }
5146 if (profile != NULL) {
Eric Laurentd8622372014-07-27 13:47:31 -07005147 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005148 mSamplingRate = profile->pickSamplingRate();
5149 mFormat = profile->pickFormat();
5150 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005151 if (profile->mGains.size() > 0) {
5152 profile->mGains[0]->getDefaultConfig(&mGain);
5153 }
Eric Laurente552edb2014-03-10 17:42:56 -07005154 }
5155}
5156
Eric Laurente0720872014-03-11 09:30:41 -07005157audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005158{
5159 if (isDuplicated()) {
5160 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5161 } else {
5162 return mDevice;
5163 }
5164}
5165
Eric Laurente0720872014-03-11 09:30:41 -07005166uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005167{
5168 if (isDuplicated()) {
5169 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5170 } else {
5171 return mLatency;
5172 }
5173}
5174
Eric Laurente0720872014-03-11 09:30:41 -07005175bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005176 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005177{
5178 if (isDuplicated()) {
5179 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5180 } else if (outputDesc->isDuplicated()){
5181 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5182 } else {
5183 return (mProfile->mModule == outputDesc->mProfile->mModule);
5184 }
5185}
5186
Eric Laurente0720872014-03-11 09:30:41 -07005187void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005188 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005189{
5190 // forward usage count change to attached outputs
5191 if (isDuplicated()) {
5192 mOutput1->changeRefCount(stream, delta);
5193 mOutput2->changeRefCount(stream, delta);
5194 }
5195 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005196 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5197 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005198 mRefCount[stream] = 0;
5199 return;
5200 }
5201 mRefCount[stream] += delta;
5202 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5203}
5204
Eric Laurente0720872014-03-11 09:30:41 -07005205audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005206{
5207 if (isDuplicated()) {
5208 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5209 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005210 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005211 }
5212}
5213
Eric Laurente0720872014-03-11 09:30:41 -07005214bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005215{
5216 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5217}
5218
Eric Laurente0720872014-03-11 09:30:41 -07005219bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005220 uint32_t inPastMs,
5221 nsecs_t sysTime) const
5222{
5223 if ((sysTime == 0) && (inPastMs != 0)) {
5224 sysTime = systemTime();
5225 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005226 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5227 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005228 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005229 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005230 return true;
5231 }
5232 }
5233 return false;
5234}
5235
Eric Laurente0720872014-03-11 09:30:41 -07005236bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005237 uint32_t inPastMs,
5238 nsecs_t sysTime) const
5239{
5240 if (mRefCount[stream] != 0) {
5241 return true;
5242 }
5243 if (inPastMs == 0) {
5244 return false;
5245 }
5246 if (sysTime == 0) {
5247 sysTime = systemTime();
5248 }
5249 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5250 return true;
5251 }
5252 return false;
5253}
5254
Eric Laurent1c333e22014-05-20 10:48:17 -07005255void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005256 struct audio_port_config *dstConfig,
5257 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005258{
Eric Laurent84c70242014-06-23 08:46:27 -07005259 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5260
Eric Laurent1f2f2232014-06-02 12:01:23 -07005261 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5262 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5263 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005264 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005265 }
5266 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5267
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 dstConfig->id = mId;
5269 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5270 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5272 dstConfig->ext.mix.handle = mIoHandle;
5273 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005274}
5275
5276void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5277 struct audio_port *port) const
5278{
Eric Laurent84c70242014-06-23 08:46:27 -07005279 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005280 mProfile->toAudioPort(port);
5281 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 toAudioPortConfig(&port->active_config);
5283 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005284 port->ext.mix.handle = mIoHandle;
5285 port->ext.mix.latency_class =
5286 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5287}
Eric Laurente552edb2014-03-10 17:42:56 -07005288
Eric Laurente0720872014-03-11 09:30:41 -07005289status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005290{
5291 const size_t SIZE = 256;
5292 char buffer[SIZE];
5293 String8 result;
5294
Eric Laurent4d416952014-08-10 14:07:09 -07005295 snprintf(buffer, SIZE, " ID: %d\n", mId);
5296 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005297 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5298 result.append(buffer);
5299 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5300 result.append(buffer);
5301 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5302 result.append(buffer);
5303 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5304 result.append(buffer);
5305 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5306 result.append(buffer);
5307 snprintf(buffer, SIZE, " Devices %08x\n", device());
5308 result.append(buffer);
5309 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5310 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005311 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5312 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5313 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005314 result.append(buffer);
5315 }
5316 write(fd, result.string(), result.size());
5317
5318 return NO_ERROR;
5319}
5320
5321// --- AudioInputDescriptor class implementation
5322
Eric Laurent1c333e22014-05-20 10:48:17 -07005323AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005324 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005326 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005328 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005329 mSamplingRate = profile->pickSamplingRate();
5330 mFormat = profile->pickFormat();
5331 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005332 if (profile->mGains.size() > 0) {
5333 profile->mGains[0]->getDefaultConfig(&mGain);
5334 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005335 }
Eric Laurente552edb2014-03-10 17:42:56 -07005336}
5337
Eric Laurent1c333e22014-05-20 10:48:17 -07005338void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 struct audio_port_config *dstConfig,
5340 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005341{
Eric Laurent84c70242014-06-23 08:46:27 -07005342 ALOG_ASSERT(mProfile != 0,
5343 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005344 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5345 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5346 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005347 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005348 }
5349
5350 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5351
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 dstConfig->id = mId;
5353 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5354 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005355 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5356 dstConfig->ext.mix.handle = mIoHandle;
5357 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005358}
5359
5360void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5361 struct audio_port *port) const
5362{
Eric Laurent84c70242014-06-23 08:46:27 -07005363 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5364
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 mProfile->toAudioPort(port);
5366 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 toAudioPortConfig(&port->active_config);
5368 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005369 port->ext.mix.handle = mIoHandle;
5370 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5371}
5372
Eric Laurente0720872014-03-11 09:30:41 -07005373status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005374{
5375 const size_t SIZE = 256;
5376 char buffer[SIZE];
5377 String8 result;
5378
Eric Laurent4d416952014-08-10 14:07:09 -07005379 snprintf(buffer, SIZE, " ID: %d\n", mId);
5380 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005381 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5382 result.append(buffer);
5383 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5384 result.append(buffer);
5385 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5386 result.append(buffer);
5387 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5388 result.append(buffer);
5389 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5390 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005391 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5392 result.append(buffer);
5393
Eric Laurente552edb2014-03-10 17:42:56 -07005394 write(fd, result.string(), result.size());
5395
5396 return NO_ERROR;
5397}
5398
5399// --- StreamDescriptor class implementation
5400
Eric Laurente0720872014-03-11 09:30:41 -07005401AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005402 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5403{
5404 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5405}
5406
Eric Laurente0720872014-03-11 09:30:41 -07005407int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005408{
Eric Laurente0720872014-03-11 09:30:41 -07005409 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005410 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5411 if (mIndexCur.indexOfKey(device) < 0) {
5412 device = AUDIO_DEVICE_OUT_DEFAULT;
5413 }
5414 return mIndexCur.valueFor(device);
5415}
5416
Eric Laurente0720872014-03-11 09:30:41 -07005417void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005418{
5419 const size_t SIZE = 256;
5420 char buffer[SIZE];
5421 String8 result;
5422
5423 snprintf(buffer, SIZE, "%s %02d %02d ",
5424 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5425 result.append(buffer);
5426 for (size_t i = 0; i < mIndexCur.size(); i++) {
5427 snprintf(buffer, SIZE, "%04x : %02d, ",
5428 mIndexCur.keyAt(i),
5429 mIndexCur.valueAt(i));
5430 result.append(buffer);
5431 }
5432 result.append("\n");
5433
5434 write(fd, result.string(), result.size());
5435}
5436
5437// --- EffectDescriptor class implementation
5438
Eric Laurente0720872014-03-11 09:30:41 -07005439status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005440{
5441 const size_t SIZE = 256;
5442 char buffer[SIZE];
5443 String8 result;
5444
5445 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5446 result.append(buffer);
5447 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5448 result.append(buffer);
5449 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5450 result.append(buffer);
5451 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5452 result.append(buffer);
5453 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5454 result.append(buffer);
5455 write(fd, result.string(), result.size());
5456
5457 return NO_ERROR;
5458}
5459
Eric Laurent1c333e22014-05-20 10:48:17 -07005460// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005461
Eric Laurente0720872014-03-11 09:30:41 -07005462AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005463 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5464 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005465{
5466}
5467
Eric Laurente0720872014-03-11 09:30:41 -07005468AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005469{
5470 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005471 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005472 }
5473 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005474 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005475 }
5476 free((void *)mName);
5477}
5478
Eric Laurent1afeecb2014-05-14 08:52:28 -07005479status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5480{
5481 cnode *node = root->first_child;
5482
5483 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5484
5485 while (node) {
5486 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5487 profile->loadSamplingRates((char *)node->value);
5488 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5489 profile->loadFormats((char *)node->value);
5490 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5491 profile->loadInChannels((char *)node->value);
5492 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5493 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5494 mDeclaredDevices);
5495 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5496 profile->loadGains(node);
5497 }
5498 node = node->next;
5499 }
5500 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5501 "loadInput() invalid supported devices");
5502 ALOGW_IF(profile->mChannelMasks.size() == 0,
5503 "loadInput() invalid supported channel masks");
5504 ALOGW_IF(profile->mSamplingRates.size() == 0,
5505 "loadInput() invalid supported sampling rates");
5506 ALOGW_IF(profile->mFormats.size() == 0,
5507 "loadInput() invalid supported formats");
5508 if (!profile->mSupportedDevices.isEmpty() &&
5509 (profile->mChannelMasks.size() != 0) &&
5510 (profile->mSamplingRates.size() != 0) &&
5511 (profile->mFormats.size() != 0)) {
5512
5513 ALOGV("loadInput() adding input Supported Devices %04x",
5514 profile->mSupportedDevices.types());
5515
5516 mInputProfiles.add(profile);
5517 return NO_ERROR;
5518 } else {
5519 return BAD_VALUE;
5520 }
5521}
5522
5523status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5524{
5525 cnode *node = root->first_child;
5526
5527 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5528
5529 while (node) {
5530 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5531 profile->loadSamplingRates((char *)node->value);
5532 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5533 profile->loadFormats((char *)node->value);
5534 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5535 profile->loadOutChannels((char *)node->value);
5536 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5537 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5538 mDeclaredDevices);
5539 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5540 profile->mFlags = parseFlagNames((char *)node->value);
5541 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5542 profile->loadGains(node);
5543 }
5544 node = node->next;
5545 }
5546 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5547 "loadOutput() invalid supported devices");
5548 ALOGW_IF(profile->mChannelMasks.size() == 0,
5549 "loadOutput() invalid supported channel masks");
5550 ALOGW_IF(profile->mSamplingRates.size() == 0,
5551 "loadOutput() invalid supported sampling rates");
5552 ALOGW_IF(profile->mFormats.size() == 0,
5553 "loadOutput() invalid supported formats");
5554 if (!profile->mSupportedDevices.isEmpty() &&
5555 (profile->mChannelMasks.size() != 0) &&
5556 (profile->mSamplingRates.size() != 0) &&
5557 (profile->mFormats.size() != 0)) {
5558
5559 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5560 profile->mSupportedDevices.types(), profile->mFlags);
5561
5562 mOutputProfiles.add(profile);
5563 return NO_ERROR;
5564 } else {
5565 return BAD_VALUE;
5566 }
5567}
5568
5569status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5570{
5571 cnode *node = root->first_child;
5572
5573 audio_devices_t type = AUDIO_DEVICE_NONE;
5574 while (node) {
5575 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5576 type = parseDeviceNames((char *)node->value);
5577 break;
5578 }
5579 node = node->next;
5580 }
5581 if (type == AUDIO_DEVICE_NONE ||
5582 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5583 ALOGW("loadDevice() bad type %08x", type);
5584 return BAD_VALUE;
5585 }
5586 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5587 deviceDesc->mModule = this;
5588
5589 node = root->first_child;
5590 while (node) {
5591 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5592 deviceDesc->mAddress = String8((char *)node->value);
5593 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5594 if (audio_is_input_device(type)) {
5595 deviceDesc->loadInChannels((char *)node->value);
5596 } else {
5597 deviceDesc->loadOutChannels((char *)node->value);
5598 }
5599 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5600 deviceDesc->loadGains(node);
5601 }
5602 node = node->next;
5603 }
5604
5605 ALOGV("loadDevice() adding device name %s type %08x address %s",
5606 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5607
5608 mDeclaredDevices.add(deviceDesc);
5609
5610 return NO_ERROR;
5611}
5612
Eric Laurente0720872014-03-11 09:30:41 -07005613void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005614{
5615 const size_t SIZE = 256;
5616 char buffer[SIZE];
5617 String8 result;
5618
5619 snprintf(buffer, SIZE, " - name: %s\n", mName);
5620 result.append(buffer);
5621 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5622 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005623 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5624 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005625 write(fd, result.string(), result.size());
5626 if (mOutputProfiles.size()) {
5627 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5628 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005629 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005630 write(fd, buffer, strlen(buffer));
5631 mOutputProfiles[i]->dump(fd);
5632 }
5633 }
5634 if (mInputProfiles.size()) {
5635 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5636 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005637 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005638 write(fd, buffer, strlen(buffer));
5639 mInputProfiles[i]->dump(fd);
5640 }
5641 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005642 if (mDeclaredDevices.size()) {
5643 write(fd, " - devices:\n", strlen(" - devices:\n"));
5644 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5645 mDeclaredDevices[i]->dump(fd, 4, i);
5646 }
5647 }
Eric Laurente552edb2014-03-10 17:42:56 -07005648}
5649
Eric Laurent1c333e22014-05-20 10:48:17 -07005650// --- AudioPort class implementation
5651
Eric Laurenta121f902014-06-03 13:32:54 -07005652
5653AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5654 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005655 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005656{
5657 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5658 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5659}
5660
Eric Laurent1c333e22014-05-20 10:48:17 -07005661void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5662{
5663 port->role = mRole;
5664 port->type = mType;
5665 unsigned int i;
5666 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005667 if (mSamplingRates[i] != 0) {
5668 port->sample_rates[i] = mSamplingRates[i];
5669 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005670 }
5671 port->num_sample_rates = i;
5672 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005673 if (mChannelMasks[i] != 0) {
5674 port->channel_masks[i] = mChannelMasks[i];
5675 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005676 }
5677 port->num_channel_masks = i;
5678 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005679 if (mFormats[i] != 0) {
5680 port->formats[i] = mFormats[i];
5681 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005682 }
5683 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005684
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005685 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005686
5687 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5688 port->gains[i] = mGains[i]->mGain;
5689 }
5690 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005691}
5692
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005693void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5694 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5695 const uint32_t rate = port->mSamplingRates.itemAt(k);
5696 if (rate != 0) { // skip "dynamic" rates
5697 bool hasRate = false;
5698 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5699 if (rate == mSamplingRates.itemAt(l)) {
5700 hasRate = true;
5701 break;
5702 }
5703 }
5704 if (!hasRate) { // never import a sampling rate twice
5705 mSamplingRates.add(rate);
5706 }
5707 }
5708 }
5709 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5710 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5711 if (mask != 0) { // skip "dynamic" masks
5712 bool hasMask = false;
5713 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5714 if (mask == mChannelMasks.itemAt(l)) {
5715 hasMask = true;
5716 break;
5717 }
5718 }
5719 if (!hasMask) { // never import a channel mask twice
5720 mChannelMasks.add(mask);
5721 }
5722 }
5723 }
5724 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5725 const audio_format_t format = port->mFormats.itemAt(k);
5726 if (format != 0) { // skip "dynamic" formats
5727 bool hasFormat = false;
5728 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5729 if (format == mFormats.itemAt(l)) {
5730 hasFormat = true;
5731 break;
5732 }
5733 }
5734 if (!hasFormat) { // never import a channel mask twice
5735 mFormats.add(format);
5736 }
5737 }
5738 }
5739}
5740
5741void AudioPolicyManager::AudioPort::clearCapabilities() {
5742 mChannelMasks.clear();
5743 mFormats.clear();
5744 mSamplingRates.clear();
5745}
Eric Laurent1c333e22014-05-20 10:48:17 -07005746
5747void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5748{
5749 char *str = strtok(name, "|");
5750
5751 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5752 // rates should be read from the output stream after it is opened for the first time
5753 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5754 mSamplingRates.add(0);
5755 return;
5756 }
5757
5758 while (str != NULL) {
5759 uint32_t rate = atoi(str);
5760 if (rate != 0) {
5761 ALOGV("loadSamplingRates() adding rate %d", rate);
5762 mSamplingRates.add(rate);
5763 }
5764 str = strtok(NULL, "|");
5765 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005766}
5767
5768void AudioPolicyManager::AudioPort::loadFormats(char *name)
5769{
5770 char *str = strtok(name, "|");
5771
5772 // by convention, "0' in the first entry in mFormats indicates the supported formats
5773 // should be read from the output stream after it is opened for the first time
5774 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5775 mFormats.add(AUDIO_FORMAT_DEFAULT);
5776 return;
5777 }
5778
5779 while (str != NULL) {
5780 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5781 ARRAY_SIZE(sFormatNameToEnumTable),
5782 str);
5783 if (format != AUDIO_FORMAT_DEFAULT) {
5784 mFormats.add(format);
5785 }
5786 str = strtok(NULL, "|");
5787 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005788}
5789
5790void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5791{
5792 const char *str = strtok(name, "|");
5793
5794 ALOGV("loadInChannels() %s", name);
5795
5796 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5797 mChannelMasks.add(0);
5798 return;
5799 }
5800
5801 while (str != NULL) {
5802 audio_channel_mask_t channelMask =
5803 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5804 ARRAY_SIZE(sInChannelsNameToEnumTable),
5805 str);
5806 if (channelMask != 0) {
5807 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5808 mChannelMasks.add(channelMask);
5809 }
5810 str = strtok(NULL, "|");
5811 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005812}
5813
5814void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5815{
5816 const char *str = strtok(name, "|");
5817
5818 ALOGV("loadOutChannels() %s", name);
5819
5820 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5821 // masks should be read from the output stream after it is opened for the first time
5822 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5823 mChannelMasks.add(0);
5824 return;
5825 }
5826
5827 while (str != NULL) {
5828 audio_channel_mask_t channelMask =
5829 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5830 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5831 str);
5832 if (channelMask != 0) {
5833 mChannelMasks.add(channelMask);
5834 }
5835 str = strtok(NULL, "|");
5836 }
5837 return;
5838}
5839
Eric Laurent1afeecb2014-05-14 08:52:28 -07005840audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5841{
5842 const char *str = strtok(name, "|");
5843
5844 ALOGV("loadGainMode() %s", name);
5845 audio_gain_mode_t mode = 0;
5846 while (str != NULL) {
5847 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5848 ARRAY_SIZE(sGainModeNameToEnumTable),
5849 str);
5850 str = strtok(NULL, "|");
5851 }
5852 return mode;
5853}
5854
Eric Laurenta121f902014-06-03 13:32:54 -07005855void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005856{
5857 cnode *node = root->first_child;
5858
Eric Laurenta121f902014-06-03 13:32:54 -07005859 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005860
5861 while (node) {
5862 if (strcmp(node->name, GAIN_MODE) == 0) {
5863 gain->mGain.mode = loadGainMode((char *)node->value);
5864 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005865 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005866 gain->mGain.channel_mask =
5867 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5868 ARRAY_SIZE(sInChannelsNameToEnumTable),
5869 (char *)node->value);
5870 } else {
5871 gain->mGain.channel_mask =
5872 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5873 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5874 (char *)node->value);
5875 }
5876 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5877 gain->mGain.min_value = atoi((char *)node->value);
5878 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5879 gain->mGain.max_value = atoi((char *)node->value);
5880 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5881 gain->mGain.default_value = atoi((char *)node->value);
5882 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5883 gain->mGain.step_value = atoi((char *)node->value);
5884 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5885 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5886 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5887 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5888 }
5889 node = node->next;
5890 }
5891
5892 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5893 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5894
5895 if (gain->mGain.mode == 0) {
5896 return;
5897 }
5898 mGains.add(gain);
5899}
5900
5901void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5902{
5903 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005904 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005905 while (node) {
5906 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005907 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005908 node = node->next;
5909 }
5910}
5911
Glenn Kastencbd48022014-07-24 13:46:44 -07005912status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005913{
5914 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5915 if (mSamplingRates[i] == samplingRate) {
5916 return NO_ERROR;
5917 }
5918 }
5919 return BAD_VALUE;
5920}
5921
Glenn Kastencbd48022014-07-24 13:46:44 -07005922status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5923 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005924{
Glenn Kastencbd48022014-07-24 13:46:44 -07005925 // Search for the closest supported sampling rate that is above (preferred)
5926 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5927 // The sampling rates do not need to be sorted in ascending order.
5928 ssize_t maxBelow = -1;
5929 ssize_t minAbove = -1;
5930 uint32_t candidate;
5931 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5932 candidate = mSamplingRates[i];
5933 if (candidate == samplingRate) {
5934 if (updatedSamplingRate != NULL) {
5935 *updatedSamplingRate = candidate;
5936 }
5937 return NO_ERROR;
5938 }
5939 // candidate < desired
5940 if (candidate < samplingRate) {
5941 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5942 maxBelow = i;
5943 }
5944 // candidate > desired
5945 } else {
5946 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5947 minAbove = i;
5948 }
5949 }
5950 }
5951 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5952 // TODO Move these assumptions out.
5953 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5954 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5955 // due to approximation by an int32_t of the
5956 // phase increments
5957 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5958 if (minAbove >= 0) {
5959 candidate = mSamplingRates[minAbove];
5960 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5961 if (updatedSamplingRate != NULL) {
5962 *updatedSamplingRate = candidate;
5963 }
5964 return NO_ERROR;
5965 }
5966 }
5967 // But if we have to up-sample from a lower sampling rate, that's OK.
5968 if (maxBelow >= 0) {
5969 candidate = mSamplingRates[maxBelow];
5970 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5971 if (updatedSamplingRate != NULL) {
5972 *updatedSamplingRate = candidate;
5973 }
5974 return NO_ERROR;
5975 }
5976 }
5977 // leave updatedSamplingRate unmodified
5978 return BAD_VALUE;
5979}
5980
5981status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5982{
5983 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005984 if (mChannelMasks[i] == channelMask) {
5985 return NO_ERROR;
5986 }
5987 }
5988 return BAD_VALUE;
5989}
5990
Glenn Kastencbd48022014-07-24 13:46:44 -07005991status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5992 const
5993{
5994 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5995 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5996 // FIXME Does not handle multi-channel automatic conversions yet
5997 audio_channel_mask_t supported = mChannelMasks[i];
5998 if (supported == channelMask) {
5999 return NO_ERROR;
6000 }
6001 if (isRecordThread) {
6002 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6003 // FIXME Abstract this out to a table.
6004 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6005 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6006 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6007 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6008 return NO_ERROR;
6009 }
6010 }
6011 }
6012 return BAD_VALUE;
6013}
6014
Eric Laurenta121f902014-06-03 13:32:54 -07006015status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6016{
6017 for (size_t i = 0; i < mFormats.size(); i ++) {
6018 if (mFormats[i] == format) {
6019 return NO_ERROR;
6020 }
6021 }
6022 return BAD_VALUE;
6023}
6024
Eric Laurent1e693b52014-07-09 15:03:28 -07006025
6026uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6027{
6028 // special case for uninitialized dynamic profile
6029 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6030 return 0;
6031 }
6032
6033 uint32_t samplingRate = 0;
6034 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6035
6036 // For mixed output and inputs, use max mixer sampling rates. Do not
6037 // limit sampling rate otherwise
6038 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6039 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
6040 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
6041 maxRate = UINT_MAX;
6042 }
6043 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6044 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6045 samplingRate = mSamplingRates[i];
6046 }
6047 }
6048 return samplingRate;
6049}
6050
6051audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6052{
6053 // special case for uninitialized dynamic profile
6054 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6055 return AUDIO_CHANNEL_NONE;
6056 }
6057
6058 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
6059 uint32_t channelCount = 0;
6060 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6061
6062 // For mixed output and inputs, use max mixer channel count. Do not
6063 // limit channel count otherwise
6064 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6065 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
6066 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
6067 maxCount = UINT_MAX;
6068 }
6069 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6070 uint32_t cnlCount;
6071 if (mUseInChannelMask) {
6072 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6073 } else {
6074 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6075 }
6076 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6077 channelMask = mChannelMasks[i];
6078 }
6079 }
6080 return channelMask;
6081}
6082
Andy Hung9a605382014-07-28 16:16:31 -07006083/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006084const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6085 AUDIO_FORMAT_DEFAULT,
6086 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006087 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006088 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006089 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006090 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006091};
6092
6093int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6094 audio_format_t format2)
6095{
6096 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6097 // compressed format and better than any PCM format. This is by design of pickFormat()
6098 if (!audio_is_linear_pcm(format1)) {
6099 if (!audio_is_linear_pcm(format2)) {
6100 return 0;
6101 }
6102 return 1;
6103 }
6104 if (!audio_is_linear_pcm(format2)) {
6105 return -1;
6106 }
6107
6108 int index1 = -1, index2 = -1;
6109 for (size_t i = 0;
6110 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6111 i ++) {
6112 if (sPcmFormatCompareTable[i] == format1) {
6113 index1 = i;
6114 }
6115 if (sPcmFormatCompareTable[i] == format2) {
6116 index2 = i;
6117 }
6118 }
6119 // format1 not found => index1 < 0 => format2 > format1
6120 // format2 not found => index2 < 0 => format2 < format1
6121 return index1 - index2;
6122}
6123
6124audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6125{
6126 // special case for uninitialized dynamic profile
6127 if (mFormats.size() == 1 && mFormats[0] == 0) {
6128 return AUDIO_FORMAT_DEFAULT;
6129 }
6130
6131 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006132 audio_format_t bestFormat =
6133 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6134 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006135 // For mixed output and inputs, use best mixer output format. Do not
6136 // limit format otherwise
6137 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6138 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006139 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006140 bestFormat = AUDIO_FORMAT_INVALID;
6141 }
6142
6143 for (size_t i = 0; i < mFormats.size(); i ++) {
6144 if ((compareFormats(mFormats[i], format) > 0) &&
6145 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6146 format = mFormats[i];
6147 }
6148 }
6149 return format;
6150}
6151
Eric Laurenta121f902014-06-03 13:32:54 -07006152status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6153 int index) const
6154{
6155 if (index < 0 || (size_t)index >= mGains.size()) {
6156 return BAD_VALUE;
6157 }
6158 return mGains[index]->checkConfig(gainConfig);
6159}
6160
Eric Laurent1afeecb2014-05-14 08:52:28 -07006161void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6162{
6163 const size_t SIZE = 256;
6164 char buffer[SIZE];
6165 String8 result;
6166
6167 if (mName.size() != 0) {
6168 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6169 result.append(buffer);
6170 }
6171
6172 if (mSamplingRates.size() != 0) {
6173 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6174 result.append(buffer);
6175 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006176 if (i == 0 && mSamplingRates[i] == 0) {
6177 snprintf(buffer, SIZE, "Dynamic");
6178 } else {
6179 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6180 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006181 result.append(buffer);
6182 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6183 }
6184 result.append("\n");
6185 }
6186
6187 if (mChannelMasks.size() != 0) {
6188 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6189 result.append(buffer);
6190 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006191 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6192
6193 if (i == 0 && mChannelMasks[i] == 0) {
6194 snprintf(buffer, SIZE, "Dynamic");
6195 } else {
6196 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6197 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006198 result.append(buffer);
6199 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6200 }
6201 result.append("\n");
6202 }
6203
6204 if (mFormats.size() != 0) {
6205 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6206 result.append(buffer);
6207 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006208 const char *formatStr = enumToString(sFormatNameToEnumTable,
6209 ARRAY_SIZE(sFormatNameToEnumTable),
6210 mFormats[i]);
6211 if (i == 0 && strcmp(formatStr, "") == 0) {
6212 snprintf(buffer, SIZE, "Dynamic");
6213 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006214 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006215 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006216 result.append(buffer);
6217 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6218 }
6219 result.append("\n");
6220 }
6221 write(fd, result.string(), result.size());
6222 if (mGains.size() != 0) {
6223 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6224 write(fd, buffer, strlen(buffer) + 1);
6225 result.append(buffer);
6226 for (size_t i = 0; i < mGains.size(); i++) {
6227 mGains[i]->dump(fd, spaces + 2, i);
6228 }
6229 }
6230}
6231
6232// --- AudioGain class implementation
6233
Eric Laurenta121f902014-06-03 13:32:54 -07006234AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006235{
Eric Laurenta121f902014-06-03 13:32:54 -07006236 mIndex = index;
6237 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006238 memset(&mGain, 0, sizeof(struct audio_gain));
6239}
6240
Eric Laurenta121f902014-06-03 13:32:54 -07006241void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6242{
6243 config->index = mIndex;
6244 config->mode = mGain.mode;
6245 config->channel_mask = mGain.channel_mask;
6246 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6247 config->values[0] = mGain.default_value;
6248 } else {
6249 uint32_t numValues;
6250 if (mUseInChannelMask) {
6251 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6252 } else {
6253 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6254 }
6255 for (size_t i = 0; i < numValues; i++) {
6256 config->values[i] = mGain.default_value;
6257 }
6258 }
6259 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6260 config->ramp_duration_ms = mGain.min_ramp_ms;
6261 }
6262}
6263
6264status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6265{
6266 if ((config->mode & ~mGain.mode) != 0) {
6267 return BAD_VALUE;
6268 }
6269 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6270 if ((config->values[0] < mGain.min_value) ||
6271 (config->values[0] > mGain.max_value)) {
6272 return BAD_VALUE;
6273 }
6274 } else {
6275 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6276 return BAD_VALUE;
6277 }
6278 uint32_t numValues;
6279 if (mUseInChannelMask) {
6280 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6281 } else {
6282 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6283 }
6284 for (size_t i = 0; i < numValues; i++) {
6285 if ((config->values[i] < mGain.min_value) ||
6286 (config->values[i] > mGain.max_value)) {
6287 return BAD_VALUE;
6288 }
6289 }
6290 }
6291 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6292 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6293 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6294 return BAD_VALUE;
6295 }
6296 }
6297 return NO_ERROR;
6298}
6299
Eric Laurent1afeecb2014-05-14 08:52:28 -07006300void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6301{
6302 const size_t SIZE = 256;
6303 char buffer[SIZE];
6304 String8 result;
6305
6306 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6307 result.append(buffer);
6308 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6309 result.append(buffer);
6310 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6311 result.append(buffer);
6312 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6313 result.append(buffer);
6314 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6315 result.append(buffer);
6316 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6317 result.append(buffer);
6318 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6319 result.append(buffer);
6320 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6321 result.append(buffer);
6322 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6323 result.append(buffer);
6324
6325 write(fd, result.string(), result.size());
6326}
6327
Eric Laurent1f2f2232014-06-02 12:01:23 -07006328// --- AudioPortConfig class implementation
6329
6330AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6331{
6332 mSamplingRate = 0;
6333 mChannelMask = AUDIO_CHANNEL_NONE;
6334 mFormat = AUDIO_FORMAT_INVALID;
6335 mGain.index = -1;
6336}
6337
Eric Laurenta121f902014-06-03 13:32:54 -07006338status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6339 const struct audio_port_config *config,
6340 struct audio_port_config *backupConfig)
6341{
6342 struct audio_port_config localBackupConfig;
6343 status_t status = NO_ERROR;
6344
6345 localBackupConfig.config_mask = config->config_mask;
6346 toAudioPortConfig(&localBackupConfig);
6347
Marco Nelissen961ec212014-08-25 15:58:39 -07006348 sp<AudioPort> audioport = getAudioPort();
6349 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006350 status = NO_INIT;
6351 goto exit;
6352 }
6353 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006354 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006355 if (status != NO_ERROR) {
6356 goto exit;
6357 }
6358 mSamplingRate = config->sample_rate;
6359 }
6360 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006361 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006362 if (status != NO_ERROR) {
6363 goto exit;
6364 }
6365 mChannelMask = config->channel_mask;
6366 }
6367 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006368 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006369 if (status != NO_ERROR) {
6370 goto exit;
6371 }
6372 mFormat = config->format;
6373 }
6374 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006375 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006376 if (status != NO_ERROR) {
6377 goto exit;
6378 }
6379 mGain = config->gain;
6380 }
6381
6382exit:
6383 if (status != NO_ERROR) {
6384 applyAudioPortConfig(&localBackupConfig);
6385 }
6386 if (backupConfig != NULL) {
6387 *backupConfig = localBackupConfig;
6388 }
6389 return status;
6390}
6391
Eric Laurent1f2f2232014-06-02 12:01:23 -07006392void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6393 struct audio_port_config *dstConfig,
6394 const struct audio_port_config *srcConfig) const
6395{
6396 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6397 dstConfig->sample_rate = mSamplingRate;
6398 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6399 dstConfig->sample_rate = srcConfig->sample_rate;
6400 }
6401 } else {
6402 dstConfig->sample_rate = 0;
6403 }
6404 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6405 dstConfig->channel_mask = mChannelMask;
6406 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6407 dstConfig->channel_mask = srcConfig->channel_mask;
6408 }
6409 } else {
6410 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6411 }
6412 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6413 dstConfig->format = mFormat;
6414 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6415 dstConfig->format = srcConfig->format;
6416 }
6417 } else {
6418 dstConfig->format = AUDIO_FORMAT_INVALID;
6419 }
6420 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6421 dstConfig->gain = mGain;
6422 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6423 dstConfig->gain = srcConfig->gain;
6424 }
6425 } else {
6426 dstConfig->gain.index = -1;
6427 }
6428 if (dstConfig->gain.index != -1) {
6429 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6430 } else {
6431 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6432 }
6433}
6434
Eric Laurent1c333e22014-05-20 10:48:17 -07006435// --- IOProfile class implementation
6436
Eric Laurent1afeecb2014-05-14 08:52:28 -07006437AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006438 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006439 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006440{
6441}
6442
Eric Laurente0720872014-03-11 09:30:41 -07006443AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006444{
6445}
6446
6447// checks if the IO profile is compatible with specified parameters.
6448// Sampling rate, format and channel mask must be specified in order to
6449// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006450bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006451 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006452 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006453 audio_format_t format,
6454 audio_channel_mask_t channelMask,
6455 audio_output_flags_t flags) const
6456{
Glenn Kastencbd48022014-07-24 13:46:44 -07006457 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6458 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6459 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006460
Glenn Kastencbd48022014-07-24 13:46:44 -07006461 if ((mSupportedDevices.types() & device) != device) {
6462 return false;
6463 }
6464
6465 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006466 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006467 }
6468 uint32_t myUpdatedSamplingRate = samplingRate;
6469 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006470 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006471 }
6472 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6473 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006474 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006475 }
6476
6477 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6478 return false;
6479 }
6480
6481 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6482 checkExactChannelMask(channelMask) != NO_ERROR)) {
6483 return false;
6484 }
6485 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6486 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6487 return false;
6488 }
6489
6490 if (isPlaybackThread && (mFlags & flags) != flags) {
6491 return false;
6492 }
6493 // The only input flag that is allowed to be different is the fast flag.
6494 // An existing fast stream is compatible with a normal track request.
6495 // An existing normal stream is compatible with a fast track request,
6496 // but the fast request will be denied by AudioFlinger and converted to normal track.
6497 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6498 ~AUDIO_INPUT_FLAG_FAST)) {
6499 return false;
6500 }
6501
6502 if (updatedSamplingRate != NULL) {
6503 *updatedSamplingRate = myUpdatedSamplingRate;
6504 }
6505 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006506}
6507
Eric Laurente0720872014-03-11 09:30:41 -07006508void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006509{
6510 const size_t SIZE = 256;
6511 char buffer[SIZE];
6512 String8 result;
6513
Eric Laurent1afeecb2014-05-14 08:52:28 -07006514 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006515
Eric Laurente552edb2014-03-10 17:42:56 -07006516 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6517 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006518 snprintf(buffer, SIZE, " - devices:\n");
6519 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006520 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006521 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6522 mSupportedDevices[i]->dump(fd, 6, i);
6523 }
Eric Laurente552edb2014-03-10 17:42:56 -07006524}
6525
Eric Laurentd4692962014-05-05 18:13:44 -07006526void AudioPolicyManager::IOProfile::log()
6527{
6528 const size_t SIZE = 256;
6529 char buffer[SIZE];
6530 String8 result;
6531
6532 ALOGV(" - sampling rates: ");
6533 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6534 ALOGV(" %d", mSamplingRates[i]);
6535 }
6536
6537 ALOGV(" - channel masks: ");
6538 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6539 ALOGV(" 0x%04x", mChannelMasks[i]);
6540 }
6541
6542 ALOGV(" - formats: ");
6543 for (size_t i = 0; i < mFormats.size(); i++) {
6544 ALOGV(" 0x%08x", mFormats[i]);
6545 }
6546
6547 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6548 ALOGV(" - flags: 0x%04x\n", mFlags);
6549}
6550
6551
Eric Laurent3a4311c2014-03-17 12:00:47 -07006552// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006553
Eric Laurent1f2f2232014-06-02 12:01:23 -07006554
6555AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6556 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6557 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6558 AUDIO_PORT_ROLE_SOURCE,
6559 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006560 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006561{
Eric Laurenta121f902014-06-03 13:32:54 -07006562 if (mGains.size() > 0) {
6563 mGains[0]->getDefaultConfig(&mGain);
6564 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006565}
6566
Eric Laurent3a4311c2014-03-17 12:00:47 -07006567bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006568{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006569 // Devices are considered equal if they:
6570 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6571 // - have the same address or one device does not specify the address
6572 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006573 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006574 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006575 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006576 mChannelMask == other->mChannelMask);
6577}
6578
6579void AudioPolicyManager::DeviceVector::refreshTypes()
6580{
Eric Laurent1c333e22014-05-20 10:48:17 -07006581 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006582 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006583 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006584 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006585 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006586}
6587
6588ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6589{
6590 for(size_t i = 0; i < size(); i++) {
6591 if (item->equals(itemAt(i))) {
6592 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006593 }
6594 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006595 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006596}
6597
Eric Laurent3a4311c2014-03-17 12:00:47 -07006598ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006599{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006600 ssize_t ret = indexOf(item);
6601
6602 if (ret < 0) {
6603 ret = SortedVector::add(item);
6604 if (ret >= 0) {
6605 refreshTypes();
6606 }
6607 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006608 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006609 ret = -1;
6610 }
6611 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006612}
6613
Eric Laurent3a4311c2014-03-17 12:00:47 -07006614ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6615{
6616 size_t i;
6617 ssize_t ret = indexOf(item);
6618
6619 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006620 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006621 } else {
6622 ret = SortedVector::removeAt(ret);
6623 if (ret >= 0) {
6624 refreshTypes();
6625 }
6626 }
6627 return ret;
6628}
6629
6630void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6631{
6632 DeviceVector deviceList;
6633
6634 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6635 types &= ~role_bit;
6636
6637 while (types) {
6638 uint32_t i = 31 - __builtin_clz(types);
6639 uint32_t type = 1 << i;
6640 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006641 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006642 }
6643}
6644
Eric Laurent1afeecb2014-05-14 08:52:28 -07006645void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6646 const DeviceVector& declaredDevices)
6647{
6648 char *devName = strtok(name, "|");
6649 while (devName != NULL) {
6650 if (strlen(devName) != 0) {
6651 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6652 ARRAY_SIZE(sDeviceNameToEnumTable),
6653 devName);
6654 if (type != AUDIO_DEVICE_NONE) {
6655 add(new DeviceDescriptor(String8(""), type));
6656 } else {
6657 sp<DeviceDescriptor> deviceDesc =
6658 declaredDevices.getDeviceFromName(String8(devName));
6659 if (deviceDesc != 0) {
6660 add(deviceDesc);
6661 }
6662 }
6663 }
6664 devName = strtok(NULL, "|");
6665 }
6666}
6667
Eric Laurent1c333e22014-05-20 10:48:17 -07006668sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6669 audio_devices_t type, String8 address) const
6670{
6671 sp<DeviceDescriptor> device;
6672 for (size_t i = 0; i < size(); i++) {
6673 if (itemAt(i)->mDeviceType == type) {
6674 device = itemAt(i);
6675 if (itemAt(i)->mAddress = address) {
6676 break;
6677 }
6678 }
6679 }
6680 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6681 type, address.string(), device.get());
6682 return device;
6683}
6684
Eric Laurent6a94d692014-05-20 11:18:06 -07006685sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6686 audio_port_handle_t id) const
6687{
6688 sp<DeviceDescriptor> device;
6689 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006690 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006691 if (itemAt(i)->mId == id) {
6692 device = itemAt(i);
6693 break;
6694 }
6695 }
6696 return device;
6697}
6698
Eric Laurent1c333e22014-05-20 10:48:17 -07006699AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6700 audio_devices_t type) const
6701{
6702 DeviceVector devices;
6703 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6704 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6705 devices.add(itemAt(i));
6706 type &= ~itemAt(i)->mDeviceType;
6707 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6708 itemAt(i)->mDeviceType, itemAt(i).get());
6709 }
6710 }
6711 return devices;
6712}
6713
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006714AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6715 audio_devices_t type, String8 address) const
6716{
6717 DeviceVector devices;
6718 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6719 for (size_t i = 0; i < size(); i++) {
6720 //ALOGV(" at i=%d: device=%x, addr=%s",
6721 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6722 if (itemAt(i)->mDeviceType == type) {
6723 if (itemAt(i)->mAddress == address) {
6724 //ALOGV(" found matching address %s", address.string());
6725 devices.add(itemAt(i));
6726 }
6727 }
6728 }
6729 return devices;
6730}
6731
Eric Laurent1afeecb2014-05-14 08:52:28 -07006732sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6733 const String8& name) const
6734{
6735 sp<DeviceDescriptor> device;
6736 for (size_t i = 0; i < size(); i++) {
6737 if (itemAt(i)->mName == name) {
6738 device = itemAt(i);
6739 break;
6740 }
6741 }
6742 return device;
6743}
6744
Eric Laurent6a94d692014-05-20 11:18:06 -07006745void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6746 struct audio_port_config *dstConfig,
6747 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006748{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006749 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6750 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006751 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006752 }
6753
6754 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6755
Eric Laurent6a94d692014-05-20 11:18:06 -07006756 dstConfig->id = mId;
6757 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006758 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006759 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006760 dstConfig->ext.device.type = mDeviceType;
6761 dstConfig->ext.device.hw_module = mModule->mHandle;
6762 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006763}
6764
6765void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6766{
Eric Laurent83b88082014-06-20 18:31:16 -07006767 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006768 AudioPort::toAudioPort(port);
6769 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006770 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006771 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006772 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006773 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6774}
6775
Eric Laurent1afeecb2014-05-14 08:52:28 -07006776status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006777{
6778 const size_t SIZE = 256;
6779 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006780 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006781
Eric Laurent1afeecb2014-05-14 08:52:28 -07006782 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6783 result.append(buffer);
6784 if (mId != 0) {
6785 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6786 result.append(buffer);
6787 }
6788 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6789 enumToString(sDeviceNameToEnumTable,
6790 ARRAY_SIZE(sDeviceNameToEnumTable),
6791 mDeviceType));
6792 result.append(buffer);
6793 if (mAddress.size() != 0) {
6794 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6795 result.append(buffer);
6796 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006797 write(fd, result.string(), result.size());
6798 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006799
6800 return NO_ERROR;
6801}
6802
Eric Laurent4d416952014-08-10 14:07:09 -07006803status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6804{
6805 const size_t SIZE = 256;
6806 char buffer[SIZE];
6807 String8 result;
6808
6809
6810 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6811 result.append(buffer);
6812 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6813 result.append(buffer);
6814 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6815 result.append(buffer);
6816 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6817 result.append(buffer);
6818 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6819 result.append(buffer);
6820 for (size_t i = 0; i < mPatch.num_sources; i++) {
6821 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6822 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6823 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6824 ARRAY_SIZE(sDeviceNameToEnumTable),
6825 mPatch.sources[i].ext.device.type));
6826 } else {
6827 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6828 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6829 }
6830 result.append(buffer);
6831 }
6832 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6833 result.append(buffer);
6834 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6835 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6836 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6837 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6838 ARRAY_SIZE(sDeviceNameToEnumTable),
6839 mPatch.sinks[i].ext.device.type));
6840 } else {
6841 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6842 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6843 }
6844 result.append(buffer);
6845 }
6846
6847 write(fd, result.string(), result.size());
6848 return NO_ERROR;
6849}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006850
6851// --- audio_policy.conf file parsing
6852
Eric Laurente0720872014-03-11 09:30:41 -07006853audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006854{
6855 uint32_t flag = 0;
6856
6857 // it is OK to cast name to non const here as we are not going to use it after
6858 // strtok() modifies it
6859 char *flagName = strtok(name, "|");
6860 while (flagName != NULL) {
6861 if (strlen(flagName) != 0) {
6862 flag |= stringToEnum(sFlagNameToEnumTable,
6863 ARRAY_SIZE(sFlagNameToEnumTable),
6864 flagName);
6865 }
6866 flagName = strtok(NULL, "|");
6867 }
6868 //force direct flag if offload flag is set: offloading implies a direct output stream
6869 // and all common behaviors are driven by checking only the direct flag
6870 // this should normally be set appropriately in the policy configuration file
6871 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6872 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6873 }
6874
6875 return (audio_output_flags_t)flag;
6876}
6877
Eric Laurente0720872014-03-11 09:30:41 -07006878audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006879{
6880 uint32_t device = 0;
6881
6882 char *devName = strtok(name, "|");
6883 while (devName != NULL) {
6884 if (strlen(devName) != 0) {
6885 device |= stringToEnum(sDeviceNameToEnumTable,
6886 ARRAY_SIZE(sDeviceNameToEnumTable),
6887 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006888 }
Eric Laurente552edb2014-03-10 17:42:56 -07006889 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006890 }
Eric Laurente552edb2014-03-10 17:42:56 -07006891 return device;
6892}
6893
Eric Laurente0720872014-03-11 09:30:41 -07006894void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006895{
Eric Laurente552edb2014-03-10 17:42:56 -07006896 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006897 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006898 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006899
Eric Laurent1afeecb2014-05-14 08:52:28 -07006900 node = config_find(root, DEVICES_TAG);
6901 if (node != NULL) {
6902 node = node->first_child;
6903 while (node) {
6904 ALOGV("loadHwModule() loading device %s", node->name);
6905 status_t tmpStatus = module->loadDevice(node);
6906 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6907 status = tmpStatus;
6908 }
6909 node = node->next;
6910 }
6911 }
6912 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006913 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006914 node = node->first_child;
6915 while (node) {
6916 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006917 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006918 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6919 status = tmpStatus;
6920 }
6921 node = node->next;
6922 }
6923 }
6924 node = config_find(root, INPUTS_TAG);
6925 if (node != NULL) {
6926 node = node->first_child;
6927 while (node) {
6928 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006929 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006930 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6931 status = tmpStatus;
6932 }
6933 node = node->next;
6934 }
6935 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006936 loadGlobalConfig(root, module);
6937
Eric Laurente552edb2014-03-10 17:42:56 -07006938 if (status == NO_ERROR) {
6939 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006940 }
6941}
6942
Eric Laurente0720872014-03-11 09:30:41 -07006943void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006944{
6945 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6946 if (node == NULL) {
6947 return;
6948 }
6949
6950 node = node->first_child;
6951 while (node) {
6952 ALOGV("loadHwModules() loading module %s", node->name);
6953 loadHwModule(node);
6954 node = node->next;
6955 }
6956}
6957
Eric Laurent1f2f2232014-06-02 12:01:23 -07006958void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006959{
6960 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006961
Eric Laurente552edb2014-03-10 17:42:56 -07006962 if (node == NULL) {
6963 return;
6964 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006965 DeviceVector declaredDevices;
6966 if (module != NULL) {
6967 declaredDevices = module->mDeclaredDevices;
6968 }
6969
Eric Laurente552edb2014-03-10 17:42:56 -07006970 node = node->first_child;
6971 while (node) {
6972 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006973 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6974 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006975 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6976 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006977 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006978 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006979 ARRAY_SIZE(sDeviceNameToEnumTable),
6980 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006981 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006982 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006983 } else {
6984 ALOGW("loadGlobalConfig() default device not specified");
6985 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006986 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006987 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006988 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6989 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006990 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006991 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6992 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6993 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006994 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6995 uint32_t major, minor;
6996 sscanf((char *)node->value, "%u.%u", &major, &minor);
6997 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6998 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6999 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007000 }
7001 node = node->next;
7002 }
7003}
7004
Eric Laurente0720872014-03-11 09:30:41 -07007005status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007006{
7007 cnode *root;
7008 char *data;
7009
7010 data = (char *)load_file(path, NULL);
7011 if (data == NULL) {
7012 return -ENODEV;
7013 }
7014 root = config_node("", "");
7015 config_load(root, data);
7016
Eric Laurente552edb2014-03-10 17:42:56 -07007017 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007018 // legacy audio_policy.conf files have one global_configuration section
7019 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007020 config_free(root);
7021 free(root);
7022 free(data);
7023
7024 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7025
7026 return NO_ERROR;
7027}
7028
Eric Laurente0720872014-03-11 09:30:41 -07007029void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007030{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007031 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007032 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007033 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7034 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007035 mAvailableOutputDevices.add(mDefaultOutputDevice);
7036 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007037
7038 module = new HwModule("primary");
7039
Eric Laurent1afeecb2014-05-14 08:52:28 -07007040 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007041 profile->mSamplingRates.add(44100);
7042 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7043 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007044 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007045 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7046 module->mOutputProfiles.add(profile);
7047
Eric Laurent1afeecb2014-05-14 08:52:28 -07007048 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007049 profile->mSamplingRates.add(8000);
7050 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7051 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007052 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007053 module->mInputProfiles.add(profile);
7054
7055 mHwModules.add(module);
7056}
7057
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007058audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7059{
7060 // flags to stream type mapping
7061 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7062 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7063 }
7064 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7065 return AUDIO_STREAM_BLUETOOTH_SCO;
7066 }
7067
7068 // usage to stream type mapping
7069 switch (attr->usage) {
7070 case AUDIO_USAGE_MEDIA:
7071 case AUDIO_USAGE_GAME:
7072 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7073 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7074 return AUDIO_STREAM_MUSIC;
7075 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7076 return AUDIO_STREAM_SYSTEM;
7077 case AUDIO_USAGE_VOICE_COMMUNICATION:
7078 return AUDIO_STREAM_VOICE_CALL;
7079
7080 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7081 return AUDIO_STREAM_DTMF;
7082
7083 case AUDIO_USAGE_ALARM:
7084 return AUDIO_STREAM_ALARM;
7085 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7086 return AUDIO_STREAM_RING;
7087
7088 case AUDIO_USAGE_NOTIFICATION:
7089 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7090 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7091 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7092 case AUDIO_USAGE_NOTIFICATION_EVENT:
7093 return AUDIO_STREAM_NOTIFICATION;
7094
7095 case AUDIO_USAGE_UNKNOWN:
7096 default:
7097 return AUDIO_STREAM_MUSIC;
7098 }
7099}
Eric Laurente552edb2014-03-10 17:42:56 -07007100}; // namespace android