blob: c00541cf7769ea8c4a31e8481c7424590823a373 [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 Laurent3a4311c2014-03-17 12:00:47 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700110 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900111 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122};
123
124const StringToEnum sFormatNameToEnumTable[] = {
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
130 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
131 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700143 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700144 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
146 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
147 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
148 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149};
150
151const StringToEnum sOutChannelsNameToEnumTable[] = {
152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
156 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
157};
158
159const StringToEnum sInChannelsNameToEnumTable[] = {
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
162 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
163};
164
Eric Laurent1afeecb2014-05-14 08:52:28 -0700165const StringToEnum sGainModeNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
168 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
169};
170
Eric Laurent3a4311c2014-03-17 12:00:47 -0700171
172uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
173 size_t size,
174 const char *name)
175{
176 for (size_t i = 0; i < size; i++) {
177 if (strcmp(table[i].name, name) == 0) {
178 ALOGV("stringToEnum() found %s", table[i].name);
179 return table[i].value;
180 }
181 }
182 return 0;
183}
184
185const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
186 size_t size,
187 uint32_t value)
188{
189 for (size_t i = 0; i < size; i++) {
190 if (table[i].value == value) {
191 return table[i].name;
192 }
193 }
194 return "";
195}
196
197bool AudioPolicyManager::stringToBool(const char *value)
198{
199 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
200}
201
202
203// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700204// AudioPolicyInterface implementation
205// ----------------------------------------------------------------------------
206
207
Eric Laurente0720872014-03-11 09:30:41 -0700208status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700209 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700210 const char *device_address)
211{
Eric Laurent22226012014-08-01 17:00:54 -0700212 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurent22226012014-08-01 17:00:54 -0700214 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
215 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700216
217 // connect/disconnect only 1 device at a time
218 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
219
Eric Laurente552edb2014-03-10 17:42:56 -0700220 // handle output devices
221 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700222 SortedVector <audio_io_handle_t> outputs;
223
Eric Laurent1afeecb2014-05-14 08:52:28 -0700224 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
225 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // save a copy of the opened output descriptors before any output is opened or closed
229 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
230 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 switch (state)
232 {
233 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700234 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700235 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700236 ALOGW("setDeviceConnectionState() device already connected: %x", device);
237 return INVALID_OPERATION;
238 }
239 ALOGV("setDeviceConnectionState() connecting device %x", device);
240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700242 index = mAvailableOutputDevices.add(devDesc);
243 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700244 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700245 if (module == 0) {
246 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
247 device);
248 mAvailableOutputDevices.remove(devDesc);
249 return INVALID_OPERATION;
250 }
251 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700252 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 } else {
254 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
256
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700257 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 // outputs should never be empty here
262 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
263 "checkOutputsForDevice() returned no outputs but status OK");
264 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
265 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700266 break;
267 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700268 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700269 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700270 ALOGW("setDeviceConnectionState() device not connected: %x", device);
271 return INVALID_OPERATION;
272 }
273
274 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
275 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700277
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700279 } break;
280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
287 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700288 checkA2dpSuspend();
289 checkOutputForAllStrategies();
290 // outputs must be closed after checkOutputForAllStrategies() is executed
291 if (!outputs.isEmpty()) {
292 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700293 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700294 // close unused outputs after device disconnection or direct outputs that have been
295 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700297 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
298 (desc->mDirectOpenCount == 0))) {
299 closeOutput(outputs[i]);
300 }
301 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 // check again after closing A2DP output to reset mA2dpSuspended if needed
303 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
305
306 updateDevicesAndOutputs();
307 for (size_t i = 0; i < mOutputs.size(); i++) {
308 // do not force device change on duplicated output because if device is 0, it will
309 // also force a device 0 for the two outputs it is duplicated to which may override
310 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700311 bool force = !mOutputs.valueAt(i)->isDuplicated()
312 && (!deviceDistinguishesOnAddress(device)
313 // always force when disconnecting (a non-duplicated device)
314 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700315 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700316 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700317 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700318 }
319
Eric Laurent72aa32f2014-05-30 18:51:48 -0700320 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700321 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700322 } // end if is output device
323
Eric Laurente552edb2014-03-10 17:42:56 -0700324 // handle input devices
325 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700326 SortedVector <audio_io_handle_t> inputs;
327
Eric Laurent1afeecb2014-05-14 08:52:28 -0700328 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
329 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700330 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700331 switch (state)
332 {
333 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700334 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700335 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700336 ALOGW("setDeviceConnectionState() device already connected: %d", device);
337 return INVALID_OPERATION;
338 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700339 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700340 if (module == NULL) {
341 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
342 device);
343 return INVALID_OPERATION;
344 }
Eric Laurentd4692962014-05-05 18:13:44 -0700345 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
346 return INVALID_OPERATION;
347 }
348
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 index = mAvailableInputDevices.add(devDesc);
350 if (index >= 0) {
351 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700352 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 } else {
354 return NO_MEMORY;
355 }
Eric Laurentd4692962014-05-05 18:13:44 -0700356 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700357
358 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700359 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700361 ALOGW("setDeviceConnectionState() device not connected: %d", device);
362 return INVALID_OPERATION;
363 }
Eric Laurentd4692962014-05-05 18:13:44 -0700364 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700365 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700366 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700367
368 default:
369 ALOGE("setDeviceConnectionState() invalid state: %x", state);
370 return BAD_VALUE;
371 }
372
Eric Laurentd4692962014-05-05 18:13:44 -0700373 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700374
Eric Laurentb52c1522014-05-20 11:27:36 -0700375 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700376 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700377 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700378
379 ALOGW("setDeviceConnectionState() invalid device: %x", device);
380 return BAD_VALUE;
381}
382
Eric Laurente0720872014-03-11 09:30:41 -0700383audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700384 const char *device_address)
385{
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700387 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700388 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700389 ssize_t index;
390 DeviceVector *deviceVector;
391
Eric Laurente552edb2014-03-10 17:42:56 -0700392 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700393 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700394 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700395 deviceVector = &mAvailableInputDevices;
396 } else {
397 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
398 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700399 }
400
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 index = deviceVector->indexOf(devDesc);
402 if (index >= 0) {
403 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
404 } else {
405 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
406 }
Eric Laurente552edb2014-03-10 17:42:56 -0700407}
408
Eric Laurente0720872014-03-11 09:30:41 -0700409void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700410{
411 ALOGV("setPhoneState() state %d", state);
412 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700414 ALOGW("setPhoneState() invalid state %d", state);
415 return;
416 }
417
418 if (state == mPhoneState ) {
419 ALOGW("setPhoneState() setting same state %d", state);
420 return;
421 }
422
423 // if leaving call state, handle special case of active streams
424 // pertaining to sonification strategy see handleIncallSonification()
425 if (isInCall()) {
426 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700427 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
428 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700429 }
430 }
431
432 // store previous phone state for management of sonification strategy below
433 int oldState = mPhoneState;
434 mPhoneState = state;
435 bool force = false;
436
437 // are we entering or starting a call
438 if (!isStateInCall(oldState) && isStateInCall(state)) {
439 ALOGV(" Entering call in setPhoneState()");
440 // force routing command to audio hardware when starting a call
441 // even if no device change is needed
442 force = true;
443 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
444 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
445 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
446 }
447 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
448 ALOGV(" Exiting call in setPhoneState()");
449 // force routing command to audio hardware when exiting a call
450 // even if no device change is needed
451 force = true;
452 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
453 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
454 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
455 }
456 } else if (isStateInCall(state) && (state != oldState)) {
457 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
458 // force routing command to audio hardware when switching between telephony and VoIP
459 // even if no device change is needed
460 force = true;
461 }
462
463 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700464 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700465 checkA2dpSuspend();
466 checkOutputForAllStrategies();
467 updateDevicesAndOutputs();
468
Eric Laurent1f2f2232014-06-02 12:01:23 -0700469 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700470
471 // force routing command to audio hardware when ending call
472 // even if no device change is needed
473 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
474 newDevice = hwOutputDesc->device();
475 }
476
477 int delayMs = 0;
478 if (isStateInCall(state)) {
479 nsecs_t sysTime = systemTime();
480 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700481 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700482 // mute media and sonification strategies and delay device switch by the largest
483 // latency of any output where either strategy is active.
484 // This avoid sending the ring tone or music tail into the earpiece or headset.
485 if ((desc->isStrategyActive(STRATEGY_MEDIA,
486 SONIFICATION_HEADSET_MUSIC_DELAY,
487 sysTime) ||
488 desc->isStrategyActive(STRATEGY_SONIFICATION,
489 SONIFICATION_HEADSET_MUSIC_DELAY,
490 sysTime)) &&
491 (delayMs < (int)desc->mLatency*2)) {
492 delayMs = desc->mLatency*2;
493 }
494 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
495 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
496 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
497 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
498 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
499 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
500 }
501 }
502
503 // change routing is necessary
504 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
505
506 // if entering in call state, handle special case of active streams
507 // pertaining to sonification strategy see handleIncallSonification()
508 if (isStateInCall(state)) {
509 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700510 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
511 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700512 }
513 }
514
515 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 if (state == AUDIO_MODE_RINGTONE &&
517 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700518 mLimitRingtoneVolume = true;
519 } else {
520 mLimitRingtoneVolume = false;
521 }
522}
523
Eric Laurente0720872014-03-11 09:30:41 -0700524void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700525 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700526{
527 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
528
529 bool forceVolumeReeval = false;
530 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700531 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
532 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
533 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700534 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
535 return;
536 }
537 forceVolumeReeval = true;
538 mForceUse[usage] = config;
539 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700540 case AUDIO_POLICY_FORCE_FOR_MEDIA:
541 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
542 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
543 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
544 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900545 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700546 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
547 return;
548 }
549 mForceUse[usage] = config;
550 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700551 case AUDIO_POLICY_FORCE_FOR_RECORD:
552 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
553 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700554 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
555 return;
556 }
557 mForceUse[usage] = config;
558 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700559 case AUDIO_POLICY_FORCE_FOR_DOCK:
560 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
561 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
562 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
563 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
564 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700565 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
566 }
567 forceVolumeReeval = true;
568 mForceUse[usage] = config;
569 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700570 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
571 if (config != AUDIO_POLICY_FORCE_NONE &&
572 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700573 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
574 }
575 forceVolumeReeval = true;
576 mForceUse[usage] = config;
577 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900578 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
579 if (config != AUDIO_POLICY_FORCE_NONE &&
580 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
581 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
582 }
583 mForceUse[usage] = config;
584 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700585 default:
586 ALOGW("setForceUse() invalid usage %d", usage);
587 break;
588 }
589
590 // check for device and output changes triggered by new force usage
591 checkA2dpSuspend();
592 checkOutputForAllStrategies();
593 updateDevicesAndOutputs();
594 for (size_t i = 0; i < mOutputs.size(); i++) {
595 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700596 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700597 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
598 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
599 applyStreamVolumes(output, newDevice, 0, true);
600 }
601 }
602
603 audio_io_handle_t activeInput = getActiveInput();
604 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700605 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700606 }
607
608}
609
Eric Laurente0720872014-03-11 09:30:41 -0700610audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700611{
612 return mForceUse[usage];
613}
614
Eric Laurente0720872014-03-11 09:30:41 -0700615void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700616{
617 ALOGV("setSystemProperty() property %s, value %s", property, value);
618}
619
620// Find a direct output profile compatible with the parameters passed, even if the input flags do
621// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700622sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700623 audio_devices_t device,
624 uint32_t samplingRate,
625 audio_format_t format,
626 audio_channel_mask_t channelMask,
627 audio_output_flags_t flags)
628{
629 for (size_t i = 0; i < mHwModules.size(); i++) {
630 if (mHwModules[i]->mHandle == 0) {
631 continue;
632 }
633 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700634 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700635 bool found = profile->isCompatibleProfile(device, samplingRate,
636 NULL /*updatedSamplingRate*/, format, channelMask,
637 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
638 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700639 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
640 return profile;
641 }
Eric Laurente552edb2014-03-10 17:42:56 -0700642 }
643 }
644 return 0;
645}
646
Eric Laurente0720872014-03-11 09:30:41 -0700647audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700648 uint32_t samplingRate,
649 audio_format_t format,
650 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700651 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700652 const audio_offload_info_t *offloadInfo)
653{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700654
Eric Laurent3b73df72014-03-11 09:06:29 -0700655 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700656 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
657 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
658 device, stream, samplingRate, format, channelMask, flags);
659
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700660 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
661 offloadInfo);
662}
663
664audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
665 uint32_t samplingRate,
666 audio_format_t format,
667 audio_channel_mask_t channelMask,
668 audio_output_flags_t flags,
669 const audio_offload_info_t *offloadInfo)
670{
671 if (attr == NULL) {
672 ALOGE("getOutputForAttr() called with NULL audio attributes");
673 return 0;
674 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700675 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
676 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700677
678 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
679 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
680 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700681
682 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
683 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
684 }
685
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700686 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
687 device, samplingRate, format, channelMask, flags);
688
689 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
690 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
691 offloadInfo);
692}
693
694audio_io_handle_t AudioPolicyManager::getOutputForDevice(
695 audio_devices_t device,
696 audio_stream_type_t stream,
697 uint32_t samplingRate,
698 audio_format_t format,
699 audio_channel_mask_t channelMask,
700 audio_output_flags_t flags,
701 const audio_offload_info_t *offloadInfo)
702{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700703 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700704 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700705 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700706
Eric Laurente552edb2014-03-10 17:42:56 -0700707#ifdef AUDIO_POLICY_TEST
708 if (mCurOutput != 0) {
709 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
710 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
711
712 if (mTestOutputs[mCurOutput] == 0) {
713 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700714 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700715 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700716 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700717 outputDesc->mFlags =
718 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700719 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700720 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
721 config.sample_rate = mTestSamplingRate;
722 config.channel_mask = mTestChannels;
723 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700724 if (offloadInfo != NULL) {
725 config.offload_info = *offloadInfo;
726 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700727 status = mpClientInterface->openOutput(0,
728 &mTestOutputs[mCurOutput],
729 &config,
730 &outputDesc->mDevice,
731 String8(""),
732 &outputDesc->mLatency,
733 outputDesc->mFlags);
734 if (status == NO_ERROR) {
735 outputDesc->mSamplingRate = config.sample_rate;
736 outputDesc->mFormat = config.format;
737 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700738 AudioParameter outputCmd = AudioParameter();
739 outputCmd.addInt(String8("set_id"),mCurOutput);
740 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
741 addOutput(mTestOutputs[mCurOutput], outputDesc);
742 }
743 }
744 return mTestOutputs[mCurOutput];
745 }
746#endif //AUDIO_POLICY_TEST
747
748 // open a direct output if required by specified parameters
749 //force direct flag if offload flag is set: offloading implies a direct output stream
750 // and all common behaviors are driven by checking only the direct flag
751 // this should normally be set appropriately in the policy configuration file
752 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700753 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700754 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700755 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
756 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
757 }
Eric Laurente552edb2014-03-10 17:42:56 -0700758
759 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
760 // creating an offloaded track and tearing it down immediately after start when audioflinger
761 // detects there is an active non offloadable effect.
762 // FIXME: We should check the audio session here but we do not have it in this context.
763 // This may prevent offloading in rare situations where effects are left active by apps
764 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700765 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700766 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
767 !isNonOffloadableEffectEnabled()) {
768 profile = getProfileForDirectOutput(device,
769 samplingRate,
770 format,
771 channelMask,
772 (audio_output_flags_t)flags);
773 }
774
Eric Laurent1c333e22014-05-20 10:48:17 -0700775 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700776 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700777
778 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700779 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700780 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
781 outputDesc = desc;
782 // reuse direct output if currently open and configured with same parameters
783 if ((samplingRate == outputDesc->mSamplingRate) &&
784 (format == outputDesc->mFormat) &&
785 (channelMask == outputDesc->mChannelMask)) {
786 outputDesc->mDirectOpenCount++;
787 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
788 return mOutputs.keyAt(i);
789 }
790 }
791 }
792 // close direct output if currently open and configured with different parameters
793 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700794 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700795 }
796 outputDesc = new AudioOutputDescriptor(profile);
797 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700798 outputDesc->mLatency = 0;
799 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700800 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
801 config.sample_rate = samplingRate;
802 config.channel_mask = channelMask;
803 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700804 if (offloadInfo != NULL) {
805 config.offload_info = *offloadInfo;
806 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700807 status = mpClientInterface->openOutput(profile->mModule->mHandle,
808 &output,
809 &config,
810 &outputDesc->mDevice,
811 String8(""),
812 &outputDesc->mLatency,
813 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700814
815 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700816 if (status != NO_ERROR ||
817 (samplingRate != 0 && samplingRate != config.sample_rate) ||
818 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
819 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700820 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
821 "format %d %d, channelMask %04x %04x", output, samplingRate,
822 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
823 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700824 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700825 mpClientInterface->closeOutput(output);
826 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700827 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700829 outputDesc->mSamplingRate = config.sample_rate;
830 outputDesc->mChannelMask = config.channel_mask;
831 outputDesc->mFormat = config.format;
832 outputDesc->mRefCount[stream] = 0;
833 outputDesc->mStopTime[stream] = 0;
834 outputDesc->mDirectOpenCount = 1;
835
Eric Laurente552edb2014-03-10 17:42:56 -0700836 audio_io_handle_t srcOutput = getOutputForEffect();
837 addOutput(output, outputDesc);
838 audio_io_handle_t dstOutput = getOutputForEffect();
839 if (dstOutput == output) {
840 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
841 }
842 mPreviousOutputs = mOutputs;
843 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700844 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700845 return output;
846 }
847
848 // ignoring channel mask due to downmix capability in mixer
849
850 // open a non direct output
851
852 // for non direct outputs, only PCM is supported
853 if (audio_is_linear_pcm(format)) {
854 // get which output is suitable for the specified stream. The actual
855 // routing change will happen when startOutput() will be called
856 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
857
858 output = selectOutput(outputs, flags);
859 }
860 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
861 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
862
863 ALOGV("getOutput() returns output %d", output);
864
865 return output;
866}
867
Eric Laurente0720872014-03-11 09:30:41 -0700868audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700869 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700870{
871 // select one output among several that provide a path to a particular device or set of
872 // devices (the list was previously build by getOutputsForDevice()).
873 // The priority is as follows:
874 // 1: the output with the highest number of requested policy flags
875 // 2: the primary output
876 // 3: the first output in the list
877
878 if (outputs.size() == 0) {
879 return 0;
880 }
881 if (outputs.size() == 1) {
882 return outputs[0];
883 }
884
885 int maxCommonFlags = 0;
886 audio_io_handle_t outputFlags = 0;
887 audio_io_handle_t outputPrimary = 0;
888
889 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700890 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700892 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700893 if (commonFlags > maxCommonFlags) {
894 outputFlags = outputs[i];
895 maxCommonFlags = commonFlags;
896 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
897 }
898 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
899 outputPrimary = outputs[i];
900 }
901 }
902 }
903
904 if (outputFlags != 0) {
905 return outputFlags;
906 }
907 if (outputPrimary != 0) {
908 return outputPrimary;
909 }
910
911 return outputs[0];
912}
913
Eric Laurente0720872014-03-11 09:30:41 -0700914status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700915 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700916 int session)
917{
918 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
919 ssize_t index = mOutputs.indexOfKey(output);
920 if (index < 0) {
921 ALOGW("startOutput() unknown output %d", output);
922 return BAD_VALUE;
923 }
924
Eric Laurent1f2f2232014-06-02 12:01:23 -0700925 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700926
927 // increment usage count for this stream on the requested output:
928 // NOTE that the usage count is the same for duplicated output and hardware output which is
929 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
930 outputDesc->changeRefCount(stream, 1);
931
932 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700933 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700934 routing_strategy strategy = getStrategy(stream);
935 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
936 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
937 uint32_t waitMs = 0;
938 bool force = false;
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 != outputDesc) {
942 // force a device change if any other output is managed by the same hw
943 // module and has a current device selection that differs from selected device.
944 // In this case, the audio HAL must receive the new device selection so that it can
945 // change the device currently selected by the other active output.
946 if (outputDesc->sharesHwModuleWith(desc) &&
947 desc->device() != newDevice) {
948 force = true;
949 }
950 // wait for audio on other active outputs to be presented when starting
951 // a notification so that audio focus effect can propagate.
952 uint32_t latency = desc->latency();
953 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
954 waitMs = latency;
955 }
956 }
957 }
958 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
959
960 // handle special case for sonification while in call
961 if (isInCall()) {
962 handleIncallSonification(stream, true, false);
963 }
964
965 // apply volume rules for current stream and device if necessary
966 checkAndSetVolume(stream,
967 mStreams[stream].getVolumeIndex(newDevice),
968 output,
969 newDevice);
970
971 // update the outputs if starting an output with a stream that can affect notification
972 // routing
973 handleNotificationRoutingForStream(stream);
974 if (waitMs > muteWaitMs) {
975 usleep((waitMs - muteWaitMs) * 2 * 1000);
976 }
977 }
978 return NO_ERROR;
979}
980
981
Eric Laurente0720872014-03-11 09:30:41 -0700982status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700983 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700984 int session)
985{
986 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
987 ssize_t index = mOutputs.indexOfKey(output);
988 if (index < 0) {
989 ALOGW("stopOutput() unknown output %d", output);
990 return BAD_VALUE;
991 }
992
Eric Laurent1f2f2232014-06-02 12:01:23 -0700993 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700994
995 // handle special case for sonification while in call
996 if (isInCall()) {
997 handleIncallSonification(stream, false, false);
998 }
999
1000 if (outputDesc->mRefCount[stream] > 0) {
1001 // decrement usage count of this stream on the output
1002 outputDesc->changeRefCount(stream, -1);
1003 // store time at which the stream was stopped - see isStreamActive()
1004 if (outputDesc->mRefCount[stream] == 0) {
1005 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001006 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001007 // delay the device switch by twice the latency because stopOutput() is executed when
1008 // the track stop() command is received and at that time the audio track buffer can
1009 // still contain data that needs to be drained. The latency only covers the audio HAL
1010 // and kernel buffers. Also the latency does not always include additional delay in the
1011 // audio path (audio DSP, CODEC ...)
1012 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1013
1014 // force restoring the device selection on other active outputs if it differs from the
1015 // one being selected for this output
1016 for (size_t i = 0; i < mOutputs.size(); i++) {
1017 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001018 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001019 if (curOutput != output &&
1020 desc->isActive() &&
1021 outputDesc->sharesHwModuleWith(desc) &&
1022 (newDevice != desc->device())) {
1023 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001024 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001025 true,
1026 outputDesc->mLatency*2);
1027 }
1028 }
1029 // update the outputs if stopping one with a stream that can affect notification routing
1030 handleNotificationRoutingForStream(stream);
1031 }
1032 return NO_ERROR;
1033 } else {
1034 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1035 return INVALID_OPERATION;
1036 }
1037}
1038
Eric Laurente0720872014-03-11 09:30:41 -07001039void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001040{
1041 ALOGV("releaseOutput() %d", output);
1042 ssize_t index = mOutputs.indexOfKey(output);
1043 if (index < 0) {
1044 ALOGW("releaseOutput() releasing unknown output %d", output);
1045 return;
1046 }
1047
1048#ifdef AUDIO_POLICY_TEST
1049 int testIndex = testOutputIndex(output);
1050 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001051 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001052 if (outputDesc->isActive()) {
1053 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 mOutputs.removeItem(output);
1055 mTestOutputs[testIndex] = 0;
1056 }
1057 return;
1058 }
1059#endif //AUDIO_POLICY_TEST
1060
Eric Laurent1f2f2232014-06-02 12:01:23 -07001061 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001062 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001063 if (desc->mDirectOpenCount <= 0) {
1064 ALOGW("releaseOutput() invalid open count %d for output %d",
1065 desc->mDirectOpenCount, output);
1066 return;
1067 }
1068 if (--desc->mDirectOpenCount == 0) {
1069 closeOutput(output);
1070 // If effects where present on the output, audioflinger moved them to the primary
1071 // output by default: move them back to the appropriate output.
1072 audio_io_handle_t dstOutput = getOutputForEffect();
1073 if (dstOutput != mPrimaryOutput) {
1074 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1075 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001076 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001077 }
1078 }
1079}
1080
1081
Eric Laurente0720872014-03-11 09:30:41 -07001082audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001083 uint32_t samplingRate,
1084 audio_format_t format,
1085 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001086 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001087 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001088{
Eric Laurent4dc68062014-07-28 17:26:49 -07001089 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001090 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001091 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001092
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001093 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001094
1095 if (device == AUDIO_DEVICE_NONE) {
1096 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001097 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001098 }
1099
1100 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001101 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001102 case AUDIO_SOURCE_VOICE_UPLINK:
1103 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1104 break;
1105 case AUDIO_SOURCE_VOICE_DOWNLINK:
1106 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1107 break;
1108 case AUDIO_SOURCE_VOICE_CALL:
1109 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1110 break;
1111 default:
1112 break;
1113 }
1114
Eric Laurent1c333e22014-05-20 10:48:17 -07001115 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001116 samplingRate,
1117 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001118 channelMask,
1119 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001120 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001121 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1122 "channelMask 0x%X, flags %#x",
1123 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001124 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001125 }
1126
1127 if (profile->mModule->mHandle == 0) {
1128 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001129 return AUDIO_IO_HANDLE_NONE;
1130 }
1131
1132 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1133 config.sample_rate = samplingRate;
1134 config.channel_mask = channelMask;
1135 config.format = format;
1136 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001137
1138 bool isSoundTrigger = false;
1139 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1140 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1141 if (index >= 0) {
1142 input = mSoundTriggerSessions.valueFor(session);
1143 isSoundTrigger = true;
1144 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1145 }
1146 }
1147
Eric Laurentcf2c0212014-07-25 16:20:43 -07001148 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1149 &input,
1150 &config,
1151 &device,
1152 String8(""),
1153 inputSource,
1154 flags);
1155
1156 // only accept input with the exact requested set of parameters
1157 if (status != NO_ERROR ||
1158 (samplingRate != config.sample_rate) ||
1159 (format != config.format) ||
1160 (channelMask != config.channel_mask)) {
1161 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1162 samplingRate, format, channelMask);
1163 if (input != AUDIO_IO_HANDLE_NONE) {
1164 mpClientInterface->closeInput(input);
1165 }
1166 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001167 }
1168
Eric Laurent1f2f2232014-06-02 12:01:23 -07001169 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001170 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001171 inputDesc->mRefCount = 0;
1172 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001173 inputDesc->mSamplingRate = samplingRate;
1174 inputDesc->mFormat = format;
1175 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001176 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001177 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001178 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001179
Eric Laurentd4692962014-05-05 18:13:44 -07001180 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001181 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001182 return input;
1183}
1184
Eric Laurent4dc68062014-07-28 17:26:49 -07001185status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1186 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001187{
1188 ALOGV("startInput() input %d", input);
1189 ssize_t index = mInputs.indexOfKey(input);
1190 if (index < 0) {
1191 ALOGW("startInput() unknown input %d", input);
1192 return BAD_VALUE;
1193 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001194 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001195
Eric Laurent4dc68062014-07-28 17:26:49 -07001196 index = inputDesc->mSessions.indexOf(session);
1197 if (index < 0) {
1198 ALOGW("startInput() unknown session %d on input %d", session, input);
1199 return BAD_VALUE;
1200 }
1201
Glenn Kasten74a8e252014-07-24 14:09:55 -07001202 // virtual input devices are compatible with other input devices
1203 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1204
1205 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001206 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001207 if (activeInput != 0 && activeInput != input) {
1208
1209 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1210 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001211 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001212 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001213 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001214 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1215 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001216 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001217 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001218 return INVALID_OPERATION;
1219 }
1220 }
1221 }
1222
Glenn Kasten74a8e252014-07-24 14:09:55 -07001223 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001224 if (activeInputsCount() == 0) {
1225 SoundTrigger::setCaptureState(true);
1226 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001227 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001228
Glenn Kasten74a8e252014-07-24 14:09:55 -07001229 // Automatically enable the remote submix output when input is started.
1230 // For remote submix (a virtual device), we open only one input per capture request.
1231 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1232 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1233 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1234 }
Eric Laurente552edb2014-03-10 17:42:56 -07001235 }
1236
Eric Laurente552edb2014-03-10 17:42:56 -07001237 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1238
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001239 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001240 return NO_ERROR;
1241}
1242
Eric Laurent4dc68062014-07-28 17:26:49 -07001243status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1244 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001245{
1246 ALOGV("stopInput() input %d", input);
1247 ssize_t index = mInputs.indexOfKey(input);
1248 if (index < 0) {
1249 ALOGW("stopInput() unknown input %d", input);
1250 return BAD_VALUE;
1251 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001252 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001253
Eric Laurent4dc68062014-07-28 17:26:49 -07001254 index = inputDesc->mSessions.indexOf(session);
1255 if (index < 0) {
1256 ALOGW("stopInput() unknown session %d on input %d", session, input);
1257 return BAD_VALUE;
1258 }
1259
Eric Laurente552edb2014-03-10 17:42:56 -07001260 if (inputDesc->mRefCount == 0) {
1261 ALOGW("stopInput() input %d already stopped", input);
1262 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001263 }
1264
1265 inputDesc->mRefCount--;
1266 if (inputDesc->mRefCount == 0) {
1267
Eric Laurente552edb2014-03-10 17:42:56 -07001268 // automatically disable the remote submix output when input is stopped
1269 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1270 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001271 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001272 }
1273
Eric Laurent1c333e22014-05-20 10:48:17 -07001274 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001275
1276 if (activeInputsCount() == 0) {
1277 SoundTrigger::setCaptureState(false);
1278 }
Eric Laurente552edb2014-03-10 17:42:56 -07001279 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001280 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001281}
1282
Eric Laurent4dc68062014-07-28 17:26:49 -07001283void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1284 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001285{
1286 ALOGV("releaseInput() %d", input);
1287 ssize_t index = mInputs.indexOfKey(input);
1288 if (index < 0) {
1289 ALOGW("releaseInput() releasing unknown input %d", input);
1290 return;
1291 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001292 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1293 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001294
1295 index = inputDesc->mSessions.indexOf(session);
1296 if (index < 0) {
1297 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1298 return;
1299 }
1300 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001301 if (inputDesc->mOpenRefCount == 0) {
1302 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1303 return;
1304 }
1305 inputDesc->mOpenRefCount--;
1306 if (inputDesc->mOpenRefCount > 0) {
1307 ALOGV("releaseInput() exit > 0");
1308 return;
1309 }
1310
Eric Laurente552edb2014-03-10 17:42:56 -07001311 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001312 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001313 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001314 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001315 ALOGV("releaseInput() exit");
1316}
1317
Eric Laurentd4692962014-05-05 18:13:44 -07001318void AudioPolicyManager::closeAllInputs() {
1319 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1320 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1321 }
1322 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001323 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001324}
1325
Eric Laurente0720872014-03-11 09:30:41 -07001326void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001327 int indexMin,
1328 int indexMax)
1329{
1330 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1331 if (indexMin < 0 || indexMin >= indexMax) {
1332 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1333 return;
1334 }
1335 mStreams[stream].mIndexMin = indexMin;
1336 mStreams[stream].mIndexMax = indexMax;
1337}
1338
Eric Laurente0720872014-03-11 09:30:41 -07001339status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001340 int index,
1341 audio_devices_t device)
1342{
1343
1344 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1345 return BAD_VALUE;
1346 }
1347 if (!audio_is_output_device(device)) {
1348 return BAD_VALUE;
1349 }
1350
1351 // Force max volume if stream cannot be muted
1352 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1353
1354 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1355 stream, device, index);
1356
1357 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1358 // clear all device specific values
1359 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1360 mStreams[stream].mIndexCur.clear();
1361 }
1362 mStreams[stream].mIndexCur.add(device, index);
1363
1364 // compute and apply stream volume on all outputs according to connected device
1365 status_t status = NO_ERROR;
1366 for (size_t i = 0; i < mOutputs.size(); i++) {
1367 audio_devices_t curDevice =
1368 getDeviceForVolume(mOutputs.valueAt(i)->device());
1369 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1370 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1371 if (volStatus != NO_ERROR) {
1372 status = volStatus;
1373 }
1374 }
1375 }
1376 return status;
1377}
1378
Eric Laurente0720872014-03-11 09:30:41 -07001379status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001380 int *index,
1381 audio_devices_t device)
1382{
1383 if (index == NULL) {
1384 return BAD_VALUE;
1385 }
1386 if (!audio_is_output_device(device)) {
1387 return BAD_VALUE;
1388 }
1389 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1390 // the strategy the stream belongs to.
1391 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1392 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1393 }
1394 device = getDeviceForVolume(device);
1395
1396 *index = mStreams[stream].getVolumeIndex(device);
1397 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1398 return NO_ERROR;
1399}
1400
Eric Laurente0720872014-03-11 09:30:41 -07001401audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001402 const SortedVector<audio_io_handle_t>& outputs)
1403{
1404 // select one output among several suitable for global effects.
1405 // The priority is as follows:
1406 // 1: An offloaded output. If the effect ends up not being offloadable,
1407 // AudioFlinger will invalidate the track and the offloaded output
1408 // will be closed causing the effect to be moved to a PCM output.
1409 // 2: A deep buffer output
1410 // 3: the first output in the list
1411
1412 if (outputs.size() == 0) {
1413 return 0;
1414 }
1415
1416 audio_io_handle_t outputOffloaded = 0;
1417 audio_io_handle_t outputDeepBuffer = 0;
1418
1419 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001421 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001422 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1423 outputOffloaded = outputs[i];
1424 }
1425 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1426 outputDeepBuffer = outputs[i];
1427 }
1428 }
1429
1430 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1431 outputOffloaded, outputDeepBuffer);
1432 if (outputOffloaded != 0) {
1433 return outputOffloaded;
1434 }
1435 if (outputDeepBuffer != 0) {
1436 return outputDeepBuffer;
1437 }
1438
1439 return outputs[0];
1440}
1441
Eric Laurente0720872014-03-11 09:30:41 -07001442audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001443{
1444 // apply simple rule where global effects are attached to the same output as MUSIC streams
1445
Eric Laurent3b73df72014-03-11 09:06:29 -07001446 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001447 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1448 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1449
1450 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1451 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1452 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1453
1454 return output;
1455}
1456
Eric Laurente0720872014-03-11 09:30:41 -07001457status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001458 audio_io_handle_t io,
1459 uint32_t strategy,
1460 int session,
1461 int id)
1462{
1463 ssize_t index = mOutputs.indexOfKey(io);
1464 if (index < 0) {
1465 index = mInputs.indexOfKey(io);
1466 if (index < 0) {
1467 ALOGW("registerEffect() unknown io %d", io);
1468 return INVALID_OPERATION;
1469 }
1470 }
1471
1472 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1473 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1474 desc->name, desc->memoryUsage);
1475 return INVALID_OPERATION;
1476 }
1477 mTotalEffectsMemory += desc->memoryUsage;
1478 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1479 desc->name, io, strategy, session, id);
1480 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1481
Eric Laurent1f2f2232014-06-02 12:01:23 -07001482 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1483 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1484 effectDesc->mIo = io;
1485 effectDesc->mStrategy = (routing_strategy)strategy;
1486 effectDesc->mSession = session;
1487 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001488
Eric Laurent1f2f2232014-06-02 12:01:23 -07001489 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001490
1491 return NO_ERROR;
1492}
1493
Eric Laurente0720872014-03-11 09:30:41 -07001494status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001495{
1496 ssize_t index = mEffects.indexOfKey(id);
1497 if (index < 0) {
1498 ALOGW("unregisterEffect() unknown effect ID %d", id);
1499 return INVALID_OPERATION;
1500 }
1501
Eric Laurent1f2f2232014-06-02 12:01:23 -07001502 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001503
Eric Laurent1f2f2232014-06-02 12:01:23 -07001504 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001505
Eric Laurent1f2f2232014-06-02 12:01:23 -07001506 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001507 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001508 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1509 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001510 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001511 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001512 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001513 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001514
1515 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001516
1517 return NO_ERROR;
1518}
1519
Eric Laurente0720872014-03-11 09:30:41 -07001520status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
1522 ssize_t index = mEffects.indexOfKey(id);
1523 if (index < 0) {
1524 ALOGW("unregisterEffect() unknown effect ID %d", id);
1525 return INVALID_OPERATION;
1526 }
1527
1528 return setEffectEnabled(mEffects.valueAt(index), enabled);
1529}
1530
Eric Laurent1f2f2232014-06-02 12:01:23 -07001531status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001532{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001533 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001534 ALOGV("setEffectEnabled(%s) effect already %s",
1535 enabled?"true":"false", enabled?"enabled":"disabled");
1536 return INVALID_OPERATION;
1537 }
1538
1539 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001540 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001541 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001542 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001543 return INVALID_OPERATION;
1544 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001545 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001546 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1547 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001548 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001549 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001550 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1551 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001552 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001553 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001554 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1555 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001556 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001557 return NO_ERROR;
1558}
1559
Eric Laurente0720872014-03-11 09:30:41 -07001560bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001561{
1562 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001563 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1564 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1565 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001566 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001567 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001568 return true;
1569 }
1570 }
1571 return false;
1572}
1573
Eric Laurente0720872014-03-11 09:30:41 -07001574bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001575{
1576 nsecs_t sysTime = systemTime();
1577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001578 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001579 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001580 return true;
1581 }
1582 }
1583 return false;
1584}
1585
Eric Laurente0720872014-03-11 09:30:41 -07001586bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001587 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001588{
1589 nsecs_t sysTime = systemTime();
1590 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001591 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001592 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001593 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001594 return true;
1595 }
1596 }
1597 return false;
1598}
1599
Eric Laurente0720872014-03-11 09:30:41 -07001600bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001601{
1602 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001603 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001604 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001605 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001606 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1607 && (inputDescriptor->mRefCount > 0)) {
1608 return true;
1609 }
1610 }
1611 return false;
1612}
1613
1614
Eric Laurente0720872014-03-11 09:30:41 -07001615status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001616{
1617 const size_t SIZE = 256;
1618 char buffer[SIZE];
1619 String8 result;
1620
1621 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1622 result.append(buffer);
1623
1624 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1625 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001626 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1627 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001628 snprintf(buffer, SIZE, " Force use for communications %d\n",
1629 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001630 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001631 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001632 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001633 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001634 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001635 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001636 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001637 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001638 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001639 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1640 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1641 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001642
Eric Laurent3a4311c2014-03-17 12:00:47 -07001643 snprintf(buffer, SIZE, " Available output devices:\n");
1644 result.append(buffer);
1645 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001646 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001647 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001648 }
1649 snprintf(buffer, SIZE, "\n Available input devices:\n");
1650 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001651 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001652 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001653 }
Eric Laurente552edb2014-03-10 17:42:56 -07001654
1655 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1656 write(fd, buffer, strlen(buffer));
1657 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001658 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001659 write(fd, buffer, strlen(buffer));
1660 mHwModules[i]->dump(fd);
1661 }
1662
1663 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1664 write(fd, buffer, strlen(buffer));
1665 for (size_t i = 0; i < mOutputs.size(); i++) {
1666 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1667 write(fd, buffer, strlen(buffer));
1668 mOutputs.valueAt(i)->dump(fd);
1669 }
1670
1671 snprintf(buffer, SIZE, "\nInputs dump:\n");
1672 write(fd, buffer, strlen(buffer));
1673 for (size_t i = 0; i < mInputs.size(); i++) {
1674 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1675 write(fd, buffer, strlen(buffer));
1676 mInputs.valueAt(i)->dump(fd);
1677 }
1678
1679 snprintf(buffer, SIZE, "\nStreams dump:\n");
1680 write(fd, buffer, strlen(buffer));
1681 snprintf(buffer, SIZE,
1682 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1683 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001684 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001685 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001686 write(fd, buffer, strlen(buffer));
1687 mStreams[i].dump(fd);
1688 }
1689
1690 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1691 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1692 write(fd, buffer, strlen(buffer));
1693
1694 snprintf(buffer, SIZE, "Registered effects:\n");
1695 write(fd, buffer, strlen(buffer));
1696 for (size_t i = 0; i < mEffects.size(); i++) {
1697 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1698 write(fd, buffer, strlen(buffer));
1699 mEffects.valueAt(i)->dump(fd);
1700 }
1701
1702
1703 return NO_ERROR;
1704}
1705
1706// This function checks for the parameters which can be offloaded.
1707// This can be enhanced depending on the capability of the DSP and policy
1708// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001709bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001710{
1711 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001712 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001713 offloadInfo.sample_rate, offloadInfo.channel_mask,
1714 offloadInfo.format,
1715 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1716 offloadInfo.has_video);
1717
1718 // Check if offload has been disabled
1719 char propValue[PROPERTY_VALUE_MAX];
1720 if (property_get("audio.offload.disable", propValue, "0")) {
1721 if (atoi(propValue) != 0) {
1722 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1723 return false;
1724 }
1725 }
1726
1727 // Check if stream type is music, then only allow offload as of now.
1728 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1729 {
1730 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1731 return false;
1732 }
1733
1734 //TODO: enable audio offloading with video when ready
1735 if (offloadInfo.has_video)
1736 {
1737 ALOGV("isOffloadSupported: has_video == true, returning false");
1738 return false;
1739 }
1740
1741 //If duration is less than minimum value defined in property, return false
1742 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1743 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1744 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1745 return false;
1746 }
1747 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1748 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1749 return false;
1750 }
1751
1752 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1753 // creating an offloaded track and tearing it down immediately after start when audioflinger
1754 // detects there is an active non offloadable effect.
1755 // FIXME: We should check the audio session here but we do not have it in this context.
1756 // This may prevent offloading in rare situations where effects are left active by apps
1757 // in the background.
1758 if (isNonOffloadableEffectEnabled()) {
1759 return false;
1760 }
1761
1762 // See if there is a profile to support this.
1763 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001764 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001765 offloadInfo.sample_rate,
1766 offloadInfo.format,
1767 offloadInfo.channel_mask,
1768 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001769 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1770 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001771}
1772
Eric Laurent6a94d692014-05-20 11:18:06 -07001773status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1774 audio_port_type_t type,
1775 unsigned int *num_ports,
1776 struct audio_port *ports,
1777 unsigned int *generation)
1778{
1779 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1780 generation == NULL) {
1781 return BAD_VALUE;
1782 }
1783 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1784 if (ports == NULL) {
1785 *num_ports = 0;
1786 }
1787
1788 size_t portsWritten = 0;
1789 size_t portsMax = *num_ports;
1790 *num_ports = 0;
1791 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1792 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1793 for (size_t i = 0;
1794 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1795 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1796 }
1797 *num_ports += mAvailableOutputDevices.size();
1798 }
1799 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1800 for (size_t i = 0;
1801 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1802 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1803 }
1804 *num_ports += mAvailableInputDevices.size();
1805 }
1806 }
1807 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1808 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1809 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1810 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1811 }
1812 *num_ports += mInputs.size();
1813 }
1814 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001815 size_t numOutputs = 0;
1816 for (size_t i = 0; i < mOutputs.size(); i++) {
1817 if (!mOutputs[i]->isDuplicated()) {
1818 numOutputs++;
1819 if (portsWritten < portsMax) {
1820 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1821 }
1822 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001823 }
Eric Laurent84c70242014-06-23 08:46:27 -07001824 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001825 }
1826 }
1827 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001828 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001829 return NO_ERROR;
1830}
1831
1832status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1833{
1834 return NO_ERROR;
1835}
1836
Eric Laurent1f2f2232014-06-02 12:01:23 -07001837sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001838 audio_port_handle_t id) const
1839{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001840 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001841 for (size_t i = 0; i < mOutputs.size(); i++) {
1842 outputDesc = mOutputs.valueAt(i);
1843 if (outputDesc->mId == id) {
1844 break;
1845 }
1846 }
1847 return outputDesc;
1848}
1849
Eric Laurent1f2f2232014-06-02 12:01:23 -07001850sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001851 audio_port_handle_t id) const
1852{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001854 for (size_t i = 0; i < mInputs.size(); i++) {
1855 inputDesc = mInputs.valueAt(i);
1856 if (inputDesc->mId == id) {
1857 break;
1858 }
1859 }
1860 return inputDesc;
1861}
1862
Eric Laurent1f2f2232014-06-02 12:01:23 -07001863sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1864 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001865{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001866 sp <HwModule> module;
1867
Eric Laurent6a94d692014-05-20 11:18:06 -07001868 for (size_t i = 0; i < mHwModules.size(); i++) {
1869 if (mHwModules[i]->mHandle == 0) {
1870 continue;
1871 }
1872 if (audio_is_output_device(device)) {
1873 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1874 {
1875 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1876 return mHwModules[i];
1877 }
1878 }
1879 } else {
1880 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1881 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1882 device & ~AUDIO_DEVICE_BIT_IN) {
1883 return mHwModules[i];
1884 }
1885 }
1886 }
1887 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001888 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001889}
1890
Eric Laurent1f2f2232014-06-02 12:01:23 -07001891sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001892{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001893 sp <HwModule> module;
1894
Eric Laurent1afeecb2014-05-14 08:52:28 -07001895 for (size_t i = 0; i < mHwModules.size(); i++)
1896 {
1897 if (strcmp(mHwModules[i]->mName, name) == 0) {
1898 return mHwModules[i];
1899 }
1900 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001901 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001902}
1903
1904
Eric Laurent6a94d692014-05-20 11:18:06 -07001905status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1906 audio_patch_handle_t *handle,
1907 uid_t uid)
1908{
1909 ALOGV("createAudioPatch()");
1910
1911 if (handle == NULL || patch == NULL) {
1912 return BAD_VALUE;
1913 }
1914 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1915
1916 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1917 return INVALID_OPERATION;
1918 }
1919 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1920 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1921 return INVALID_OPERATION;
1922 }
1923
1924 sp<AudioPatch> patchDesc;
1925 ssize_t index = mAudioPatches.indexOfKey(*handle);
1926
1927 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1928 patch->sinks[0].type);
1929 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1930 patch->sources[0].role,
1931 patch->sources[0].type);
1932
1933 if (index >= 0) {
1934 patchDesc = mAudioPatches.valueAt(index);
1935 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1936 mUidCached, patchDesc->mUid, uid);
1937 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1938 return INVALID_OPERATION;
1939 }
1940 } else {
1941 *handle = 0;
1942 }
1943
1944 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1945 // TODO add support for mix to mix connection
1946 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1947 ALOGV("createAudioPatch() source mix sink not device");
1948 return BAD_VALUE;
1949 }
1950 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001951 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001952 if (outputDesc == NULL) {
1953 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1954 return BAD_VALUE;
1955 }
Eric Laurent84c70242014-06-23 08:46:27 -07001956 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1957 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001958 if (patchDesc != 0) {
1959 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1960 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1961 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1962 return BAD_VALUE;
1963 }
1964 }
1965 sp<DeviceDescriptor> devDesc =
1966 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1967 if (devDesc == 0) {
1968 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1969 return BAD_VALUE;
1970 }
1971
Eric Laurent84c70242014-06-23 08:46:27 -07001972 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001973 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001974 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001975 patch->sources[0].format,
1976 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001977 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001978 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001979 return INVALID_OPERATION;
1980 }
1981 // TODO: reconfigure output format and channels here
1982 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001983 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001984 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001985 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001986 true,
1987 0,
1988 handle);
1989 index = mAudioPatches.indexOfKey(*handle);
1990 if (index >= 0) {
1991 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1992 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1993 }
1994 patchDesc = mAudioPatches.valueAt(index);
1995 patchDesc->mUid = uid;
1996 ALOGV("createAudioPatch() success");
1997 } else {
1998 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1999 return INVALID_OPERATION;
2000 }
2001 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2002 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2003 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07002004 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002005 if (inputDesc == NULL) {
2006 return BAD_VALUE;
2007 }
2008 if (patchDesc != 0) {
2009 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2010 return BAD_VALUE;
2011 }
2012 }
2013 sp<DeviceDescriptor> devDesc =
2014 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2015 if (devDesc == 0) {
2016 return BAD_VALUE;
2017 }
2018
Eric Laurent84c70242014-06-23 08:46:27 -07002019 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002020 patch->sinks[0].sample_rate,
2021 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002022 patch->sinks[0].format,
2023 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002024 // FIXME for the parameter type,
2025 // and the NONE
2026 (audio_output_flags_t)
2027 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002028 return INVALID_OPERATION;
2029 }
2030 // TODO: reconfigure output format and channels here
2031 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002032 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002033 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002034 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002035 true,
2036 handle);
2037 index = mAudioPatches.indexOfKey(*handle);
2038 if (index >= 0) {
2039 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2040 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2041 }
2042 patchDesc = mAudioPatches.valueAt(index);
2043 patchDesc->mUid = uid;
2044 ALOGV("createAudioPatch() success");
2045 } else {
2046 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2047 return INVALID_OPERATION;
2048 }
2049 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2050 // device to device connection
2051 if (patchDesc != 0) {
2052 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2053 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2054 return BAD_VALUE;
2055 }
2056 }
2057
2058 sp<DeviceDescriptor> srcDeviceDesc =
2059 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2060 sp<DeviceDescriptor> sinkDeviceDesc =
2061 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2062 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2063 return BAD_VALUE;
2064 }
2065 //update source and sink with our own data as the data passed in the patch may
2066 // be incomplete.
2067 struct audio_patch newPatch = *patch;
2068 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2069 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2070
Eric Laurent6a94d692014-05-20 11:18:06 -07002071 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002072 SortedVector<audio_io_handle_t> outputs =
2073 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2074 // if the sink device is reachable via an opened output stream, request to go via
2075 // this output stream by adding a second source to the patch description
2076 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2077 if (output != AUDIO_IO_HANDLE_NONE) {
2078 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2079 if (outputDesc->isDuplicated()) {
2080 return INVALID_OPERATION;
2081 }
2082 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2083 newPatch.num_sources = 2;
2084 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002085 }
2086 // TODO: check from routing capabilities in config file and other conflicting patches
2087
2088 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2089 if (index >= 0) {
2090 afPatchHandle = patchDesc->mAfPatchHandle;
2091 }
2092
2093 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2094 &afPatchHandle,
2095 0);
2096 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2097 status, afPatchHandle);
2098 if (status == NO_ERROR) {
2099 if (index < 0) {
2100 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2101 &newPatch, uid);
2102 addAudioPatch(patchDesc->mHandle, patchDesc);
2103 } else {
2104 patchDesc->mPatch = newPatch;
2105 }
2106 patchDesc->mAfPatchHandle = afPatchHandle;
2107 *handle = patchDesc->mHandle;
2108 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002109 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002110 } else {
2111 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2112 status);
2113 return INVALID_OPERATION;
2114 }
2115 } else {
2116 return BAD_VALUE;
2117 }
2118 } else {
2119 return BAD_VALUE;
2120 }
2121 return NO_ERROR;
2122}
2123
2124status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2125 uid_t uid)
2126{
2127 ALOGV("releaseAudioPatch() patch %d", handle);
2128
2129 ssize_t index = mAudioPatches.indexOfKey(handle);
2130
2131 if (index < 0) {
2132 return BAD_VALUE;
2133 }
2134 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2135 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2136 mUidCached, patchDesc->mUid, uid);
2137 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2138 return INVALID_OPERATION;
2139 }
2140
2141 struct audio_patch *patch = &patchDesc->mPatch;
2142 patchDesc->mUid = mUidCached;
2143 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002144 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002145 if (outputDesc == NULL) {
2146 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2147 return BAD_VALUE;
2148 }
2149
2150 setOutputDevice(outputDesc->mIoHandle,
2151 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2152 true,
2153 0,
2154 NULL);
2155 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2156 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002157 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002158 if (inputDesc == NULL) {
2159 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2160 return BAD_VALUE;
2161 }
2162 setInputDevice(inputDesc->mIoHandle,
2163 getNewInputDevice(inputDesc->mIoHandle),
2164 true,
2165 NULL);
2166 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2167 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2168 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2169 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2170 status, patchDesc->mAfPatchHandle);
2171 removeAudioPatch(patchDesc->mHandle);
2172 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002173 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002174 } else {
2175 return BAD_VALUE;
2176 }
2177 } else {
2178 return BAD_VALUE;
2179 }
2180 return NO_ERROR;
2181}
2182
2183status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2184 struct audio_patch *patches,
2185 unsigned int *generation)
2186{
2187 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2188 generation == NULL) {
2189 return BAD_VALUE;
2190 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002191 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002192 *num_patches, patches, mAudioPatches.size());
2193 if (patches == NULL) {
2194 *num_patches = 0;
2195 }
2196
2197 size_t patchesWritten = 0;
2198 size_t patchesMax = *num_patches;
2199 for (size_t i = 0;
2200 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2201 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2202 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002203 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002204 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2205 }
2206 *num_patches = mAudioPatches.size();
2207
2208 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002209 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002210 return NO_ERROR;
2211}
2212
Eric Laurente1715a42014-05-20 11:30:42 -07002213status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002214{
Eric Laurente1715a42014-05-20 11:30:42 -07002215 ALOGV("setAudioPortConfig()");
2216
2217 if (config == NULL) {
2218 return BAD_VALUE;
2219 }
2220 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2221 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002222 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2223 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002224 }
2225
Eric Laurenta121f902014-06-03 13:32:54 -07002226 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002227 if (config->type == AUDIO_PORT_TYPE_MIX) {
2228 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002229 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002230 if (outputDesc == NULL) {
2231 return BAD_VALUE;
2232 }
Eric Laurent84c70242014-06-23 08:46:27 -07002233 ALOG_ASSERT(!outputDesc->isDuplicated(),
2234 "setAudioPortConfig() called on duplicated output %d",
2235 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002236 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002237 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002238 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002239 if (inputDesc == NULL) {
2240 return BAD_VALUE;
2241 }
Eric Laurenta121f902014-06-03 13:32:54 -07002242 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002243 } else {
2244 return BAD_VALUE;
2245 }
2246 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2247 sp<DeviceDescriptor> deviceDesc;
2248 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2249 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2250 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2251 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2252 } else {
2253 return BAD_VALUE;
2254 }
2255 if (deviceDesc == NULL) {
2256 return BAD_VALUE;
2257 }
Eric Laurenta121f902014-06-03 13:32:54 -07002258 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002259 } else {
2260 return BAD_VALUE;
2261 }
2262
Eric Laurenta121f902014-06-03 13:32:54 -07002263 struct audio_port_config backupConfig;
2264 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2265 if (status == NO_ERROR) {
2266 struct audio_port_config newConfig;
2267 audioPortConfig->toAudioPortConfig(&newConfig, config);
2268 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002269 }
Eric Laurenta121f902014-06-03 13:32:54 -07002270 if (status != NO_ERROR) {
2271 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002272 }
Eric Laurente1715a42014-05-20 11:30:42 -07002273
2274 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002275}
2276
2277void AudioPolicyManager::clearAudioPatches(uid_t uid)
2278{
2279 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2280 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2281 if (patchDesc->mUid == uid) {
2282 // releaseAudioPatch() removes the patch from mAudioPatches
2283 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2284 i--;
2285 }
2286 }
2287 }
2288}
2289
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002290status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2291 audio_io_handle_t *ioHandle,
2292 audio_devices_t *device)
2293{
2294 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2295 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2296 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2297
2298 mSoundTriggerSessions.add(*session, *ioHandle);
2299
2300 return NO_ERROR;
2301}
2302
2303status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2304{
2305 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2306 if (index < 0) {
2307 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2308 return BAD_VALUE;
2309 }
2310
2311 mSoundTriggerSessions.removeItem(session);
2312 return NO_ERROR;
2313}
2314
Eric Laurent6a94d692014-05-20 11:18:06 -07002315status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2316 const sp<AudioPatch>& patch)
2317{
2318 ssize_t index = mAudioPatches.indexOfKey(handle);
2319
2320 if (index >= 0) {
2321 ALOGW("addAudioPatch() patch %d already in", handle);
2322 return ALREADY_EXISTS;
2323 }
2324 mAudioPatches.add(handle, patch);
2325 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2326 "sink handle %d",
2327 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2328 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2329 return NO_ERROR;
2330}
2331
2332status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2333{
2334 ssize_t index = mAudioPatches.indexOfKey(handle);
2335
2336 if (index < 0) {
2337 ALOGW("removeAudioPatch() patch %d not in", handle);
2338 return ALREADY_EXISTS;
2339 }
2340 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2341 mAudioPatches.valueAt(index)->mAfPatchHandle);
2342 mAudioPatches.removeItemsAt(index);
2343 return NO_ERROR;
2344}
2345
Eric Laurente552edb2014-03-10 17:42:56 -07002346// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002347// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002348// ----------------------------------------------------------------------------
2349
Eric Laurent3a4311c2014-03-17 12:00:47 -07002350uint32_t AudioPolicyManager::nextUniqueId()
2351{
2352 return android_atomic_inc(&mNextUniqueId);
2353}
2354
Eric Laurent6a94d692014-05-20 11:18:06 -07002355uint32_t AudioPolicyManager::nextAudioPortGeneration()
2356{
2357 return android_atomic_inc(&mAudioPortGeneration);
2358}
2359
Eric Laurente0720872014-03-11 09:30:41 -07002360AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002361 :
2362#ifdef AUDIO_POLICY_TEST
2363 Thread(false),
2364#endif //AUDIO_POLICY_TEST
2365 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002366 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002367 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2368 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002369 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002370 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2371 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002372{
Eric Laurent6a94d692014-05-20 11:18:06 -07002373 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002374 mpClientInterface = clientInterface;
2375
Eric Laurent3b73df72014-03-11 09:06:29 -07002376 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2377 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002378 }
2379
Eric Laurent1afeecb2014-05-14 08:52:28 -07002380 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002381 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2382 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2383 ALOGE("could not load audio policy configuration file, setting defaults");
2384 defaultAudioPolicyConfig();
2385 }
2386 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002387 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002388
2389 // must be done after reading the policy
2390 initializeVolumeCurves();
2391
2392 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002393 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2394 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002395 for (size_t i = 0; i < mHwModules.size(); i++) {
2396 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2397 if (mHwModules[i]->mHandle == 0) {
2398 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2399 continue;
2400 }
2401 // open all output streams needed to access attached devices
2402 // except for direct output streams that are only opened when they are actually
2403 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002404 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002405 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2406 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002407 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002408
Eric Laurent3a4311c2014-03-17 12:00:47 -07002409 if (outProfile->mSupportedDevices.isEmpty()) {
2410 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2411 continue;
2412 }
2413
Eric Laurent83b88082014-06-20 18:31:16 -07002414 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2415 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2416 profileType = mDefaultOutputDevice->mDeviceType;
2417 } else {
2418 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2419 }
2420 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002421 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002422 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002423
Eric Laurent83b88082014-06-20 18:31:16 -07002424 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002425 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2426 config.sample_rate = outputDesc->mSamplingRate;
2427 config.channel_mask = outputDesc->mChannelMask;
2428 config.format = outputDesc->mFormat;
2429 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2430 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2431 &output,
2432 &config,
2433 &outputDesc->mDevice,
2434 String8(""),
2435 &outputDesc->mLatency,
2436 outputDesc->mFlags);
2437
2438 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002439 ALOGW("Cannot open output stream for device %08x on hw module %s",
2440 outputDesc->mDevice,
2441 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002442 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002443 outputDesc->mSamplingRate = config.sample_rate;
2444 outputDesc->mChannelMask = config.channel_mask;
2445 outputDesc->mFormat = config.format;
2446
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002447 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002448 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002449 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002450 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002451 // give a valid ID to an attached device once confirmed it is reachable
2452 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2453 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002454 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002455 }
2456 }
Eric Laurente552edb2014-03-10 17:42:56 -07002457 if (mPrimaryOutput == 0 &&
2458 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2459 mPrimaryOutput = output;
2460 }
2461 addOutput(output, outputDesc);
2462 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002463 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002464 true);
2465 }
2466 }
2467 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002468 // open input streams needed to access attached devices to validate
2469 // mAvailableInputDevices list
2470 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2471 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002472 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002473
Eric Laurent3a4311c2014-03-17 12:00:47 -07002474 if (inProfile->mSupportedDevices.isEmpty()) {
2475 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2476 continue;
2477 }
2478
Eric Laurent83b88082014-06-20 18:31:16 -07002479 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2480 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002481 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002482
2483 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002484 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002485
Eric Laurentcf2c0212014-07-25 16:20:43 -07002486 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2487 config.sample_rate = inputDesc->mSamplingRate;
2488 config.channel_mask = inputDesc->mChannelMask;
2489 config.format = inputDesc->mFormat;
2490 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2491 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2492 &input,
2493 &config,
2494 &inputDesc->mDevice,
2495 String8(""),
2496 AUDIO_SOURCE_MIC,
2497 AUDIO_INPUT_FLAG_NONE);
2498
2499 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002500 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002501 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002502 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002503 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002504 // give a valid ID to an attached device once confirmed it is reachable
2505 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2506 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002507 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002508 }
2509 }
2510 mpClientInterface->closeInput(input);
2511 } else {
2512 ALOGW("Cannot open input stream for device %08x on hw module %s",
2513 inputDesc->mDevice,
2514 mHwModules[i]->mName);
2515 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002516 }
2517 }
2518 }
2519 // make sure all attached devices have been allocated a unique ID
2520 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2521 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002522 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002523 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2524 continue;
2525 }
2526 i++;
2527 }
2528 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2529 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002530 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002531 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2532 continue;
2533 }
2534 i++;
2535 }
2536 // make sure default device is reachable
2537 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002538 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002539 }
Eric Laurente552edb2014-03-10 17:42:56 -07002540
2541 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2542
2543 updateDevicesAndOutputs();
2544
2545#ifdef AUDIO_POLICY_TEST
2546 if (mPrimaryOutput != 0) {
2547 AudioParameter outputCmd = AudioParameter();
2548 outputCmd.addInt(String8("set_id"), 0);
2549 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2550
2551 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2552 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002553 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2554 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002555 mTestLatencyMs = 0;
2556 mCurOutput = 0;
2557 mDirectOutput = false;
2558 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2559 mTestOutputs[i] = 0;
2560 }
2561
2562 const size_t SIZE = 256;
2563 char buffer[SIZE];
2564 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2565 run(buffer, ANDROID_PRIORITY_AUDIO);
2566 }
2567#endif //AUDIO_POLICY_TEST
2568}
2569
Eric Laurente0720872014-03-11 09:30:41 -07002570AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002571{
2572#ifdef AUDIO_POLICY_TEST
2573 exit();
2574#endif //AUDIO_POLICY_TEST
2575 for (size_t i = 0; i < mOutputs.size(); i++) {
2576 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002577 }
2578 for (size_t i = 0; i < mInputs.size(); i++) {
2579 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002580 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002581 mAvailableOutputDevices.clear();
2582 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002583 mOutputs.clear();
2584 mInputs.clear();
2585 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002586}
2587
Eric Laurente0720872014-03-11 09:30:41 -07002588status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002589{
2590 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2591}
2592
2593#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002594bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002595{
2596 ALOGV("entering threadLoop()");
2597 while (!exitPending())
2598 {
2599 String8 command;
2600 int valueInt;
2601 String8 value;
2602
2603 Mutex::Autolock _l(mLock);
2604 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2605
2606 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2607 AudioParameter param = AudioParameter(command);
2608
2609 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2610 valueInt != 0) {
2611 ALOGV("Test command %s received", command.string());
2612 String8 target;
2613 if (param.get(String8("target"), target) != NO_ERROR) {
2614 target = "Manager";
2615 }
2616 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2617 param.remove(String8("test_cmd_policy_output"));
2618 mCurOutput = valueInt;
2619 }
2620 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2621 param.remove(String8("test_cmd_policy_direct"));
2622 if (value == "false") {
2623 mDirectOutput = false;
2624 } else if (value == "true") {
2625 mDirectOutput = true;
2626 }
2627 }
2628 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2629 param.remove(String8("test_cmd_policy_input"));
2630 mTestInput = valueInt;
2631 }
2632
2633 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2634 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002635 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002636 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002637 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002638 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002639 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002640 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002641 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002642 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002643 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002644 if (target == "Manager") {
2645 mTestFormat = format;
2646 } else if (mTestOutputs[mCurOutput] != 0) {
2647 AudioParameter outputParam = AudioParameter();
2648 outputParam.addInt(String8("format"), format);
2649 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2650 }
2651 }
2652 }
2653 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2654 param.remove(String8("test_cmd_policy_channels"));
2655 int channels = 0;
2656
2657 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002658 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002659 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002660 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
2662 if (channels != 0) {
2663 if (target == "Manager") {
2664 mTestChannels = channels;
2665 } else if (mTestOutputs[mCurOutput] != 0) {
2666 AudioParameter outputParam = AudioParameter();
2667 outputParam.addInt(String8("channels"), channels);
2668 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2669 }
2670 }
2671 }
2672 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2673 param.remove(String8("test_cmd_policy_sampleRate"));
2674 if (valueInt >= 0 && valueInt <= 96000) {
2675 int samplingRate = valueInt;
2676 if (target == "Manager") {
2677 mTestSamplingRate = samplingRate;
2678 } else if (mTestOutputs[mCurOutput] != 0) {
2679 AudioParameter outputParam = AudioParameter();
2680 outputParam.addInt(String8("sampling_rate"), samplingRate);
2681 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2682 }
2683 }
2684 }
2685
2686 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2687 param.remove(String8("test_cmd_policy_reopen"));
2688
Eric Laurent1f2f2232014-06-02 12:01:23 -07002689 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002690 mpClientInterface->closeOutput(mPrimaryOutput);
2691
2692 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2693
Eric Laurente552edb2014-03-10 17:42:56 -07002694 mOutputs.removeItem(mPrimaryOutput);
2695
Eric Laurent1f2f2232014-06-02 12:01:23 -07002696 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002697 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002698 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2699 config.sample_rate = outputDesc->mSamplingRate;
2700 config.channel_mask = outputDesc->mChannelMask;
2701 config.format = outputDesc->mFormat;
2702 status_t status = mpClientInterface->openOutput(moduleHandle,
2703 &mPrimaryOutput,
2704 &config,
2705 &outputDesc->mDevice,
2706 String8(""),
2707 &outputDesc->mLatency,
2708 outputDesc->mFlags);
2709 if (status != NO_ERROR) {
2710 ALOGE("Failed to reopen hardware output stream, "
2711 "samplingRate: %d, format %d, channels %d",
2712 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002713 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002714 outputDesc->mSamplingRate = config.sample_rate;
2715 outputDesc->mChannelMask = config.channel_mask;
2716 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002717 AudioParameter outputCmd = AudioParameter();
2718 outputCmd.addInt(String8("set_id"), 0);
2719 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2720 addOutput(mPrimaryOutput, outputDesc);
2721 }
2722 }
2723
2724
2725 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2726 }
2727 }
2728 return false;
2729}
2730
Eric Laurente0720872014-03-11 09:30:41 -07002731void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002732{
2733 {
2734 AutoMutex _l(mLock);
2735 requestExit();
2736 mWaitWorkCV.signal();
2737 }
2738 requestExitAndWait();
2739}
2740
Eric Laurente0720872014-03-11 09:30:41 -07002741int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002742{
2743 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2744 if (output == mTestOutputs[i]) return i;
2745 }
2746 return 0;
2747}
2748#endif //AUDIO_POLICY_TEST
2749
2750// ---
2751
Eric Laurent1f2f2232014-06-02 12:01:23 -07002752void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002753{
Eric Laurent1c333e22014-05-20 10:48:17 -07002754 outputDesc->mIoHandle = output;
2755 outputDesc->mId = nextUniqueId();
2756 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002758}
2759
Eric Laurent1f2f2232014-06-02 12:01:23 -07002760void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002761{
Eric Laurent1c333e22014-05-20 10:48:17 -07002762 inputDesc->mIoHandle = input;
2763 inputDesc->mId = nextUniqueId();
2764 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002765 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002766}
Eric Laurente552edb2014-03-10 17:42:56 -07002767
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002768void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2769 const String8 address /*in*/,
2770 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2771 // look for a match on the given address on the addresses of the outputs:
2772 // find the address by finding the patch that maps to this output
2773 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2774 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2775 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2776 if (patchIdx >= 0) {
2777 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2778 const int numSinks = patchDesc->mPatch.num_sinks;
2779 for (ssize_t j=0; j < numSinks; j++) {
2780 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2781 const char* patchAddr =
2782 patchDesc->mPatch.sinks[j].ext.device.address;
2783 if (strncmp(patchAddr,
2784 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2785 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2786 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2787 outputs.add(desc->mIoHandle);
2788 break;
2789 }
2790 }
2791 }
2792 }
2793}
2794
Eric Laurente0720872014-03-11 09:30:41 -07002795status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002796 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002797 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002798 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002799{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002800 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002801
Eric Laurent3b73df72014-03-11 09:06:29 -07002802 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002803 // first list already open outputs that can be routed to this device
2804 for (size_t i = 0; i < mOutputs.size(); i++) {
2805 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002806 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002807 if (!deviceDistinguishesOnAddress(device)) {
2808 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2809 outputs.add(mOutputs.keyAt(i));
2810 } else {
2811 ALOGV(" checking address match due to device 0x%x", device);
2812 findIoHandlesByAddress(desc, address, outputs);
2813 }
Eric Laurente552edb2014-03-10 17:42:56 -07002814 }
2815 }
2816 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002817 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002818 for (size_t i = 0; i < mHwModules.size(); i++)
2819 {
2820 if (mHwModules[i]->mHandle == 0) {
2821 continue;
2822 }
2823 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2824 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002825 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002826 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002827 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2828 }
2829 }
2830 }
2831
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002832 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2833
Eric Laurente552edb2014-03-10 17:42:56 -07002834 if (profiles.isEmpty() && outputs.isEmpty()) {
2835 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2836 return BAD_VALUE;
2837 }
2838
2839 // open outputs for matching profiles if needed. Direct outputs are also opened to
2840 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2841 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002842 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002843
2844 // nothing to do if one output is already opened for this profile
2845 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002846 for (j = 0; j < outputs.size(); j++) {
2847 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002848 if (!desc->isDuplicated() && desc->mProfile == profile) {
2849 break;
2850 }
2851 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002852 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002853 continue;
2854 }
2855
Eric Laurent83b88082014-06-20 18:31:16 -07002856 ALOGV("opening output for device %08x with params %s profile %p",
2857 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002858 desc = new AudioOutputDescriptor(profile);
2859 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002860 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2861 config.sample_rate = desc->mSamplingRate;
2862 config.channel_mask = desc->mChannelMask;
2863 config.format = desc->mFormat;
2864 config.offload_info.sample_rate = desc->mSamplingRate;
2865 config.offload_info.channel_mask = desc->mChannelMask;
2866 config.offload_info.format = desc->mFormat;
2867 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2868 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2869 &output,
2870 &config,
2871 &desc->mDevice,
2872 address,
2873 &desc->mLatency,
2874 desc->mFlags);
2875 if (status == NO_ERROR) {
2876 desc->mSamplingRate = config.sample_rate;
2877 desc->mChannelMask = config.channel_mask;
2878 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002879
Eric Laurentd4692962014-05-05 18:13:44 -07002880 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002881 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002882 char *param = audio_device_address_to_parameter(device, address);
2883 mpClientInterface->setParameters(output, String8(param));
2884 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002885 }
2886
Eric Laurentd4692962014-05-05 18:13:44 -07002887 // Here is where we step through and resolve any "dynamic" fields
2888 String8 reply;
2889 char *value;
2890 if (profile->mSamplingRates[0] == 0) {
2891 reply = mpClientInterface->getParameters(output,
2892 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002893 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002894 reply.string());
2895 value = strpbrk((char *)reply.string(), "=");
2896 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002897 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002898 }
Eric Laurentd4692962014-05-05 18:13:44 -07002899 }
2900 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2901 reply = mpClientInterface->getParameters(output,
2902 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002903 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002904 reply.string());
2905 value = strpbrk((char *)reply.string(), "=");
2906 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002907 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002908 }
Eric Laurentd4692962014-05-05 18:13:44 -07002909 }
2910 if (profile->mChannelMasks[0] == 0) {
2911 reply = mpClientInterface->getParameters(output,
2912 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002913 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002914 reply.string());
2915 value = strpbrk((char *)reply.string(), "=");
2916 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002917 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002918 }
Eric Laurentd4692962014-05-05 18:13:44 -07002919 }
2920 if (((profile->mSamplingRates[0] == 0) &&
2921 (profile->mSamplingRates.size() < 2)) ||
2922 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2923 (profile->mFormats.size() < 2)) ||
2924 ((profile->mChannelMasks[0] == 0) &&
2925 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002926 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002927 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002928 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002929 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2930 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002931 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002932 config.sample_rate = profile->pickSamplingRate();
2933 config.channel_mask = profile->pickChannelMask();
2934 config.format = profile->pickFormat();
2935 config.offload_info.sample_rate = config.sample_rate;
2936 config.offload_info.channel_mask = config.channel_mask;
2937 config.offload_info.format = config.format;
2938 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2939 &output,
2940 &config,
2941 &desc->mDevice,
2942 address,
2943 &desc->mLatency,
2944 desc->mFlags);
2945 if (status == NO_ERROR) {
2946 desc->mSamplingRate = config.sample_rate;
2947 desc->mChannelMask = config.channel_mask;
2948 desc->mFormat = config.format;
2949 } else {
2950 output = AUDIO_IO_HANDLE_NONE;
2951 }
Eric Laurentd4692962014-05-05 18:13:44 -07002952 }
2953
Eric Laurentcf2c0212014-07-25 16:20:43 -07002954 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002955 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002956 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002957 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002958
Eric Laurentd4692962014-05-05 18:13:44 -07002959 // set initial stream volume for device
2960 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002961
Eric Laurentd4692962014-05-05 18:13:44 -07002962 //TODO: configure audio effect output stage here
2963
2964 // open a duplicating output thread for the new output and the primary output
2965 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2966 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002967 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002968 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002969 sp<AudioOutputDescriptor> dupOutputDesc =
2970 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002971 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2972 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2973 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2974 dupOutputDesc->mFormat = desc->mFormat;
2975 dupOutputDesc->mChannelMask = desc->mChannelMask;
2976 dupOutputDesc->mLatency = desc->mLatency;
2977 addOutput(duplicatedOutput, dupOutputDesc);
2978 applyStreamVolumes(duplicatedOutput, device, 0, true);
2979 } else {
2980 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2981 mPrimaryOutput, output);
2982 mpClientInterface->closeOutput(output);
2983 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002984 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002985 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002986 }
Eric Laurente552edb2014-03-10 17:42:56 -07002987 }
2988 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002989 } else {
2990 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002991 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002992 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002993 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002994 profiles.removeAt(profile_index);
2995 profile_index--;
2996 } else {
2997 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002998 if (deviceDistinguishesOnAddress(device)) {
2999 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3000 device, address.string());
3001 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3002 NULL/*patch handle*/, address.string());
3003 }
Eric Laurente552edb2014-03-10 17:42:56 -07003004 ALOGV("checkOutputsForDevice(): adding output %d", output);
3005 }
3006 }
3007
3008 if (profiles.isEmpty()) {
3009 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3010 return BAD_VALUE;
3011 }
Eric Laurentd4692962014-05-05 18:13:44 -07003012 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003013 // check if one opened output is not needed any more after disconnecting one device
3014 for (size_t i = 0; i < mOutputs.size(); i++) {
3015 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003016 if (!desc->isDuplicated()) {
3017 if (!(desc->mProfile->mSupportedDevices.types()
3018 & mAvailableOutputDevices.types())) {
3019 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3020 mOutputs.keyAt(i));
3021 outputs.add(mOutputs.keyAt(i));
3022 } else if (deviceDistinguishesOnAddress(device) &&
3023 // exact match on device
3024 (desc->mProfile->mSupportedDevices.types() == device)) {
3025 findIoHandlesByAddress(desc, address, outputs);
3026 }
Eric Laurente552edb2014-03-10 17:42:56 -07003027 }
3028 }
Eric Laurentd4692962014-05-05 18:13:44 -07003029 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003030 for (size_t i = 0; i < mHwModules.size(); i++)
3031 {
3032 if (mHwModules[i]->mHandle == 0) {
3033 continue;
3034 }
3035 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3036 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003037 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003038 if (profile->mSupportedDevices.types() & device) {
3039 ALOGV("checkOutputsForDevice(): "
3040 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003041 if (profile->mSamplingRates[0] == 0) {
3042 profile->mSamplingRates.clear();
3043 profile->mSamplingRates.add(0);
3044 }
3045 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3046 profile->mFormats.clear();
3047 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3048 }
3049 if (profile->mChannelMasks[0] == 0) {
3050 profile->mChannelMasks.clear();
3051 profile->mChannelMasks.add(0);
3052 }
3053 }
3054 }
3055 }
3056 }
3057 return NO_ERROR;
3058}
3059
Eric Laurentd4692962014-05-05 18:13:44 -07003060status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3061 audio_policy_dev_state_t state,
3062 SortedVector<audio_io_handle_t>& inputs,
3063 const String8 address)
3064{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003065 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003066 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3067 // first list already open inputs that can be routed to this device
3068 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3069 desc = mInputs.valueAt(input_index);
3070 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3071 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3072 inputs.add(mInputs.keyAt(input_index));
3073 }
3074 }
3075
3076 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003077 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003078 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3079 {
3080 if (mHwModules[module_idx]->mHandle == 0) {
3081 continue;
3082 }
3083 for (size_t profile_index = 0;
3084 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3085 profile_index++)
3086 {
3087 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3088 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003089 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003090 profile_index, module_idx);
3091 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3092 }
3093 }
3094 }
3095
3096 if (profiles.isEmpty() && inputs.isEmpty()) {
3097 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3098 return BAD_VALUE;
3099 }
3100
3101 // open inputs for matching profiles if needed. Direct inputs are also opened to
3102 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3103 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3104
Eric Laurent1c333e22014-05-20 10:48:17 -07003105 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003106 // nothing to do if one input is already opened for this profile
3107 size_t input_index;
3108 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3109 desc = mInputs.valueAt(input_index);
3110 if (desc->mProfile == profile) {
3111 break;
3112 }
3113 }
3114 if (input_index != mInputs.size()) {
3115 continue;
3116 }
3117
3118 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3119 desc = new AudioInputDescriptor(profile);
3120 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003121 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3122 config.sample_rate = desc->mSamplingRate;
3123 config.channel_mask = desc->mChannelMask;
3124 config.format = desc->mFormat;
3125 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3126 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3127 &input,
3128 &config,
3129 &desc->mDevice,
3130 address,
3131 AUDIO_SOURCE_MIC,
3132 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003133
Eric Laurentcf2c0212014-07-25 16:20:43 -07003134 if (status == NO_ERROR) {
3135 desc->mSamplingRate = config.sample_rate;
3136 desc->mChannelMask = config.channel_mask;
3137 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003138
Eric Laurentd4692962014-05-05 18:13:44 -07003139 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003140 char *param = audio_device_address_to_parameter(device, address);
3141 mpClientInterface->setParameters(input, String8(param));
3142 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003143 }
3144
3145 // Here is where we step through and resolve any "dynamic" fields
3146 String8 reply;
3147 char *value;
3148 if (profile->mSamplingRates[0] == 0) {
3149 reply = mpClientInterface->getParameters(input,
3150 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3151 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3152 reply.string());
3153 value = strpbrk((char *)reply.string(), "=");
3154 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003155 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003156 }
3157 }
3158 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3159 reply = mpClientInterface->getParameters(input,
3160 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3161 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3162 value = strpbrk((char *)reply.string(), "=");
3163 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003164 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003165 }
3166 }
3167 if (profile->mChannelMasks[0] == 0) {
3168 reply = mpClientInterface->getParameters(input,
3169 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3170 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3171 reply.string());
3172 value = strpbrk((char *)reply.string(), "=");
3173 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003174 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003175 }
3176 }
3177 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3178 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3179 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3180 ALOGW("checkInputsForDevice() direct input missing param");
3181 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003182 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003183 }
3184
3185 if (input != 0) {
3186 addInput(input, desc);
3187 }
3188 } // endif input != 0
3189
Eric Laurentcf2c0212014-07-25 16:20:43 -07003190 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003191 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003192 profiles.removeAt(profile_index);
3193 profile_index--;
3194 } else {
3195 inputs.add(input);
3196 ALOGV("checkInputsForDevice(): adding input %d", input);
3197 }
3198 } // end scan profiles
3199
3200 if (profiles.isEmpty()) {
3201 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3202 return BAD_VALUE;
3203 }
3204 } else {
3205 // Disconnect
3206 // check if one opened input is not needed any more after disconnecting one device
3207 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3208 desc = mInputs.valueAt(input_index);
3209 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3210 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3211 mInputs.keyAt(input_index));
3212 inputs.add(mInputs.keyAt(input_index));
3213 }
3214 }
3215 // Clear any profiles associated with the disconnected device.
3216 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3217 if (mHwModules[module_index]->mHandle == 0) {
3218 continue;
3219 }
3220 for (size_t profile_index = 0;
3221 profile_index < mHwModules[module_index]->mInputProfiles.size();
3222 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003223 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003224 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003225 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003226 profile_index, module_index);
3227 if (profile->mSamplingRates[0] == 0) {
3228 profile->mSamplingRates.clear();
3229 profile->mSamplingRates.add(0);
3230 }
3231 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3232 profile->mFormats.clear();
3233 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3234 }
3235 if (profile->mChannelMasks[0] == 0) {
3236 profile->mChannelMasks.clear();
3237 profile->mChannelMasks.add(0);
3238 }
3239 }
3240 }
3241 }
3242 } // end disconnect
3243
3244 return NO_ERROR;
3245}
3246
3247
Eric Laurente0720872014-03-11 09:30:41 -07003248void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003249{
3250 ALOGV("closeOutput(%d)", output);
3251
Eric Laurent1f2f2232014-06-02 12:01:23 -07003252 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003253 if (outputDesc == NULL) {
3254 ALOGW("closeOutput() unknown output %d", output);
3255 return;
3256 }
3257
3258 // look for duplicated outputs connected to the output being removed.
3259 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003260 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003261 if (dupOutputDesc->isDuplicated() &&
3262 (dupOutputDesc->mOutput1 == outputDesc ||
3263 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003264 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003265 if (dupOutputDesc->mOutput1 == outputDesc) {
3266 outputDesc2 = dupOutputDesc->mOutput2;
3267 } else {
3268 outputDesc2 = dupOutputDesc->mOutput1;
3269 }
3270 // As all active tracks on duplicated output will be deleted,
3271 // and as they were also referenced on the other output, the reference
3272 // count for their stream type must be adjusted accordingly on
3273 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003274 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003275 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003276 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003277 }
3278 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3279 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3280
3281 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003282 mOutputs.removeItem(duplicatedOutput);
3283 }
3284 }
3285
3286 AudioParameter param;
3287 param.add(String8("closing"), String8("true"));
3288 mpClientInterface->setParameters(output, param.toString());
3289
3290 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003291 mOutputs.removeItem(output);
3292 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003293 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003294}
3295
Eric Laurente0720872014-03-11 09:30:41 -07003296SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003297 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003298{
3299 SortedVector<audio_io_handle_t> outputs;
3300
3301 ALOGVV("getOutputsForDevice() device %04x", device);
3302 for (size_t i = 0; i < openOutputs.size(); i++) {
3303 ALOGVV("output %d isDuplicated=%d device=%04x",
3304 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3305 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3306 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3307 outputs.add(openOutputs.keyAt(i));
3308 }
3309 }
3310 return outputs;
3311}
3312
Eric Laurente0720872014-03-11 09:30:41 -07003313bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003314 SortedVector<audio_io_handle_t>& outputs2)
3315{
3316 if (outputs1.size() != outputs2.size()) {
3317 return false;
3318 }
3319 for (size_t i = 0; i < outputs1.size(); i++) {
3320 if (outputs1[i] != outputs2[i]) {
3321 return false;
3322 }
3323 }
3324 return true;
3325}
3326
Eric Laurente0720872014-03-11 09:30:41 -07003327void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003328{
3329 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3330 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3331 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3332 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3333
3334 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3335 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3336 strategy, srcOutputs[0], dstOutputs[0]);
3337 // mute strategy while moving tracks from one output to another
3338 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003339 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003340 if (desc->isStrategyActive(strategy)) {
3341 setStrategyMute(strategy, true, srcOutputs[i]);
3342 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3343 }
3344 }
3345
3346 // Move effects associated to this strategy from previous output to new output
3347 if (strategy == STRATEGY_MEDIA) {
3348 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3349 SortedVector<audio_io_handle_t> moved;
3350 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003351 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3352 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3353 effectDesc->mIo != fxOutput) {
3354 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003355 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3356 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003357 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003358 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003359 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003360 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003361 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003362 }
3363 }
3364 }
3365 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003366 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3367 if (getStrategy((audio_stream_type_t)i) == strategy) {
3368 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003369 }
3370 }
3371 }
3372}
3373
Eric Laurente0720872014-03-11 09:30:41 -07003374void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003375{
3376 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3377 checkOutputForStrategy(STRATEGY_PHONE);
3378 checkOutputForStrategy(STRATEGY_SONIFICATION);
3379 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3380 checkOutputForStrategy(STRATEGY_MEDIA);
3381 checkOutputForStrategy(STRATEGY_DTMF);
3382}
3383
Eric Laurente0720872014-03-11 09:30:41 -07003384audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003385{
Eric Laurente552edb2014-03-10 17:42:56 -07003386 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003387 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003388 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3389 return mOutputs.keyAt(i);
3390 }
3391 }
3392
3393 return 0;
3394}
3395
Eric Laurente0720872014-03-11 09:30:41 -07003396void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003397{
Eric Laurente552edb2014-03-10 17:42:56 -07003398 audio_io_handle_t a2dpOutput = getA2dpOutput();
3399 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003400 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003401 return;
3402 }
3403
Eric Laurent3a4311c2014-03-17 12:00:47 -07003404 bool isScoConnected =
3405 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003406 // suspend A2DP output if:
3407 // (NOT already suspended) &&
3408 // ((SCO device is connected &&
3409 // (forced usage for communication || for record is SCO))) ||
3410 // (phone state is ringing || in call)
3411 //
3412 // restore A2DP output if:
3413 // (Already suspended) &&
3414 // ((SCO device is NOT connected ||
3415 // (forced usage NOT for communication && NOT for record is SCO))) &&
3416 // (phone state is NOT ringing && NOT in call)
3417 //
3418 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003419 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003420 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3421 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3422 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3423 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003424
3425 mpClientInterface->restoreOutput(a2dpOutput);
3426 mA2dpSuspended = false;
3427 }
3428 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003429 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003430 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3431 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3432 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3433 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003434
3435 mpClientInterface->suspendOutput(a2dpOutput);
3436 mA2dpSuspended = true;
3437 }
3438 }
3439}
3440
Eric Laurent1c333e22014-05-20 10:48:17 -07003441audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003442{
3443 audio_devices_t device = AUDIO_DEVICE_NONE;
3444
Eric Laurent1f2f2232014-06-02 12:01:23 -07003445 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003446
3447 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3448 if (index >= 0) {
3449 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3450 if (patchDesc->mUid != mUidCached) {
3451 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3452 outputDesc->device(), outputDesc->mPatchHandle);
3453 return outputDesc->device();
3454 }
3455 }
3456
Eric Laurente552edb2014-03-10 17:42:56 -07003457 // check the following by order of priority to request a routing change if necessary:
3458 // 1: the strategy enforced audible is active on the output:
3459 // use device for strategy enforced audible
3460 // 2: we are in call or the strategy phone is active on the output:
3461 // use device for strategy phone
3462 // 3: the strategy sonification is active on the output:
3463 // use device for strategy sonification
3464 // 4: the strategy "respectful" sonification is active on the output:
3465 // use device for strategy "respectful" sonification
3466 // 5: the strategy media is active on the output:
3467 // use device for strategy media
3468 // 6: the strategy DTMF is active on the output:
3469 // use device for strategy DTMF
3470 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3471 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3472 } else if (isInCall() ||
3473 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3474 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3475 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3476 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3477 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3478 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3479 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3480 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3481 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3482 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3483 }
3484
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 ALOGV("getNewOutputDevice() selected device %x", device);
3486 return device;
3487}
3488
3489audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3490{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003491 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003492
3493 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3494 if (index >= 0) {
3495 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3496 if (patchDesc->mUid != mUidCached) {
3497 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3498 inputDesc->mDevice, inputDesc->mPatchHandle);
3499 return inputDesc->mDevice;
3500 }
3501 }
3502
Eric Laurent1c333e22014-05-20 10:48:17 -07003503 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3504
3505 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003506 return device;
3507}
3508
Eric Laurente0720872014-03-11 09:30:41 -07003509uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003510 return (uint32_t)getStrategy(stream);
3511}
3512
Eric Laurente0720872014-03-11 09:30:41 -07003513audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003514 // By checking the range of stream before calling getStrategy, we avoid
3515 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3516 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003517 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003518 return AUDIO_DEVICE_NONE;
3519 }
3520 audio_devices_t devices;
3521 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3522 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3523 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3524 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003525 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003526 if (outputDesc->isStrategyActive(strategy)) {
3527 devices = outputDesc->device();
3528 break;
3529 }
Eric Laurente552edb2014-03-10 17:42:56 -07003530 }
3531 return devices;
3532}
3533
Eric Laurente0720872014-03-11 09:30:41 -07003534AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003535 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003536 // stream to strategy mapping
3537 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003538 case AUDIO_STREAM_VOICE_CALL:
3539 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003540 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003541 case AUDIO_STREAM_RING:
3542 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003543 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003544 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003545 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003546 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003547 return STRATEGY_DTMF;
3548 default:
3549 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003550 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003551 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3552 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003553 case AUDIO_STREAM_TTS:
3554 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003555 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003556 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003557 return STRATEGY_ENFORCED_AUDIBLE;
3558 }
3559}
3560
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003561uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3562 // flags to strategy mapping
3563 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3564 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3565 }
3566
3567 // usage to strategy mapping
3568 switch (attr->usage) {
3569 case AUDIO_USAGE_MEDIA:
3570 case AUDIO_USAGE_GAME:
3571 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3572 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3573 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3574 return (uint32_t) STRATEGY_MEDIA;
3575
3576 case AUDIO_USAGE_VOICE_COMMUNICATION:
3577 return (uint32_t) STRATEGY_PHONE;
3578
3579 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3580 return (uint32_t) STRATEGY_DTMF;
3581
3582 case AUDIO_USAGE_ALARM:
3583 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3584 return (uint32_t) STRATEGY_SONIFICATION;
3585
3586 case AUDIO_USAGE_NOTIFICATION:
3587 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3588 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3589 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3590 case AUDIO_USAGE_NOTIFICATION_EVENT:
3591 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3592
3593 case AUDIO_USAGE_UNKNOWN:
3594 default:
3595 return (uint32_t) STRATEGY_MEDIA;
3596 }
3597}
3598
Eric Laurente0720872014-03-11 09:30:41 -07003599void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003600 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003601 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003602 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3603 updateDevicesAndOutputs();
3604 break;
3605 default:
3606 break;
3607 }
3608}
3609
Eric Laurente0720872014-03-11 09:30:41 -07003610audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003611 bool fromCache)
3612{
3613 uint32_t device = AUDIO_DEVICE_NONE;
3614
3615 if (fromCache) {
3616 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3617 strategy, mDeviceForStrategy[strategy]);
3618 return mDeviceForStrategy[strategy];
3619 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003620 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003621 switch (strategy) {
3622
3623 case STRATEGY_SONIFICATION_RESPECTFUL:
3624 if (isInCall()) {
3625 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003626 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003627 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3628 // while media is playing on a remote device, use the the sonification behavior.
3629 // Note that we test this usecase before testing if media is playing because
3630 // the isStreamActive() method only informs about the activity of a stream, not
3631 // if it's for local playback. Note also that we use the same delay between both tests
3632 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003633 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003634 // while media is playing (or has recently played), use the same device
3635 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3636 } else {
3637 // when media is not playing anymore, fall back on the sonification behavior
3638 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3639 }
3640
3641 break;
3642
3643 case STRATEGY_DTMF:
3644 if (!isInCall()) {
3645 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3646 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3647 break;
3648 }
3649 // when in call, DTMF and PHONE strategies follow the same rules
3650 // FALL THROUGH
3651
3652 case STRATEGY_PHONE:
3653 // for phone strategy, we first consider the forced use and then the available devices by order
3654 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003655 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3656 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003657 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003658 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003659 if (device) break;
3660 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003661 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003662 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003663 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003664 if (device) break;
3665 // if SCO device is requested but no SCO device is available, fall back to default case
3666 // FALL THROUGH
3667
3668 default: // FORCE_NONE
3669 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003670 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003671 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003672 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003673 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003674 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003675 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003676 if (device) break;
3677 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003678 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003680 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003681 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003682 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003683 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003684 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003685 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003686 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003687 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003688 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003689 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003690 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003691 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003692 if (device) break;
3693 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003694 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003695 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003696 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003697 if (device == AUDIO_DEVICE_NONE) {
3698 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3699 }
3700 break;
3701
Eric Laurent3b73df72014-03-11 09:06:29 -07003702 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003703 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3704 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003705 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003706 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003707 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003708 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003709 if (device) break;
3710 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003711 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003712 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003713 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003714 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003715 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003716 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003717 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003718 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003719 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003720 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003721 if (device) break;
3722 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003723 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3724 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003725 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003726 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003727 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003728 if (device == AUDIO_DEVICE_NONE) {
3729 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3730 }
3731 break;
3732 }
3733 break;
3734
3735 case STRATEGY_SONIFICATION:
3736
3737 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3738 // handleIncallSonification().
3739 if (isInCall()) {
3740 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3741 break;
3742 }
3743 // FALL THROUGH
3744
3745 case STRATEGY_ENFORCED_AUDIBLE:
3746 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3747 // except:
3748 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3749 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3750
3751 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003752 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003753 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003754 if (device == AUDIO_DEVICE_NONE) {
3755 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3756 }
3757 }
3758 // The second device used for sonification is the same as the device used by media strategy
3759 // FALL THROUGH
3760
3761 case STRATEGY_MEDIA: {
3762 uint32_t device2 = AUDIO_DEVICE_NONE;
3763 if (strategy != STRATEGY_SONIFICATION) {
3764 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003765 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003766 }
3767 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003768 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003769 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003770 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003771 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003772 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003773 }
3774 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003775 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003776 }
3777 }
3778 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003779 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003780 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003781 if ((device2 == AUDIO_DEVICE_NONE)) {
3782 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3783 }
Eric Laurente552edb2014-03-10 17:42:56 -07003784 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003785 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003786 }
3787 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003788 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003789 }
3790 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003791 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003792 }
3793 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003794 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003795 }
3796 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3797 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003798 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003799 }
3800 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003801 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003802 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003803 }
3804 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003805 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003806 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003807 int device3 = AUDIO_DEVICE_NONE;
3808 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003809 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003810 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3811 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003812 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003813 }
Eric Laurente552edb2014-03-10 17:42:56 -07003814
Jungshik Jang839e4f32014-06-26 17:23:40 +09003815 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003816 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3817 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3818 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003819
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003820 // If hdmi system audio mode is on, remove speaker out of output list.
3821 if ((strategy == STRATEGY_MEDIA) &&
3822 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3823 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3824 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3825 }
3826
Eric Laurente552edb2014-03-10 17:42:56 -07003827 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003828 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003829 if (device == AUDIO_DEVICE_NONE) {
3830 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3831 }
3832 } break;
3833
3834 default:
3835 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3836 break;
3837 }
3838
3839 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3840 return device;
3841}
3842
Eric Laurente0720872014-03-11 09:30:41 -07003843void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003844{
3845 for (int i = 0; i < NUM_STRATEGIES; i++) {
3846 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3847 }
3848 mPreviousOutputs = mOutputs;
3849}
3850
Eric Laurent1f2f2232014-06-02 12:01:23 -07003851uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003852 audio_devices_t prevDevice,
3853 uint32_t delayMs)
3854{
3855 // mute/unmute strategies using an incompatible device combination
3856 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3857 // if unmuting, unmute only after the specified delay
3858 if (outputDesc->isDuplicated()) {
3859 return 0;
3860 }
3861
3862 uint32_t muteWaitMs = 0;
3863 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003864 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003865
3866 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3867 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3868 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3869 bool doMute = false;
3870
3871 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3872 doMute = true;
3873 outputDesc->mStrategyMutedByDevice[i] = true;
3874 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3875 doMute = true;
3876 outputDesc->mStrategyMutedByDevice[i] = false;
3877 }
Eric Laurent99401132014-05-07 19:48:15 -07003878 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003879 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003880 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003881 // skip output if it does not share any device with current output
3882 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3883 == AUDIO_DEVICE_NONE) {
3884 continue;
3885 }
3886 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3887 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3888 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3889 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3890 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003891 if (mute) {
3892 // FIXME: should not need to double latency if volume could be applied
3893 // immediately by the audioflinger mixer. We must account for the delay
3894 // between now and the next time the audioflinger thread for this output
3895 // will process a buffer (which corresponds to one buffer size,
3896 // usually 1/2 or 1/4 of the latency).
3897 if (muteWaitMs < desc->latency() * 2) {
3898 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003899 }
3900 }
3901 }
3902 }
3903 }
3904 }
3905
Eric Laurent99401132014-05-07 19:48:15 -07003906 // temporary mute output if device selection changes to avoid volume bursts due to
3907 // different per device volumes
3908 if (outputDesc->isActive() && (device != prevDevice)) {
3909 if (muteWaitMs < outputDesc->latency() * 2) {
3910 muteWaitMs = outputDesc->latency() * 2;
3911 }
3912 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3913 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003914 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003915 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003916 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003917 muteWaitMs *2, device);
3918 }
3919 }
3920 }
3921
Eric Laurente552edb2014-03-10 17:42:56 -07003922 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3923 if (muteWaitMs > delayMs) {
3924 muteWaitMs -= delayMs;
3925 usleep(muteWaitMs * 1000);
3926 return muteWaitMs;
3927 }
3928 return 0;
3929}
3930
Eric Laurente0720872014-03-11 09:30:41 -07003931uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003932 audio_devices_t device,
3933 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003934 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003935 audio_patch_handle_t *patchHandle,
3936 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003937{
3938 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003939 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003940 AudioParameter param;
3941 uint32_t muteWaitMs;
3942
3943 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003944 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3945 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003946 return muteWaitMs;
3947 }
3948 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3949 // output profile
3950 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003951 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003952 return 0;
3953 }
3954
3955 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003956 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003957
3958 audio_devices_t prevDevice = outputDesc->mDevice;
3959
3960 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3961
3962 if (device != AUDIO_DEVICE_NONE) {
3963 outputDesc->mDevice = device;
3964 }
3965 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3966
3967 // Do not change the routing if:
3968 // - the requested device is AUDIO_DEVICE_NONE
3969 // - the requested device is the same as current device and force is not specified.
3970 // Doing this check here allows the caller to call setOutputDevice() without conditions
3971 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3972 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3973 return muteWaitMs;
3974 }
3975
3976 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003977
Eric Laurente552edb2014-03-10 17:42:56 -07003978 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003979 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003981 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003982 DeviceVector deviceList = (address == NULL) ?
3983 mAvailableOutputDevices.getDevicesFromType(device)
3984 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003985 if (!deviceList.isEmpty()) {
3986 struct audio_patch patch;
3987 outputDesc->toAudioPortConfig(&patch.sources[0]);
3988 patch.num_sources = 1;
3989 patch.num_sinks = 0;
3990 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3991 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003992 patch.num_sinks++;
3993 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 ssize_t index;
3995 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3996 index = mAudioPatches.indexOfKey(*patchHandle);
3997 } else {
3998 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3999 }
4000 sp< AudioPatch> patchDesc;
4001 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4002 if (index >= 0) {
4003 patchDesc = mAudioPatches.valueAt(index);
4004 afPatchHandle = patchDesc->mAfPatchHandle;
4005 }
4006
Eric Laurent1c333e22014-05-20 10:48:17 -07004007 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004008 &afPatchHandle,
4009 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004010 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4011 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004012 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004013 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004014 if (index < 0) {
4015 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4016 &patch, mUidCached);
4017 addAudioPatch(patchDesc->mHandle, patchDesc);
4018 } else {
4019 patchDesc->mPatch = patch;
4020 }
4021 patchDesc->mAfPatchHandle = afPatchHandle;
4022 patchDesc->mUid = mUidCached;
4023 if (patchHandle) {
4024 *patchHandle = patchDesc->mHandle;
4025 }
4026 outputDesc->mPatchHandle = patchDesc->mHandle;
4027 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004028 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004029 }
4030 }
4031 }
Eric Laurente552edb2014-03-10 17:42:56 -07004032
4033 // update stream volumes according to new device
4034 applyStreamVolumes(output, device, delayMs);
4035
4036 return muteWaitMs;
4037}
4038
Eric Laurent1c333e22014-05-20 10:48:17 -07004039status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 int delayMs,
4041 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004042{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004043 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004044 ssize_t index;
4045 if (patchHandle) {
4046 index = mAudioPatches.indexOfKey(*patchHandle);
4047 } else {
4048 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4049 }
4050 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004051 return INVALID_OPERATION;
4052 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004053 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4054 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004055 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4056 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004057 removeAudioPatch(patchDesc->mHandle);
4058 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004059 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004060 return status;
4061}
4062
4063status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4064 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004065 bool force,
4066 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004067{
4068 status_t status = NO_ERROR;
4069
Eric Laurent1f2f2232014-06-02 12:01:23 -07004070 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004071 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4072 inputDesc->mDevice = device;
4073
4074 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4075 if (!deviceList.isEmpty()) {
4076 struct audio_patch patch;
4077 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004078 // AUDIO_SOURCE_HOTWORD is for internal use only:
4079 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004080 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4081 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004082 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4083 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004084 patch.num_sinks = 1;
4085 //only one input device for now
4086 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004087 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004088 ssize_t index;
4089 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4090 index = mAudioPatches.indexOfKey(*patchHandle);
4091 } else {
4092 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4093 }
4094 sp< AudioPatch> patchDesc;
4095 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4096 if (index >= 0) {
4097 patchDesc = mAudioPatches.valueAt(index);
4098 afPatchHandle = patchDesc->mAfPatchHandle;
4099 }
4100
Eric Laurent1c333e22014-05-20 10:48:17 -07004101 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004102 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004103 0);
4104 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004106 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004107 if (index < 0) {
4108 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4109 &patch, mUidCached);
4110 addAudioPatch(patchDesc->mHandle, patchDesc);
4111 } else {
4112 patchDesc->mPatch = patch;
4113 }
4114 patchDesc->mAfPatchHandle = afPatchHandle;
4115 patchDesc->mUid = mUidCached;
4116 if (patchHandle) {
4117 *patchHandle = patchDesc->mHandle;
4118 }
4119 inputDesc->mPatchHandle = patchDesc->mHandle;
4120 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004121 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004122 }
4123 }
4124 }
4125 return status;
4126}
4127
Eric Laurent6a94d692014-05-20 11:18:06 -07004128status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4129 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004130{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004131 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 ssize_t index;
4133 if (patchHandle) {
4134 index = mAudioPatches.indexOfKey(*patchHandle);
4135 } else {
4136 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4137 }
4138 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004139 return INVALID_OPERATION;
4140 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004141 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4142 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004143 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4144 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004145 removeAudioPatch(patchDesc->mHandle);
4146 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004147 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004148 return status;
4149}
4150
4151sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004152 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004153 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004154 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004155 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004156{
4157 // Choose an input profile based on the requested capture parameters: select the first available
4158 // profile supporting all requested parameters.
4159
4160 for (size_t i = 0; i < mHwModules.size(); i++)
4161 {
4162 if (mHwModules[i]->mHandle == 0) {
4163 continue;
4164 }
4165 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4166 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004167 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004168 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004169 if (profile->isCompatibleProfile(device, samplingRate,
4170 &samplingRate /*updatedSamplingRate*/,
4171 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004172 return profile;
4173 }
4174 }
4175 }
4176 return NULL;
4177}
4178
Eric Laurente0720872014-03-11 09:30:41 -07004179audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004180{
4181 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004182 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4183 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004184 switch (inputSource) {
4185 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004186 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004187 device = AUDIO_DEVICE_IN_VOICE_CALL;
4188 break;
4189 }
4190 // FALL THROUGH
4191
4192 case AUDIO_SOURCE_DEFAULT:
4193 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004194 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4195 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4196 break;
4197 }
4198 // FALL THROUGH
4199
Eric Laurente552edb2014-03-10 17:42:56 -07004200 case AUDIO_SOURCE_VOICE_RECOGNITION:
4201 case AUDIO_SOURCE_HOTWORD:
4202 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004203 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004204 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004205 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004206 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004207 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004208 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4209 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004210 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004211 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4212 }
4213 break;
4214 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004215 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004216 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004217 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004218 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4219 }
4220 break;
4221 case AUDIO_SOURCE_VOICE_DOWNLINK:
4222 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004223 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004224 device = AUDIO_DEVICE_IN_VOICE_CALL;
4225 }
4226 break;
4227 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004228 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004229 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4230 }
4231 break;
4232 default:
4233 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4234 break;
4235 }
4236 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4237 return device;
4238}
4239
Eric Laurente0720872014-03-11 09:30:41 -07004240bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004241{
4242 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4243 device &= ~AUDIO_DEVICE_BIT_IN;
4244 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4245 return true;
4246 }
4247 return false;
4248}
4249
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004250bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4251 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4252}
4253
Eric Laurente0720872014-03-11 09:30:41 -07004254audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004255{
4256 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004257 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 if ((input_descriptor->mRefCount > 0)
4259 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4260 return mInputs.keyAt(i);
4261 }
4262 }
4263 return 0;
4264}
4265
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004266uint32_t AudioPolicyManager::activeInputsCount() const
4267{
4268 uint32_t count = 0;
4269 for (size_t i = 0; i < mInputs.size(); i++) {
4270 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4271 if (desc->mRefCount > 0) {
4272 return count++;
4273 }
4274 }
4275 return count;
4276}
4277
Eric Laurente552edb2014-03-10 17:42:56 -07004278
Eric Laurente0720872014-03-11 09:30:41 -07004279audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004280{
4281 if (device == AUDIO_DEVICE_NONE) {
4282 // this happens when forcing a route update and no track is active on an output.
4283 // In this case the returned category is not important.
4284 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004285 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004286 // Multiple device selection is either:
4287 // - speaker + one other device: give priority to speaker in this case.
4288 // - one A2DP device + another device: happens with duplicated output. In this case
4289 // retain the device on the A2DP output as the other must not correspond to an active
4290 // selection if not the speaker.
4291 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4292 device = AUDIO_DEVICE_OUT_SPEAKER;
4293 } else {
4294 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4295 }
4296 }
4297
Eric Laurent3b73df72014-03-11 09:06:29 -07004298 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004299 "getDeviceForVolume() invalid device combination: %08x",
4300 device);
4301
4302 return device;
4303}
4304
Eric Laurente0720872014-03-11 09:30:41 -07004305AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004306{
4307 switch(getDeviceForVolume(device)) {
4308 case AUDIO_DEVICE_OUT_EARPIECE:
4309 return DEVICE_CATEGORY_EARPIECE;
4310 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4311 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4312 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4313 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4314 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4315 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4316 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004317 case AUDIO_DEVICE_OUT_LINE:
4318 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4319 /*USB? Remote submix?*/
4320 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004321 case AUDIO_DEVICE_OUT_SPEAKER:
4322 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4323 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004324 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4325 case AUDIO_DEVICE_OUT_USB_DEVICE:
4326 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4327 default:
4328 return DEVICE_CATEGORY_SPEAKER;
4329 }
4330}
4331
Eric Laurente0720872014-03-11 09:30:41 -07004332float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004333 int indexInUi)
4334{
4335 device_category deviceCategory = getDeviceCategory(device);
4336 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4337
4338 // the volume index in the UI is relative to the min and max volume indices for this stream type
4339 int nbSteps = 1 + curve[VOLMAX].mIndex -
4340 curve[VOLMIN].mIndex;
4341 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4342 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4343
4344 // find what part of the curve this index volume belongs to, or if it's out of bounds
4345 int segment = 0;
4346 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4347 return 0.0f;
4348 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4349 segment = 0;
4350 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4351 segment = 1;
4352 } else if (volIdx <= curve[VOLMAX].mIndex) {
4353 segment = 2;
4354 } else { // out of bounds
4355 return 1.0f;
4356 }
4357
4358 // linear interpolation in the attenuation table in dB
4359 float decibels = curve[segment].mDBAttenuation +
4360 ((float)(volIdx - curve[segment].mIndex)) *
4361 ( (curve[segment+1].mDBAttenuation -
4362 curve[segment].mDBAttenuation) /
4363 ((float)(curve[segment+1].mIndex -
4364 curve[segment].mIndex)) );
4365
4366 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4367
4368 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4369 curve[segment].mIndex, volIdx,
4370 curve[segment+1].mIndex,
4371 curve[segment].mDBAttenuation,
4372 decibels,
4373 curve[segment+1].mDBAttenuation,
4374 amplification);
4375
4376 return amplification;
4377}
4378
Eric Laurente0720872014-03-11 09:30:41 -07004379const AudioPolicyManager::VolumeCurvePoint
4380 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004381 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4382};
4383
Eric Laurente0720872014-03-11 09:30:41 -07004384const AudioPolicyManager::VolumeCurvePoint
4385 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004386 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4387};
4388
Eric Laurente0720872014-03-11 09:30:41 -07004389const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004390 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4391 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4392};
4393
4394const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004395 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004396 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4397};
4398
Eric Laurente0720872014-03-11 09:30:41 -07004399const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004400 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004401 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004402};
4403
4404const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004405 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004406 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4407};
4408
Eric Laurente0720872014-03-11 09:30:41 -07004409const AudioPolicyManager::VolumeCurvePoint
4410 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004411 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4412};
4413
4414// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4415// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4416// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4417// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4418
Eric Laurente0720872014-03-11 09:30:41 -07004419const AudioPolicyManager::VolumeCurvePoint
4420 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004421 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4422};
4423
Eric Laurente0720872014-03-11 09:30:41 -07004424const AudioPolicyManager::VolumeCurvePoint
4425 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004426 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4427};
4428
Eric Laurente0720872014-03-11 09:30:41 -07004429const AudioPolicyManager::VolumeCurvePoint
4430 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004431 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4432};
4433
Eric Laurente0720872014-03-11 09:30:41 -07004434const AudioPolicyManager::VolumeCurvePoint
4435 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004436 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4437};
4438
Eric Laurente0720872014-03-11 09:30:41 -07004439const AudioPolicyManager::VolumeCurvePoint
4440 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004441 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4442};
4443
Eric Laurente0720872014-03-11 09:30:41 -07004444const AudioPolicyManager::VolumeCurvePoint
4445 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4446 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004447 { // AUDIO_STREAM_VOICE_CALL
4448 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4449 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004450 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4451 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004452 },
4453 { // AUDIO_STREAM_SYSTEM
4454 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4455 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004456 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4457 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004458 },
4459 { // AUDIO_STREAM_RING
4460 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4461 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004462 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4463 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004464 },
4465 { // AUDIO_STREAM_MUSIC
4466 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4467 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004468 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4469 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004470 },
4471 { // AUDIO_STREAM_ALARM
4472 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4473 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004474 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4475 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004476 },
4477 { // AUDIO_STREAM_NOTIFICATION
4478 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4479 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004480 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4481 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004482 },
4483 { // AUDIO_STREAM_BLUETOOTH_SCO
4484 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4485 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004486 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4487 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004488 },
4489 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4490 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4491 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004492 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4493 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004494 },
4495 { // AUDIO_STREAM_DTMF
4496 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4497 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004498 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4499 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004500 },
4501 { // AUDIO_STREAM_TTS
4502 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4503 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004504 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4505 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004506 },
4507};
4508
Eric Laurente0720872014-03-11 09:30:41 -07004509void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004510{
4511 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4512 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4513 mStreams[i].mVolumeCurve[j] =
4514 sVolumeProfiles[i][j];
4515 }
4516 }
4517
4518 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4519 if (mSpeakerDrcEnabled) {
4520 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4521 sDefaultSystemVolumeCurveDrc;
4522 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4523 sSpeakerSonificationVolumeCurveDrc;
4524 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4525 sSpeakerSonificationVolumeCurveDrc;
4526 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4527 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004528 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4529 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004530 }
4531}
4532
Eric Laurente0720872014-03-11 09:30:41 -07004533float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004534 int index,
4535 audio_io_handle_t output,
4536 audio_devices_t device)
4537{
4538 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004539 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 StreamDescriptor &streamDesc = mStreams[stream];
4541
4542 if (device == AUDIO_DEVICE_NONE) {
4543 device = outputDesc->device();
4544 }
4545
Eric Laurente552edb2014-03-10 17:42:56 -07004546 volume = volIndexToAmpl(device, streamDesc, index);
4547
4548 // if a headset is connected, apply the following rules to ring tones and notifications
4549 // to avoid sound level bursts in user's ears:
4550 // - always attenuate ring tones and notifications volume by 6dB
4551 // - if music is playing, always limit the volume to current music volume,
4552 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004553 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004554 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4555 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4556 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4557 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4558 ((stream_strategy == STRATEGY_SONIFICATION)
4559 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004560 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004561 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004562 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004563 streamDesc.mCanBeMuted) {
4564 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4565 // when the phone is ringing we must consider that music could have been paused just before
4566 // by the music application and behave as if music was active if the last music track was
4567 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004568 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004569 mLimitRingtoneVolume) {
4570 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004571 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4572 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004573 output,
4574 musicDevice);
4575 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4576 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4577 if (volume > minVol) {
4578 volume = minVol;
4579 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4580 }
4581 }
4582 }
4583
4584 return volume;
4585}
4586
Eric Laurente0720872014-03-11 09:30:41 -07004587status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004588 int index,
4589 audio_io_handle_t output,
4590 audio_devices_t device,
4591 int delayMs,
4592 bool force)
4593{
4594
4595 // do not change actual stream volume if the stream is muted
4596 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4597 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4598 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4599 return NO_ERROR;
4600 }
4601
4602 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004603 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4604 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4605 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4606 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004607 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004608 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004609 return INVALID_OPERATION;
4610 }
4611
4612 float volume = computeVolume(stream, index, output, device);
4613 // We actually change the volume if:
4614 // - the float value returned by computeVolume() changed
4615 // - the force flag is set
4616 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4617 force) {
4618 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4619 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4620 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4621 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004622 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4623 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004624 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004625 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004626 }
4627
Eric Laurent3b73df72014-03-11 09:06:29 -07004628 if (stream == AUDIO_STREAM_VOICE_CALL ||
4629 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004630 float voiceVolume;
4631 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004632 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004633 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4634 } else {
4635 voiceVolume = 1.0;
4636 }
4637
4638 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4639 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4640 mLastVoiceVolume = voiceVolume;
4641 }
4642 }
4643
4644 return NO_ERROR;
4645}
4646
Eric Laurente0720872014-03-11 09:30:41 -07004647void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004648 audio_devices_t device,
4649 int delayMs,
4650 bool force)
4651{
4652 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4653
Eric Laurent3b73df72014-03-11 09:06:29 -07004654 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4655 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004656 mStreams[stream].getVolumeIndex(device),
4657 output,
4658 device,
4659 delayMs,
4660 force);
4661 }
4662}
4663
Eric Laurente0720872014-03-11 09:30:41 -07004664void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004665 bool on,
4666 audio_io_handle_t output,
4667 int delayMs,
4668 audio_devices_t device)
4669{
4670 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004671 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4672 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4673 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 }
4675 }
4676}
4677
Eric Laurente0720872014-03-11 09:30:41 -07004678void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004679 bool on,
4680 audio_io_handle_t output,
4681 int delayMs,
4682 audio_devices_t device)
4683{
4684 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004685 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004686 if (device == AUDIO_DEVICE_NONE) {
4687 device = outputDesc->device();
4688 }
4689
4690 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4691 stream, on, output, outputDesc->mMuteCount[stream], device);
4692
4693 if (on) {
4694 if (outputDesc->mMuteCount[stream] == 0) {
4695 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004696 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4697 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004698 checkAndSetVolume(stream, 0, output, device, delayMs);
4699 }
4700 }
4701 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4702 outputDesc->mMuteCount[stream]++;
4703 } else {
4704 if (outputDesc->mMuteCount[stream] == 0) {
4705 ALOGV("setStreamMute() unmuting non muted stream!");
4706 return;
4707 }
4708 if (--outputDesc->mMuteCount[stream] == 0) {
4709 checkAndSetVolume(stream,
4710 streamDesc.getVolumeIndex(device),
4711 output,
4712 device,
4713 delayMs);
4714 }
4715 }
4716}
4717
Eric Laurente0720872014-03-11 09:30:41 -07004718void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004719 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004720{
4721 // if the stream pertains to sonification strategy and we are in call we must
4722 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4723 // in the device used for phone strategy and play the tone if the selected device does not
4724 // interfere with the device used for phone strategy
4725 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4726 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004727 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004728 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4729 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004730 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004731 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4732 stream, starting, outputDesc->mDevice, stateChange);
4733 if (outputDesc->mRefCount[stream]) {
4734 int muteCount = 1;
4735 if (stateChange) {
4736 muteCount = outputDesc->mRefCount[stream];
4737 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004738 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004739 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4740 for (int i = 0; i < muteCount; i++) {
4741 setStreamMute(stream, starting, mPrimaryOutput);
4742 }
4743 } else {
4744 ALOGV("handleIncallSonification() high visibility");
4745 if (outputDesc->device() &
4746 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4747 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4748 for (int i = 0; i < muteCount; i++) {
4749 setStreamMute(stream, starting, mPrimaryOutput);
4750 }
4751 }
4752 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004753 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4754 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004755 } else {
4756 mpClientInterface->stopTone();
4757 }
4758 }
4759 }
4760 }
4761}
4762
Eric Laurente0720872014-03-11 09:30:41 -07004763bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004764{
4765 return isStateInCall(mPhoneState);
4766}
4767
Eric Laurente0720872014-03-11 09:30:41 -07004768bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004769 return ((state == AUDIO_MODE_IN_CALL) ||
4770 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004771}
4772
Eric Laurente0720872014-03-11 09:30:41 -07004773uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004774{
4775 return MAX_EFFECTS_CPU_LOAD;
4776}
4777
Eric Laurente0720872014-03-11 09:30:41 -07004778uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004779{
4780 return MAX_EFFECTS_MEMORY;
4781}
4782
Eric Laurent6a94d692014-05-20 11:18:06 -07004783
Eric Laurente552edb2014-03-10 17:42:56 -07004784// --- AudioOutputDescriptor class implementation
4785
Eric Laurente0720872014-03-11 09:30:41 -07004786AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004787 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004788 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004790 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4791{
4792 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004793 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004794 mRefCount[i] = 0;
4795 mCurVolume[i] = -1.0;
4796 mMuteCount[i] = 0;
4797 mStopTime[i] = 0;
4798 }
4799 for (int i = 0; i < NUM_STRATEGIES; i++) {
4800 mStrategyMutedByDevice[i] = false;
4801 }
4802 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004803 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004804 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004805 mSamplingRate = profile->pickSamplingRate();
4806 mFormat = profile->pickFormat();
4807 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004808 if (profile->mGains.size() > 0) {
4809 profile->mGains[0]->getDefaultConfig(&mGain);
4810 }
Eric Laurente552edb2014-03-10 17:42:56 -07004811 }
4812}
4813
Eric Laurente0720872014-03-11 09:30:41 -07004814audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004815{
4816 if (isDuplicated()) {
4817 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4818 } else {
4819 return mDevice;
4820 }
4821}
4822
Eric Laurente0720872014-03-11 09:30:41 -07004823uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004824{
4825 if (isDuplicated()) {
4826 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4827 } else {
4828 return mLatency;
4829 }
4830}
4831
Eric Laurente0720872014-03-11 09:30:41 -07004832bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004833 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004834{
4835 if (isDuplicated()) {
4836 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4837 } else if (outputDesc->isDuplicated()){
4838 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4839 } else {
4840 return (mProfile->mModule == outputDesc->mProfile->mModule);
4841 }
4842}
4843
Eric Laurente0720872014-03-11 09:30:41 -07004844void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004845 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004846{
4847 // forward usage count change to attached outputs
4848 if (isDuplicated()) {
4849 mOutput1->changeRefCount(stream, delta);
4850 mOutput2->changeRefCount(stream, delta);
4851 }
4852 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004853 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4854 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004855 mRefCount[stream] = 0;
4856 return;
4857 }
4858 mRefCount[stream] += delta;
4859 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4860}
4861
Eric Laurente0720872014-03-11 09:30:41 -07004862audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004863{
4864 if (isDuplicated()) {
4865 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4866 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004867 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004868 }
4869}
4870
Eric Laurente0720872014-03-11 09:30:41 -07004871bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004872{
4873 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4874}
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004877 uint32_t inPastMs,
4878 nsecs_t sysTime) const
4879{
4880 if ((sysTime == 0) && (inPastMs != 0)) {
4881 sysTime = systemTime();
4882 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004883 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4884 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004885 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004886 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004887 return true;
4888 }
4889 }
4890 return false;
4891}
4892
Eric Laurente0720872014-03-11 09:30:41 -07004893bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004894 uint32_t inPastMs,
4895 nsecs_t sysTime) const
4896{
4897 if (mRefCount[stream] != 0) {
4898 return true;
4899 }
4900 if (inPastMs == 0) {
4901 return false;
4902 }
4903 if (sysTime == 0) {
4904 sysTime = systemTime();
4905 }
4906 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4907 return true;
4908 }
4909 return false;
4910}
4911
Eric Laurent1c333e22014-05-20 10:48:17 -07004912void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 struct audio_port_config *dstConfig,
4914 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004915{
Eric Laurent84c70242014-06-23 08:46:27 -07004916 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4917
Eric Laurent1f2f2232014-06-02 12:01:23 -07004918 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4919 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4920 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004921 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004922 }
4923 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4924
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 dstConfig->id = mId;
4926 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4927 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004928 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4929 dstConfig->ext.mix.handle = mIoHandle;
4930 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004931}
4932
4933void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4934 struct audio_port *port) const
4935{
Eric Laurent84c70242014-06-23 08:46:27 -07004936 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004937 mProfile->toAudioPort(port);
4938 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 toAudioPortConfig(&port->active_config);
4940 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004941 port->ext.mix.handle = mIoHandle;
4942 port->ext.mix.latency_class =
4943 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4944}
Eric Laurente552edb2014-03-10 17:42:56 -07004945
Eric Laurente0720872014-03-11 09:30:41 -07004946status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004947{
4948 const size_t SIZE = 256;
4949 char buffer[SIZE];
4950 String8 result;
4951
4952 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4953 result.append(buffer);
4954 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4955 result.append(buffer);
4956 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4957 result.append(buffer);
4958 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4959 result.append(buffer);
4960 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4961 result.append(buffer);
4962 snprintf(buffer, SIZE, " Devices %08x\n", device());
4963 result.append(buffer);
4964 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4965 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004966 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4967 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4968 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004969 result.append(buffer);
4970 }
4971 write(fd, result.string(), result.size());
4972
4973 return NO_ERROR;
4974}
4975
4976// --- AudioInputDescriptor class implementation
4977
Eric Laurent1c333e22014-05-20 10:48:17 -07004978AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004979 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004980 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004981 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004982{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004983 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004984 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004985 mSamplingRate = profile->pickSamplingRate();
4986 mFormat = profile->pickFormat();
4987 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004988 if (profile->mGains.size() > 0) {
4989 profile->mGains[0]->getDefaultConfig(&mGain);
4990 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004991 }
Eric Laurente552edb2014-03-10 17:42:56 -07004992}
4993
Eric Laurent1c333e22014-05-20 10:48:17 -07004994void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 struct audio_port_config *dstConfig,
4996 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004997{
Eric Laurent84c70242014-06-23 08:46:27 -07004998 ALOG_ASSERT(mProfile != 0,
4999 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005000 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5001 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5002 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005003 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005004 }
5005
5006 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5007
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 dstConfig->id = mId;
5009 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5010 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005011 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5012 dstConfig->ext.mix.handle = mIoHandle;
5013 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005014}
5015
5016void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5017 struct audio_port *port) const
5018{
Eric Laurent84c70242014-06-23 08:46:27 -07005019 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5020
Eric Laurent1c333e22014-05-20 10:48:17 -07005021 mProfile->toAudioPort(port);
5022 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 toAudioPortConfig(&port->active_config);
5024 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005025 port->ext.mix.handle = mIoHandle;
5026 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5027}
5028
Eric Laurente0720872014-03-11 09:30:41 -07005029status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005030{
5031 const size_t SIZE = 256;
5032 char buffer[SIZE];
5033 String8 result;
5034
5035 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5036 result.append(buffer);
5037 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5038 result.append(buffer);
5039 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5040 result.append(buffer);
5041 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5042 result.append(buffer);
5043 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5044 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005045 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5046 result.append(buffer);
5047
Eric Laurente552edb2014-03-10 17:42:56 -07005048 write(fd, result.string(), result.size());
5049
5050 return NO_ERROR;
5051}
5052
5053// --- StreamDescriptor class implementation
5054
Eric Laurente0720872014-03-11 09:30:41 -07005055AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005056 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5057{
5058 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5059}
5060
Eric Laurente0720872014-03-11 09:30:41 -07005061int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005062{
Eric Laurente0720872014-03-11 09:30:41 -07005063 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005064 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5065 if (mIndexCur.indexOfKey(device) < 0) {
5066 device = AUDIO_DEVICE_OUT_DEFAULT;
5067 }
5068 return mIndexCur.valueFor(device);
5069}
5070
Eric Laurente0720872014-03-11 09:30:41 -07005071void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005072{
5073 const size_t SIZE = 256;
5074 char buffer[SIZE];
5075 String8 result;
5076
5077 snprintf(buffer, SIZE, "%s %02d %02d ",
5078 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5079 result.append(buffer);
5080 for (size_t i = 0; i < mIndexCur.size(); i++) {
5081 snprintf(buffer, SIZE, "%04x : %02d, ",
5082 mIndexCur.keyAt(i),
5083 mIndexCur.valueAt(i));
5084 result.append(buffer);
5085 }
5086 result.append("\n");
5087
5088 write(fd, result.string(), result.size());
5089}
5090
5091// --- EffectDescriptor class implementation
5092
Eric Laurente0720872014-03-11 09:30:41 -07005093status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005094{
5095 const size_t SIZE = 256;
5096 char buffer[SIZE];
5097 String8 result;
5098
5099 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5100 result.append(buffer);
5101 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5102 result.append(buffer);
5103 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5104 result.append(buffer);
5105 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5106 result.append(buffer);
5107 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5108 result.append(buffer);
5109 write(fd, result.string(), result.size());
5110
5111 return NO_ERROR;
5112}
5113
Eric Laurent1c333e22014-05-20 10:48:17 -07005114// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005115
Eric Laurente0720872014-03-11 09:30:41 -07005116AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005117 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5118 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005119{
5120}
5121
Eric Laurente0720872014-03-11 09:30:41 -07005122AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005123{
5124 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005125 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005126 }
5127 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005128 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005129 }
5130 free((void *)mName);
5131}
5132
Eric Laurent1afeecb2014-05-14 08:52:28 -07005133status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5134{
5135 cnode *node = root->first_child;
5136
5137 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5138
5139 while (node) {
5140 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5141 profile->loadSamplingRates((char *)node->value);
5142 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5143 profile->loadFormats((char *)node->value);
5144 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5145 profile->loadInChannels((char *)node->value);
5146 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5147 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5148 mDeclaredDevices);
5149 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5150 profile->loadGains(node);
5151 }
5152 node = node->next;
5153 }
5154 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5155 "loadInput() invalid supported devices");
5156 ALOGW_IF(profile->mChannelMasks.size() == 0,
5157 "loadInput() invalid supported channel masks");
5158 ALOGW_IF(profile->mSamplingRates.size() == 0,
5159 "loadInput() invalid supported sampling rates");
5160 ALOGW_IF(profile->mFormats.size() == 0,
5161 "loadInput() invalid supported formats");
5162 if (!profile->mSupportedDevices.isEmpty() &&
5163 (profile->mChannelMasks.size() != 0) &&
5164 (profile->mSamplingRates.size() != 0) &&
5165 (profile->mFormats.size() != 0)) {
5166
5167 ALOGV("loadInput() adding input Supported Devices %04x",
5168 profile->mSupportedDevices.types());
5169
5170 mInputProfiles.add(profile);
5171 return NO_ERROR;
5172 } else {
5173 return BAD_VALUE;
5174 }
5175}
5176
5177status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5178{
5179 cnode *node = root->first_child;
5180
5181 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5182
5183 while (node) {
5184 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5185 profile->loadSamplingRates((char *)node->value);
5186 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5187 profile->loadFormats((char *)node->value);
5188 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5189 profile->loadOutChannels((char *)node->value);
5190 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5191 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5192 mDeclaredDevices);
5193 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5194 profile->mFlags = parseFlagNames((char *)node->value);
5195 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5196 profile->loadGains(node);
5197 }
5198 node = node->next;
5199 }
5200 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5201 "loadOutput() invalid supported devices");
5202 ALOGW_IF(profile->mChannelMasks.size() == 0,
5203 "loadOutput() invalid supported channel masks");
5204 ALOGW_IF(profile->mSamplingRates.size() == 0,
5205 "loadOutput() invalid supported sampling rates");
5206 ALOGW_IF(profile->mFormats.size() == 0,
5207 "loadOutput() invalid supported formats");
5208 if (!profile->mSupportedDevices.isEmpty() &&
5209 (profile->mChannelMasks.size() != 0) &&
5210 (profile->mSamplingRates.size() != 0) &&
5211 (profile->mFormats.size() != 0)) {
5212
5213 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5214 profile->mSupportedDevices.types(), profile->mFlags);
5215
5216 mOutputProfiles.add(profile);
5217 return NO_ERROR;
5218 } else {
5219 return BAD_VALUE;
5220 }
5221}
5222
5223status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5224{
5225 cnode *node = root->first_child;
5226
5227 audio_devices_t type = AUDIO_DEVICE_NONE;
5228 while (node) {
5229 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5230 type = parseDeviceNames((char *)node->value);
5231 break;
5232 }
5233 node = node->next;
5234 }
5235 if (type == AUDIO_DEVICE_NONE ||
5236 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5237 ALOGW("loadDevice() bad type %08x", type);
5238 return BAD_VALUE;
5239 }
5240 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5241 deviceDesc->mModule = this;
5242
5243 node = root->first_child;
5244 while (node) {
5245 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5246 deviceDesc->mAddress = String8((char *)node->value);
5247 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5248 if (audio_is_input_device(type)) {
5249 deviceDesc->loadInChannels((char *)node->value);
5250 } else {
5251 deviceDesc->loadOutChannels((char *)node->value);
5252 }
5253 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5254 deviceDesc->loadGains(node);
5255 }
5256 node = node->next;
5257 }
5258
5259 ALOGV("loadDevice() adding device name %s type %08x address %s",
5260 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5261
5262 mDeclaredDevices.add(deviceDesc);
5263
5264 return NO_ERROR;
5265}
5266
Eric Laurente0720872014-03-11 09:30:41 -07005267void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005268{
5269 const size_t SIZE = 256;
5270 char buffer[SIZE];
5271 String8 result;
5272
5273 snprintf(buffer, SIZE, " - name: %s\n", mName);
5274 result.append(buffer);
5275 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5276 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005277 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5278 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005279 write(fd, result.string(), result.size());
5280 if (mOutputProfiles.size()) {
5281 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5282 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005283 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005284 write(fd, buffer, strlen(buffer));
5285 mOutputProfiles[i]->dump(fd);
5286 }
5287 }
5288 if (mInputProfiles.size()) {
5289 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5290 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005291 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005292 write(fd, buffer, strlen(buffer));
5293 mInputProfiles[i]->dump(fd);
5294 }
5295 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005296 if (mDeclaredDevices.size()) {
5297 write(fd, " - devices:\n", strlen(" - devices:\n"));
5298 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5299 mDeclaredDevices[i]->dump(fd, 4, i);
5300 }
5301 }
Eric Laurente552edb2014-03-10 17:42:56 -07005302}
5303
Eric Laurent1c333e22014-05-20 10:48:17 -07005304// --- AudioPort class implementation
5305
Eric Laurenta121f902014-06-03 13:32:54 -07005306
5307AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5308 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005309 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005310{
5311 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5312 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5313}
5314
Eric Laurent1c333e22014-05-20 10:48:17 -07005315void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5316{
5317 port->role = mRole;
5318 port->type = mType;
5319 unsigned int i;
5320 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5321 port->sample_rates[i] = mSamplingRates[i];
5322 }
5323 port->num_sample_rates = i;
5324 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5325 port->channel_masks[i] = mChannelMasks[i];
5326 }
5327 port->num_channel_masks = i;
5328 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5329 port->formats[i] = mFormats[i];
5330 }
5331 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005332
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005333 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005334
5335 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5336 port->gains[i] = mGains[i]->mGain;
5337 }
5338 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005339}
5340
5341
5342void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5343{
5344 char *str = strtok(name, "|");
5345
5346 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5347 // rates should be read from the output stream after it is opened for the first time
5348 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5349 mSamplingRates.add(0);
5350 return;
5351 }
5352
5353 while (str != NULL) {
5354 uint32_t rate = atoi(str);
5355 if (rate != 0) {
5356 ALOGV("loadSamplingRates() adding rate %d", rate);
5357 mSamplingRates.add(rate);
5358 }
5359 str = strtok(NULL, "|");
5360 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005361}
5362
5363void AudioPolicyManager::AudioPort::loadFormats(char *name)
5364{
5365 char *str = strtok(name, "|");
5366
5367 // by convention, "0' in the first entry in mFormats indicates the supported formats
5368 // should be read from the output stream after it is opened for the first time
5369 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5370 mFormats.add(AUDIO_FORMAT_DEFAULT);
5371 return;
5372 }
5373
5374 while (str != NULL) {
5375 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5376 ARRAY_SIZE(sFormatNameToEnumTable),
5377 str);
5378 if (format != AUDIO_FORMAT_DEFAULT) {
5379 mFormats.add(format);
5380 }
5381 str = strtok(NULL, "|");
5382 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005383}
5384
5385void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5386{
5387 const char *str = strtok(name, "|");
5388
5389 ALOGV("loadInChannels() %s", name);
5390
5391 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5392 mChannelMasks.add(0);
5393 return;
5394 }
5395
5396 while (str != NULL) {
5397 audio_channel_mask_t channelMask =
5398 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5399 ARRAY_SIZE(sInChannelsNameToEnumTable),
5400 str);
5401 if (channelMask != 0) {
5402 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5403 mChannelMasks.add(channelMask);
5404 }
5405 str = strtok(NULL, "|");
5406 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005407}
5408
5409void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5410{
5411 const char *str = strtok(name, "|");
5412
5413 ALOGV("loadOutChannels() %s", name);
5414
5415 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5416 // masks should be read from the output stream after it is opened for the first time
5417 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5418 mChannelMasks.add(0);
5419 return;
5420 }
5421
5422 while (str != NULL) {
5423 audio_channel_mask_t channelMask =
5424 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5425 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5426 str);
5427 if (channelMask != 0) {
5428 mChannelMasks.add(channelMask);
5429 }
5430 str = strtok(NULL, "|");
5431 }
5432 return;
5433}
5434
Eric Laurent1afeecb2014-05-14 08:52:28 -07005435audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5436{
5437 const char *str = strtok(name, "|");
5438
5439 ALOGV("loadGainMode() %s", name);
5440 audio_gain_mode_t mode = 0;
5441 while (str != NULL) {
5442 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5443 ARRAY_SIZE(sGainModeNameToEnumTable),
5444 str);
5445 str = strtok(NULL, "|");
5446 }
5447 return mode;
5448}
5449
Eric Laurenta121f902014-06-03 13:32:54 -07005450void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005451{
5452 cnode *node = root->first_child;
5453
Eric Laurenta121f902014-06-03 13:32:54 -07005454 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005455
5456 while (node) {
5457 if (strcmp(node->name, GAIN_MODE) == 0) {
5458 gain->mGain.mode = loadGainMode((char *)node->value);
5459 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005460 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005461 gain->mGain.channel_mask =
5462 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5463 ARRAY_SIZE(sInChannelsNameToEnumTable),
5464 (char *)node->value);
5465 } else {
5466 gain->mGain.channel_mask =
5467 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5468 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5469 (char *)node->value);
5470 }
5471 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5472 gain->mGain.min_value = atoi((char *)node->value);
5473 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5474 gain->mGain.max_value = atoi((char *)node->value);
5475 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5476 gain->mGain.default_value = atoi((char *)node->value);
5477 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5478 gain->mGain.step_value = atoi((char *)node->value);
5479 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5480 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5481 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5482 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5483 }
5484 node = node->next;
5485 }
5486
5487 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5488 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5489
5490 if (gain->mGain.mode == 0) {
5491 return;
5492 }
5493 mGains.add(gain);
5494}
5495
5496void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5497{
5498 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005499 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005500 while (node) {
5501 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005502 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005503 node = node->next;
5504 }
5505}
5506
Glenn Kastencbd48022014-07-24 13:46:44 -07005507status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005508{
5509 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5510 if (mSamplingRates[i] == samplingRate) {
5511 return NO_ERROR;
5512 }
5513 }
5514 return BAD_VALUE;
5515}
5516
Glenn Kastencbd48022014-07-24 13:46:44 -07005517status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5518 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005519{
Glenn Kastencbd48022014-07-24 13:46:44 -07005520 // Search for the closest supported sampling rate that is above (preferred)
5521 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5522 // The sampling rates do not need to be sorted in ascending order.
5523 ssize_t maxBelow = -1;
5524 ssize_t minAbove = -1;
5525 uint32_t candidate;
5526 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5527 candidate = mSamplingRates[i];
5528 if (candidate == samplingRate) {
5529 if (updatedSamplingRate != NULL) {
5530 *updatedSamplingRate = candidate;
5531 }
5532 return NO_ERROR;
5533 }
5534 // candidate < desired
5535 if (candidate < samplingRate) {
5536 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5537 maxBelow = i;
5538 }
5539 // candidate > desired
5540 } else {
5541 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5542 minAbove = i;
5543 }
5544 }
5545 }
5546 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5547 // TODO Move these assumptions out.
5548 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5549 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5550 // due to approximation by an int32_t of the
5551 // phase increments
5552 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5553 if (minAbove >= 0) {
5554 candidate = mSamplingRates[minAbove];
5555 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5556 if (updatedSamplingRate != NULL) {
5557 *updatedSamplingRate = candidate;
5558 }
5559 return NO_ERROR;
5560 }
5561 }
5562 // But if we have to up-sample from a lower sampling rate, that's OK.
5563 if (maxBelow >= 0) {
5564 candidate = mSamplingRates[maxBelow];
5565 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5566 if (updatedSamplingRate != NULL) {
5567 *updatedSamplingRate = candidate;
5568 }
5569 return NO_ERROR;
5570 }
5571 }
5572 // leave updatedSamplingRate unmodified
5573 return BAD_VALUE;
5574}
5575
5576status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5577{
5578 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005579 if (mChannelMasks[i] == channelMask) {
5580 return NO_ERROR;
5581 }
5582 }
5583 return BAD_VALUE;
5584}
5585
Glenn Kastencbd48022014-07-24 13:46:44 -07005586status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5587 const
5588{
5589 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5590 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5591 // FIXME Does not handle multi-channel automatic conversions yet
5592 audio_channel_mask_t supported = mChannelMasks[i];
5593 if (supported == channelMask) {
5594 return NO_ERROR;
5595 }
5596 if (isRecordThread) {
5597 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5598 // FIXME Abstract this out to a table.
5599 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5600 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5601 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5602 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5603 return NO_ERROR;
5604 }
5605 }
5606 }
5607 return BAD_VALUE;
5608}
5609
Eric Laurenta121f902014-06-03 13:32:54 -07005610status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5611{
5612 for (size_t i = 0; i < mFormats.size(); i ++) {
5613 if (mFormats[i] == format) {
5614 return NO_ERROR;
5615 }
5616 }
5617 return BAD_VALUE;
5618}
5619
Eric Laurent1e693b52014-07-09 15:03:28 -07005620
5621uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5622{
5623 // special case for uninitialized dynamic profile
5624 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5625 return 0;
5626 }
5627
5628 uint32_t samplingRate = 0;
5629 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5630
5631 // For mixed output and inputs, use max mixer sampling rates. Do not
5632 // limit sampling rate otherwise
5633 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5634 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5635 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5636 maxRate = UINT_MAX;
5637 }
5638 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5639 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5640 samplingRate = mSamplingRates[i];
5641 }
5642 }
5643 return samplingRate;
5644}
5645
5646audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5647{
5648 // special case for uninitialized dynamic profile
5649 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5650 return AUDIO_CHANNEL_NONE;
5651 }
5652
5653 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5654 uint32_t channelCount = 0;
5655 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5656
5657 // For mixed output and inputs, use max mixer channel count. Do not
5658 // limit channel count otherwise
5659 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5660 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5661 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5662 maxCount = UINT_MAX;
5663 }
5664 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5665 uint32_t cnlCount;
5666 if (mUseInChannelMask) {
5667 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5668 } else {
5669 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5670 }
5671 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5672 channelMask = mChannelMasks[i];
5673 }
5674 }
5675 return channelMask;
5676}
5677
Andy Hung9a605382014-07-28 16:16:31 -07005678/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005679const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5680 AUDIO_FORMAT_DEFAULT,
5681 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005682 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005683 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005684 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005685 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005686};
5687
5688int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5689 audio_format_t format2)
5690{
5691 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5692 // compressed format and better than any PCM format. This is by design of pickFormat()
5693 if (!audio_is_linear_pcm(format1)) {
5694 if (!audio_is_linear_pcm(format2)) {
5695 return 0;
5696 }
5697 return 1;
5698 }
5699 if (!audio_is_linear_pcm(format2)) {
5700 return -1;
5701 }
5702
5703 int index1 = -1, index2 = -1;
5704 for (size_t i = 0;
5705 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5706 i ++) {
5707 if (sPcmFormatCompareTable[i] == format1) {
5708 index1 = i;
5709 }
5710 if (sPcmFormatCompareTable[i] == format2) {
5711 index2 = i;
5712 }
5713 }
5714 // format1 not found => index1 < 0 => format2 > format1
5715 // format2 not found => index2 < 0 => format2 < format1
5716 return index1 - index2;
5717}
5718
5719audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5720{
5721 // special case for uninitialized dynamic profile
5722 if (mFormats.size() == 1 && mFormats[0] == 0) {
5723 return AUDIO_FORMAT_DEFAULT;
5724 }
5725
5726 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005727 audio_format_t bestFormat =
5728 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5729 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005730 // For mixed output and inputs, use best mixer output format. Do not
5731 // limit format otherwise
5732 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5733 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005734 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005735 bestFormat = AUDIO_FORMAT_INVALID;
5736 }
5737
5738 for (size_t i = 0; i < mFormats.size(); i ++) {
5739 if ((compareFormats(mFormats[i], format) > 0) &&
5740 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5741 format = mFormats[i];
5742 }
5743 }
5744 return format;
5745}
5746
Eric Laurenta121f902014-06-03 13:32:54 -07005747status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5748 int index) const
5749{
5750 if (index < 0 || (size_t)index >= mGains.size()) {
5751 return BAD_VALUE;
5752 }
5753 return mGains[index]->checkConfig(gainConfig);
5754}
5755
Eric Laurent1afeecb2014-05-14 08:52:28 -07005756void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5757{
5758 const size_t SIZE = 256;
5759 char buffer[SIZE];
5760 String8 result;
5761
5762 if (mName.size() != 0) {
5763 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5764 result.append(buffer);
5765 }
5766
5767 if (mSamplingRates.size() != 0) {
5768 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5769 result.append(buffer);
5770 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005771 if (i == 0 && mSamplingRates[i] == 0) {
5772 snprintf(buffer, SIZE, "Dynamic");
5773 } else {
5774 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5775 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005776 result.append(buffer);
5777 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5778 }
5779 result.append("\n");
5780 }
5781
5782 if (mChannelMasks.size() != 0) {
5783 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5784 result.append(buffer);
5785 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005786 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5787
5788 if (i == 0 && mChannelMasks[i] == 0) {
5789 snprintf(buffer, SIZE, "Dynamic");
5790 } else {
5791 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5792 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005793 result.append(buffer);
5794 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5795 }
5796 result.append("\n");
5797 }
5798
5799 if (mFormats.size() != 0) {
5800 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5801 result.append(buffer);
5802 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005803 const char *formatStr = enumToString(sFormatNameToEnumTable,
5804 ARRAY_SIZE(sFormatNameToEnumTable),
5805 mFormats[i]);
5806 if (i == 0 && strcmp(formatStr, "") == 0) {
5807 snprintf(buffer, SIZE, "Dynamic");
5808 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005809 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005810 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005811 result.append(buffer);
5812 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5813 }
5814 result.append("\n");
5815 }
5816 write(fd, result.string(), result.size());
5817 if (mGains.size() != 0) {
5818 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5819 write(fd, buffer, strlen(buffer) + 1);
5820 result.append(buffer);
5821 for (size_t i = 0; i < mGains.size(); i++) {
5822 mGains[i]->dump(fd, spaces + 2, i);
5823 }
5824 }
5825}
5826
5827// --- AudioGain class implementation
5828
Eric Laurenta121f902014-06-03 13:32:54 -07005829AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005830{
Eric Laurenta121f902014-06-03 13:32:54 -07005831 mIndex = index;
5832 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005833 memset(&mGain, 0, sizeof(struct audio_gain));
5834}
5835
Eric Laurenta121f902014-06-03 13:32:54 -07005836void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5837{
5838 config->index = mIndex;
5839 config->mode = mGain.mode;
5840 config->channel_mask = mGain.channel_mask;
5841 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5842 config->values[0] = mGain.default_value;
5843 } else {
5844 uint32_t numValues;
5845 if (mUseInChannelMask) {
5846 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5847 } else {
5848 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5849 }
5850 for (size_t i = 0; i < numValues; i++) {
5851 config->values[i] = mGain.default_value;
5852 }
5853 }
5854 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5855 config->ramp_duration_ms = mGain.min_ramp_ms;
5856 }
5857}
5858
5859status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5860{
5861 if ((config->mode & ~mGain.mode) != 0) {
5862 return BAD_VALUE;
5863 }
5864 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5865 if ((config->values[0] < mGain.min_value) ||
5866 (config->values[0] > mGain.max_value)) {
5867 return BAD_VALUE;
5868 }
5869 } else {
5870 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5871 return BAD_VALUE;
5872 }
5873 uint32_t numValues;
5874 if (mUseInChannelMask) {
5875 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5876 } else {
5877 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5878 }
5879 for (size_t i = 0; i < numValues; i++) {
5880 if ((config->values[i] < mGain.min_value) ||
5881 (config->values[i] > mGain.max_value)) {
5882 return BAD_VALUE;
5883 }
5884 }
5885 }
5886 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5887 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5888 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5889 return BAD_VALUE;
5890 }
5891 }
5892 return NO_ERROR;
5893}
5894
Eric Laurent1afeecb2014-05-14 08:52:28 -07005895void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5896{
5897 const size_t SIZE = 256;
5898 char buffer[SIZE];
5899 String8 result;
5900
5901 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5902 result.append(buffer);
5903 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5904 result.append(buffer);
5905 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5906 result.append(buffer);
5907 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5908 result.append(buffer);
5909 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5910 result.append(buffer);
5911 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5912 result.append(buffer);
5913 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5914 result.append(buffer);
5915 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5916 result.append(buffer);
5917 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5918 result.append(buffer);
5919
5920 write(fd, result.string(), result.size());
5921}
5922
Eric Laurent1f2f2232014-06-02 12:01:23 -07005923// --- AudioPortConfig class implementation
5924
5925AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5926{
5927 mSamplingRate = 0;
5928 mChannelMask = AUDIO_CHANNEL_NONE;
5929 mFormat = AUDIO_FORMAT_INVALID;
5930 mGain.index = -1;
5931}
5932
Eric Laurenta121f902014-06-03 13:32:54 -07005933status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5934 const struct audio_port_config *config,
5935 struct audio_port_config *backupConfig)
5936{
5937 struct audio_port_config localBackupConfig;
5938 status_t status = NO_ERROR;
5939
5940 localBackupConfig.config_mask = config->config_mask;
5941 toAudioPortConfig(&localBackupConfig);
5942
5943 if (mAudioPort == 0) {
5944 status = NO_INIT;
5945 goto exit;
5946 }
5947 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005948 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005949 if (status != NO_ERROR) {
5950 goto exit;
5951 }
5952 mSamplingRate = config->sample_rate;
5953 }
5954 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005955 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005956 if (status != NO_ERROR) {
5957 goto exit;
5958 }
5959 mChannelMask = config->channel_mask;
5960 }
5961 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5962 status = mAudioPort->checkFormat(config->format);
5963 if (status != NO_ERROR) {
5964 goto exit;
5965 }
5966 mFormat = config->format;
5967 }
5968 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5969 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5970 if (status != NO_ERROR) {
5971 goto exit;
5972 }
5973 mGain = config->gain;
5974 }
5975
5976exit:
5977 if (status != NO_ERROR) {
5978 applyAudioPortConfig(&localBackupConfig);
5979 }
5980 if (backupConfig != NULL) {
5981 *backupConfig = localBackupConfig;
5982 }
5983 return status;
5984}
5985
Eric Laurent1f2f2232014-06-02 12:01:23 -07005986void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5987 struct audio_port_config *dstConfig,
5988 const struct audio_port_config *srcConfig) const
5989{
5990 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5991 dstConfig->sample_rate = mSamplingRate;
5992 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5993 dstConfig->sample_rate = srcConfig->sample_rate;
5994 }
5995 } else {
5996 dstConfig->sample_rate = 0;
5997 }
5998 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5999 dstConfig->channel_mask = mChannelMask;
6000 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6001 dstConfig->channel_mask = srcConfig->channel_mask;
6002 }
6003 } else {
6004 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6005 }
6006 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6007 dstConfig->format = mFormat;
6008 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6009 dstConfig->format = srcConfig->format;
6010 }
6011 } else {
6012 dstConfig->format = AUDIO_FORMAT_INVALID;
6013 }
6014 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6015 dstConfig->gain = mGain;
6016 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6017 dstConfig->gain = srcConfig->gain;
6018 }
6019 } else {
6020 dstConfig->gain.index = -1;
6021 }
6022 if (dstConfig->gain.index != -1) {
6023 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6024 } else {
6025 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6026 }
6027}
6028
Eric Laurent1c333e22014-05-20 10:48:17 -07006029// --- IOProfile class implementation
6030
Eric Laurent1afeecb2014-05-14 08:52:28 -07006031AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006032 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006033 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006034{
6035}
6036
Eric Laurente0720872014-03-11 09:30:41 -07006037AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006038{
6039}
6040
6041// checks if the IO profile is compatible with specified parameters.
6042// Sampling rate, format and channel mask must be specified in order to
6043// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006044bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006045 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006046 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006047 audio_format_t format,
6048 audio_channel_mask_t channelMask,
6049 audio_output_flags_t flags) const
6050{
Glenn Kastencbd48022014-07-24 13:46:44 -07006051 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6052 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6053 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006054
Glenn Kastencbd48022014-07-24 13:46:44 -07006055 if ((mSupportedDevices.types() & device) != device) {
6056 return false;
6057 }
6058
6059 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006060 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006061 }
6062 uint32_t myUpdatedSamplingRate = samplingRate;
6063 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006064 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006065 }
6066 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6067 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006068 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006069 }
6070
6071 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6072 return false;
6073 }
6074
6075 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6076 checkExactChannelMask(channelMask) != NO_ERROR)) {
6077 return false;
6078 }
6079 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6080 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6081 return false;
6082 }
6083
6084 if (isPlaybackThread && (mFlags & flags) != flags) {
6085 return false;
6086 }
6087 // The only input flag that is allowed to be different is the fast flag.
6088 // An existing fast stream is compatible with a normal track request.
6089 // An existing normal stream is compatible with a fast track request,
6090 // but the fast request will be denied by AudioFlinger and converted to normal track.
6091 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6092 ~AUDIO_INPUT_FLAG_FAST)) {
6093 return false;
6094 }
6095
6096 if (updatedSamplingRate != NULL) {
6097 *updatedSamplingRate = myUpdatedSamplingRate;
6098 }
6099 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006100}
6101
Eric Laurente0720872014-03-11 09:30:41 -07006102void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006103{
6104 const size_t SIZE = 256;
6105 char buffer[SIZE];
6106 String8 result;
6107
Eric Laurent1afeecb2014-05-14 08:52:28 -07006108 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006109
Eric Laurente552edb2014-03-10 17:42:56 -07006110 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6111 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006112 snprintf(buffer, SIZE, " - devices:\n");
6113 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006114 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006115 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6116 mSupportedDevices[i]->dump(fd, 6, i);
6117 }
Eric Laurente552edb2014-03-10 17:42:56 -07006118}
6119
Eric Laurentd4692962014-05-05 18:13:44 -07006120void AudioPolicyManager::IOProfile::log()
6121{
6122 const size_t SIZE = 256;
6123 char buffer[SIZE];
6124 String8 result;
6125
6126 ALOGV(" - sampling rates: ");
6127 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6128 ALOGV(" %d", mSamplingRates[i]);
6129 }
6130
6131 ALOGV(" - channel masks: ");
6132 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6133 ALOGV(" 0x%04x", mChannelMasks[i]);
6134 }
6135
6136 ALOGV(" - formats: ");
6137 for (size_t i = 0; i < mFormats.size(); i++) {
6138 ALOGV(" 0x%08x", mFormats[i]);
6139 }
6140
6141 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6142 ALOGV(" - flags: 0x%04x\n", mFlags);
6143}
6144
6145
Eric Laurent3a4311c2014-03-17 12:00:47 -07006146// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006147
Eric Laurent1f2f2232014-06-02 12:01:23 -07006148
6149AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6150 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6151 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6152 AUDIO_PORT_ROLE_SOURCE,
6153 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006154 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006155{
6156 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006157 if (mGains.size() > 0) {
6158 mGains[0]->getDefaultConfig(&mGain);
6159 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006160}
6161
Eric Laurent3a4311c2014-03-17 12:00:47 -07006162bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006163{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006164 // Devices are considered equal if they:
6165 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6166 // - have the same address or one device does not specify the address
6167 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006168 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006169 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006170 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006171 mChannelMask == other->mChannelMask);
6172}
6173
6174void AudioPolicyManager::DeviceVector::refreshTypes()
6175{
Eric Laurent1c333e22014-05-20 10:48:17 -07006176 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006177 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006178 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006179 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006180 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006181}
6182
6183ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6184{
6185 for(size_t i = 0; i < size(); i++) {
6186 if (item->equals(itemAt(i))) {
6187 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006188 }
6189 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006190 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006191}
6192
Eric Laurent3a4311c2014-03-17 12:00:47 -07006193ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006194{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006195 ssize_t ret = indexOf(item);
6196
6197 if (ret < 0) {
6198 ret = SortedVector::add(item);
6199 if (ret >= 0) {
6200 refreshTypes();
6201 }
6202 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006203 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006204 ret = -1;
6205 }
6206 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006207}
6208
Eric Laurent3a4311c2014-03-17 12:00:47 -07006209ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6210{
6211 size_t i;
6212 ssize_t ret = indexOf(item);
6213
6214 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006215 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006216 } else {
6217 ret = SortedVector::removeAt(ret);
6218 if (ret >= 0) {
6219 refreshTypes();
6220 }
6221 }
6222 return ret;
6223}
6224
6225void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6226{
6227 DeviceVector deviceList;
6228
6229 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6230 types &= ~role_bit;
6231
6232 while (types) {
6233 uint32_t i = 31 - __builtin_clz(types);
6234 uint32_t type = 1 << i;
6235 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006236 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006237 }
6238}
6239
Eric Laurent1afeecb2014-05-14 08:52:28 -07006240void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6241 const DeviceVector& declaredDevices)
6242{
6243 char *devName = strtok(name, "|");
6244 while (devName != NULL) {
6245 if (strlen(devName) != 0) {
6246 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6247 ARRAY_SIZE(sDeviceNameToEnumTable),
6248 devName);
6249 if (type != AUDIO_DEVICE_NONE) {
6250 add(new DeviceDescriptor(String8(""), type));
6251 } else {
6252 sp<DeviceDescriptor> deviceDesc =
6253 declaredDevices.getDeviceFromName(String8(devName));
6254 if (deviceDesc != 0) {
6255 add(deviceDesc);
6256 }
6257 }
6258 }
6259 devName = strtok(NULL, "|");
6260 }
6261}
6262
Eric Laurent1c333e22014-05-20 10:48:17 -07006263sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6264 audio_devices_t type, String8 address) const
6265{
6266 sp<DeviceDescriptor> device;
6267 for (size_t i = 0; i < size(); i++) {
6268 if (itemAt(i)->mDeviceType == type) {
6269 device = itemAt(i);
6270 if (itemAt(i)->mAddress = address) {
6271 break;
6272 }
6273 }
6274 }
6275 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6276 type, address.string(), device.get());
6277 return device;
6278}
6279
Eric Laurent6a94d692014-05-20 11:18:06 -07006280sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6281 audio_port_handle_t id) const
6282{
6283 sp<DeviceDescriptor> device;
6284 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006285 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006286 if (itemAt(i)->mId == id) {
6287 device = itemAt(i);
6288 break;
6289 }
6290 }
6291 return device;
6292}
6293
Eric Laurent1c333e22014-05-20 10:48:17 -07006294AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6295 audio_devices_t type) const
6296{
6297 DeviceVector devices;
6298 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6299 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6300 devices.add(itemAt(i));
6301 type &= ~itemAt(i)->mDeviceType;
6302 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6303 itemAt(i)->mDeviceType, itemAt(i).get());
6304 }
6305 }
6306 return devices;
6307}
6308
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006309AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6310 audio_devices_t type, String8 address) const
6311{
6312 DeviceVector devices;
6313 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6314 for (size_t i = 0; i < size(); i++) {
6315 //ALOGV(" at i=%d: device=%x, addr=%s",
6316 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6317 if (itemAt(i)->mDeviceType == type) {
6318 if (itemAt(i)->mAddress == address) {
6319 //ALOGV(" found matching address %s", address.string());
6320 devices.add(itemAt(i));
6321 }
6322 }
6323 }
6324 return devices;
6325}
6326
Eric Laurent1afeecb2014-05-14 08:52:28 -07006327sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6328 const String8& name) const
6329{
6330 sp<DeviceDescriptor> device;
6331 for (size_t i = 0; i < size(); i++) {
6332 if (itemAt(i)->mName == name) {
6333 device = itemAt(i);
6334 break;
6335 }
6336 }
6337 return device;
6338}
6339
Eric Laurent6a94d692014-05-20 11:18:06 -07006340void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6341 struct audio_port_config *dstConfig,
6342 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006343{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006344 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6345 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006346 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006347 }
6348
6349 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6350
Eric Laurent6a94d692014-05-20 11:18:06 -07006351 dstConfig->id = mId;
6352 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006353 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006354 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006355 dstConfig->ext.device.type = mDeviceType;
6356 dstConfig->ext.device.hw_module = mModule->mHandle;
6357 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006358}
6359
6360void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6361{
Eric Laurent83b88082014-06-20 18:31:16 -07006362 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006363 AudioPort::toAudioPort(port);
6364 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006365 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006366 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006367 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006368 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6369}
6370
Eric Laurent1afeecb2014-05-14 08:52:28 -07006371status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006372{
6373 const size_t SIZE = 256;
6374 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006375 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006376
Eric Laurent1afeecb2014-05-14 08:52:28 -07006377 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6378 result.append(buffer);
6379 if (mId != 0) {
6380 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6381 result.append(buffer);
6382 }
6383 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6384 enumToString(sDeviceNameToEnumTable,
6385 ARRAY_SIZE(sDeviceNameToEnumTable),
6386 mDeviceType));
6387 result.append(buffer);
6388 if (mAddress.size() != 0) {
6389 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6390 result.append(buffer);
6391 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006392 write(fd, result.string(), result.size());
6393 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006394
6395 return NO_ERROR;
6396}
6397
6398
6399// --- audio_policy.conf file parsing
6400
Eric Laurente0720872014-03-11 09:30:41 -07006401audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006402{
6403 uint32_t flag = 0;
6404
6405 // it is OK to cast name to non const here as we are not going to use it after
6406 // strtok() modifies it
6407 char *flagName = strtok(name, "|");
6408 while (flagName != NULL) {
6409 if (strlen(flagName) != 0) {
6410 flag |= stringToEnum(sFlagNameToEnumTable,
6411 ARRAY_SIZE(sFlagNameToEnumTable),
6412 flagName);
6413 }
6414 flagName = strtok(NULL, "|");
6415 }
6416 //force direct flag if offload flag is set: offloading implies a direct output stream
6417 // and all common behaviors are driven by checking only the direct flag
6418 // this should normally be set appropriately in the policy configuration file
6419 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6420 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6421 }
6422
6423 return (audio_output_flags_t)flag;
6424}
6425
Eric Laurente0720872014-03-11 09:30:41 -07006426audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006427{
6428 uint32_t device = 0;
6429
6430 char *devName = strtok(name, "|");
6431 while (devName != NULL) {
6432 if (strlen(devName) != 0) {
6433 device |= stringToEnum(sDeviceNameToEnumTable,
6434 ARRAY_SIZE(sDeviceNameToEnumTable),
6435 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006436 }
Eric Laurente552edb2014-03-10 17:42:56 -07006437 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439 return device;
6440}
6441
Eric Laurente0720872014-03-11 09:30:41 -07006442void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006443{
Eric Laurente552edb2014-03-10 17:42:56 -07006444 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006445 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006446 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006447
Eric Laurent1afeecb2014-05-14 08:52:28 -07006448 node = config_find(root, DEVICES_TAG);
6449 if (node != NULL) {
6450 node = node->first_child;
6451 while (node) {
6452 ALOGV("loadHwModule() loading device %s", node->name);
6453 status_t tmpStatus = module->loadDevice(node);
6454 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6455 status = tmpStatus;
6456 }
6457 node = node->next;
6458 }
6459 }
6460 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006461 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006462 node = node->first_child;
6463 while (node) {
6464 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006465 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006466 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6467 status = tmpStatus;
6468 }
6469 node = node->next;
6470 }
6471 }
6472 node = config_find(root, INPUTS_TAG);
6473 if (node != NULL) {
6474 node = node->first_child;
6475 while (node) {
6476 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006477 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006478 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6479 status = tmpStatus;
6480 }
6481 node = node->next;
6482 }
6483 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006484 loadGlobalConfig(root, module);
6485
Eric Laurente552edb2014-03-10 17:42:56 -07006486 if (status == NO_ERROR) {
6487 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006488 }
6489}
6490
Eric Laurente0720872014-03-11 09:30:41 -07006491void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006492{
6493 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6494 if (node == NULL) {
6495 return;
6496 }
6497
6498 node = node->first_child;
6499 while (node) {
6500 ALOGV("loadHwModules() loading module %s", node->name);
6501 loadHwModule(node);
6502 node = node->next;
6503 }
6504}
6505
Eric Laurent1f2f2232014-06-02 12:01:23 -07006506void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006507{
6508 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006509
Eric Laurente552edb2014-03-10 17:42:56 -07006510 if (node == NULL) {
6511 return;
6512 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006513 DeviceVector declaredDevices;
6514 if (module != NULL) {
6515 declaredDevices = module->mDeclaredDevices;
6516 }
6517
Eric Laurente552edb2014-03-10 17:42:56 -07006518 node = node->first_child;
6519 while (node) {
6520 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006521 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6522 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006523 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6524 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006525 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006526 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006527 ARRAY_SIZE(sDeviceNameToEnumTable),
6528 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006529 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006530 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006531 } else {
6532 ALOGW("loadGlobalConfig() default device not specified");
6533 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006534 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006535 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006536 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6537 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006538 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006539 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6540 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6541 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006542 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6543 uint32_t major, minor;
6544 sscanf((char *)node->value, "%u.%u", &major, &minor);
6545 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6546 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6547 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006548 }
6549 node = node->next;
6550 }
6551}
6552
Eric Laurente0720872014-03-11 09:30:41 -07006553status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006554{
6555 cnode *root;
6556 char *data;
6557
6558 data = (char *)load_file(path, NULL);
6559 if (data == NULL) {
6560 return -ENODEV;
6561 }
6562 root = config_node("", "");
6563 config_load(root, data);
6564
Eric Laurente552edb2014-03-10 17:42:56 -07006565 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006566 // legacy audio_policy.conf files have one global_configuration section
6567 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006568 config_free(root);
6569 free(root);
6570 free(data);
6571
6572 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6573
6574 return NO_ERROR;
6575}
6576
Eric Laurente0720872014-03-11 09:30:41 -07006577void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006578{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006579 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006580 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006581 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6582 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006583 mAvailableOutputDevices.add(mDefaultOutputDevice);
6584 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006585
6586 module = new HwModule("primary");
6587
Eric Laurent1afeecb2014-05-14 08:52:28 -07006588 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006589 profile->mSamplingRates.add(44100);
6590 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6591 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006592 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006593 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6594 module->mOutputProfiles.add(profile);
6595
Eric Laurent1afeecb2014-05-14 08:52:28 -07006596 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006597 profile->mSamplingRates.add(8000);
6598 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6599 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006600 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006601 module->mInputProfiles.add(profile);
6602
6603 mHwModules.add(module);
6604}
6605
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006606audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6607{
6608 // flags to stream type mapping
6609 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6610 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6611 }
6612 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6613 return AUDIO_STREAM_BLUETOOTH_SCO;
6614 }
6615
6616 // usage to stream type mapping
6617 switch (attr->usage) {
6618 case AUDIO_USAGE_MEDIA:
6619 case AUDIO_USAGE_GAME:
6620 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6621 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6622 return AUDIO_STREAM_MUSIC;
6623 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6624 return AUDIO_STREAM_SYSTEM;
6625 case AUDIO_USAGE_VOICE_COMMUNICATION:
6626 return AUDIO_STREAM_VOICE_CALL;
6627
6628 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6629 return AUDIO_STREAM_DTMF;
6630
6631 case AUDIO_USAGE_ALARM:
6632 return AUDIO_STREAM_ALARM;
6633 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6634 return AUDIO_STREAM_RING;
6635
6636 case AUDIO_USAGE_NOTIFICATION:
6637 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6638 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6639 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6640 case AUDIO_USAGE_NOTIFICATION_EVENT:
6641 return AUDIO_STREAM_NOTIFICATION;
6642
6643 case AUDIO_USAGE_UNKNOWN:
6644 default:
6645 return AUDIO_STREAM_MUSIC;
6646 }
6647}
Eric Laurente552edb2014-03-10 17:42:56 -07006648}; // namespace android