blob: b09ba71dd23a48c562570e6b2f8a98a97d848067 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070085 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070090 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050091 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700110 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900111 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122};
123
124const StringToEnum sFormatNameToEnumTable[] = {
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
130 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
131 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700143 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700144 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
146 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
147 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
148 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149};
150
151const StringToEnum sOutChannelsNameToEnumTable[] = {
152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
156 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
157};
158
159const StringToEnum sInChannelsNameToEnumTable[] = {
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
162 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
163};
164
Eric Laurent1afeecb2014-05-14 08:52:28 -0700165const StringToEnum sGainModeNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
168 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
169};
170
Eric Laurent3a4311c2014-03-17 12:00:47 -0700171
172uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
173 size_t size,
174 const char *name)
175{
176 for (size_t i = 0; i < size; i++) {
177 if (strcmp(table[i].name, name) == 0) {
178 ALOGV("stringToEnum() found %s", table[i].name);
179 return table[i].value;
180 }
181 }
182 return 0;
183}
184
185const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
186 size_t size,
187 uint32_t value)
188{
189 for (size_t i = 0; i < size; i++) {
190 if (table[i].value == value) {
191 return table[i].name;
192 }
193 }
194 return "";
195}
196
197bool AudioPolicyManager::stringToBool(const char *value)
198{
199 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
200}
201
202
203// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700204// AudioPolicyInterface implementation
205// ----------------------------------------------------------------------------
206
207
Eric Laurente0720872014-03-11 09:30:41 -0700208status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700209 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700210 const char *device_address)
211{
Eric Laurent22226012014-08-01 17:00:54 -0700212 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurent22226012014-08-01 17:00:54 -0700214 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
215 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700216
217 // connect/disconnect only 1 device at a time
218 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
219
Eric Laurente552edb2014-03-10 17:42:56 -0700220 // handle output devices
221 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700222 SortedVector <audio_io_handle_t> outputs;
223
Eric Laurent1afeecb2014-05-14 08:52:28 -0700224 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
225 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // save a copy of the opened output descriptors before any output is opened or closed
229 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
230 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 switch (state)
232 {
233 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700234 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700235 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700236 ALOGW("setDeviceConnectionState() device already connected: %x", device);
237 return INVALID_OPERATION;
238 }
239 ALOGV("setDeviceConnectionState() connecting device %x", device);
240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700242 index = mAvailableOutputDevices.add(devDesc);
243 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700244 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700245 if (module == 0) {
246 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
247 device);
248 mAvailableOutputDevices.remove(devDesc);
249 return INVALID_OPERATION;
250 }
251 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700252 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 } else {
254 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
256
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700257 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 // outputs should never be empty here
262 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
263 "checkOutputsForDevice() returned no outputs but status OK");
264 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
265 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700266 break;
267 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700268 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700269 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700270 ALOGW("setDeviceConnectionState() device not connected: %x", device);
271 return INVALID_OPERATION;
272 }
273
274 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
275 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700277
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700279 } break;
280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
287 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700288 checkA2dpSuspend();
289 checkOutputForAllStrategies();
290 // outputs must be closed after checkOutputForAllStrategies() is executed
291 if (!outputs.isEmpty()) {
292 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700293 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700294 // close unused outputs after device disconnection or direct outputs that have been
295 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700297 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
298 (desc->mDirectOpenCount == 0))) {
299 closeOutput(outputs[i]);
300 }
301 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 // check again after closing A2DP output to reset mA2dpSuspended if needed
303 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
305
306 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700307 if (mPhoneState == AUDIO_MODE_IN_CALL) {
308 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
309 updateCallRouting(newDevice);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700312 audio_io_handle_t output = mOutputs.keyAt(i);
313 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
314 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
315 true /*fromCache*/);
316 // do not force device change on duplicated output because if device is 0, it will
317 // also force a device 0 for the two outputs it is duplicated to which may override
318 // a valid device selection on those outputs.
319 bool force = !mOutputs.valueAt(i)->isDuplicated()
320 && (!deviceDistinguishesOnAddress(device)
321 // always force when disconnecting (a non-duplicated device)
322 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
323 setOutputDevice(output, newDevice, force, 0);
324 }
Eric Laurente552edb2014-03-10 17:42:56 -0700325 }
326
Eric Laurent72aa32f2014-05-30 18:51:48 -0700327 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700328 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700329 } // end if is output device
330
Eric Laurente552edb2014-03-10 17:42:56 -0700331 // handle input devices
332 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700333 SortedVector <audio_io_handle_t> inputs;
334
Eric Laurent1afeecb2014-05-14 08:52:28 -0700335 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
336 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700337 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700338 switch (state)
339 {
340 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700341 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700342 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700343 ALOGW("setDeviceConnectionState() device already connected: %d", device);
344 return INVALID_OPERATION;
345 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700346 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700347 if (module == NULL) {
348 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
349 device);
350 return INVALID_OPERATION;
351 }
Eric Laurentd4692962014-05-05 18:13:44 -0700352 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
353 return INVALID_OPERATION;
354 }
355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 index = mAvailableInputDevices.add(devDesc);
357 if (index >= 0) {
358 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700359 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 } else {
361 return NO_MEMORY;
362 }
Eric Laurentd4692962014-05-05 18:13:44 -0700363 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700364
365 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700368 ALOGW("setDeviceConnectionState() device not connected: %d", device);
369 return INVALID_OPERATION;
370 }
Eric Laurentd4692962014-05-05 18:13:44 -0700371 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700373 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700374
375 default:
376 ALOGE("setDeviceConnectionState() invalid state: %x", state);
377 return BAD_VALUE;
378 }
379
Eric Laurentd4692962014-05-05 18:13:44 -0700380 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700381
Eric Laurentc2730ba2014-07-20 15:47:07 -0700382 if (mPhoneState == AUDIO_MODE_IN_CALL) {
383 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
384 updateCallRouting(newDevice);
385 }
386
Eric Laurentb52c1522014-05-20 11:27:36 -0700387 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700388 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700389 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700390
391 ALOGW("setDeviceConnectionState() invalid device: %x", device);
392 return BAD_VALUE;
393}
394
Eric Laurente0720872014-03-11 09:30:41 -0700395audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700396 const char *device_address)
397{
Eric Laurent3b73df72014-03-11 09:06:29 -0700398 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700399 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700400 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 ssize_t index;
402 DeviceVector *deviceVector;
403
Eric Laurente552edb2014-03-10 17:42:56 -0700404 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700405 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700406 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 deviceVector = &mAvailableInputDevices;
408 } else {
409 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
410 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700411 }
412
Eric Laurent3a4311c2014-03-17 12:00:47 -0700413 index = deviceVector->indexOf(devDesc);
414 if (index >= 0) {
415 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
416 } else {
417 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
418 }
Eric Laurente552edb2014-03-10 17:42:56 -0700419}
420
Eric Laurentc2730ba2014-07-20 15:47:07 -0700421void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
422{
423 bool createTxPatch = false;
424 struct audio_patch patch;
425 patch.num_sources = 1;
426 patch.num_sinks = 1;
427 status_t status;
428 audio_patch_handle_t afPatchHandle;
429 DeviceVector deviceList;
430
431 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
432 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
433
434 // release existing RX patch if any
435 if (mCallRxPatch != 0) {
436 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
437 mCallRxPatch.clear();
438 }
439 // release TX patch if any
440 if (mCallTxPatch != 0) {
441 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
442 mCallTxPatch.clear();
443 }
444
445 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
446 // via setOutputDevice() on primary output.
447 // Otherwise, create two audio patches for TX and RX path.
448 if (availablePrimaryOutputDevices() & rxDevice) {
449 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
450 // If the TX device is also on the primary HW module, setOutputDevice() will take care
451 // of it due to legacy implementation. If not, create a patch.
452 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
453 == AUDIO_DEVICE_NONE) {
454 createTxPatch = true;
455 }
456 } else {
457 // create RX path audio patch
458 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
459 ALOG_ASSERT(!deviceList.isEmpty(),
460 "updateCallRouting() selected device not in output device list");
461 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
462 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
463 ALOG_ASSERT(!deviceList.isEmpty(),
464 "updateCallRouting() no telephony RX device");
465 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
466
467 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
468 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
469
470 // request to reuse existing output stream if one is already opened to reach the RX device
471 SortedVector<audio_io_handle_t> outputs =
472 getOutputsForDevice(rxDevice, mOutputs);
473 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
474 if (output != AUDIO_IO_HANDLE_NONE) {
475 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
476 ALOG_ASSERT(!outputDesc->isDuplicated(),
477 "updateCallRouting() RX device output is duplicated");
478 outputDesc->toAudioPortConfig(&patch.sources[1]);
479 patch.num_sources = 2;
480 }
481
482 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
483 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
484 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
485 status);
486 if (status == NO_ERROR) {
487 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
488 &patch, mUidCached);
489 mCallRxPatch->mAfPatchHandle = afPatchHandle;
490 mCallRxPatch->mUid = mUidCached;
491 }
492 createTxPatch = true;
493 }
494 if (createTxPatch) {
495
496 struct audio_patch patch;
497 patch.num_sources = 1;
498 patch.num_sinks = 1;
499 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
500 ALOG_ASSERT(!deviceList.isEmpty(),
501 "updateCallRouting() selected device not in input device list");
502 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
503 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
504 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
505 ALOG_ASSERT(!deviceList.isEmpty(),
506 "updateCallRouting() no telephony TX device");
507 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
508 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
509
510 SortedVector<audio_io_handle_t> outputs =
511 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
512 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
513 // request to reuse existing output stream if one is already opened to reach the TX
514 // path output device
515 if (output != AUDIO_IO_HANDLE_NONE) {
516 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
517 ALOG_ASSERT(!outputDesc->isDuplicated(),
518 "updateCallRouting() RX device output is duplicated");
519 outputDesc->toAudioPortConfig(&patch.sources[1]);
520 patch.num_sources = 2;
521 }
522
523 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
524 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
525 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
526 status);
527 if (status == NO_ERROR) {
528 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
529 &patch, mUidCached);
530 mCallTxPatch->mAfPatchHandle = afPatchHandle;
531 mCallTxPatch->mUid = mUidCached;
532 }
533 }
534}
535
Eric Laurente0720872014-03-11 09:30:41 -0700536void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700537{
538 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGW("setPhoneState() invalid state %d", state);
541 return;
542 }
543
544 if (state == mPhoneState ) {
545 ALOGW("setPhoneState() setting same state %d", state);
546 return;
547 }
548
549 // if leaving call state, handle special case of active streams
550 // pertaining to sonification strategy see handleIncallSonification()
551 if (isInCall()) {
552 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700553 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
554 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700555 }
556 }
557
558 // store previous phone state for management of sonification strategy below
559 int oldState = mPhoneState;
560 mPhoneState = state;
561 bool force = false;
562
563 // are we entering or starting a call
564 if (!isStateInCall(oldState) && isStateInCall(state)) {
565 ALOGV(" Entering call in setPhoneState()");
566 // force routing command to audio hardware when starting a call
567 // even if no device change is needed
568 force = true;
569 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
570 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
571 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
572 }
573 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
574 ALOGV(" Exiting call in setPhoneState()");
575 // force routing command to audio hardware when exiting a call
576 // even if no device change is needed
577 force = true;
578 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
579 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
580 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
581 }
582 } else if (isStateInCall(state) && (state != oldState)) {
583 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
584 // force routing command to audio hardware when switching between telephony and VoIP
585 // even if no device change is needed
586 force = true;
587 }
588
589 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700590 checkA2dpSuspend();
591 checkOutputForAllStrategies();
592 updateDevicesAndOutputs();
593
Eric Laurent1f2f2232014-06-02 12:01:23 -0700594 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700595
Eric Laurente552edb2014-03-10 17:42:56 -0700596 int delayMs = 0;
597 if (isStateInCall(state)) {
598 nsecs_t sysTime = systemTime();
599 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700600 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700601 // mute media and sonification strategies and delay device switch by the largest
602 // latency of any output where either strategy is active.
603 // This avoid sending the ring tone or music tail into the earpiece or headset.
604 if ((desc->isStrategyActive(STRATEGY_MEDIA,
605 SONIFICATION_HEADSET_MUSIC_DELAY,
606 sysTime) ||
607 desc->isStrategyActive(STRATEGY_SONIFICATION,
608 SONIFICATION_HEADSET_MUSIC_DELAY,
609 sysTime)) &&
610 (delayMs < (int)desc->mLatency*2)) {
611 delayMs = desc->mLatency*2;
612 }
613 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
614 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
615 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
616 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
617 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
618 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
619 }
620 }
621
Eric Laurentc2730ba2014-07-20 15:47:07 -0700622 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
623 // the device returned is not necessarily reachable via this output
624 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
625 // force routing command to audio hardware when ending call
626 // even if no device change is needed
627 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
628 rxDevice = hwOutputDesc->device();
629 }
Eric Laurente552edb2014-03-10 17:42:56 -0700630
Eric Laurentc2730ba2014-07-20 15:47:07 -0700631 if (state == AUDIO_MODE_IN_CALL) {
632 updateCallRouting(rxDevice, delayMs);
633 } else if (oldState == AUDIO_MODE_IN_CALL) {
634 if (mCallRxPatch != 0) {
635 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
636 mCallRxPatch.clear();
637 }
638 if (mCallTxPatch != 0) {
639 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
640 mCallTxPatch.clear();
641 }
642 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
643 } else {
644 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
645 }
Eric Laurente552edb2014-03-10 17:42:56 -0700646 // if entering in call state, handle special case of active streams
647 // pertaining to sonification strategy see handleIncallSonification()
648 if (isStateInCall(state)) {
649 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
651 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700652 }
653 }
654
655 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 if (state == AUDIO_MODE_RINGTONE &&
657 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700658 mLimitRingtoneVolume = true;
659 } else {
660 mLimitRingtoneVolume = false;
661 }
662}
663
Eric Laurente0720872014-03-11 09:30:41 -0700664void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700665 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700666{
667 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
668
669 bool forceVolumeReeval = false;
670 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700671 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
672 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
673 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700674 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
675 return;
676 }
677 forceVolumeReeval = true;
678 mForceUse[usage] = config;
679 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700680 case AUDIO_POLICY_FORCE_FOR_MEDIA:
681 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
682 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
683 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
684 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900685 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700686 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
687 return;
688 }
689 mForceUse[usage] = config;
690 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 case AUDIO_POLICY_FORCE_FOR_RECORD:
692 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
693 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700694 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
695 return;
696 }
697 mForceUse[usage] = config;
698 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700699 case AUDIO_POLICY_FORCE_FOR_DOCK:
700 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
701 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
702 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
703 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
704 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700705 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
706 }
707 forceVolumeReeval = true;
708 mForceUse[usage] = config;
709 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700710 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
711 if (config != AUDIO_POLICY_FORCE_NONE &&
712 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
714 }
715 forceVolumeReeval = true;
716 mForceUse[usage] = config;
717 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900718 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
719 if (config != AUDIO_POLICY_FORCE_NONE &&
720 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
721 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
722 }
723 mForceUse[usage] = config;
724 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700725 default:
726 ALOGW("setForceUse() invalid usage %d", usage);
727 break;
728 }
729
730 // check for device and output changes triggered by new force usage
731 checkA2dpSuspend();
732 checkOutputForAllStrategies();
733 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700734 if (mPhoneState == AUDIO_MODE_IN_CALL) {
735 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
736 updateCallRouting(newDevice);
737 }
Eric Laurente552edb2014-03-10 17:42:56 -0700738 for (size_t i = 0; i < mOutputs.size(); i++) {
739 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700740 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
742 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
743 }
Eric Laurente552edb2014-03-10 17:42:56 -0700744 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
745 applyStreamVolumes(output, newDevice, 0, true);
746 }
747 }
748
749 audio_io_handle_t activeInput = getActiveInput();
750 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700751 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700752 }
753
754}
755
Eric Laurente0720872014-03-11 09:30:41 -0700756audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700757{
758 return mForceUse[usage];
759}
760
Eric Laurente0720872014-03-11 09:30:41 -0700761void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700762{
763 ALOGV("setSystemProperty() property %s, value %s", property, value);
764}
765
766// Find a direct output profile compatible with the parameters passed, even if the input flags do
767// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700768sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700769 audio_devices_t device,
770 uint32_t samplingRate,
771 audio_format_t format,
772 audio_channel_mask_t channelMask,
773 audio_output_flags_t flags)
774{
775 for (size_t i = 0; i < mHwModules.size(); i++) {
776 if (mHwModules[i]->mHandle == 0) {
777 continue;
778 }
779 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700780 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700781 bool found = profile->isCompatibleProfile(device, samplingRate,
782 NULL /*updatedSamplingRate*/, format, channelMask,
783 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
784 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700785 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
786 return profile;
787 }
Eric Laurente552edb2014-03-10 17:42:56 -0700788 }
789 }
790 return 0;
791}
792
Eric Laurente0720872014-03-11 09:30:41 -0700793audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700794 uint32_t samplingRate,
795 audio_format_t format,
796 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700797 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700798 const audio_offload_info_t *offloadInfo)
799{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700800
Eric Laurent3b73df72014-03-11 09:06:29 -0700801 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700802 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
803 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
804 device, stream, samplingRate, format, channelMask, flags);
805
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700806 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
807 offloadInfo);
808}
809
810audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
811 uint32_t samplingRate,
812 audio_format_t format,
813 audio_channel_mask_t channelMask,
814 audio_output_flags_t flags,
815 const audio_offload_info_t *offloadInfo)
816{
817 if (attr == NULL) {
818 ALOGE("getOutputForAttr() called with NULL audio attributes");
819 return 0;
820 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700821 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
822 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700823
824 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
825 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
826 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700827
828 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
829 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
830 }
831
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700832 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
833 device, samplingRate, format, channelMask, flags);
834
835 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
836 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
837 offloadInfo);
838}
839
840audio_io_handle_t AudioPolicyManager::getOutputForDevice(
841 audio_devices_t device,
842 audio_stream_type_t stream,
843 uint32_t samplingRate,
844 audio_format_t format,
845 audio_channel_mask_t channelMask,
846 audio_output_flags_t flags,
847 const audio_offload_info_t *offloadInfo)
848{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700849 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700850 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700851 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700852
Eric Laurente552edb2014-03-10 17:42:56 -0700853#ifdef AUDIO_POLICY_TEST
854 if (mCurOutput != 0) {
855 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
856 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
857
858 if (mTestOutputs[mCurOutput] == 0) {
859 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700860 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700861 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700862 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700863 outputDesc->mFlags =
864 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700865 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700866 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
867 config.sample_rate = mTestSamplingRate;
868 config.channel_mask = mTestChannels;
869 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700870 if (offloadInfo != NULL) {
871 config.offload_info = *offloadInfo;
872 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700873 status = mpClientInterface->openOutput(0,
874 &mTestOutputs[mCurOutput],
875 &config,
876 &outputDesc->mDevice,
877 String8(""),
878 &outputDesc->mLatency,
879 outputDesc->mFlags);
880 if (status == NO_ERROR) {
881 outputDesc->mSamplingRate = config.sample_rate;
882 outputDesc->mFormat = config.format;
883 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700884 AudioParameter outputCmd = AudioParameter();
885 outputCmd.addInt(String8("set_id"),mCurOutput);
886 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
887 addOutput(mTestOutputs[mCurOutput], outputDesc);
888 }
889 }
890 return mTestOutputs[mCurOutput];
891 }
892#endif //AUDIO_POLICY_TEST
893
894 // open a direct output if required by specified parameters
895 //force direct flag if offload flag is set: offloading implies a direct output stream
896 // and all common behaviors are driven by checking only the direct flag
897 // this should normally be set appropriately in the policy configuration file
898 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700899 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700900 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700901 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
902 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
905 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
906 // creating an offloaded track and tearing it down immediately after start when audioflinger
907 // detects there is an active non offloadable effect.
908 // FIXME: We should check the audio session here but we do not have it in this context.
909 // This may prevent offloading in rare situations where effects are left active by apps
910 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700911 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700912 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
913 !isNonOffloadableEffectEnabled()) {
914 profile = getProfileForDirectOutput(device,
915 samplingRate,
916 format,
917 channelMask,
918 (audio_output_flags_t)flags);
919 }
920
Eric Laurent1c333e22014-05-20 10:48:17 -0700921 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700922 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700923
924 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700925 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
927 outputDesc = desc;
928 // reuse direct output if currently open and configured with same parameters
929 if ((samplingRate == outputDesc->mSamplingRate) &&
930 (format == outputDesc->mFormat) &&
931 (channelMask == outputDesc->mChannelMask)) {
932 outputDesc->mDirectOpenCount++;
933 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
934 return mOutputs.keyAt(i);
935 }
936 }
937 }
938 // close direct output if currently open and configured with different parameters
939 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700940 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942 outputDesc = new AudioOutputDescriptor(profile);
943 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700944 outputDesc->mLatency = 0;
945 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700946 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
947 config.sample_rate = samplingRate;
948 config.channel_mask = channelMask;
949 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700950 if (offloadInfo != NULL) {
951 config.offload_info = *offloadInfo;
952 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700953 status = mpClientInterface->openOutput(profile->mModule->mHandle,
954 &output,
955 &config,
956 &outputDesc->mDevice,
957 String8(""),
958 &outputDesc->mLatency,
959 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700960
961 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 if (status != NO_ERROR ||
963 (samplingRate != 0 && samplingRate != config.sample_rate) ||
964 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
965 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
967 "format %d %d, channelMask %04x %04x", output, samplingRate,
968 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
969 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700970 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700971 mpClientInterface->closeOutput(output);
972 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700973 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700975 outputDesc->mSamplingRate = config.sample_rate;
976 outputDesc->mChannelMask = config.channel_mask;
977 outputDesc->mFormat = config.format;
978 outputDesc->mRefCount[stream] = 0;
979 outputDesc->mStopTime[stream] = 0;
980 outputDesc->mDirectOpenCount = 1;
981
Eric Laurente552edb2014-03-10 17:42:56 -0700982 audio_io_handle_t srcOutput = getOutputForEffect();
983 addOutput(output, outputDesc);
984 audio_io_handle_t dstOutput = getOutputForEffect();
985 if (dstOutput == output) {
986 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
987 }
988 mPreviousOutputs = mOutputs;
989 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700990 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700991 return output;
992 }
993
994 // ignoring channel mask due to downmix capability in mixer
995
996 // open a non direct output
997
998 // for non direct outputs, only PCM is supported
999 if (audio_is_linear_pcm(format)) {
1000 // get which output is suitable for the specified stream. The actual
1001 // routing change will happen when startOutput() will be called
1002 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1003
1004 output = selectOutput(outputs, flags);
1005 }
1006 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1007 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1008
1009 ALOGV("getOutput() returns output %d", output);
1010
1011 return output;
1012}
1013
Eric Laurente0720872014-03-11 09:30:41 -07001014audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -07001015 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
1017 // select one output among several that provide a path to a particular device or set of
1018 // devices (the list was previously build by getOutputsForDevice()).
1019 // The priority is as follows:
1020 // 1: the output with the highest number of requested policy flags
1021 // 2: the primary output
1022 // 3: the first output in the list
1023
1024 if (outputs.size() == 0) {
1025 return 0;
1026 }
1027 if (outputs.size() == 1) {
1028 return outputs[0];
1029 }
1030
1031 int maxCommonFlags = 0;
1032 audio_io_handle_t outputFlags = 0;
1033 audio_io_handle_t outputPrimary = 0;
1034
1035 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001036 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001038 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001039 if (commonFlags > maxCommonFlags) {
1040 outputFlags = outputs[i];
1041 maxCommonFlags = commonFlags;
1042 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1043 }
1044 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1045 outputPrimary = outputs[i];
1046 }
1047 }
1048 }
1049
1050 if (outputFlags != 0) {
1051 return outputFlags;
1052 }
1053 if (outputPrimary != 0) {
1054 return outputPrimary;
1055 }
1056
1057 return outputs[0];
1058}
1059
Eric Laurente0720872014-03-11 09:30:41 -07001060status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001061 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001062 int session)
1063{
1064 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1065 ssize_t index = mOutputs.indexOfKey(output);
1066 if (index < 0) {
1067 ALOGW("startOutput() unknown output %d", output);
1068 return BAD_VALUE;
1069 }
1070
Eric Laurent1f2f2232014-06-02 12:01:23 -07001071 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
1073 // increment usage count for this stream on the requested output:
1074 // NOTE that the usage count is the same for duplicated output and hardware output which is
1075 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1076 outputDesc->changeRefCount(stream, 1);
1077
1078 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001079 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001080 routing_strategy strategy = getStrategy(stream);
1081 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1082 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1083 uint32_t waitMs = 0;
1084 bool force = false;
1085 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001086 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001087 if (desc != outputDesc) {
1088 // force a device change if any other output is managed by the same hw
1089 // module and has a current device selection that differs from selected device.
1090 // In this case, the audio HAL must receive the new device selection so that it can
1091 // change the device currently selected by the other active output.
1092 if (outputDesc->sharesHwModuleWith(desc) &&
1093 desc->device() != newDevice) {
1094 force = true;
1095 }
1096 // wait for audio on other active outputs to be presented when starting
1097 // a notification so that audio focus effect can propagate.
1098 uint32_t latency = desc->latency();
1099 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1100 waitMs = latency;
1101 }
1102 }
1103 }
1104 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1105
1106 // handle special case for sonification while in call
1107 if (isInCall()) {
1108 handleIncallSonification(stream, true, false);
1109 }
1110
1111 // apply volume rules for current stream and device if necessary
1112 checkAndSetVolume(stream,
1113 mStreams[stream].getVolumeIndex(newDevice),
1114 output,
1115 newDevice);
1116
1117 // update the outputs if starting an output with a stream that can affect notification
1118 // routing
1119 handleNotificationRoutingForStream(stream);
1120 if (waitMs > muteWaitMs) {
1121 usleep((waitMs - muteWaitMs) * 2 * 1000);
1122 }
1123 }
1124 return NO_ERROR;
1125}
1126
1127
Eric Laurente0720872014-03-11 09:30:41 -07001128status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001129 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001130 int session)
1131{
1132 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1133 ssize_t index = mOutputs.indexOfKey(output);
1134 if (index < 0) {
1135 ALOGW("stopOutput() unknown output %d", output);
1136 return BAD_VALUE;
1137 }
1138
Eric Laurent1f2f2232014-06-02 12:01:23 -07001139 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001140
1141 // handle special case for sonification while in call
1142 if (isInCall()) {
1143 handleIncallSonification(stream, false, false);
1144 }
1145
1146 if (outputDesc->mRefCount[stream] > 0) {
1147 // decrement usage count of this stream on the output
1148 outputDesc->changeRefCount(stream, -1);
1149 // store time at which the stream was stopped - see isStreamActive()
1150 if (outputDesc->mRefCount[stream] == 0) {
1151 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001152 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001153 // delay the device switch by twice the latency because stopOutput() is executed when
1154 // the track stop() command is received and at that time the audio track buffer can
1155 // still contain data that needs to be drained. The latency only covers the audio HAL
1156 // and kernel buffers. Also the latency does not always include additional delay in the
1157 // audio path (audio DSP, CODEC ...)
1158 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1159
1160 // force restoring the device selection on other active outputs if it differs from the
1161 // one being selected for this output
1162 for (size_t i = 0; i < mOutputs.size(); i++) {
1163 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001164 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001165 if (curOutput != output &&
1166 desc->isActive() &&
1167 outputDesc->sharesHwModuleWith(desc) &&
1168 (newDevice != desc->device())) {
1169 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001170 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001171 true,
1172 outputDesc->mLatency*2);
1173 }
1174 }
1175 // update the outputs if stopping one with a stream that can affect notification routing
1176 handleNotificationRoutingForStream(stream);
1177 }
1178 return NO_ERROR;
1179 } else {
1180 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1181 return INVALID_OPERATION;
1182 }
1183}
1184
Eric Laurente0720872014-03-11 09:30:41 -07001185void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
1187 ALOGV("releaseOutput() %d", output);
1188 ssize_t index = mOutputs.indexOfKey(output);
1189 if (index < 0) {
1190 ALOGW("releaseOutput() releasing unknown output %d", output);
1191 return;
1192 }
1193
1194#ifdef AUDIO_POLICY_TEST
1195 int testIndex = testOutputIndex(output);
1196 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001197 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001198 if (outputDesc->isActive()) {
1199 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001200 mOutputs.removeItem(output);
1201 mTestOutputs[testIndex] = 0;
1202 }
1203 return;
1204 }
1205#endif //AUDIO_POLICY_TEST
1206
Eric Laurent1f2f2232014-06-02 12:01:23 -07001207 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001208 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001209 if (desc->mDirectOpenCount <= 0) {
1210 ALOGW("releaseOutput() invalid open count %d for output %d",
1211 desc->mDirectOpenCount, output);
1212 return;
1213 }
1214 if (--desc->mDirectOpenCount == 0) {
1215 closeOutput(output);
1216 // If effects where present on the output, audioflinger moved them to the primary
1217 // output by default: move them back to the appropriate output.
1218 audio_io_handle_t dstOutput = getOutputForEffect();
1219 if (dstOutput != mPrimaryOutput) {
1220 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1221 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001222 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001223 }
1224 }
1225}
1226
1227
Eric Laurente0720872014-03-11 09:30:41 -07001228audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001229 uint32_t samplingRate,
1230 audio_format_t format,
1231 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001232 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001233 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001234{
Eric Laurent4dc68062014-07-28 17:26:49 -07001235 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001236 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001237 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001238
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001239 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001240
1241 if (device == AUDIO_DEVICE_NONE) {
1242 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001243 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001244 }
1245
1246 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001247 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001248 case AUDIO_SOURCE_VOICE_UPLINK:
1249 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1250 break;
1251 case AUDIO_SOURCE_VOICE_DOWNLINK:
1252 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1253 break;
1254 case AUDIO_SOURCE_VOICE_CALL:
1255 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1256 break;
1257 default:
1258 break;
1259 }
1260
Eric Laurent1c333e22014-05-20 10:48:17 -07001261 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001262 samplingRate,
1263 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001264 channelMask,
1265 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001266 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001267 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1268 "channelMask 0x%X, flags %#x",
1269 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001270 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001271 }
1272
1273 if (profile->mModule->mHandle == 0) {
1274 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001275 return AUDIO_IO_HANDLE_NONE;
1276 }
1277
1278 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1279 config.sample_rate = samplingRate;
1280 config.channel_mask = channelMask;
1281 config.format = format;
1282 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001283
1284 bool isSoundTrigger = false;
1285 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1286 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1287 if (index >= 0) {
1288 input = mSoundTriggerSessions.valueFor(session);
1289 isSoundTrigger = true;
1290 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1291 }
1292 }
1293
Eric Laurentcf2c0212014-07-25 16:20:43 -07001294 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1295 &input,
1296 &config,
1297 &device,
1298 String8(""),
1299 inputSource,
1300 flags);
1301
1302 // only accept input with the exact requested set of parameters
1303 if (status != NO_ERROR ||
1304 (samplingRate != config.sample_rate) ||
1305 (format != config.format) ||
1306 (channelMask != config.channel_mask)) {
1307 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1308 samplingRate, format, channelMask);
1309 if (input != AUDIO_IO_HANDLE_NONE) {
1310 mpClientInterface->closeInput(input);
1311 }
1312 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001313 }
1314
Eric Laurent1f2f2232014-06-02 12:01:23 -07001315 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001316 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001317 inputDesc->mRefCount = 0;
1318 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001319 inputDesc->mSamplingRate = samplingRate;
1320 inputDesc->mFormat = format;
1321 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001322 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001323 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001324 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001325
Eric Laurentd4692962014-05-05 18:13:44 -07001326 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001327 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001328 return input;
1329}
1330
Eric Laurent4dc68062014-07-28 17:26:49 -07001331status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1332 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001333{
1334 ALOGV("startInput() input %d", input);
1335 ssize_t index = mInputs.indexOfKey(input);
1336 if (index < 0) {
1337 ALOGW("startInput() unknown input %d", input);
1338 return BAD_VALUE;
1339 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001340 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001341
Eric Laurent4dc68062014-07-28 17:26:49 -07001342 index = inputDesc->mSessions.indexOf(session);
1343 if (index < 0) {
1344 ALOGW("startInput() unknown session %d on input %d", session, input);
1345 return BAD_VALUE;
1346 }
1347
Glenn Kasten74a8e252014-07-24 14:09:55 -07001348 // virtual input devices are compatible with other input devices
1349 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1350
1351 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001352 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001353 if (activeInput != 0 && activeInput != input) {
1354
1355 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1356 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001357 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001358 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001359 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001360 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1361 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001362 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001363 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001364 return INVALID_OPERATION;
1365 }
1366 }
1367 }
1368
Glenn Kasten74a8e252014-07-24 14:09:55 -07001369 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001370 if (activeInputsCount() == 0) {
1371 SoundTrigger::setCaptureState(true);
1372 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001373 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001374
Glenn Kasten74a8e252014-07-24 14:09:55 -07001375 // Automatically enable the remote submix output when input is started.
1376 // For remote submix (a virtual device), we open only one input per capture request.
1377 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1378 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1379 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1380 }
Eric Laurente552edb2014-03-10 17:42:56 -07001381 }
1382
Eric Laurente552edb2014-03-10 17:42:56 -07001383 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1384
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001385 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001386 return NO_ERROR;
1387}
1388
Eric Laurent4dc68062014-07-28 17:26:49 -07001389status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1390 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001391{
1392 ALOGV("stopInput() input %d", input);
1393 ssize_t index = mInputs.indexOfKey(input);
1394 if (index < 0) {
1395 ALOGW("stopInput() unknown input %d", input);
1396 return BAD_VALUE;
1397 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001398 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001399
Eric Laurent4dc68062014-07-28 17:26:49 -07001400 index = inputDesc->mSessions.indexOf(session);
1401 if (index < 0) {
1402 ALOGW("stopInput() unknown session %d on input %d", session, input);
1403 return BAD_VALUE;
1404 }
1405
Eric Laurente552edb2014-03-10 17:42:56 -07001406 if (inputDesc->mRefCount == 0) {
1407 ALOGW("stopInput() input %d already stopped", input);
1408 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001409 }
1410
1411 inputDesc->mRefCount--;
1412 if (inputDesc->mRefCount == 0) {
1413
Eric Laurente552edb2014-03-10 17:42:56 -07001414 // automatically disable the remote submix output when input is stopped
1415 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1416 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001417 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001418 }
1419
Eric Laurent1c333e22014-05-20 10:48:17 -07001420 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001421
1422 if (activeInputsCount() == 0) {
1423 SoundTrigger::setCaptureState(false);
1424 }
Eric Laurente552edb2014-03-10 17:42:56 -07001425 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001426 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001427}
1428
Eric Laurent4dc68062014-07-28 17:26:49 -07001429void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1430 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001431{
1432 ALOGV("releaseInput() %d", input);
1433 ssize_t index = mInputs.indexOfKey(input);
1434 if (index < 0) {
1435 ALOGW("releaseInput() releasing unknown input %d", input);
1436 return;
1437 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001438 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1439 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001440
1441 index = inputDesc->mSessions.indexOf(session);
1442 if (index < 0) {
1443 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1444 return;
1445 }
1446 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001447 if (inputDesc->mOpenRefCount == 0) {
1448 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1449 return;
1450 }
1451 inputDesc->mOpenRefCount--;
1452 if (inputDesc->mOpenRefCount > 0) {
1453 ALOGV("releaseInput() exit > 0");
1454 return;
1455 }
1456
Eric Laurente552edb2014-03-10 17:42:56 -07001457 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001458 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001459 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001460 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001461 ALOGV("releaseInput() exit");
1462}
1463
Eric Laurentd4692962014-05-05 18:13:44 -07001464void AudioPolicyManager::closeAllInputs() {
1465 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1466 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1467 }
1468 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001469 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001470}
1471
Eric Laurente0720872014-03-11 09:30:41 -07001472void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001473 int indexMin,
1474 int indexMax)
1475{
1476 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1477 if (indexMin < 0 || indexMin >= indexMax) {
1478 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1479 return;
1480 }
1481 mStreams[stream].mIndexMin = indexMin;
1482 mStreams[stream].mIndexMax = indexMax;
1483}
1484
Eric Laurente0720872014-03-11 09:30:41 -07001485status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001486 int index,
1487 audio_devices_t device)
1488{
1489
1490 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1491 return BAD_VALUE;
1492 }
1493 if (!audio_is_output_device(device)) {
1494 return BAD_VALUE;
1495 }
1496
1497 // Force max volume if stream cannot be muted
1498 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1499
1500 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1501 stream, device, index);
1502
1503 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1504 // clear all device specific values
1505 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1506 mStreams[stream].mIndexCur.clear();
1507 }
1508 mStreams[stream].mIndexCur.add(device, index);
1509
1510 // compute and apply stream volume on all outputs according to connected device
1511 status_t status = NO_ERROR;
1512 for (size_t i = 0; i < mOutputs.size(); i++) {
1513 audio_devices_t curDevice =
1514 getDeviceForVolume(mOutputs.valueAt(i)->device());
1515 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1516 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1517 if (volStatus != NO_ERROR) {
1518 status = volStatus;
1519 }
1520 }
1521 }
1522 return status;
1523}
1524
Eric Laurente0720872014-03-11 09:30:41 -07001525status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001526 int *index,
1527 audio_devices_t device)
1528{
1529 if (index == NULL) {
1530 return BAD_VALUE;
1531 }
1532 if (!audio_is_output_device(device)) {
1533 return BAD_VALUE;
1534 }
1535 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1536 // the strategy the stream belongs to.
1537 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1538 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1539 }
1540 device = getDeviceForVolume(device);
1541
1542 *index = mStreams[stream].getVolumeIndex(device);
1543 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1544 return NO_ERROR;
1545}
1546
Eric Laurente0720872014-03-11 09:30:41 -07001547audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001548 const SortedVector<audio_io_handle_t>& outputs)
1549{
1550 // select one output among several suitable for global effects.
1551 // The priority is as follows:
1552 // 1: An offloaded output. If the effect ends up not being offloadable,
1553 // AudioFlinger will invalidate the track and the offloaded output
1554 // will be closed causing the effect to be moved to a PCM output.
1555 // 2: A deep buffer output
1556 // 3: the first output in the list
1557
1558 if (outputs.size() == 0) {
1559 return 0;
1560 }
1561
1562 audio_io_handle_t outputOffloaded = 0;
1563 audio_io_handle_t outputDeepBuffer = 0;
1564
1565 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001566 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001567 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001568 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1569 outputOffloaded = outputs[i];
1570 }
1571 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1572 outputDeepBuffer = outputs[i];
1573 }
1574 }
1575
1576 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1577 outputOffloaded, outputDeepBuffer);
1578 if (outputOffloaded != 0) {
1579 return outputOffloaded;
1580 }
1581 if (outputDeepBuffer != 0) {
1582 return outputDeepBuffer;
1583 }
1584
1585 return outputs[0];
1586}
1587
Eric Laurente0720872014-03-11 09:30:41 -07001588audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001589{
1590 // apply simple rule where global effects are attached to the same output as MUSIC streams
1591
Eric Laurent3b73df72014-03-11 09:06:29 -07001592 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001593 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1594 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1595
1596 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1597 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1598 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1599
1600 return output;
1601}
1602
Eric Laurente0720872014-03-11 09:30:41 -07001603status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001604 audio_io_handle_t io,
1605 uint32_t strategy,
1606 int session,
1607 int id)
1608{
1609 ssize_t index = mOutputs.indexOfKey(io);
1610 if (index < 0) {
1611 index = mInputs.indexOfKey(io);
1612 if (index < 0) {
1613 ALOGW("registerEffect() unknown io %d", io);
1614 return INVALID_OPERATION;
1615 }
1616 }
1617
1618 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1619 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1620 desc->name, desc->memoryUsage);
1621 return INVALID_OPERATION;
1622 }
1623 mTotalEffectsMemory += desc->memoryUsage;
1624 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1625 desc->name, io, strategy, session, id);
1626 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1627
Eric Laurent1f2f2232014-06-02 12:01:23 -07001628 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1629 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1630 effectDesc->mIo = io;
1631 effectDesc->mStrategy = (routing_strategy)strategy;
1632 effectDesc->mSession = session;
1633 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001634
Eric Laurent1f2f2232014-06-02 12:01:23 -07001635 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001636
1637 return NO_ERROR;
1638}
1639
Eric Laurente0720872014-03-11 09:30:41 -07001640status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001641{
1642 ssize_t index = mEffects.indexOfKey(id);
1643 if (index < 0) {
1644 ALOGW("unregisterEffect() unknown effect ID %d", id);
1645 return INVALID_OPERATION;
1646 }
1647
Eric Laurent1f2f2232014-06-02 12:01:23 -07001648 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurent1f2f2232014-06-02 12:01:23 -07001650 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001651
Eric Laurent1f2f2232014-06-02 12:01:23 -07001652 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001653 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001654 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1655 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001656 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001657 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001658 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001659 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001660
1661 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001662
1663 return NO_ERROR;
1664}
1665
Eric Laurente0720872014-03-11 09:30:41 -07001666status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001667{
1668 ssize_t index = mEffects.indexOfKey(id);
1669 if (index < 0) {
1670 ALOGW("unregisterEffect() unknown effect ID %d", id);
1671 return INVALID_OPERATION;
1672 }
1673
1674 return setEffectEnabled(mEffects.valueAt(index), enabled);
1675}
1676
Eric Laurent1f2f2232014-06-02 12:01:23 -07001677status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001678{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001679 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001680 ALOGV("setEffectEnabled(%s) effect already %s",
1681 enabled?"true":"false", enabled?"enabled":"disabled");
1682 return INVALID_OPERATION;
1683 }
1684
1685 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001686 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001687 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001688 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001689 return INVALID_OPERATION;
1690 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001691 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001692 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1693 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001694 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001695 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001696 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1697 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001698 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001699 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001700 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1701 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001702 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001703 return NO_ERROR;
1704}
1705
Eric Laurente0720872014-03-11 09:30:41 -07001706bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001707{
1708 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001709 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1710 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1711 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001712 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001713 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001714 return true;
1715 }
1716 }
1717 return false;
1718}
1719
Eric Laurente0720872014-03-11 09:30:41 -07001720bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001721{
1722 nsecs_t sysTime = systemTime();
1723 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001724 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001725 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001726 return true;
1727 }
1728 }
1729 return false;
1730}
1731
Eric Laurente0720872014-03-11 09:30:41 -07001732bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001733 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001734{
1735 nsecs_t sysTime = systemTime();
1736 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001737 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001738 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001739 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001740 return true;
1741 }
1742 }
1743 return false;
1744}
1745
Eric Laurente0720872014-03-11 09:30:41 -07001746bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001747{
1748 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001749 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001750 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001751 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001752 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1753 && (inputDescriptor->mRefCount > 0)) {
1754 return true;
1755 }
1756 }
1757 return false;
1758}
1759
1760
Eric Laurente0720872014-03-11 09:30:41 -07001761status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001762{
1763 const size_t SIZE = 256;
1764 char buffer[SIZE];
1765 String8 result;
1766
1767 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1768 result.append(buffer);
1769
1770 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1771 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001772 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1773 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001774 snprintf(buffer, SIZE, " Force use for communications %d\n",
1775 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001776 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001777 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001778 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001779 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001780 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001781 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001782 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001783 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001784 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001785 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1786 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1787 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001788
Eric Laurent3a4311c2014-03-17 12:00:47 -07001789 snprintf(buffer, SIZE, " Available output devices:\n");
1790 result.append(buffer);
1791 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001792 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001793 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001794 }
1795 snprintf(buffer, SIZE, "\n Available input devices:\n");
1796 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001797 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001798 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001799 }
Eric Laurente552edb2014-03-10 17:42:56 -07001800
1801 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1802 write(fd, buffer, strlen(buffer));
1803 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001804 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001805 write(fd, buffer, strlen(buffer));
1806 mHwModules[i]->dump(fd);
1807 }
1808
1809 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1810 write(fd, buffer, strlen(buffer));
1811 for (size_t i = 0; i < mOutputs.size(); i++) {
1812 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1813 write(fd, buffer, strlen(buffer));
1814 mOutputs.valueAt(i)->dump(fd);
1815 }
1816
1817 snprintf(buffer, SIZE, "\nInputs dump:\n");
1818 write(fd, buffer, strlen(buffer));
1819 for (size_t i = 0; i < mInputs.size(); i++) {
1820 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1821 write(fd, buffer, strlen(buffer));
1822 mInputs.valueAt(i)->dump(fd);
1823 }
1824
1825 snprintf(buffer, SIZE, "\nStreams dump:\n");
1826 write(fd, buffer, strlen(buffer));
1827 snprintf(buffer, SIZE,
1828 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1829 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001830 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001831 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001832 write(fd, buffer, strlen(buffer));
1833 mStreams[i].dump(fd);
1834 }
1835
1836 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1837 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1838 write(fd, buffer, strlen(buffer));
1839
1840 snprintf(buffer, SIZE, "Registered effects:\n");
1841 write(fd, buffer, strlen(buffer));
1842 for (size_t i = 0; i < mEffects.size(); i++) {
1843 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1844 write(fd, buffer, strlen(buffer));
1845 mEffects.valueAt(i)->dump(fd);
1846 }
1847
Eric Laurent4d416952014-08-10 14:07:09 -07001848 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1849 write(fd, buffer, strlen(buffer));
1850 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1851 mAudioPatches[i]->dump(fd, 2, i);
1852 }
Eric Laurente552edb2014-03-10 17:42:56 -07001853
1854 return NO_ERROR;
1855}
1856
1857// This function checks for the parameters which can be offloaded.
1858// This can be enhanced depending on the capability of the DSP and policy
1859// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001860bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001861{
1862 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001863 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001864 offloadInfo.sample_rate, offloadInfo.channel_mask,
1865 offloadInfo.format,
1866 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1867 offloadInfo.has_video);
1868
1869 // Check if offload has been disabled
1870 char propValue[PROPERTY_VALUE_MAX];
1871 if (property_get("audio.offload.disable", propValue, "0")) {
1872 if (atoi(propValue) != 0) {
1873 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1874 return false;
1875 }
1876 }
1877
1878 // Check if stream type is music, then only allow offload as of now.
1879 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1880 {
1881 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1882 return false;
1883 }
1884
1885 //TODO: enable audio offloading with video when ready
1886 if (offloadInfo.has_video)
1887 {
1888 ALOGV("isOffloadSupported: has_video == true, returning false");
1889 return false;
1890 }
1891
1892 //If duration is less than minimum value defined in property, return false
1893 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1894 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1895 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1896 return false;
1897 }
1898 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1899 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1900 return false;
1901 }
1902
1903 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1904 // creating an offloaded track and tearing it down immediately after start when audioflinger
1905 // detects there is an active non offloadable effect.
1906 // FIXME: We should check the audio session here but we do not have it in this context.
1907 // This may prevent offloading in rare situations where effects are left active by apps
1908 // in the background.
1909 if (isNonOffloadableEffectEnabled()) {
1910 return false;
1911 }
1912
1913 // See if there is a profile to support this.
1914 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001915 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001916 offloadInfo.sample_rate,
1917 offloadInfo.format,
1918 offloadInfo.channel_mask,
1919 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001920 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1921 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001922}
1923
Eric Laurent6a94d692014-05-20 11:18:06 -07001924status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1925 audio_port_type_t type,
1926 unsigned int *num_ports,
1927 struct audio_port *ports,
1928 unsigned int *generation)
1929{
1930 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1931 generation == NULL) {
1932 return BAD_VALUE;
1933 }
1934 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1935 if (ports == NULL) {
1936 *num_ports = 0;
1937 }
1938
1939 size_t portsWritten = 0;
1940 size_t portsMax = *num_ports;
1941 *num_ports = 0;
1942 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1943 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1944 for (size_t i = 0;
1945 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1946 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1947 }
1948 *num_ports += mAvailableOutputDevices.size();
1949 }
1950 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1951 for (size_t i = 0;
1952 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1953 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1954 }
1955 *num_ports += mAvailableInputDevices.size();
1956 }
1957 }
1958 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1959 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1960 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1961 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1962 }
1963 *num_ports += mInputs.size();
1964 }
1965 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001966 size_t numOutputs = 0;
1967 for (size_t i = 0; i < mOutputs.size(); i++) {
1968 if (!mOutputs[i]->isDuplicated()) {
1969 numOutputs++;
1970 if (portsWritten < portsMax) {
1971 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1972 }
1973 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001974 }
Eric Laurent84c70242014-06-23 08:46:27 -07001975 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001976 }
1977 }
1978 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001979 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001980 return NO_ERROR;
1981}
1982
1983status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1984{
1985 return NO_ERROR;
1986}
1987
Eric Laurent1f2f2232014-06-02 12:01:23 -07001988sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001989 audio_port_handle_t id) const
1990{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001991 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001992 for (size_t i = 0; i < mOutputs.size(); i++) {
1993 outputDesc = mOutputs.valueAt(i);
1994 if (outputDesc->mId == id) {
1995 break;
1996 }
1997 }
1998 return outputDesc;
1999}
2000
Eric Laurent1f2f2232014-06-02 12:01:23 -07002001sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002002 audio_port_handle_t id) const
2003{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002004 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002005 for (size_t i = 0; i < mInputs.size(); i++) {
2006 inputDesc = mInputs.valueAt(i);
2007 if (inputDesc->mId == id) {
2008 break;
2009 }
2010 }
2011 return inputDesc;
2012}
2013
Eric Laurent1f2f2232014-06-02 12:01:23 -07002014sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2015 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002016{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002017 sp <HwModule> module;
2018
Eric Laurent6a94d692014-05-20 11:18:06 -07002019 for (size_t i = 0; i < mHwModules.size(); i++) {
2020 if (mHwModules[i]->mHandle == 0) {
2021 continue;
2022 }
2023 if (audio_is_output_device(device)) {
2024 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2025 {
2026 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2027 return mHwModules[i];
2028 }
2029 }
2030 } else {
2031 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2032 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2033 device & ~AUDIO_DEVICE_BIT_IN) {
2034 return mHwModules[i];
2035 }
2036 }
2037 }
2038 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002039 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002040}
2041
Eric Laurent1f2f2232014-06-02 12:01:23 -07002042sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002043{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002044 sp <HwModule> module;
2045
Eric Laurent1afeecb2014-05-14 08:52:28 -07002046 for (size_t i = 0; i < mHwModules.size(); i++)
2047 {
2048 if (strcmp(mHwModules[i]->mName, name) == 0) {
2049 return mHwModules[i];
2050 }
2051 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002052 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002053}
2054
Eric Laurentc2730ba2014-07-20 15:47:07 -07002055audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2056{
2057 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2058 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2059 return devices & mAvailableOutputDevices.types();
2060}
2061
2062audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2063{
2064 audio_module_handle_t primaryHandle =
2065 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2066 audio_devices_t devices = AUDIO_DEVICE_NONE;
2067 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2068 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2069 devices |= mAvailableInputDevices[i]->mDeviceType;
2070 }
2071 }
2072 return devices;
2073}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002074
Eric Laurent6a94d692014-05-20 11:18:06 -07002075status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2076 audio_patch_handle_t *handle,
2077 uid_t uid)
2078{
2079 ALOGV("createAudioPatch()");
2080
2081 if (handle == NULL || patch == NULL) {
2082 return BAD_VALUE;
2083 }
2084 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2085
Eric Laurent874c42872014-08-08 15:13:39 -07002086 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2087 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2088 return BAD_VALUE;
2089 }
2090 // only one source per audio patch supported for now
2091 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002092 return INVALID_OPERATION;
2093 }
Eric Laurent874c42872014-08-08 15:13:39 -07002094
2095 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002096 return INVALID_OPERATION;
2097 }
Eric Laurent874c42872014-08-08 15:13:39 -07002098 for (size_t i = 0; i < patch->num_sinks; i++) {
2099 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2100 return INVALID_OPERATION;
2101 }
2102 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002103
2104 sp<AudioPatch> patchDesc;
2105 ssize_t index = mAudioPatches.indexOfKey(*handle);
2106
Eric Laurent6a94d692014-05-20 11:18:06 -07002107 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2108 patch->sources[0].role,
2109 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002110#if LOG_NDEBUG == 0
2111 for (size_t i = 0; i < patch->num_sinks; i++) {
2112 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2113 patch->sinks[i].role,
2114 patch->sinks[i].type);
2115 }
2116#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002117
2118 if (index >= 0) {
2119 patchDesc = mAudioPatches.valueAt(index);
2120 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2121 mUidCached, patchDesc->mUid, uid);
2122 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2123 return INVALID_OPERATION;
2124 }
2125 } else {
2126 *handle = 0;
2127 }
2128
2129 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002130 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002131 if (outputDesc == NULL) {
2132 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2133 return BAD_VALUE;
2134 }
Eric Laurent84c70242014-06-23 08:46:27 -07002135 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2136 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002137 if (patchDesc != 0) {
2138 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2139 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2140 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2141 return BAD_VALUE;
2142 }
2143 }
Eric Laurent874c42872014-08-08 15:13:39 -07002144 DeviceVector devices;
2145 for (size_t i = 0; i < patch->num_sinks; i++) {
2146 // Only support mix to devices connection
2147 // TODO add support for mix to mix connection
2148 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2149 ALOGV("createAudioPatch() source mix but sink is not a device");
2150 return INVALID_OPERATION;
2151 }
2152 sp<DeviceDescriptor> devDesc =
2153 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2154 if (devDesc == 0) {
2155 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2156 return BAD_VALUE;
2157 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002158
Eric Laurent874c42872014-08-08 15:13:39 -07002159 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2160 patch->sources[0].sample_rate,
2161 NULL, // updatedSamplingRate
2162 patch->sources[0].format,
2163 patch->sources[0].channel_mask,
2164 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2165 ALOGV("createAudioPatch() profile not supported for device %08x",
2166 devDesc->mDeviceType);
2167 return INVALID_OPERATION;
2168 }
2169 devices.add(devDesc);
2170 }
2171 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002172 return INVALID_OPERATION;
2173 }
Eric Laurent874c42872014-08-08 15:13:39 -07002174
Eric Laurent6a94d692014-05-20 11:18:06 -07002175 // TODO: reconfigure output format and channels here
2176 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002177 devices.types(), outputDesc->mIoHandle);
2178 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002179 index = mAudioPatches.indexOfKey(*handle);
2180 if (index >= 0) {
2181 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2182 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2183 }
2184 patchDesc = mAudioPatches.valueAt(index);
2185 patchDesc->mUid = uid;
2186 ALOGV("createAudioPatch() success");
2187 } else {
2188 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2189 return INVALID_OPERATION;
2190 }
2191 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2192 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2193 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002194 // only one sink supported when connecting an input device to a mix
2195 if (patch->num_sinks > 1) {
2196 return INVALID_OPERATION;
2197 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002198 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002199 if (inputDesc == NULL) {
2200 return BAD_VALUE;
2201 }
2202 if (patchDesc != 0) {
2203 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2204 return BAD_VALUE;
2205 }
2206 }
2207 sp<DeviceDescriptor> devDesc =
2208 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2209 if (devDesc == 0) {
2210 return BAD_VALUE;
2211 }
2212
Eric Laurent84c70242014-06-23 08:46:27 -07002213 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002214 patch->sinks[0].sample_rate,
2215 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002216 patch->sinks[0].format,
2217 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002218 // FIXME for the parameter type,
2219 // and the NONE
2220 (audio_output_flags_t)
2221 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002222 return INVALID_OPERATION;
2223 }
2224 // TODO: reconfigure output format and channels here
2225 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002226 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002227 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002228 index = mAudioPatches.indexOfKey(*handle);
2229 if (index >= 0) {
2230 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2231 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2232 }
2233 patchDesc = mAudioPatches.valueAt(index);
2234 patchDesc->mUid = uid;
2235 ALOGV("createAudioPatch() success");
2236 } else {
2237 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2238 return INVALID_OPERATION;
2239 }
2240 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2241 // device to device connection
2242 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002243 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002244 return BAD_VALUE;
2245 }
2246 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002247 sp<DeviceDescriptor> srcDeviceDesc =
2248 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent874c42872014-08-08 15:13:39 -07002249
Eric Laurent6a94d692014-05-20 11:18:06 -07002250 //update source and sink with our own data as the data passed in the patch may
2251 // be incomplete.
2252 struct audio_patch newPatch = *patch;
2253 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent874c42872014-08-08 15:13:39 -07002254 if (srcDeviceDesc == 0) {
2255 return BAD_VALUE;
2256 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002257
Eric Laurent874c42872014-08-08 15:13:39 -07002258 for (size_t i = 0; i < patch->num_sinks; i++) {
2259 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2260 ALOGV("createAudioPatch() source device but one sink is not a device");
2261 return INVALID_OPERATION;
2262 }
2263
2264 sp<DeviceDescriptor> sinkDeviceDesc =
2265 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2266 if (sinkDeviceDesc == 0) {
2267 return BAD_VALUE;
2268 }
2269 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2270
2271 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2272 // only one sink supported when connected devices across HW modules
2273 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002274 return INVALID_OPERATION;
2275 }
Eric Laurent874c42872014-08-08 15:13:39 -07002276 SortedVector<audio_io_handle_t> outputs =
2277 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2278 mOutputs);
2279 // if the sink device is reachable via an opened output stream, request to go via
2280 // this output stream by adding a second source to the patch description
2281 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2282 if (output != AUDIO_IO_HANDLE_NONE) {
2283 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2284 if (outputDesc->isDuplicated()) {
2285 return INVALID_OPERATION;
2286 }
2287 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2288 newPatch.num_sources = 2;
2289 }
Eric Laurent83b88082014-06-20 18:31:16 -07002290 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002291 }
2292 // TODO: check from routing capabilities in config file and other conflicting patches
2293
2294 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2295 if (index >= 0) {
2296 afPatchHandle = patchDesc->mAfPatchHandle;
2297 }
2298
2299 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2300 &afPatchHandle,
2301 0);
2302 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2303 status, afPatchHandle);
2304 if (status == NO_ERROR) {
2305 if (index < 0) {
2306 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2307 &newPatch, uid);
2308 addAudioPatch(patchDesc->mHandle, patchDesc);
2309 } else {
2310 patchDesc->mPatch = newPatch;
2311 }
2312 patchDesc->mAfPatchHandle = afPatchHandle;
2313 *handle = patchDesc->mHandle;
2314 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002315 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002316 } else {
2317 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2318 status);
2319 return INVALID_OPERATION;
2320 }
2321 } else {
2322 return BAD_VALUE;
2323 }
2324 } else {
2325 return BAD_VALUE;
2326 }
2327 return NO_ERROR;
2328}
2329
2330status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2331 uid_t uid)
2332{
2333 ALOGV("releaseAudioPatch() patch %d", handle);
2334
2335 ssize_t index = mAudioPatches.indexOfKey(handle);
2336
2337 if (index < 0) {
2338 return BAD_VALUE;
2339 }
2340 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2341 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2342 mUidCached, patchDesc->mUid, uid);
2343 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2344 return INVALID_OPERATION;
2345 }
2346
2347 struct audio_patch *patch = &patchDesc->mPatch;
2348 patchDesc->mUid = mUidCached;
2349 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002350 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002351 if (outputDesc == NULL) {
2352 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2353 return BAD_VALUE;
2354 }
2355
2356 setOutputDevice(outputDesc->mIoHandle,
2357 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2358 true,
2359 0,
2360 NULL);
2361 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2362 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002363 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002364 if (inputDesc == NULL) {
2365 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2366 return BAD_VALUE;
2367 }
2368 setInputDevice(inputDesc->mIoHandle,
2369 getNewInputDevice(inputDesc->mIoHandle),
2370 true,
2371 NULL);
2372 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2373 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2374 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2375 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2376 status, patchDesc->mAfPatchHandle);
2377 removeAudioPatch(patchDesc->mHandle);
2378 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002379 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002380 } else {
2381 return BAD_VALUE;
2382 }
2383 } else {
2384 return BAD_VALUE;
2385 }
2386 return NO_ERROR;
2387}
2388
2389status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2390 struct audio_patch *patches,
2391 unsigned int *generation)
2392{
2393 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2394 generation == NULL) {
2395 return BAD_VALUE;
2396 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002397 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002398 *num_patches, patches, mAudioPatches.size());
2399 if (patches == NULL) {
2400 *num_patches = 0;
2401 }
2402
2403 size_t patchesWritten = 0;
2404 size_t patchesMax = *num_patches;
2405 for (size_t i = 0;
2406 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2407 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2408 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002409 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002410 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2411 }
2412 *num_patches = mAudioPatches.size();
2413
2414 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002415 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002416 return NO_ERROR;
2417}
2418
Eric Laurente1715a42014-05-20 11:30:42 -07002419status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002420{
Eric Laurente1715a42014-05-20 11:30:42 -07002421 ALOGV("setAudioPortConfig()");
2422
2423 if (config == NULL) {
2424 return BAD_VALUE;
2425 }
2426 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2427 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002428 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2429 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002430 }
2431
Eric Laurenta121f902014-06-03 13:32:54 -07002432 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002433 if (config->type == AUDIO_PORT_TYPE_MIX) {
2434 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002435 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002436 if (outputDesc == NULL) {
2437 return BAD_VALUE;
2438 }
Eric Laurent84c70242014-06-23 08:46:27 -07002439 ALOG_ASSERT(!outputDesc->isDuplicated(),
2440 "setAudioPortConfig() called on duplicated output %d",
2441 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002442 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002443 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002444 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002445 if (inputDesc == NULL) {
2446 return BAD_VALUE;
2447 }
Eric Laurenta121f902014-06-03 13:32:54 -07002448 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002449 } else {
2450 return BAD_VALUE;
2451 }
2452 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2453 sp<DeviceDescriptor> deviceDesc;
2454 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2455 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2456 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2457 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2458 } else {
2459 return BAD_VALUE;
2460 }
2461 if (deviceDesc == NULL) {
2462 return BAD_VALUE;
2463 }
Eric Laurenta121f902014-06-03 13:32:54 -07002464 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002465 } else {
2466 return BAD_VALUE;
2467 }
2468
Eric Laurenta121f902014-06-03 13:32:54 -07002469 struct audio_port_config backupConfig;
2470 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2471 if (status == NO_ERROR) {
2472 struct audio_port_config newConfig;
2473 audioPortConfig->toAudioPortConfig(&newConfig, config);
2474 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002475 }
Eric Laurenta121f902014-06-03 13:32:54 -07002476 if (status != NO_ERROR) {
2477 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002478 }
Eric Laurente1715a42014-05-20 11:30:42 -07002479
2480 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002481}
2482
2483void AudioPolicyManager::clearAudioPatches(uid_t uid)
2484{
2485 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2486 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2487 if (patchDesc->mUid == uid) {
2488 // releaseAudioPatch() removes the patch from mAudioPatches
2489 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2490 i--;
2491 }
2492 }
2493 }
2494}
2495
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002496status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2497 audio_io_handle_t *ioHandle,
2498 audio_devices_t *device)
2499{
2500 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2501 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2502 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2503
2504 mSoundTriggerSessions.add(*session, *ioHandle);
2505
2506 return NO_ERROR;
2507}
2508
2509status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2510{
2511 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2512 if (index < 0) {
2513 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2514 return BAD_VALUE;
2515 }
2516
2517 mSoundTriggerSessions.removeItem(session);
2518 return NO_ERROR;
2519}
2520
Eric Laurent6a94d692014-05-20 11:18:06 -07002521status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2522 const sp<AudioPatch>& patch)
2523{
2524 ssize_t index = mAudioPatches.indexOfKey(handle);
2525
2526 if (index >= 0) {
2527 ALOGW("addAudioPatch() patch %d already in", handle);
2528 return ALREADY_EXISTS;
2529 }
2530 mAudioPatches.add(handle, patch);
2531 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2532 "sink handle %d",
2533 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2534 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2535 return NO_ERROR;
2536}
2537
2538status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2539{
2540 ssize_t index = mAudioPatches.indexOfKey(handle);
2541
2542 if (index < 0) {
2543 ALOGW("removeAudioPatch() patch %d not in", handle);
2544 return ALREADY_EXISTS;
2545 }
2546 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2547 mAudioPatches.valueAt(index)->mAfPatchHandle);
2548 mAudioPatches.removeItemsAt(index);
2549 return NO_ERROR;
2550}
2551
Eric Laurente552edb2014-03-10 17:42:56 -07002552// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002553// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002554// ----------------------------------------------------------------------------
2555
Eric Laurent3a4311c2014-03-17 12:00:47 -07002556uint32_t AudioPolicyManager::nextUniqueId()
2557{
2558 return android_atomic_inc(&mNextUniqueId);
2559}
2560
Eric Laurent6a94d692014-05-20 11:18:06 -07002561uint32_t AudioPolicyManager::nextAudioPortGeneration()
2562{
2563 return android_atomic_inc(&mAudioPortGeneration);
2564}
2565
Eric Laurente0720872014-03-11 09:30:41 -07002566AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002567 :
2568#ifdef AUDIO_POLICY_TEST
2569 Thread(false),
2570#endif //AUDIO_POLICY_TEST
2571 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002572 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002573 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2574 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002575 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002576 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2577 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002578{
Eric Laurent6a94d692014-05-20 11:18:06 -07002579 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002580 mpClientInterface = clientInterface;
2581
Eric Laurent3b73df72014-03-11 09:06:29 -07002582 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2583 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002584 }
2585
Eric Laurent1afeecb2014-05-14 08:52:28 -07002586 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002587 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2588 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2589 ALOGE("could not load audio policy configuration file, setting defaults");
2590 defaultAudioPolicyConfig();
2591 }
2592 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002593 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002594
2595 // must be done after reading the policy
2596 initializeVolumeCurves();
2597
2598 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002599 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2600 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002601 for (size_t i = 0; i < mHwModules.size(); i++) {
2602 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2603 if (mHwModules[i]->mHandle == 0) {
2604 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2605 continue;
2606 }
2607 // open all output streams needed to access attached devices
2608 // except for direct output streams that are only opened when they are actually
2609 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002610 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002611 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2612 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002613 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002614
Eric Laurent3a4311c2014-03-17 12:00:47 -07002615 if (outProfile->mSupportedDevices.isEmpty()) {
2616 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2617 continue;
2618 }
2619
Eric Laurent83b88082014-06-20 18:31:16 -07002620 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2621 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2622 profileType = mDefaultOutputDevice->mDeviceType;
2623 } else {
2624 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2625 }
2626 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002627 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002628 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002629
Eric Laurent83b88082014-06-20 18:31:16 -07002630 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002631 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2632 config.sample_rate = outputDesc->mSamplingRate;
2633 config.channel_mask = outputDesc->mChannelMask;
2634 config.format = outputDesc->mFormat;
2635 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2636 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2637 &output,
2638 &config,
2639 &outputDesc->mDevice,
2640 String8(""),
2641 &outputDesc->mLatency,
2642 outputDesc->mFlags);
2643
2644 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002645 ALOGW("Cannot open output stream for device %08x on hw module %s",
2646 outputDesc->mDevice,
2647 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002648 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002649 outputDesc->mSamplingRate = config.sample_rate;
2650 outputDesc->mChannelMask = config.channel_mask;
2651 outputDesc->mFormat = config.format;
2652
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002653 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002654 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002655 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002656 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002657 // give a valid ID to an attached device once confirmed it is reachable
2658 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2659 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002660 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002661 }
2662 }
Eric Laurente552edb2014-03-10 17:42:56 -07002663 if (mPrimaryOutput == 0 &&
2664 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2665 mPrimaryOutput = output;
2666 }
2667 addOutput(output, outputDesc);
2668 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002669 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002670 true);
2671 }
2672 }
2673 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002674 // open input streams needed to access attached devices to validate
2675 // mAvailableInputDevices list
2676 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2677 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002678 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002679
Eric Laurent3a4311c2014-03-17 12:00:47 -07002680 if (inProfile->mSupportedDevices.isEmpty()) {
2681 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2682 continue;
2683 }
2684
Eric Laurent83b88082014-06-20 18:31:16 -07002685 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2686 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002687 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688
2689 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002690 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002691
Eric Laurentcf2c0212014-07-25 16:20:43 -07002692 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2693 config.sample_rate = inputDesc->mSamplingRate;
2694 config.channel_mask = inputDesc->mChannelMask;
2695 config.format = inputDesc->mFormat;
2696 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2697 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2698 &input,
2699 &config,
2700 &inputDesc->mDevice,
2701 String8(""),
2702 AUDIO_SOURCE_MIC,
2703 AUDIO_INPUT_FLAG_NONE);
2704
2705 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002706 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002707 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002708 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002709 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002710 // give a valid ID to an attached device once confirmed it is reachable
2711 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2712 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002713 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002714 }
2715 }
2716 mpClientInterface->closeInput(input);
2717 } else {
2718 ALOGW("Cannot open input stream for device %08x on hw module %s",
2719 inputDesc->mDevice,
2720 mHwModules[i]->mName);
2721 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002722 }
2723 }
2724 }
2725 // make sure all attached devices have been allocated a unique ID
2726 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2727 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002728 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002729 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2730 continue;
2731 }
2732 i++;
2733 }
2734 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2735 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002736 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002737 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2738 continue;
2739 }
2740 i++;
2741 }
2742 // make sure default device is reachable
2743 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002744 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002745 }
Eric Laurente552edb2014-03-10 17:42:56 -07002746
2747 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2748
2749 updateDevicesAndOutputs();
2750
2751#ifdef AUDIO_POLICY_TEST
2752 if (mPrimaryOutput != 0) {
2753 AudioParameter outputCmd = AudioParameter();
2754 outputCmd.addInt(String8("set_id"), 0);
2755 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2756
2757 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2758 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002759 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2760 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002761 mTestLatencyMs = 0;
2762 mCurOutput = 0;
2763 mDirectOutput = false;
2764 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2765 mTestOutputs[i] = 0;
2766 }
2767
2768 const size_t SIZE = 256;
2769 char buffer[SIZE];
2770 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2771 run(buffer, ANDROID_PRIORITY_AUDIO);
2772 }
2773#endif //AUDIO_POLICY_TEST
2774}
2775
Eric Laurente0720872014-03-11 09:30:41 -07002776AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002777{
2778#ifdef AUDIO_POLICY_TEST
2779 exit();
2780#endif //AUDIO_POLICY_TEST
2781 for (size_t i = 0; i < mOutputs.size(); i++) {
2782 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002783 }
2784 for (size_t i = 0; i < mInputs.size(); i++) {
2785 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002786 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002787 mAvailableOutputDevices.clear();
2788 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002789 mOutputs.clear();
2790 mInputs.clear();
2791 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002792}
2793
Eric Laurente0720872014-03-11 09:30:41 -07002794status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002795{
2796 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2797}
2798
2799#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002800bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002801{
2802 ALOGV("entering threadLoop()");
2803 while (!exitPending())
2804 {
2805 String8 command;
2806 int valueInt;
2807 String8 value;
2808
2809 Mutex::Autolock _l(mLock);
2810 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2811
2812 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2813 AudioParameter param = AudioParameter(command);
2814
2815 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2816 valueInt != 0) {
2817 ALOGV("Test command %s received", command.string());
2818 String8 target;
2819 if (param.get(String8("target"), target) != NO_ERROR) {
2820 target = "Manager";
2821 }
2822 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2823 param.remove(String8("test_cmd_policy_output"));
2824 mCurOutput = valueInt;
2825 }
2826 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2827 param.remove(String8("test_cmd_policy_direct"));
2828 if (value == "false") {
2829 mDirectOutput = false;
2830 } else if (value == "true") {
2831 mDirectOutput = true;
2832 }
2833 }
2834 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2835 param.remove(String8("test_cmd_policy_input"));
2836 mTestInput = valueInt;
2837 }
2838
2839 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2840 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002841 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002842 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002843 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002844 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002845 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002846 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002847 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002848 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002849 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002850 if (target == "Manager") {
2851 mTestFormat = format;
2852 } else if (mTestOutputs[mCurOutput] != 0) {
2853 AudioParameter outputParam = AudioParameter();
2854 outputParam.addInt(String8("format"), format);
2855 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2856 }
2857 }
2858 }
2859 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2860 param.remove(String8("test_cmd_policy_channels"));
2861 int channels = 0;
2862
2863 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002864 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002865 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002866 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002867 }
2868 if (channels != 0) {
2869 if (target == "Manager") {
2870 mTestChannels = channels;
2871 } else if (mTestOutputs[mCurOutput] != 0) {
2872 AudioParameter outputParam = AudioParameter();
2873 outputParam.addInt(String8("channels"), channels);
2874 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2875 }
2876 }
2877 }
2878 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2879 param.remove(String8("test_cmd_policy_sampleRate"));
2880 if (valueInt >= 0 && valueInt <= 96000) {
2881 int samplingRate = valueInt;
2882 if (target == "Manager") {
2883 mTestSamplingRate = samplingRate;
2884 } else if (mTestOutputs[mCurOutput] != 0) {
2885 AudioParameter outputParam = AudioParameter();
2886 outputParam.addInt(String8("sampling_rate"), samplingRate);
2887 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2888 }
2889 }
2890 }
2891
2892 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2893 param.remove(String8("test_cmd_policy_reopen"));
2894
Eric Laurent1f2f2232014-06-02 12:01:23 -07002895 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002896 mpClientInterface->closeOutput(mPrimaryOutput);
2897
2898 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2899
Eric Laurente552edb2014-03-10 17:42:56 -07002900 mOutputs.removeItem(mPrimaryOutput);
2901
Eric Laurent1f2f2232014-06-02 12:01:23 -07002902 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002903 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002904 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2905 config.sample_rate = outputDesc->mSamplingRate;
2906 config.channel_mask = outputDesc->mChannelMask;
2907 config.format = outputDesc->mFormat;
2908 status_t status = mpClientInterface->openOutput(moduleHandle,
2909 &mPrimaryOutput,
2910 &config,
2911 &outputDesc->mDevice,
2912 String8(""),
2913 &outputDesc->mLatency,
2914 outputDesc->mFlags);
2915 if (status != NO_ERROR) {
2916 ALOGE("Failed to reopen hardware output stream, "
2917 "samplingRate: %d, format %d, channels %d",
2918 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002919 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002920 outputDesc->mSamplingRate = config.sample_rate;
2921 outputDesc->mChannelMask = config.channel_mask;
2922 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002923 AudioParameter outputCmd = AudioParameter();
2924 outputCmd.addInt(String8("set_id"), 0);
2925 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2926 addOutput(mPrimaryOutput, outputDesc);
2927 }
2928 }
2929
2930
2931 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2932 }
2933 }
2934 return false;
2935}
2936
Eric Laurente0720872014-03-11 09:30:41 -07002937void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002938{
2939 {
2940 AutoMutex _l(mLock);
2941 requestExit();
2942 mWaitWorkCV.signal();
2943 }
2944 requestExitAndWait();
2945}
2946
Eric Laurente0720872014-03-11 09:30:41 -07002947int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002948{
2949 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2950 if (output == mTestOutputs[i]) return i;
2951 }
2952 return 0;
2953}
2954#endif //AUDIO_POLICY_TEST
2955
2956// ---
2957
Eric Laurent1f2f2232014-06-02 12:01:23 -07002958void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002959{
Eric Laurent1c333e22014-05-20 10:48:17 -07002960 outputDesc->mIoHandle = output;
2961 outputDesc->mId = nextUniqueId();
2962 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002963 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002964}
2965
Eric Laurent1f2f2232014-06-02 12:01:23 -07002966void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002967{
Eric Laurent1c333e22014-05-20 10:48:17 -07002968 inputDesc->mIoHandle = input;
2969 inputDesc->mId = nextUniqueId();
2970 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002972}
Eric Laurente552edb2014-03-10 17:42:56 -07002973
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002974void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2975 const String8 address /*in*/,
2976 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2977 // look for a match on the given address on the addresses of the outputs:
2978 // find the address by finding the patch that maps to this output
2979 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2980 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2981 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2982 if (patchIdx >= 0) {
2983 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2984 const int numSinks = patchDesc->mPatch.num_sinks;
2985 for (ssize_t j=0; j < numSinks; j++) {
2986 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2987 const char* patchAddr =
2988 patchDesc->mPatch.sinks[j].ext.device.address;
2989 if (strncmp(patchAddr,
2990 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2991 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2992 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2993 outputs.add(desc->mIoHandle);
2994 break;
2995 }
2996 }
2997 }
2998 }
2999}
3000
Eric Laurente0720872014-03-11 09:30:41 -07003001status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07003002 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003003 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003004 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003005{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003006 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07003007
Eric Laurent3b73df72014-03-11 09:06:29 -07003008 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003009 // first list already open outputs that can be routed to this device
3010 for (size_t i = 0; i < mOutputs.size(); i++) {
3011 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003012 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003013 if (!deviceDistinguishesOnAddress(device)) {
3014 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3015 outputs.add(mOutputs.keyAt(i));
3016 } else {
3017 ALOGV(" checking address match due to device 0x%x", device);
3018 findIoHandlesByAddress(desc, address, outputs);
3019 }
Eric Laurente552edb2014-03-10 17:42:56 -07003020 }
3021 }
3022 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003023 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003024 for (size_t i = 0; i < mHwModules.size(); i++)
3025 {
3026 if (mHwModules[i]->mHandle == 0) {
3027 continue;
3028 }
3029 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3030 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003031 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003032 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003033 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3034 }
3035 }
3036 }
3037
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003038 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3039
Eric Laurente552edb2014-03-10 17:42:56 -07003040 if (profiles.isEmpty() && outputs.isEmpty()) {
3041 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3042 return BAD_VALUE;
3043 }
3044
3045 // open outputs for matching profiles if needed. Direct outputs are also opened to
3046 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3047 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003048 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003049
3050 // nothing to do if one output is already opened for this profile
3051 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003052 for (j = 0; j < outputs.size(); j++) {
3053 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003054 if (!desc->isDuplicated() && desc->mProfile == profile) {
3055 break;
3056 }
3057 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003058 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003059 continue;
3060 }
3061
Eric Laurent83b88082014-06-20 18:31:16 -07003062 ALOGV("opening output for device %08x with params %s profile %p",
3063 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003064 desc = new AudioOutputDescriptor(profile);
3065 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003066 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3067 config.sample_rate = desc->mSamplingRate;
3068 config.channel_mask = desc->mChannelMask;
3069 config.format = desc->mFormat;
3070 config.offload_info.sample_rate = desc->mSamplingRate;
3071 config.offload_info.channel_mask = desc->mChannelMask;
3072 config.offload_info.format = desc->mFormat;
3073 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3074 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3075 &output,
3076 &config,
3077 &desc->mDevice,
3078 address,
3079 &desc->mLatency,
3080 desc->mFlags);
3081 if (status == NO_ERROR) {
3082 desc->mSamplingRate = config.sample_rate;
3083 desc->mChannelMask = config.channel_mask;
3084 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003085
Eric Laurentd4692962014-05-05 18:13:44 -07003086 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003087 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003088 char *param = audio_device_address_to_parameter(device, address);
3089 mpClientInterface->setParameters(output, String8(param));
3090 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003091 }
3092
Eric Laurentd4692962014-05-05 18:13:44 -07003093 // Here is where we step through and resolve any "dynamic" fields
3094 String8 reply;
3095 char *value;
3096 if (profile->mSamplingRates[0] == 0) {
3097 reply = mpClientInterface->getParameters(output,
3098 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003099 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003100 reply.string());
3101 value = strpbrk((char *)reply.string(), "=");
3102 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003103 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003104 }
Eric Laurentd4692962014-05-05 18:13:44 -07003105 }
3106 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3107 reply = mpClientInterface->getParameters(output,
3108 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003109 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003110 reply.string());
3111 value = strpbrk((char *)reply.string(), "=");
3112 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003113 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003114 }
Eric Laurentd4692962014-05-05 18:13:44 -07003115 }
3116 if (profile->mChannelMasks[0] == 0) {
3117 reply = mpClientInterface->getParameters(output,
3118 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003119 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003120 reply.string());
3121 value = strpbrk((char *)reply.string(), "=");
3122 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003123 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003124 }
Eric Laurentd4692962014-05-05 18:13:44 -07003125 }
3126 if (((profile->mSamplingRates[0] == 0) &&
3127 (profile->mSamplingRates.size() < 2)) ||
3128 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3129 (profile->mFormats.size() < 2)) ||
3130 ((profile->mChannelMasks[0] == 0) &&
3131 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003132 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003133 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003134 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003135 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3136 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003137 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003138 config.sample_rate = profile->pickSamplingRate();
3139 config.channel_mask = profile->pickChannelMask();
3140 config.format = profile->pickFormat();
3141 config.offload_info.sample_rate = config.sample_rate;
3142 config.offload_info.channel_mask = config.channel_mask;
3143 config.offload_info.format = config.format;
3144 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3145 &output,
3146 &config,
3147 &desc->mDevice,
3148 address,
3149 &desc->mLatency,
3150 desc->mFlags);
3151 if (status == NO_ERROR) {
3152 desc->mSamplingRate = config.sample_rate;
3153 desc->mChannelMask = config.channel_mask;
3154 desc->mFormat = config.format;
3155 } else {
3156 output = AUDIO_IO_HANDLE_NONE;
3157 }
Eric Laurentd4692962014-05-05 18:13:44 -07003158 }
3159
Eric Laurentcf2c0212014-07-25 16:20:43 -07003160 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003161 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003162 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003163 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003164
Eric Laurentd4692962014-05-05 18:13:44 -07003165 // set initial stream volume for device
3166 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003167
Eric Laurentd4692962014-05-05 18:13:44 -07003168 //TODO: configure audio effect output stage here
3169
3170 // open a duplicating output thread for the new output and the primary output
3171 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3172 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003173 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003174 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003175 sp<AudioOutputDescriptor> dupOutputDesc =
3176 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003177 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3178 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3179 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3180 dupOutputDesc->mFormat = desc->mFormat;
3181 dupOutputDesc->mChannelMask = desc->mChannelMask;
3182 dupOutputDesc->mLatency = desc->mLatency;
3183 addOutput(duplicatedOutput, dupOutputDesc);
3184 applyStreamVolumes(duplicatedOutput, device, 0, true);
3185 } else {
3186 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3187 mPrimaryOutput, output);
3188 mpClientInterface->closeOutput(output);
3189 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003190 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003191 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003192 }
Eric Laurente552edb2014-03-10 17:42:56 -07003193 }
3194 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003195 } else {
3196 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003197 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003198 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003199 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003200 profiles.removeAt(profile_index);
3201 profile_index--;
3202 } else {
3203 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003204 if (deviceDistinguishesOnAddress(device)) {
3205 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3206 device, address.string());
3207 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3208 NULL/*patch handle*/, address.string());
3209 }
Eric Laurente552edb2014-03-10 17:42:56 -07003210 ALOGV("checkOutputsForDevice(): adding output %d", output);
3211 }
3212 }
3213
3214 if (profiles.isEmpty()) {
3215 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3216 return BAD_VALUE;
3217 }
Eric Laurentd4692962014-05-05 18:13:44 -07003218 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003219 // check if one opened output is not needed any more after disconnecting one device
3220 for (size_t i = 0; i < mOutputs.size(); i++) {
3221 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003222 if (!desc->isDuplicated()) {
3223 if (!(desc->mProfile->mSupportedDevices.types()
3224 & mAvailableOutputDevices.types())) {
3225 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3226 mOutputs.keyAt(i));
3227 outputs.add(mOutputs.keyAt(i));
3228 } else if (deviceDistinguishesOnAddress(device) &&
3229 // exact match on device
3230 (desc->mProfile->mSupportedDevices.types() == device)) {
3231 findIoHandlesByAddress(desc, address, outputs);
3232 }
Eric Laurente552edb2014-03-10 17:42:56 -07003233 }
3234 }
Eric Laurentd4692962014-05-05 18:13:44 -07003235 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003236 for (size_t i = 0; i < mHwModules.size(); i++)
3237 {
3238 if (mHwModules[i]->mHandle == 0) {
3239 continue;
3240 }
3241 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3242 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003243 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003244 if (profile->mSupportedDevices.types() & device) {
3245 ALOGV("checkOutputsForDevice(): "
3246 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003247 if (profile->mSamplingRates[0] == 0) {
3248 profile->mSamplingRates.clear();
3249 profile->mSamplingRates.add(0);
3250 }
3251 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3252 profile->mFormats.clear();
3253 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3254 }
3255 if (profile->mChannelMasks[0] == 0) {
3256 profile->mChannelMasks.clear();
3257 profile->mChannelMasks.add(0);
3258 }
3259 }
3260 }
3261 }
3262 }
3263 return NO_ERROR;
3264}
3265
Eric Laurentd4692962014-05-05 18:13:44 -07003266status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3267 audio_policy_dev_state_t state,
3268 SortedVector<audio_io_handle_t>& inputs,
3269 const String8 address)
3270{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003271 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003272 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3273 // first list already open inputs that can be routed to this device
3274 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3275 desc = mInputs.valueAt(input_index);
3276 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3277 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3278 inputs.add(mInputs.keyAt(input_index));
3279 }
3280 }
3281
3282 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003283 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003284 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3285 {
3286 if (mHwModules[module_idx]->mHandle == 0) {
3287 continue;
3288 }
3289 for (size_t profile_index = 0;
3290 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3291 profile_index++)
3292 {
3293 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3294 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003295 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003296 profile_index, module_idx);
3297 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3298 }
3299 }
3300 }
3301
3302 if (profiles.isEmpty() && inputs.isEmpty()) {
3303 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3304 return BAD_VALUE;
3305 }
3306
3307 // open inputs for matching profiles if needed. Direct inputs are also opened to
3308 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3309 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3310
Eric Laurent1c333e22014-05-20 10:48:17 -07003311 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003312 // nothing to do if one input is already opened for this profile
3313 size_t input_index;
3314 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3315 desc = mInputs.valueAt(input_index);
3316 if (desc->mProfile == profile) {
3317 break;
3318 }
3319 }
3320 if (input_index != mInputs.size()) {
3321 continue;
3322 }
3323
3324 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3325 desc = new AudioInputDescriptor(profile);
3326 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003327 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3328 config.sample_rate = desc->mSamplingRate;
3329 config.channel_mask = desc->mChannelMask;
3330 config.format = desc->mFormat;
3331 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3332 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3333 &input,
3334 &config,
3335 &desc->mDevice,
3336 address,
3337 AUDIO_SOURCE_MIC,
3338 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003339
Eric Laurentcf2c0212014-07-25 16:20:43 -07003340 if (status == NO_ERROR) {
3341 desc->mSamplingRate = config.sample_rate;
3342 desc->mChannelMask = config.channel_mask;
3343 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003344
Eric Laurentd4692962014-05-05 18:13:44 -07003345 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003346 char *param = audio_device_address_to_parameter(device, address);
3347 mpClientInterface->setParameters(input, String8(param));
3348 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003349 }
3350
3351 // Here is where we step through and resolve any "dynamic" fields
3352 String8 reply;
3353 char *value;
3354 if (profile->mSamplingRates[0] == 0) {
3355 reply = mpClientInterface->getParameters(input,
3356 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3357 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3358 reply.string());
3359 value = strpbrk((char *)reply.string(), "=");
3360 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003361 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003362 }
3363 }
3364 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3365 reply = mpClientInterface->getParameters(input,
3366 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3367 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3368 value = strpbrk((char *)reply.string(), "=");
3369 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003370 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003371 }
3372 }
3373 if (profile->mChannelMasks[0] == 0) {
3374 reply = mpClientInterface->getParameters(input,
3375 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3376 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3377 reply.string());
3378 value = strpbrk((char *)reply.string(), "=");
3379 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003380 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003381 }
3382 }
3383 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3384 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3385 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3386 ALOGW("checkInputsForDevice() direct input missing param");
3387 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003388 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003389 }
3390
3391 if (input != 0) {
3392 addInput(input, desc);
3393 }
3394 } // endif input != 0
3395
Eric Laurentcf2c0212014-07-25 16:20:43 -07003396 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003397 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003398 profiles.removeAt(profile_index);
3399 profile_index--;
3400 } else {
3401 inputs.add(input);
3402 ALOGV("checkInputsForDevice(): adding input %d", input);
3403 }
3404 } // end scan profiles
3405
3406 if (profiles.isEmpty()) {
3407 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3408 return BAD_VALUE;
3409 }
3410 } else {
3411 // Disconnect
3412 // check if one opened input is not needed any more after disconnecting one device
3413 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3414 desc = mInputs.valueAt(input_index);
3415 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3416 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3417 mInputs.keyAt(input_index));
3418 inputs.add(mInputs.keyAt(input_index));
3419 }
3420 }
3421 // Clear any profiles associated with the disconnected device.
3422 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3423 if (mHwModules[module_index]->mHandle == 0) {
3424 continue;
3425 }
3426 for (size_t profile_index = 0;
3427 profile_index < mHwModules[module_index]->mInputProfiles.size();
3428 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003429 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003430 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003431 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003432 profile_index, module_index);
3433 if (profile->mSamplingRates[0] == 0) {
3434 profile->mSamplingRates.clear();
3435 profile->mSamplingRates.add(0);
3436 }
3437 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3438 profile->mFormats.clear();
3439 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3440 }
3441 if (profile->mChannelMasks[0] == 0) {
3442 profile->mChannelMasks.clear();
3443 profile->mChannelMasks.add(0);
3444 }
3445 }
3446 }
3447 }
3448 } // end disconnect
3449
3450 return NO_ERROR;
3451}
3452
3453
Eric Laurente0720872014-03-11 09:30:41 -07003454void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003455{
3456 ALOGV("closeOutput(%d)", output);
3457
Eric Laurent1f2f2232014-06-02 12:01:23 -07003458 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003459 if (outputDesc == NULL) {
3460 ALOGW("closeOutput() unknown output %d", output);
3461 return;
3462 }
3463
3464 // look for duplicated outputs connected to the output being removed.
3465 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003466 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003467 if (dupOutputDesc->isDuplicated() &&
3468 (dupOutputDesc->mOutput1 == outputDesc ||
3469 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003470 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003471 if (dupOutputDesc->mOutput1 == outputDesc) {
3472 outputDesc2 = dupOutputDesc->mOutput2;
3473 } else {
3474 outputDesc2 = dupOutputDesc->mOutput1;
3475 }
3476 // As all active tracks on duplicated output will be deleted,
3477 // and as they were also referenced on the other output, the reference
3478 // count for their stream type must be adjusted accordingly on
3479 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003480 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003481 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003482 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
3484 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3485 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3486
3487 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003488 mOutputs.removeItem(duplicatedOutput);
3489 }
3490 }
3491
3492 AudioParameter param;
3493 param.add(String8("closing"), String8("true"));
3494 mpClientInterface->setParameters(output, param.toString());
3495
3496 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003497 mOutputs.removeItem(output);
3498 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003499 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003500}
3501
Eric Laurente0720872014-03-11 09:30:41 -07003502SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003503 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003504{
3505 SortedVector<audio_io_handle_t> outputs;
3506
3507 ALOGVV("getOutputsForDevice() device %04x", device);
3508 for (size_t i = 0; i < openOutputs.size(); i++) {
3509 ALOGVV("output %d isDuplicated=%d device=%04x",
3510 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3511 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3512 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3513 outputs.add(openOutputs.keyAt(i));
3514 }
3515 }
3516 return outputs;
3517}
3518
Eric Laurente0720872014-03-11 09:30:41 -07003519bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003520 SortedVector<audio_io_handle_t>& outputs2)
3521{
3522 if (outputs1.size() != outputs2.size()) {
3523 return false;
3524 }
3525 for (size_t i = 0; i < outputs1.size(); i++) {
3526 if (outputs1[i] != outputs2[i]) {
3527 return false;
3528 }
3529 }
3530 return true;
3531}
3532
Eric Laurente0720872014-03-11 09:30:41 -07003533void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003534{
3535 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3536 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3537 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3538 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3539
3540 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3541 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3542 strategy, srcOutputs[0], dstOutputs[0]);
3543 // mute strategy while moving tracks from one output to another
3544 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003545 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003546 if (desc->isStrategyActive(strategy)) {
3547 setStrategyMute(strategy, true, srcOutputs[i]);
3548 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3549 }
3550 }
3551
3552 // Move effects associated to this strategy from previous output to new output
3553 if (strategy == STRATEGY_MEDIA) {
3554 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3555 SortedVector<audio_io_handle_t> moved;
3556 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003557 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3558 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3559 effectDesc->mIo != fxOutput) {
3560 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003561 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3562 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003563 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003564 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003565 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003566 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003567 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003568 }
3569 }
3570 }
3571 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003572 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3573 if (getStrategy((audio_stream_type_t)i) == strategy) {
3574 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003575 }
3576 }
3577 }
3578}
3579
Eric Laurente0720872014-03-11 09:30:41 -07003580void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003581{
3582 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3583 checkOutputForStrategy(STRATEGY_PHONE);
3584 checkOutputForStrategy(STRATEGY_SONIFICATION);
3585 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3586 checkOutputForStrategy(STRATEGY_MEDIA);
3587 checkOutputForStrategy(STRATEGY_DTMF);
3588}
3589
Eric Laurente0720872014-03-11 09:30:41 -07003590audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003591{
Eric Laurente552edb2014-03-10 17:42:56 -07003592 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003593 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003594 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3595 return mOutputs.keyAt(i);
3596 }
3597 }
3598
3599 return 0;
3600}
3601
Eric Laurente0720872014-03-11 09:30:41 -07003602void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003603{
Eric Laurente552edb2014-03-10 17:42:56 -07003604 audio_io_handle_t a2dpOutput = getA2dpOutput();
3605 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003606 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003607 return;
3608 }
3609
Eric Laurent3a4311c2014-03-17 12:00:47 -07003610 bool isScoConnected =
3611 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003612 // suspend A2DP output if:
3613 // (NOT already suspended) &&
3614 // ((SCO device is connected &&
3615 // (forced usage for communication || for record is SCO))) ||
3616 // (phone state is ringing || in call)
3617 //
3618 // restore A2DP output if:
3619 // (Already suspended) &&
3620 // ((SCO device is NOT connected ||
3621 // (forced usage NOT for communication && NOT for record is SCO))) &&
3622 // (phone state is NOT ringing && NOT in call)
3623 //
3624 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003625 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003626 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3627 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3628 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3629 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003630
3631 mpClientInterface->restoreOutput(a2dpOutput);
3632 mA2dpSuspended = false;
3633 }
3634 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003635 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003636 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3637 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3638 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3639 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003640
3641 mpClientInterface->suspendOutput(a2dpOutput);
3642 mA2dpSuspended = true;
3643 }
3644 }
3645}
3646
Eric Laurent1c333e22014-05-20 10:48:17 -07003647audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003648{
3649 audio_devices_t device = AUDIO_DEVICE_NONE;
3650
Eric Laurent1f2f2232014-06-02 12:01:23 -07003651 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003652
3653 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3654 if (index >= 0) {
3655 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3656 if (patchDesc->mUid != mUidCached) {
3657 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3658 outputDesc->device(), outputDesc->mPatchHandle);
3659 return outputDesc->device();
3660 }
3661 }
3662
Eric Laurente552edb2014-03-10 17:42:56 -07003663 // check the following by order of priority to request a routing change if necessary:
3664 // 1: the strategy enforced audible is active on the output:
3665 // use device for strategy enforced audible
3666 // 2: we are in call or the strategy phone is active on the output:
3667 // use device for strategy phone
3668 // 3: the strategy sonification is active on the output:
3669 // use device for strategy sonification
3670 // 4: the strategy "respectful" sonification is active on the output:
3671 // use device for strategy "respectful" sonification
3672 // 5: the strategy media is active on the output:
3673 // use device for strategy media
3674 // 6: the strategy DTMF is active on the output:
3675 // use device for strategy DTMF
3676 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3677 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3678 } else if (isInCall() ||
3679 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3680 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3681 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3682 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3683 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3684 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3685 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3686 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3687 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3688 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3689 }
3690
Eric Laurent1c333e22014-05-20 10:48:17 -07003691 ALOGV("getNewOutputDevice() selected device %x", device);
3692 return device;
3693}
3694
3695audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3696{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003697 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003698
3699 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3700 if (index >= 0) {
3701 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3702 if (patchDesc->mUid != mUidCached) {
3703 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3704 inputDesc->mDevice, inputDesc->mPatchHandle);
3705 return inputDesc->mDevice;
3706 }
3707 }
3708
Eric Laurent1c333e22014-05-20 10:48:17 -07003709 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3710
3711 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003712 return device;
3713}
3714
Eric Laurente0720872014-03-11 09:30:41 -07003715uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003716 return (uint32_t)getStrategy(stream);
3717}
3718
Eric Laurente0720872014-03-11 09:30:41 -07003719audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003720 // By checking the range of stream before calling getStrategy, we avoid
3721 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3722 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003723 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003724 return AUDIO_DEVICE_NONE;
3725 }
3726 audio_devices_t devices;
3727 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3728 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3729 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3730 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003731 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003732 if (outputDesc->isStrategyActive(strategy)) {
3733 devices = outputDesc->device();
3734 break;
3735 }
Eric Laurente552edb2014-03-10 17:42:56 -07003736 }
3737 return devices;
3738}
3739
Eric Laurente0720872014-03-11 09:30:41 -07003740AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003741 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003742 // stream to strategy mapping
3743 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003744 case AUDIO_STREAM_VOICE_CALL:
3745 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003746 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003747 case AUDIO_STREAM_RING:
3748 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003749 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003750 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003751 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003752 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003753 return STRATEGY_DTMF;
3754 default:
3755 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003756 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003757 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3758 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003759 case AUDIO_STREAM_TTS:
3760 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003761 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003762 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003763 return STRATEGY_ENFORCED_AUDIBLE;
3764 }
3765}
3766
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003767uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3768 // flags to strategy mapping
3769 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3770 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3771 }
3772
3773 // usage to strategy mapping
3774 switch (attr->usage) {
3775 case AUDIO_USAGE_MEDIA:
3776 case AUDIO_USAGE_GAME:
3777 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3778 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3779 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3780 return (uint32_t) STRATEGY_MEDIA;
3781
3782 case AUDIO_USAGE_VOICE_COMMUNICATION:
3783 return (uint32_t) STRATEGY_PHONE;
3784
3785 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3786 return (uint32_t) STRATEGY_DTMF;
3787
3788 case AUDIO_USAGE_ALARM:
3789 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3790 return (uint32_t) STRATEGY_SONIFICATION;
3791
3792 case AUDIO_USAGE_NOTIFICATION:
3793 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3794 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3795 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3796 case AUDIO_USAGE_NOTIFICATION_EVENT:
3797 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3798
3799 case AUDIO_USAGE_UNKNOWN:
3800 default:
3801 return (uint32_t) STRATEGY_MEDIA;
3802 }
3803}
3804
Eric Laurente0720872014-03-11 09:30:41 -07003805void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003806 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003807 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003808 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3809 updateDevicesAndOutputs();
3810 break;
3811 default:
3812 break;
3813 }
3814}
3815
Eric Laurente0720872014-03-11 09:30:41 -07003816audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003817 bool fromCache)
3818{
3819 uint32_t device = AUDIO_DEVICE_NONE;
3820
3821 if (fromCache) {
3822 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3823 strategy, mDeviceForStrategy[strategy]);
3824 return mDeviceForStrategy[strategy];
3825 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003826 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003827 switch (strategy) {
3828
3829 case STRATEGY_SONIFICATION_RESPECTFUL:
3830 if (isInCall()) {
3831 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003832 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003833 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3834 // while media is playing on a remote device, use the the sonification behavior.
3835 // Note that we test this usecase before testing if media is playing because
3836 // the isStreamActive() method only informs about the activity of a stream, not
3837 // if it's for local playback. Note also that we use the same delay between both tests
3838 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003839 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003840 // while media is playing (or has recently played), use the same device
3841 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3842 } else {
3843 // when media is not playing anymore, fall back on the sonification behavior
3844 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3845 }
3846
3847 break;
3848
3849 case STRATEGY_DTMF:
3850 if (!isInCall()) {
3851 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3852 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3853 break;
3854 }
3855 // when in call, DTMF and PHONE strategies follow the same rules
3856 // FALL THROUGH
3857
3858 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003859 // Force use of only devices on primary output if:
3860 // - in call AND
3861 // - cannot route from voice call RX OR
3862 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3863 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3864 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3865 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3866 if (((mAvailableInputDevices.types() &
3867 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3868 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
3869 (hwOutputDesc->mAudioPort->mModule->mHalVersion <
3870 AUDIO_DEVICE_API_VERSION_3_0))) {
3871 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3872 }
3873 }
Eric Laurente552edb2014-03-10 17:42:56 -07003874 // for phone strategy, we first consider the forced use and then the available devices by order
3875 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003876 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3877 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003878 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003879 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003880 if (device) break;
3881 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003882 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003883 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003884 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003885 if (device) break;
3886 // if SCO device is requested but no SCO device is available, fall back to default case
3887 // FALL THROUGH
3888
3889 default: // FORCE_NONE
3890 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003891 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003892 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003893 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003894 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003895 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003896 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003897 if (device) break;
3898 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003899 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003900 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003901 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003902 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07003903 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3904 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003905 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003906 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003907 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003908 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003909 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003910 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003911 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003912 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003913 if (device) break;
3914 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003915 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003916 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003917 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003918 if (device == AUDIO_DEVICE_NONE) {
3919 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3920 }
3921 break;
3922
Eric Laurent3b73df72014-03-11 09:06:29 -07003923 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003924 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3925 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003926 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003927 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003928 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003929 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003930 if (device) break;
3931 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003932 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003933 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003934 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003936 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003938 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003939 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003940 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003941 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003942 if (device) break;
3943 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003944 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3945 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003946 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003947 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003948 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003949 if (device == AUDIO_DEVICE_NONE) {
3950 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3951 }
3952 break;
3953 }
3954 break;
3955
3956 case STRATEGY_SONIFICATION:
3957
3958 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3959 // handleIncallSonification().
3960 if (isInCall()) {
3961 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3962 break;
3963 }
3964 // FALL THROUGH
3965
3966 case STRATEGY_ENFORCED_AUDIBLE:
3967 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3968 // except:
3969 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3970 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3971
3972 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003973 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003974 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003975 if (device == AUDIO_DEVICE_NONE) {
3976 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3977 }
3978 }
3979 // The second device used for sonification is the same as the device used by media strategy
3980 // FALL THROUGH
3981
3982 case STRATEGY_MEDIA: {
3983 uint32_t device2 = AUDIO_DEVICE_NONE;
3984 if (strategy != STRATEGY_SONIFICATION) {
3985 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003986 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003987 }
3988 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003989 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003990 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003991 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003992 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003993 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003994 }
3995 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003996 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
3998 }
3999 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004000 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004001 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004002 if ((device2 == AUDIO_DEVICE_NONE)) {
4003 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4004 }
Eric Laurente552edb2014-03-10 17:42:56 -07004005 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004006 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004007 }
4008 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004009 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004010 }
4011 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004012 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004013 }
4014 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004015 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004016 }
4017 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4018 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004019 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004020 }
4021 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004022 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004023 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004024 }
4025 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004027 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004028 int device3 = AUDIO_DEVICE_NONE;
4029 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004030 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004031 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4032 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004033 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004034 }
Eric Laurente552edb2014-03-10 17:42:56 -07004035
Jungshik Jang839e4f32014-06-26 17:23:40 +09004036 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004037 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4038 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4039 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004040
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004041 // If hdmi system audio mode is on, remove speaker out of output list.
4042 if ((strategy == STRATEGY_MEDIA) &&
4043 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4044 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4045 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4046 }
4047
Eric Laurente552edb2014-03-10 17:42:56 -07004048 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004049 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004050 if (device == AUDIO_DEVICE_NONE) {
4051 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4052 }
4053 } break;
4054
4055 default:
4056 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4057 break;
4058 }
4059
4060 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4061 return device;
4062}
4063
Eric Laurente0720872014-03-11 09:30:41 -07004064void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004065{
4066 for (int i = 0; i < NUM_STRATEGIES; i++) {
4067 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4068 }
4069 mPreviousOutputs = mOutputs;
4070}
4071
Eric Laurent1f2f2232014-06-02 12:01:23 -07004072uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004073 audio_devices_t prevDevice,
4074 uint32_t delayMs)
4075{
4076 // mute/unmute strategies using an incompatible device combination
4077 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4078 // if unmuting, unmute only after the specified delay
4079 if (outputDesc->isDuplicated()) {
4080 return 0;
4081 }
4082
4083 uint32_t muteWaitMs = 0;
4084 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004085 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004086
4087 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4088 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4089 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4090 bool doMute = false;
4091
4092 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4093 doMute = true;
4094 outputDesc->mStrategyMutedByDevice[i] = true;
4095 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4096 doMute = true;
4097 outputDesc->mStrategyMutedByDevice[i] = false;
4098 }
Eric Laurent99401132014-05-07 19:48:15 -07004099 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004100 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004101 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004102 // skip output if it does not share any device with current output
4103 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4104 == AUDIO_DEVICE_NONE) {
4105 continue;
4106 }
4107 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4108 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4109 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4110 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4111 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004112 if (mute) {
4113 // FIXME: should not need to double latency if volume could be applied
4114 // immediately by the audioflinger mixer. We must account for the delay
4115 // between now and the next time the audioflinger thread for this output
4116 // will process a buffer (which corresponds to one buffer size,
4117 // usually 1/2 or 1/4 of the latency).
4118 if (muteWaitMs < desc->latency() * 2) {
4119 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
4121 }
4122 }
4123 }
4124 }
4125 }
4126
Eric Laurent99401132014-05-07 19:48:15 -07004127 // temporary mute output if device selection changes to avoid volume bursts due to
4128 // different per device volumes
4129 if (outputDesc->isActive() && (device != prevDevice)) {
4130 if (muteWaitMs < outputDesc->latency() * 2) {
4131 muteWaitMs = outputDesc->latency() * 2;
4132 }
4133 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4134 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004135 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004136 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004137 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004138 muteWaitMs *2, device);
4139 }
4140 }
4141 }
4142
Eric Laurente552edb2014-03-10 17:42:56 -07004143 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4144 if (muteWaitMs > delayMs) {
4145 muteWaitMs -= delayMs;
4146 usleep(muteWaitMs * 1000);
4147 return muteWaitMs;
4148 }
4149 return 0;
4150}
4151
Eric Laurente0720872014-03-11 09:30:41 -07004152uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004153 audio_devices_t device,
4154 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004156 audio_patch_handle_t *patchHandle,
4157 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004158{
4159 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004160 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004161 AudioParameter param;
4162 uint32_t muteWaitMs;
4163
4164 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004165 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4166 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004167 return muteWaitMs;
4168 }
4169 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4170 // output profile
4171 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004173 return 0;
4174 }
4175
4176 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004178
4179 audio_devices_t prevDevice = outputDesc->mDevice;
4180
4181 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4182
4183 if (device != AUDIO_DEVICE_NONE) {
4184 outputDesc->mDevice = device;
4185 }
4186 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4187
4188 // Do not change the routing if:
4189 // - the requested device is AUDIO_DEVICE_NONE
4190 // - the requested device is the same as current device and force is not specified.
4191 // Doing this check here allows the caller to call setOutputDevice() without conditions
4192 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4193 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4194 return muteWaitMs;
4195 }
4196
4197 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004198
Eric Laurente552edb2014-03-10 17:42:56 -07004199 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004200 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004201 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004202 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004203 DeviceVector deviceList = (address == NULL) ?
4204 mAvailableOutputDevices.getDevicesFromType(device)
4205 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004206 if (!deviceList.isEmpty()) {
4207 struct audio_patch patch;
4208 outputDesc->toAudioPortConfig(&patch.sources[0]);
4209 patch.num_sources = 1;
4210 patch.num_sinks = 0;
4211 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4212 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004213 patch.num_sinks++;
4214 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 ssize_t index;
4216 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4217 index = mAudioPatches.indexOfKey(*patchHandle);
4218 } else {
4219 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4220 }
4221 sp< AudioPatch> patchDesc;
4222 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4223 if (index >= 0) {
4224 patchDesc = mAudioPatches.valueAt(index);
4225 afPatchHandle = patchDesc->mAfPatchHandle;
4226 }
4227
Eric Laurent1c333e22014-05-20 10:48:17 -07004228 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004229 &afPatchHandle,
4230 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004231 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4232 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004233 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004234 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004235 if (index < 0) {
4236 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4237 &patch, mUidCached);
4238 addAudioPatch(patchDesc->mHandle, patchDesc);
4239 } else {
4240 patchDesc->mPatch = patch;
4241 }
4242 patchDesc->mAfPatchHandle = afPatchHandle;
4243 patchDesc->mUid = mUidCached;
4244 if (patchHandle) {
4245 *patchHandle = patchDesc->mHandle;
4246 }
4247 outputDesc->mPatchHandle = patchDesc->mHandle;
4248 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004249 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004250 }
4251 }
4252 }
Eric Laurente552edb2014-03-10 17:42:56 -07004253
4254 // update stream volumes according to new device
4255 applyStreamVolumes(output, device, delayMs);
4256
4257 return muteWaitMs;
4258}
4259
Eric Laurent1c333e22014-05-20 10:48:17 -07004260status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004261 int delayMs,
4262 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004263{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004264 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 ssize_t index;
4266 if (patchHandle) {
4267 index = mAudioPatches.indexOfKey(*patchHandle);
4268 } else {
4269 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4270 }
4271 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004272 return INVALID_OPERATION;
4273 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004274 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4275 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004276 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4277 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004278 removeAudioPatch(patchDesc->mHandle);
4279 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004280 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004281 return status;
4282}
4283
4284status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4285 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004286 bool force,
4287 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004288{
4289 status_t status = NO_ERROR;
4290
Eric Laurent1f2f2232014-06-02 12:01:23 -07004291 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004292 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4293 inputDesc->mDevice = device;
4294
4295 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4296 if (!deviceList.isEmpty()) {
4297 struct audio_patch patch;
4298 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004299 // AUDIO_SOURCE_HOTWORD is for internal use only:
4300 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004301 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4302 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004303 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4304 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004305 patch.num_sinks = 1;
4306 //only one input device for now
4307 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004308 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004309 ssize_t index;
4310 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4311 index = mAudioPatches.indexOfKey(*patchHandle);
4312 } else {
4313 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4314 }
4315 sp< AudioPatch> patchDesc;
4316 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4317 if (index >= 0) {
4318 patchDesc = mAudioPatches.valueAt(index);
4319 afPatchHandle = patchDesc->mAfPatchHandle;
4320 }
4321
Eric Laurent1c333e22014-05-20 10:48:17 -07004322 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004324 0);
4325 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004326 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004327 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004328 if (index < 0) {
4329 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4330 &patch, mUidCached);
4331 addAudioPatch(patchDesc->mHandle, patchDesc);
4332 } else {
4333 patchDesc->mPatch = patch;
4334 }
4335 patchDesc->mAfPatchHandle = afPatchHandle;
4336 patchDesc->mUid = mUidCached;
4337 if (patchHandle) {
4338 *patchHandle = patchDesc->mHandle;
4339 }
4340 inputDesc->mPatchHandle = patchDesc->mHandle;
4341 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004342 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004343 }
4344 }
4345 }
4346 return status;
4347}
4348
Eric Laurent6a94d692014-05-20 11:18:06 -07004349status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4350 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004351{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004352 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004353 ssize_t index;
4354 if (patchHandle) {
4355 index = mAudioPatches.indexOfKey(*patchHandle);
4356 } else {
4357 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4358 }
4359 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004360 return INVALID_OPERATION;
4361 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004362 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4363 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004364 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4365 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004366 removeAudioPatch(patchDesc->mHandle);
4367 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004368 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004369 return status;
4370}
4371
4372sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004373 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004374 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004375 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004376 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004377{
4378 // Choose an input profile based on the requested capture parameters: select the first available
4379 // profile supporting all requested parameters.
4380
4381 for (size_t i = 0; i < mHwModules.size(); i++)
4382 {
4383 if (mHwModules[i]->mHandle == 0) {
4384 continue;
4385 }
4386 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4387 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004388 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004389 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004390 if (profile->isCompatibleProfile(device, samplingRate,
4391 &samplingRate /*updatedSamplingRate*/,
4392 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004393 return profile;
4394 }
4395 }
4396 }
4397 return NULL;
4398}
4399
Eric Laurente0720872014-03-11 09:30:41 -07004400audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004401{
4402 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004403 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4404 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004405 switch (inputSource) {
4406 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004407 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004408 device = AUDIO_DEVICE_IN_VOICE_CALL;
4409 break;
4410 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004411 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004412
4413 case AUDIO_SOURCE_DEFAULT:
4414 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004415 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4416 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004417 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4418 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4419 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4420 device = AUDIO_DEVICE_IN_USB_DEVICE;
4421 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4422 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004423 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004424 break;
4425
4426 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4427 // Allow only use of devices on primary input if in call and HAL does not support routing
4428 // to voice call path.
4429 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4430 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4431 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4432 }
4433
4434 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4435 case AUDIO_POLICY_FORCE_BT_SCO:
4436 // if SCO device is requested but no SCO device is available, fall back to default case
4437 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4438 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4439 break;
4440 }
4441 // FALL THROUGH
4442
4443 default: // FORCE_NONE
4444 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4445 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4446 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4447 device = AUDIO_DEVICE_IN_USB_DEVICE;
4448 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4449 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4450 }
4451 break;
4452
4453 case AUDIO_POLICY_FORCE_SPEAKER:
4454 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4455 device = AUDIO_DEVICE_IN_BACK_MIC;
4456 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4457 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4458 }
4459 break;
4460 }
4461 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004462
Eric Laurente552edb2014-03-10 17:42:56 -07004463 case AUDIO_SOURCE_VOICE_RECOGNITION:
4464 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004465 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004466 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004467 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004468 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004469 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004470 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4471 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004472 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004473 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4474 }
4475 break;
4476 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004477 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004478 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004479 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004480 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4481 }
4482 break;
4483 case AUDIO_SOURCE_VOICE_DOWNLINK:
4484 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004485 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004486 device = AUDIO_DEVICE_IN_VOICE_CALL;
4487 }
4488 break;
4489 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004490 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004491 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4492 }
4493 break;
4494 default:
4495 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4496 break;
4497 }
4498 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4499 return device;
4500}
4501
Eric Laurente0720872014-03-11 09:30:41 -07004502bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004503{
4504 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4505 device &= ~AUDIO_DEVICE_BIT_IN;
4506 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4507 return true;
4508 }
4509 return false;
4510}
4511
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004512bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4513 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4514}
4515
Eric Laurente0720872014-03-11 09:30:41 -07004516audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004517{
4518 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004519 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004520 if ((input_descriptor->mRefCount > 0)
4521 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4522 return mInputs.keyAt(i);
4523 }
4524 }
4525 return 0;
4526}
4527
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004528uint32_t AudioPolicyManager::activeInputsCount() const
4529{
4530 uint32_t count = 0;
4531 for (size_t i = 0; i < mInputs.size(); i++) {
4532 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4533 if (desc->mRefCount > 0) {
4534 return count++;
4535 }
4536 }
4537 return count;
4538}
4539
Eric Laurente552edb2014-03-10 17:42:56 -07004540
Eric Laurente0720872014-03-11 09:30:41 -07004541audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004542{
4543 if (device == AUDIO_DEVICE_NONE) {
4544 // this happens when forcing a route update and no track is active on an output.
4545 // In this case the returned category is not important.
4546 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004547 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004548 // Multiple device selection is either:
4549 // - speaker + one other device: give priority to speaker in this case.
4550 // - one A2DP device + another device: happens with duplicated output. In this case
4551 // retain the device on the A2DP output as the other must not correspond to an active
4552 // selection if not the speaker.
4553 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4554 device = AUDIO_DEVICE_OUT_SPEAKER;
4555 } else {
4556 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4557 }
4558 }
4559
Eric Laurent3b73df72014-03-11 09:06:29 -07004560 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004561 "getDeviceForVolume() invalid device combination: %08x",
4562 device);
4563
4564 return device;
4565}
4566
Eric Laurente0720872014-03-11 09:30:41 -07004567AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004568{
4569 switch(getDeviceForVolume(device)) {
4570 case AUDIO_DEVICE_OUT_EARPIECE:
4571 return DEVICE_CATEGORY_EARPIECE;
4572 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4573 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4574 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4575 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4576 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4577 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4578 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004579 case AUDIO_DEVICE_OUT_LINE:
4580 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4581 /*USB? Remote submix?*/
4582 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004583 case AUDIO_DEVICE_OUT_SPEAKER:
4584 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4585 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004586 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4587 case AUDIO_DEVICE_OUT_USB_DEVICE:
4588 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4589 default:
4590 return DEVICE_CATEGORY_SPEAKER;
4591 }
4592}
4593
Eric Laurente0720872014-03-11 09:30:41 -07004594float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004595 int indexInUi)
4596{
4597 device_category deviceCategory = getDeviceCategory(device);
4598 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4599
4600 // the volume index in the UI is relative to the min and max volume indices for this stream type
4601 int nbSteps = 1 + curve[VOLMAX].mIndex -
4602 curve[VOLMIN].mIndex;
4603 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4604 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4605
4606 // find what part of the curve this index volume belongs to, or if it's out of bounds
4607 int segment = 0;
4608 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4609 return 0.0f;
4610 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4611 segment = 0;
4612 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4613 segment = 1;
4614 } else if (volIdx <= curve[VOLMAX].mIndex) {
4615 segment = 2;
4616 } else { // out of bounds
4617 return 1.0f;
4618 }
4619
4620 // linear interpolation in the attenuation table in dB
4621 float decibels = curve[segment].mDBAttenuation +
4622 ((float)(volIdx - curve[segment].mIndex)) *
4623 ( (curve[segment+1].mDBAttenuation -
4624 curve[segment].mDBAttenuation) /
4625 ((float)(curve[segment+1].mIndex -
4626 curve[segment].mIndex)) );
4627
4628 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4629
4630 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4631 curve[segment].mIndex, volIdx,
4632 curve[segment+1].mIndex,
4633 curve[segment].mDBAttenuation,
4634 decibels,
4635 curve[segment+1].mDBAttenuation,
4636 amplification);
4637
4638 return amplification;
4639}
4640
Eric Laurente0720872014-03-11 09:30:41 -07004641const AudioPolicyManager::VolumeCurvePoint
4642 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004643 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4644};
4645
Eric Laurente0720872014-03-11 09:30:41 -07004646const AudioPolicyManager::VolumeCurvePoint
4647 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004648 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4649};
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004652 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4653 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4654};
4655
4656const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004657 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004658 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4659};
4660
Eric Laurente0720872014-03-11 09:30:41 -07004661const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004662 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004663 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004664};
4665
4666const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004667 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004668 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4669};
4670
Eric Laurente0720872014-03-11 09:30:41 -07004671const AudioPolicyManager::VolumeCurvePoint
4672 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004673 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4674};
4675
4676// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4677// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4678// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4679// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4680
Eric Laurente0720872014-03-11 09:30:41 -07004681const AudioPolicyManager::VolumeCurvePoint
4682 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004683 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4684};
4685
Eric Laurente0720872014-03-11 09:30:41 -07004686const AudioPolicyManager::VolumeCurvePoint
4687 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004688 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4689};
4690
Eric Laurente0720872014-03-11 09:30:41 -07004691const AudioPolicyManager::VolumeCurvePoint
4692 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004693 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4694};
4695
Eric Laurente0720872014-03-11 09:30:41 -07004696const AudioPolicyManager::VolumeCurvePoint
4697 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004698 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4699};
4700
Eric Laurente0720872014-03-11 09:30:41 -07004701const AudioPolicyManager::VolumeCurvePoint
4702 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004703 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4704};
4705
Eric Laurente0720872014-03-11 09:30:41 -07004706const AudioPolicyManager::VolumeCurvePoint
4707 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4708 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004709 { // AUDIO_STREAM_VOICE_CALL
4710 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4711 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004712 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4713 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004714 },
4715 { // AUDIO_STREAM_SYSTEM
4716 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4717 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004718 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4719 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004720 },
4721 { // AUDIO_STREAM_RING
4722 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4723 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004724 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4725 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004726 },
4727 { // AUDIO_STREAM_MUSIC
4728 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4729 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004730 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4731 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004732 },
4733 { // AUDIO_STREAM_ALARM
4734 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4735 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004736 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4737 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004738 },
4739 { // AUDIO_STREAM_NOTIFICATION
4740 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4741 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004742 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4743 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004744 },
4745 { // AUDIO_STREAM_BLUETOOTH_SCO
4746 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4747 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004748 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4749 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004750 },
4751 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4752 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4753 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004754 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4755 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004756 },
4757 { // AUDIO_STREAM_DTMF
4758 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4759 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004760 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4761 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004762 },
4763 { // AUDIO_STREAM_TTS
4764 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4765 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004766 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4767 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004768 },
4769};
4770
Eric Laurente0720872014-03-11 09:30:41 -07004771void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004772{
4773 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4774 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4775 mStreams[i].mVolumeCurve[j] =
4776 sVolumeProfiles[i][j];
4777 }
4778 }
4779
4780 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4781 if (mSpeakerDrcEnabled) {
4782 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4783 sDefaultSystemVolumeCurveDrc;
4784 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4785 sSpeakerSonificationVolumeCurveDrc;
4786 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4787 sSpeakerSonificationVolumeCurveDrc;
4788 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4789 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004790 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4791 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004792 }
4793}
4794
Eric Laurente0720872014-03-11 09:30:41 -07004795float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004796 int index,
4797 audio_io_handle_t output,
4798 audio_devices_t device)
4799{
4800 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004801 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004802 StreamDescriptor &streamDesc = mStreams[stream];
4803
4804 if (device == AUDIO_DEVICE_NONE) {
4805 device = outputDesc->device();
4806 }
4807
Eric Laurente552edb2014-03-10 17:42:56 -07004808 volume = volIndexToAmpl(device, streamDesc, index);
4809
4810 // if a headset is connected, apply the following rules to ring tones and notifications
4811 // to avoid sound level bursts in user's ears:
4812 // - always attenuate ring tones and notifications volume by 6dB
4813 // - if music is playing, always limit the volume to current music volume,
4814 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004815 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004816 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4817 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4818 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4819 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4820 ((stream_strategy == STRATEGY_SONIFICATION)
4821 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004822 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004823 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004824 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004825 streamDesc.mCanBeMuted) {
4826 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4827 // when the phone is ringing we must consider that music could have been paused just before
4828 // by the music application and behave as if music was active if the last music track was
4829 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004830 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004831 mLimitRingtoneVolume) {
4832 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004833 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4834 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004835 output,
4836 musicDevice);
4837 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4838 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4839 if (volume > minVol) {
4840 volume = minVol;
4841 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4842 }
4843 }
4844 }
4845
4846 return volume;
4847}
4848
Eric Laurente0720872014-03-11 09:30:41 -07004849status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004850 int index,
4851 audio_io_handle_t output,
4852 audio_devices_t device,
4853 int delayMs,
4854 bool force)
4855{
4856
4857 // do not change actual stream volume if the stream is muted
4858 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4859 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4860 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4861 return NO_ERROR;
4862 }
4863
4864 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004865 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4866 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4867 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4868 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004869 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004870 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004871 return INVALID_OPERATION;
4872 }
4873
4874 float volume = computeVolume(stream, index, output, device);
4875 // We actually change the volume if:
4876 // - the float value returned by computeVolume() changed
4877 // - the force flag is set
4878 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4879 force) {
4880 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4881 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4882 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4883 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004884 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4885 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004886 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004887 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004888 }
4889
Eric Laurent3b73df72014-03-11 09:06:29 -07004890 if (stream == AUDIO_STREAM_VOICE_CALL ||
4891 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004892 float voiceVolume;
4893 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004894 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004895 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4896 } else {
4897 voiceVolume = 1.0;
4898 }
4899
4900 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4901 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4902 mLastVoiceVolume = voiceVolume;
4903 }
4904 }
4905
4906 return NO_ERROR;
4907}
4908
Eric Laurente0720872014-03-11 09:30:41 -07004909void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004910 audio_devices_t device,
4911 int delayMs,
4912 bool force)
4913{
4914 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4915
Eric Laurent3b73df72014-03-11 09:06:29 -07004916 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4917 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004918 mStreams[stream].getVolumeIndex(device),
4919 output,
4920 device,
4921 delayMs,
4922 force);
4923 }
4924}
4925
Eric Laurente0720872014-03-11 09:30:41 -07004926void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004927 bool on,
4928 audio_io_handle_t output,
4929 int delayMs,
4930 audio_devices_t device)
4931{
4932 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004933 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4934 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4935 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004936 }
4937 }
4938}
4939
Eric Laurente0720872014-03-11 09:30:41 -07004940void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004941 bool on,
4942 audio_io_handle_t output,
4943 int delayMs,
4944 audio_devices_t device)
4945{
4946 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004947 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004948 if (device == AUDIO_DEVICE_NONE) {
4949 device = outputDesc->device();
4950 }
4951
4952 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4953 stream, on, output, outputDesc->mMuteCount[stream], device);
4954
4955 if (on) {
4956 if (outputDesc->mMuteCount[stream] == 0) {
4957 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004958 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4959 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004960 checkAndSetVolume(stream, 0, output, device, delayMs);
4961 }
4962 }
4963 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4964 outputDesc->mMuteCount[stream]++;
4965 } else {
4966 if (outputDesc->mMuteCount[stream] == 0) {
4967 ALOGV("setStreamMute() unmuting non muted stream!");
4968 return;
4969 }
4970 if (--outputDesc->mMuteCount[stream] == 0) {
4971 checkAndSetVolume(stream,
4972 streamDesc.getVolumeIndex(device),
4973 output,
4974 device,
4975 delayMs);
4976 }
4977 }
4978}
4979
Eric Laurente0720872014-03-11 09:30:41 -07004980void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004981 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004982{
4983 // if the stream pertains to sonification strategy and we are in call we must
4984 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4985 // in the device used for phone strategy and play the tone if the selected device does not
4986 // interfere with the device used for phone strategy
4987 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4988 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004989 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004990 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4991 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004992 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004993 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4994 stream, starting, outputDesc->mDevice, stateChange);
4995 if (outputDesc->mRefCount[stream]) {
4996 int muteCount = 1;
4997 if (stateChange) {
4998 muteCount = outputDesc->mRefCount[stream];
4999 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005000 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005001 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5002 for (int i = 0; i < muteCount; i++) {
5003 setStreamMute(stream, starting, mPrimaryOutput);
5004 }
5005 } else {
5006 ALOGV("handleIncallSonification() high visibility");
5007 if (outputDesc->device() &
5008 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5009 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5010 for (int i = 0; i < muteCount; i++) {
5011 setStreamMute(stream, starting, mPrimaryOutput);
5012 }
5013 }
5014 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005015 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5016 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005017 } else {
5018 mpClientInterface->stopTone();
5019 }
5020 }
5021 }
5022 }
5023}
5024
Eric Laurente0720872014-03-11 09:30:41 -07005025bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005026{
5027 return isStateInCall(mPhoneState);
5028}
5029
Eric Laurente0720872014-03-11 09:30:41 -07005030bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005031 return ((state == AUDIO_MODE_IN_CALL) ||
5032 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005033}
5034
Eric Laurente0720872014-03-11 09:30:41 -07005035uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005036{
5037 return MAX_EFFECTS_CPU_LOAD;
5038}
5039
Eric Laurente0720872014-03-11 09:30:41 -07005040uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005041{
5042 return MAX_EFFECTS_MEMORY;
5043}
5044
Eric Laurent6a94d692014-05-20 11:18:06 -07005045
Eric Laurente552edb2014-03-10 17:42:56 -07005046// --- AudioOutputDescriptor class implementation
5047
Eric Laurente0720872014-03-11 09:30:41 -07005048AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005049 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005050 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005051 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005052 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5053{
5054 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005055 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005056 mRefCount[i] = 0;
5057 mCurVolume[i] = -1.0;
5058 mMuteCount[i] = 0;
5059 mStopTime[i] = 0;
5060 }
5061 for (int i = 0; i < NUM_STRATEGIES; i++) {
5062 mStrategyMutedByDevice[i] = false;
5063 }
5064 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005065 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07005066 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005067 mSamplingRate = profile->pickSamplingRate();
5068 mFormat = profile->pickFormat();
5069 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005070 if (profile->mGains.size() > 0) {
5071 profile->mGains[0]->getDefaultConfig(&mGain);
5072 }
Eric Laurente552edb2014-03-10 17:42:56 -07005073 }
5074}
5075
Eric Laurente0720872014-03-11 09:30:41 -07005076audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005077{
5078 if (isDuplicated()) {
5079 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5080 } else {
5081 return mDevice;
5082 }
5083}
5084
Eric Laurente0720872014-03-11 09:30:41 -07005085uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005086{
5087 if (isDuplicated()) {
5088 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5089 } else {
5090 return mLatency;
5091 }
5092}
5093
Eric Laurente0720872014-03-11 09:30:41 -07005094bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005095 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005096{
5097 if (isDuplicated()) {
5098 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5099 } else if (outputDesc->isDuplicated()){
5100 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5101 } else {
5102 return (mProfile->mModule == outputDesc->mProfile->mModule);
5103 }
5104}
5105
Eric Laurente0720872014-03-11 09:30:41 -07005106void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005107 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005108{
5109 // forward usage count change to attached outputs
5110 if (isDuplicated()) {
5111 mOutput1->changeRefCount(stream, delta);
5112 mOutput2->changeRefCount(stream, delta);
5113 }
5114 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005115 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5116 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005117 mRefCount[stream] = 0;
5118 return;
5119 }
5120 mRefCount[stream] += delta;
5121 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5122}
5123
Eric Laurente0720872014-03-11 09:30:41 -07005124audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005125{
5126 if (isDuplicated()) {
5127 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5128 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005129 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005130 }
5131}
5132
Eric Laurente0720872014-03-11 09:30:41 -07005133bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005134{
5135 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5136}
5137
Eric Laurente0720872014-03-11 09:30:41 -07005138bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005139 uint32_t inPastMs,
5140 nsecs_t sysTime) const
5141{
5142 if ((sysTime == 0) && (inPastMs != 0)) {
5143 sysTime = systemTime();
5144 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005145 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5146 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005147 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005148 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005149 return true;
5150 }
5151 }
5152 return false;
5153}
5154
Eric Laurente0720872014-03-11 09:30:41 -07005155bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005156 uint32_t inPastMs,
5157 nsecs_t sysTime) const
5158{
5159 if (mRefCount[stream] != 0) {
5160 return true;
5161 }
5162 if (inPastMs == 0) {
5163 return false;
5164 }
5165 if (sysTime == 0) {
5166 sysTime = systemTime();
5167 }
5168 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5169 return true;
5170 }
5171 return false;
5172}
5173
Eric Laurent1c333e22014-05-20 10:48:17 -07005174void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005175 struct audio_port_config *dstConfig,
5176 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005177{
Eric Laurent84c70242014-06-23 08:46:27 -07005178 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5179
Eric Laurent1f2f2232014-06-02 12:01:23 -07005180 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5181 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5182 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005183 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005184 }
5185 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5186
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 dstConfig->id = mId;
5188 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5189 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5191 dstConfig->ext.mix.handle = mIoHandle;
5192 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005193}
5194
5195void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5196 struct audio_port *port) const
5197{
Eric Laurent84c70242014-06-23 08:46:27 -07005198 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005199 mProfile->toAudioPort(port);
5200 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 toAudioPortConfig(&port->active_config);
5202 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005203 port->ext.mix.handle = mIoHandle;
5204 port->ext.mix.latency_class =
5205 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5206}
Eric Laurente552edb2014-03-10 17:42:56 -07005207
Eric Laurente0720872014-03-11 09:30:41 -07005208status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005209{
5210 const size_t SIZE = 256;
5211 char buffer[SIZE];
5212 String8 result;
5213
Eric Laurent4d416952014-08-10 14:07:09 -07005214 snprintf(buffer, SIZE, " ID: %d\n", mId);
5215 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005216 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5217 result.append(buffer);
5218 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5219 result.append(buffer);
5220 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5221 result.append(buffer);
5222 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5223 result.append(buffer);
5224 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5225 result.append(buffer);
5226 snprintf(buffer, SIZE, " Devices %08x\n", device());
5227 result.append(buffer);
5228 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5229 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005230 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5231 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5232 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005233 result.append(buffer);
5234 }
5235 write(fd, result.string(), result.size());
5236
5237 return NO_ERROR;
5238}
5239
5240// --- AudioInputDescriptor class implementation
5241
Eric Laurent1c333e22014-05-20 10:48:17 -07005242AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005243 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005244 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005245 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005246{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005247 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005248 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07005249 mSamplingRate = profile->pickSamplingRate();
5250 mFormat = profile->pickFormat();
5251 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005252 if (profile->mGains.size() > 0) {
5253 profile->mGains[0]->getDefaultConfig(&mGain);
5254 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005255 }
Eric Laurente552edb2014-03-10 17:42:56 -07005256}
5257
Eric Laurent1c333e22014-05-20 10:48:17 -07005258void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 struct audio_port_config *dstConfig,
5260 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005261{
Eric Laurent84c70242014-06-23 08:46:27 -07005262 ALOG_ASSERT(mProfile != 0,
5263 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005264 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5265 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5266 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005267 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005268 }
5269
5270 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5271
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 dstConfig->id = mId;
5273 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5274 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005275 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5276 dstConfig->ext.mix.handle = mIoHandle;
5277 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005278}
5279
5280void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5281 struct audio_port *port) const
5282{
Eric Laurent84c70242014-06-23 08:46:27 -07005283 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5284
Eric Laurent1c333e22014-05-20 10:48:17 -07005285 mProfile->toAudioPort(port);
5286 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 toAudioPortConfig(&port->active_config);
5288 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005289 port->ext.mix.handle = mIoHandle;
5290 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5291}
5292
Eric Laurente0720872014-03-11 09:30:41 -07005293status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005294{
5295 const size_t SIZE = 256;
5296 char buffer[SIZE];
5297 String8 result;
5298
Eric Laurent4d416952014-08-10 14:07:09 -07005299 snprintf(buffer, SIZE, " ID: %d\n", mId);
5300 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005301 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5302 result.append(buffer);
5303 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5304 result.append(buffer);
5305 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5306 result.append(buffer);
5307 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5308 result.append(buffer);
5309 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5310 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005311 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5312 result.append(buffer);
5313
Eric Laurente552edb2014-03-10 17:42:56 -07005314 write(fd, result.string(), result.size());
5315
5316 return NO_ERROR;
5317}
5318
5319// --- StreamDescriptor class implementation
5320
Eric Laurente0720872014-03-11 09:30:41 -07005321AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005322 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5323{
5324 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5325}
5326
Eric Laurente0720872014-03-11 09:30:41 -07005327int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005328{
Eric Laurente0720872014-03-11 09:30:41 -07005329 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005330 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5331 if (mIndexCur.indexOfKey(device) < 0) {
5332 device = AUDIO_DEVICE_OUT_DEFAULT;
5333 }
5334 return mIndexCur.valueFor(device);
5335}
5336
Eric Laurente0720872014-03-11 09:30:41 -07005337void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005338{
5339 const size_t SIZE = 256;
5340 char buffer[SIZE];
5341 String8 result;
5342
5343 snprintf(buffer, SIZE, "%s %02d %02d ",
5344 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5345 result.append(buffer);
5346 for (size_t i = 0; i < mIndexCur.size(); i++) {
5347 snprintf(buffer, SIZE, "%04x : %02d, ",
5348 mIndexCur.keyAt(i),
5349 mIndexCur.valueAt(i));
5350 result.append(buffer);
5351 }
5352 result.append("\n");
5353
5354 write(fd, result.string(), result.size());
5355}
5356
5357// --- EffectDescriptor class implementation
5358
Eric Laurente0720872014-03-11 09:30:41 -07005359status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005360{
5361 const size_t SIZE = 256;
5362 char buffer[SIZE];
5363 String8 result;
5364
5365 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5366 result.append(buffer);
5367 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5368 result.append(buffer);
5369 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5370 result.append(buffer);
5371 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5372 result.append(buffer);
5373 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5374 result.append(buffer);
5375 write(fd, result.string(), result.size());
5376
5377 return NO_ERROR;
5378}
5379
Eric Laurent1c333e22014-05-20 10:48:17 -07005380// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005381
Eric Laurente0720872014-03-11 09:30:41 -07005382AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005383 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5384 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005385{
5386}
5387
Eric Laurente0720872014-03-11 09:30:41 -07005388AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005389{
5390 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005391 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005392 }
5393 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005394 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005395 }
5396 free((void *)mName);
5397}
5398
Eric Laurent1afeecb2014-05-14 08:52:28 -07005399status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5400{
5401 cnode *node = root->first_child;
5402
5403 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5404
5405 while (node) {
5406 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5407 profile->loadSamplingRates((char *)node->value);
5408 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5409 profile->loadFormats((char *)node->value);
5410 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5411 profile->loadInChannels((char *)node->value);
5412 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5413 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5414 mDeclaredDevices);
5415 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5416 profile->loadGains(node);
5417 }
5418 node = node->next;
5419 }
5420 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5421 "loadInput() invalid supported devices");
5422 ALOGW_IF(profile->mChannelMasks.size() == 0,
5423 "loadInput() invalid supported channel masks");
5424 ALOGW_IF(profile->mSamplingRates.size() == 0,
5425 "loadInput() invalid supported sampling rates");
5426 ALOGW_IF(profile->mFormats.size() == 0,
5427 "loadInput() invalid supported formats");
5428 if (!profile->mSupportedDevices.isEmpty() &&
5429 (profile->mChannelMasks.size() != 0) &&
5430 (profile->mSamplingRates.size() != 0) &&
5431 (profile->mFormats.size() != 0)) {
5432
5433 ALOGV("loadInput() adding input Supported Devices %04x",
5434 profile->mSupportedDevices.types());
5435
5436 mInputProfiles.add(profile);
5437 return NO_ERROR;
5438 } else {
5439 return BAD_VALUE;
5440 }
5441}
5442
5443status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5444{
5445 cnode *node = root->first_child;
5446
5447 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5448
5449 while (node) {
5450 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5451 profile->loadSamplingRates((char *)node->value);
5452 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5453 profile->loadFormats((char *)node->value);
5454 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5455 profile->loadOutChannels((char *)node->value);
5456 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5457 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5458 mDeclaredDevices);
5459 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5460 profile->mFlags = parseFlagNames((char *)node->value);
5461 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5462 profile->loadGains(node);
5463 }
5464 node = node->next;
5465 }
5466 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5467 "loadOutput() invalid supported devices");
5468 ALOGW_IF(profile->mChannelMasks.size() == 0,
5469 "loadOutput() invalid supported channel masks");
5470 ALOGW_IF(profile->mSamplingRates.size() == 0,
5471 "loadOutput() invalid supported sampling rates");
5472 ALOGW_IF(profile->mFormats.size() == 0,
5473 "loadOutput() invalid supported formats");
5474 if (!profile->mSupportedDevices.isEmpty() &&
5475 (profile->mChannelMasks.size() != 0) &&
5476 (profile->mSamplingRates.size() != 0) &&
5477 (profile->mFormats.size() != 0)) {
5478
5479 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5480 profile->mSupportedDevices.types(), profile->mFlags);
5481
5482 mOutputProfiles.add(profile);
5483 return NO_ERROR;
5484 } else {
5485 return BAD_VALUE;
5486 }
5487}
5488
5489status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5490{
5491 cnode *node = root->first_child;
5492
5493 audio_devices_t type = AUDIO_DEVICE_NONE;
5494 while (node) {
5495 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5496 type = parseDeviceNames((char *)node->value);
5497 break;
5498 }
5499 node = node->next;
5500 }
5501 if (type == AUDIO_DEVICE_NONE ||
5502 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5503 ALOGW("loadDevice() bad type %08x", type);
5504 return BAD_VALUE;
5505 }
5506 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5507 deviceDesc->mModule = this;
5508
5509 node = root->first_child;
5510 while (node) {
5511 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5512 deviceDesc->mAddress = String8((char *)node->value);
5513 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5514 if (audio_is_input_device(type)) {
5515 deviceDesc->loadInChannels((char *)node->value);
5516 } else {
5517 deviceDesc->loadOutChannels((char *)node->value);
5518 }
5519 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5520 deviceDesc->loadGains(node);
5521 }
5522 node = node->next;
5523 }
5524
5525 ALOGV("loadDevice() adding device name %s type %08x address %s",
5526 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5527
5528 mDeclaredDevices.add(deviceDesc);
5529
5530 return NO_ERROR;
5531}
5532
Eric Laurente0720872014-03-11 09:30:41 -07005533void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005534{
5535 const size_t SIZE = 256;
5536 char buffer[SIZE];
5537 String8 result;
5538
5539 snprintf(buffer, SIZE, " - name: %s\n", mName);
5540 result.append(buffer);
5541 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5542 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005543 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5544 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005545 write(fd, result.string(), result.size());
5546 if (mOutputProfiles.size()) {
5547 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5548 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005549 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005550 write(fd, buffer, strlen(buffer));
5551 mOutputProfiles[i]->dump(fd);
5552 }
5553 }
5554 if (mInputProfiles.size()) {
5555 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5556 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005557 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005558 write(fd, buffer, strlen(buffer));
5559 mInputProfiles[i]->dump(fd);
5560 }
5561 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005562 if (mDeclaredDevices.size()) {
5563 write(fd, " - devices:\n", strlen(" - devices:\n"));
5564 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5565 mDeclaredDevices[i]->dump(fd, 4, i);
5566 }
5567 }
Eric Laurente552edb2014-03-10 17:42:56 -07005568}
5569
Eric Laurent1c333e22014-05-20 10:48:17 -07005570// --- AudioPort class implementation
5571
Eric Laurenta121f902014-06-03 13:32:54 -07005572
5573AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5574 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005575 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005576{
5577 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5578 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5579}
5580
Eric Laurent1c333e22014-05-20 10:48:17 -07005581void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5582{
5583 port->role = mRole;
5584 port->type = mType;
5585 unsigned int i;
5586 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5587 port->sample_rates[i] = mSamplingRates[i];
5588 }
5589 port->num_sample_rates = i;
5590 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5591 port->channel_masks[i] = mChannelMasks[i];
5592 }
5593 port->num_channel_masks = i;
5594 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5595 port->formats[i] = mFormats[i];
5596 }
5597 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005598
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005599 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005600
5601 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5602 port->gains[i] = mGains[i]->mGain;
5603 }
5604 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005605}
5606
5607
5608void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5609{
5610 char *str = strtok(name, "|");
5611
5612 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5613 // rates should be read from the output stream after it is opened for the first time
5614 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5615 mSamplingRates.add(0);
5616 return;
5617 }
5618
5619 while (str != NULL) {
5620 uint32_t rate = atoi(str);
5621 if (rate != 0) {
5622 ALOGV("loadSamplingRates() adding rate %d", rate);
5623 mSamplingRates.add(rate);
5624 }
5625 str = strtok(NULL, "|");
5626 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005627}
5628
5629void AudioPolicyManager::AudioPort::loadFormats(char *name)
5630{
5631 char *str = strtok(name, "|");
5632
5633 // by convention, "0' in the first entry in mFormats indicates the supported formats
5634 // should be read from the output stream after it is opened for the first time
5635 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5636 mFormats.add(AUDIO_FORMAT_DEFAULT);
5637 return;
5638 }
5639
5640 while (str != NULL) {
5641 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5642 ARRAY_SIZE(sFormatNameToEnumTable),
5643 str);
5644 if (format != AUDIO_FORMAT_DEFAULT) {
5645 mFormats.add(format);
5646 }
5647 str = strtok(NULL, "|");
5648 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005649}
5650
5651void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5652{
5653 const char *str = strtok(name, "|");
5654
5655 ALOGV("loadInChannels() %s", name);
5656
5657 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5658 mChannelMasks.add(0);
5659 return;
5660 }
5661
5662 while (str != NULL) {
5663 audio_channel_mask_t channelMask =
5664 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5665 ARRAY_SIZE(sInChannelsNameToEnumTable),
5666 str);
5667 if (channelMask != 0) {
5668 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5669 mChannelMasks.add(channelMask);
5670 }
5671 str = strtok(NULL, "|");
5672 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005673}
5674
5675void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5676{
5677 const char *str = strtok(name, "|");
5678
5679 ALOGV("loadOutChannels() %s", name);
5680
5681 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5682 // masks should be read from the output stream after it is opened for the first time
5683 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5684 mChannelMasks.add(0);
5685 return;
5686 }
5687
5688 while (str != NULL) {
5689 audio_channel_mask_t channelMask =
5690 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5691 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5692 str);
5693 if (channelMask != 0) {
5694 mChannelMasks.add(channelMask);
5695 }
5696 str = strtok(NULL, "|");
5697 }
5698 return;
5699}
5700
Eric Laurent1afeecb2014-05-14 08:52:28 -07005701audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5702{
5703 const char *str = strtok(name, "|");
5704
5705 ALOGV("loadGainMode() %s", name);
5706 audio_gain_mode_t mode = 0;
5707 while (str != NULL) {
5708 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5709 ARRAY_SIZE(sGainModeNameToEnumTable),
5710 str);
5711 str = strtok(NULL, "|");
5712 }
5713 return mode;
5714}
5715
Eric Laurenta121f902014-06-03 13:32:54 -07005716void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005717{
5718 cnode *node = root->first_child;
5719
Eric Laurenta121f902014-06-03 13:32:54 -07005720 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005721
5722 while (node) {
5723 if (strcmp(node->name, GAIN_MODE) == 0) {
5724 gain->mGain.mode = loadGainMode((char *)node->value);
5725 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005726 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005727 gain->mGain.channel_mask =
5728 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5729 ARRAY_SIZE(sInChannelsNameToEnumTable),
5730 (char *)node->value);
5731 } else {
5732 gain->mGain.channel_mask =
5733 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5734 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5735 (char *)node->value);
5736 }
5737 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5738 gain->mGain.min_value = atoi((char *)node->value);
5739 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5740 gain->mGain.max_value = atoi((char *)node->value);
5741 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5742 gain->mGain.default_value = atoi((char *)node->value);
5743 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5744 gain->mGain.step_value = atoi((char *)node->value);
5745 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5746 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5747 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5748 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5749 }
5750 node = node->next;
5751 }
5752
5753 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5754 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5755
5756 if (gain->mGain.mode == 0) {
5757 return;
5758 }
5759 mGains.add(gain);
5760}
5761
5762void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5763{
5764 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005765 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005766 while (node) {
5767 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005768 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005769 node = node->next;
5770 }
5771}
5772
Glenn Kastencbd48022014-07-24 13:46:44 -07005773status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005774{
5775 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5776 if (mSamplingRates[i] == samplingRate) {
5777 return NO_ERROR;
5778 }
5779 }
5780 return BAD_VALUE;
5781}
5782
Glenn Kastencbd48022014-07-24 13:46:44 -07005783status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5784 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005785{
Glenn Kastencbd48022014-07-24 13:46:44 -07005786 // Search for the closest supported sampling rate that is above (preferred)
5787 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5788 // The sampling rates do not need to be sorted in ascending order.
5789 ssize_t maxBelow = -1;
5790 ssize_t minAbove = -1;
5791 uint32_t candidate;
5792 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5793 candidate = mSamplingRates[i];
5794 if (candidate == samplingRate) {
5795 if (updatedSamplingRate != NULL) {
5796 *updatedSamplingRate = candidate;
5797 }
5798 return NO_ERROR;
5799 }
5800 // candidate < desired
5801 if (candidate < samplingRate) {
5802 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5803 maxBelow = i;
5804 }
5805 // candidate > desired
5806 } else {
5807 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5808 minAbove = i;
5809 }
5810 }
5811 }
5812 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5813 // TODO Move these assumptions out.
5814 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5815 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5816 // due to approximation by an int32_t of the
5817 // phase increments
5818 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5819 if (minAbove >= 0) {
5820 candidate = mSamplingRates[minAbove];
5821 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5822 if (updatedSamplingRate != NULL) {
5823 *updatedSamplingRate = candidate;
5824 }
5825 return NO_ERROR;
5826 }
5827 }
5828 // But if we have to up-sample from a lower sampling rate, that's OK.
5829 if (maxBelow >= 0) {
5830 candidate = mSamplingRates[maxBelow];
5831 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5832 if (updatedSamplingRate != NULL) {
5833 *updatedSamplingRate = candidate;
5834 }
5835 return NO_ERROR;
5836 }
5837 }
5838 // leave updatedSamplingRate unmodified
5839 return BAD_VALUE;
5840}
5841
5842status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5843{
5844 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005845 if (mChannelMasks[i] == channelMask) {
5846 return NO_ERROR;
5847 }
5848 }
5849 return BAD_VALUE;
5850}
5851
Glenn Kastencbd48022014-07-24 13:46:44 -07005852status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5853 const
5854{
5855 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5856 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5857 // FIXME Does not handle multi-channel automatic conversions yet
5858 audio_channel_mask_t supported = mChannelMasks[i];
5859 if (supported == channelMask) {
5860 return NO_ERROR;
5861 }
5862 if (isRecordThread) {
5863 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5864 // FIXME Abstract this out to a table.
5865 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5866 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5867 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5868 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5869 return NO_ERROR;
5870 }
5871 }
5872 }
5873 return BAD_VALUE;
5874}
5875
Eric Laurenta121f902014-06-03 13:32:54 -07005876status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5877{
5878 for (size_t i = 0; i < mFormats.size(); i ++) {
5879 if (mFormats[i] == format) {
5880 return NO_ERROR;
5881 }
5882 }
5883 return BAD_VALUE;
5884}
5885
Eric Laurent1e693b52014-07-09 15:03:28 -07005886
5887uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5888{
5889 // special case for uninitialized dynamic profile
5890 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5891 return 0;
5892 }
5893
5894 uint32_t samplingRate = 0;
5895 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5896
5897 // For mixed output and inputs, use max mixer sampling rates. Do not
5898 // limit sampling rate otherwise
5899 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5900 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5901 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5902 maxRate = UINT_MAX;
5903 }
5904 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5905 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5906 samplingRate = mSamplingRates[i];
5907 }
5908 }
5909 return samplingRate;
5910}
5911
5912audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5913{
5914 // special case for uninitialized dynamic profile
5915 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5916 return AUDIO_CHANNEL_NONE;
5917 }
5918
5919 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5920 uint32_t channelCount = 0;
5921 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5922
5923 // For mixed output and inputs, use max mixer channel count. Do not
5924 // limit channel count otherwise
5925 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5926 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5927 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5928 maxCount = UINT_MAX;
5929 }
5930 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5931 uint32_t cnlCount;
5932 if (mUseInChannelMask) {
5933 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5934 } else {
5935 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5936 }
5937 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5938 channelMask = mChannelMasks[i];
5939 }
5940 }
5941 return channelMask;
5942}
5943
Andy Hung9a605382014-07-28 16:16:31 -07005944/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005945const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5946 AUDIO_FORMAT_DEFAULT,
5947 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005948 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005949 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005950 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005951 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005952};
5953
5954int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5955 audio_format_t format2)
5956{
5957 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5958 // compressed format and better than any PCM format. This is by design of pickFormat()
5959 if (!audio_is_linear_pcm(format1)) {
5960 if (!audio_is_linear_pcm(format2)) {
5961 return 0;
5962 }
5963 return 1;
5964 }
5965 if (!audio_is_linear_pcm(format2)) {
5966 return -1;
5967 }
5968
5969 int index1 = -1, index2 = -1;
5970 for (size_t i = 0;
5971 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5972 i ++) {
5973 if (sPcmFormatCompareTable[i] == format1) {
5974 index1 = i;
5975 }
5976 if (sPcmFormatCompareTable[i] == format2) {
5977 index2 = i;
5978 }
5979 }
5980 // format1 not found => index1 < 0 => format2 > format1
5981 // format2 not found => index2 < 0 => format2 < format1
5982 return index1 - index2;
5983}
5984
5985audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5986{
5987 // special case for uninitialized dynamic profile
5988 if (mFormats.size() == 1 && mFormats[0] == 0) {
5989 return AUDIO_FORMAT_DEFAULT;
5990 }
5991
5992 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005993 audio_format_t bestFormat =
5994 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5995 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005996 // For mixed output and inputs, use best mixer output format. Do not
5997 // limit format otherwise
5998 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5999 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006000 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006001 bestFormat = AUDIO_FORMAT_INVALID;
6002 }
6003
6004 for (size_t i = 0; i < mFormats.size(); i ++) {
6005 if ((compareFormats(mFormats[i], format) > 0) &&
6006 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6007 format = mFormats[i];
6008 }
6009 }
6010 return format;
6011}
6012
Eric Laurenta121f902014-06-03 13:32:54 -07006013status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6014 int index) const
6015{
6016 if (index < 0 || (size_t)index >= mGains.size()) {
6017 return BAD_VALUE;
6018 }
6019 return mGains[index]->checkConfig(gainConfig);
6020}
6021
Eric Laurent1afeecb2014-05-14 08:52:28 -07006022void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6023{
6024 const size_t SIZE = 256;
6025 char buffer[SIZE];
6026 String8 result;
6027
6028 if (mName.size() != 0) {
6029 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6030 result.append(buffer);
6031 }
6032
6033 if (mSamplingRates.size() != 0) {
6034 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6035 result.append(buffer);
6036 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006037 if (i == 0 && mSamplingRates[i] == 0) {
6038 snprintf(buffer, SIZE, "Dynamic");
6039 } else {
6040 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6041 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006042 result.append(buffer);
6043 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6044 }
6045 result.append("\n");
6046 }
6047
6048 if (mChannelMasks.size() != 0) {
6049 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6050 result.append(buffer);
6051 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006052 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6053
6054 if (i == 0 && mChannelMasks[i] == 0) {
6055 snprintf(buffer, SIZE, "Dynamic");
6056 } else {
6057 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6058 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006059 result.append(buffer);
6060 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6061 }
6062 result.append("\n");
6063 }
6064
6065 if (mFormats.size() != 0) {
6066 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6067 result.append(buffer);
6068 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006069 const char *formatStr = enumToString(sFormatNameToEnumTable,
6070 ARRAY_SIZE(sFormatNameToEnumTable),
6071 mFormats[i]);
6072 if (i == 0 && strcmp(formatStr, "") == 0) {
6073 snprintf(buffer, SIZE, "Dynamic");
6074 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006075 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006076 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006077 result.append(buffer);
6078 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6079 }
6080 result.append("\n");
6081 }
6082 write(fd, result.string(), result.size());
6083 if (mGains.size() != 0) {
6084 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6085 write(fd, buffer, strlen(buffer) + 1);
6086 result.append(buffer);
6087 for (size_t i = 0; i < mGains.size(); i++) {
6088 mGains[i]->dump(fd, spaces + 2, i);
6089 }
6090 }
6091}
6092
6093// --- AudioGain class implementation
6094
Eric Laurenta121f902014-06-03 13:32:54 -07006095AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006096{
Eric Laurenta121f902014-06-03 13:32:54 -07006097 mIndex = index;
6098 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006099 memset(&mGain, 0, sizeof(struct audio_gain));
6100}
6101
Eric Laurenta121f902014-06-03 13:32:54 -07006102void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6103{
6104 config->index = mIndex;
6105 config->mode = mGain.mode;
6106 config->channel_mask = mGain.channel_mask;
6107 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6108 config->values[0] = mGain.default_value;
6109 } else {
6110 uint32_t numValues;
6111 if (mUseInChannelMask) {
6112 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6113 } else {
6114 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6115 }
6116 for (size_t i = 0; i < numValues; i++) {
6117 config->values[i] = mGain.default_value;
6118 }
6119 }
6120 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6121 config->ramp_duration_ms = mGain.min_ramp_ms;
6122 }
6123}
6124
6125status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6126{
6127 if ((config->mode & ~mGain.mode) != 0) {
6128 return BAD_VALUE;
6129 }
6130 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6131 if ((config->values[0] < mGain.min_value) ||
6132 (config->values[0] > mGain.max_value)) {
6133 return BAD_VALUE;
6134 }
6135 } else {
6136 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6137 return BAD_VALUE;
6138 }
6139 uint32_t numValues;
6140 if (mUseInChannelMask) {
6141 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6142 } else {
6143 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6144 }
6145 for (size_t i = 0; i < numValues; i++) {
6146 if ((config->values[i] < mGain.min_value) ||
6147 (config->values[i] > mGain.max_value)) {
6148 return BAD_VALUE;
6149 }
6150 }
6151 }
6152 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6153 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6154 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6155 return BAD_VALUE;
6156 }
6157 }
6158 return NO_ERROR;
6159}
6160
Eric Laurent1afeecb2014-05-14 08:52:28 -07006161void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6162{
6163 const size_t SIZE = 256;
6164 char buffer[SIZE];
6165 String8 result;
6166
6167 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6168 result.append(buffer);
6169 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6170 result.append(buffer);
6171 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6172 result.append(buffer);
6173 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6174 result.append(buffer);
6175 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6176 result.append(buffer);
6177 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6178 result.append(buffer);
6179 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6180 result.append(buffer);
6181 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6182 result.append(buffer);
6183 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6184 result.append(buffer);
6185
6186 write(fd, result.string(), result.size());
6187}
6188
Eric Laurent1f2f2232014-06-02 12:01:23 -07006189// --- AudioPortConfig class implementation
6190
6191AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6192{
6193 mSamplingRate = 0;
6194 mChannelMask = AUDIO_CHANNEL_NONE;
6195 mFormat = AUDIO_FORMAT_INVALID;
6196 mGain.index = -1;
6197}
6198
Eric Laurenta121f902014-06-03 13:32:54 -07006199status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6200 const struct audio_port_config *config,
6201 struct audio_port_config *backupConfig)
6202{
6203 struct audio_port_config localBackupConfig;
6204 status_t status = NO_ERROR;
6205
6206 localBackupConfig.config_mask = config->config_mask;
6207 toAudioPortConfig(&localBackupConfig);
6208
6209 if (mAudioPort == 0) {
6210 status = NO_INIT;
6211 goto exit;
6212 }
6213 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07006214 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006215 if (status != NO_ERROR) {
6216 goto exit;
6217 }
6218 mSamplingRate = config->sample_rate;
6219 }
6220 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07006221 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006222 if (status != NO_ERROR) {
6223 goto exit;
6224 }
6225 mChannelMask = config->channel_mask;
6226 }
6227 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6228 status = mAudioPort->checkFormat(config->format);
6229 if (status != NO_ERROR) {
6230 goto exit;
6231 }
6232 mFormat = config->format;
6233 }
6234 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6235 status = mAudioPort->checkGain(&config->gain, config->gain.index);
6236 if (status != NO_ERROR) {
6237 goto exit;
6238 }
6239 mGain = config->gain;
6240 }
6241
6242exit:
6243 if (status != NO_ERROR) {
6244 applyAudioPortConfig(&localBackupConfig);
6245 }
6246 if (backupConfig != NULL) {
6247 *backupConfig = localBackupConfig;
6248 }
6249 return status;
6250}
6251
Eric Laurent1f2f2232014-06-02 12:01:23 -07006252void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6253 struct audio_port_config *dstConfig,
6254 const struct audio_port_config *srcConfig) const
6255{
6256 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6257 dstConfig->sample_rate = mSamplingRate;
6258 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6259 dstConfig->sample_rate = srcConfig->sample_rate;
6260 }
6261 } else {
6262 dstConfig->sample_rate = 0;
6263 }
6264 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6265 dstConfig->channel_mask = mChannelMask;
6266 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6267 dstConfig->channel_mask = srcConfig->channel_mask;
6268 }
6269 } else {
6270 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6271 }
6272 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6273 dstConfig->format = mFormat;
6274 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6275 dstConfig->format = srcConfig->format;
6276 }
6277 } else {
6278 dstConfig->format = AUDIO_FORMAT_INVALID;
6279 }
6280 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6281 dstConfig->gain = mGain;
6282 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6283 dstConfig->gain = srcConfig->gain;
6284 }
6285 } else {
6286 dstConfig->gain.index = -1;
6287 }
6288 if (dstConfig->gain.index != -1) {
6289 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6290 } else {
6291 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6292 }
6293}
6294
Eric Laurent1c333e22014-05-20 10:48:17 -07006295// --- IOProfile class implementation
6296
Eric Laurent1afeecb2014-05-14 08:52:28 -07006297AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006298 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006299 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006300{
6301}
6302
Eric Laurente0720872014-03-11 09:30:41 -07006303AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006304{
6305}
6306
6307// checks if the IO profile is compatible with specified parameters.
6308// Sampling rate, format and channel mask must be specified in order to
6309// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006310bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006311 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006312 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006313 audio_format_t format,
6314 audio_channel_mask_t channelMask,
6315 audio_output_flags_t flags) const
6316{
Glenn Kastencbd48022014-07-24 13:46:44 -07006317 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6318 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6319 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006320
Glenn Kastencbd48022014-07-24 13:46:44 -07006321 if ((mSupportedDevices.types() & device) != device) {
6322 return false;
6323 }
6324
6325 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006326 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006327 }
6328 uint32_t myUpdatedSamplingRate = samplingRate;
6329 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006330 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006331 }
6332 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6333 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006334 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006335 }
6336
6337 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6338 return false;
6339 }
6340
6341 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6342 checkExactChannelMask(channelMask) != NO_ERROR)) {
6343 return false;
6344 }
6345 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6346 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6347 return false;
6348 }
6349
6350 if (isPlaybackThread && (mFlags & flags) != flags) {
6351 return false;
6352 }
6353 // The only input flag that is allowed to be different is the fast flag.
6354 // An existing fast stream is compatible with a normal track request.
6355 // An existing normal stream is compatible with a fast track request,
6356 // but the fast request will be denied by AudioFlinger and converted to normal track.
6357 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6358 ~AUDIO_INPUT_FLAG_FAST)) {
6359 return false;
6360 }
6361
6362 if (updatedSamplingRate != NULL) {
6363 *updatedSamplingRate = myUpdatedSamplingRate;
6364 }
6365 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006366}
6367
Eric Laurente0720872014-03-11 09:30:41 -07006368void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006369{
6370 const size_t SIZE = 256;
6371 char buffer[SIZE];
6372 String8 result;
6373
Eric Laurent1afeecb2014-05-14 08:52:28 -07006374 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006375
Eric Laurente552edb2014-03-10 17:42:56 -07006376 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6377 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006378 snprintf(buffer, SIZE, " - devices:\n");
6379 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006380 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006381 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6382 mSupportedDevices[i]->dump(fd, 6, i);
6383 }
Eric Laurente552edb2014-03-10 17:42:56 -07006384}
6385
Eric Laurentd4692962014-05-05 18:13:44 -07006386void AudioPolicyManager::IOProfile::log()
6387{
6388 const size_t SIZE = 256;
6389 char buffer[SIZE];
6390 String8 result;
6391
6392 ALOGV(" - sampling rates: ");
6393 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6394 ALOGV(" %d", mSamplingRates[i]);
6395 }
6396
6397 ALOGV(" - channel masks: ");
6398 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6399 ALOGV(" 0x%04x", mChannelMasks[i]);
6400 }
6401
6402 ALOGV(" - formats: ");
6403 for (size_t i = 0; i < mFormats.size(); i++) {
6404 ALOGV(" 0x%08x", mFormats[i]);
6405 }
6406
6407 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6408 ALOGV(" - flags: 0x%04x\n", mFlags);
6409}
6410
6411
Eric Laurent3a4311c2014-03-17 12:00:47 -07006412// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006413
Eric Laurent1f2f2232014-06-02 12:01:23 -07006414
6415AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6416 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6417 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6418 AUDIO_PORT_ROLE_SOURCE,
6419 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006420 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006421{
6422 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006423 if (mGains.size() > 0) {
6424 mGains[0]->getDefaultConfig(&mGain);
6425 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006426}
6427
Eric Laurent3a4311c2014-03-17 12:00:47 -07006428bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006429{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006430 // Devices are considered equal if they:
6431 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6432 // - have the same address or one device does not specify the address
6433 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006434 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006435 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006436 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006437 mChannelMask == other->mChannelMask);
6438}
6439
6440void AudioPolicyManager::DeviceVector::refreshTypes()
6441{
Eric Laurent1c333e22014-05-20 10:48:17 -07006442 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006443 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006444 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006445 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006446 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006447}
6448
6449ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6450{
6451 for(size_t i = 0; i < size(); i++) {
6452 if (item->equals(itemAt(i))) {
6453 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006454 }
6455 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006456 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006457}
6458
Eric Laurent3a4311c2014-03-17 12:00:47 -07006459ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006460{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006461 ssize_t ret = indexOf(item);
6462
6463 if (ret < 0) {
6464 ret = SortedVector::add(item);
6465 if (ret >= 0) {
6466 refreshTypes();
6467 }
6468 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006469 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006470 ret = -1;
6471 }
6472 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006473}
6474
Eric Laurent3a4311c2014-03-17 12:00:47 -07006475ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6476{
6477 size_t i;
6478 ssize_t ret = indexOf(item);
6479
6480 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006481 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006482 } else {
6483 ret = SortedVector::removeAt(ret);
6484 if (ret >= 0) {
6485 refreshTypes();
6486 }
6487 }
6488 return ret;
6489}
6490
6491void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6492{
6493 DeviceVector deviceList;
6494
6495 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6496 types &= ~role_bit;
6497
6498 while (types) {
6499 uint32_t i = 31 - __builtin_clz(types);
6500 uint32_t type = 1 << i;
6501 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006502 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006503 }
6504}
6505
Eric Laurent1afeecb2014-05-14 08:52:28 -07006506void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6507 const DeviceVector& declaredDevices)
6508{
6509 char *devName = strtok(name, "|");
6510 while (devName != NULL) {
6511 if (strlen(devName) != 0) {
6512 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6513 ARRAY_SIZE(sDeviceNameToEnumTable),
6514 devName);
6515 if (type != AUDIO_DEVICE_NONE) {
6516 add(new DeviceDescriptor(String8(""), type));
6517 } else {
6518 sp<DeviceDescriptor> deviceDesc =
6519 declaredDevices.getDeviceFromName(String8(devName));
6520 if (deviceDesc != 0) {
6521 add(deviceDesc);
6522 }
6523 }
6524 }
6525 devName = strtok(NULL, "|");
6526 }
6527}
6528
Eric Laurent1c333e22014-05-20 10:48:17 -07006529sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6530 audio_devices_t type, String8 address) const
6531{
6532 sp<DeviceDescriptor> device;
6533 for (size_t i = 0; i < size(); i++) {
6534 if (itemAt(i)->mDeviceType == type) {
6535 device = itemAt(i);
6536 if (itemAt(i)->mAddress = address) {
6537 break;
6538 }
6539 }
6540 }
6541 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6542 type, address.string(), device.get());
6543 return device;
6544}
6545
Eric Laurent6a94d692014-05-20 11:18:06 -07006546sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6547 audio_port_handle_t id) const
6548{
6549 sp<DeviceDescriptor> device;
6550 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006551 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006552 if (itemAt(i)->mId == id) {
6553 device = itemAt(i);
6554 break;
6555 }
6556 }
6557 return device;
6558}
6559
Eric Laurent1c333e22014-05-20 10:48:17 -07006560AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6561 audio_devices_t type) const
6562{
6563 DeviceVector devices;
6564 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6565 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6566 devices.add(itemAt(i));
6567 type &= ~itemAt(i)->mDeviceType;
6568 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6569 itemAt(i)->mDeviceType, itemAt(i).get());
6570 }
6571 }
6572 return devices;
6573}
6574
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006575AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6576 audio_devices_t type, String8 address) const
6577{
6578 DeviceVector devices;
6579 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6580 for (size_t i = 0; i < size(); i++) {
6581 //ALOGV(" at i=%d: device=%x, addr=%s",
6582 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6583 if (itemAt(i)->mDeviceType == type) {
6584 if (itemAt(i)->mAddress == address) {
6585 //ALOGV(" found matching address %s", address.string());
6586 devices.add(itemAt(i));
6587 }
6588 }
6589 }
6590 return devices;
6591}
6592
Eric Laurent1afeecb2014-05-14 08:52:28 -07006593sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6594 const String8& name) const
6595{
6596 sp<DeviceDescriptor> device;
6597 for (size_t i = 0; i < size(); i++) {
6598 if (itemAt(i)->mName == name) {
6599 device = itemAt(i);
6600 break;
6601 }
6602 }
6603 return device;
6604}
6605
Eric Laurent6a94d692014-05-20 11:18:06 -07006606void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6607 struct audio_port_config *dstConfig,
6608 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006609{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006610 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6611 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006612 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006613 }
6614
6615 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6616
Eric Laurent6a94d692014-05-20 11:18:06 -07006617 dstConfig->id = mId;
6618 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006619 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006620 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006621 dstConfig->ext.device.type = mDeviceType;
6622 dstConfig->ext.device.hw_module = mModule->mHandle;
6623 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006624}
6625
6626void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6627{
Eric Laurent83b88082014-06-20 18:31:16 -07006628 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006629 AudioPort::toAudioPort(port);
6630 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006631 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006632 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006633 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006634 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6635}
6636
Eric Laurent1afeecb2014-05-14 08:52:28 -07006637status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006638{
6639 const size_t SIZE = 256;
6640 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006641 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006642
Eric Laurent1afeecb2014-05-14 08:52:28 -07006643 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6644 result.append(buffer);
6645 if (mId != 0) {
6646 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6647 result.append(buffer);
6648 }
6649 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6650 enumToString(sDeviceNameToEnumTable,
6651 ARRAY_SIZE(sDeviceNameToEnumTable),
6652 mDeviceType));
6653 result.append(buffer);
6654 if (mAddress.size() != 0) {
6655 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6656 result.append(buffer);
6657 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006658 write(fd, result.string(), result.size());
6659 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006660
6661 return NO_ERROR;
6662}
6663
Eric Laurent4d416952014-08-10 14:07:09 -07006664status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6665{
6666 const size_t SIZE = 256;
6667 char buffer[SIZE];
6668 String8 result;
6669
6670
6671 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6672 result.append(buffer);
6673 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6674 result.append(buffer);
6675 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6676 result.append(buffer);
6677 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6678 result.append(buffer);
6679 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6680 result.append(buffer);
6681 for (size_t i = 0; i < mPatch.num_sources; i++) {
6682 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6683 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6684 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6685 ARRAY_SIZE(sDeviceNameToEnumTable),
6686 mPatch.sources[i].ext.device.type));
6687 } else {
6688 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6689 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6690 }
6691 result.append(buffer);
6692 }
6693 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6694 result.append(buffer);
6695 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6696 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6697 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6698 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6699 ARRAY_SIZE(sDeviceNameToEnumTable),
6700 mPatch.sinks[i].ext.device.type));
6701 } else {
6702 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6703 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6704 }
6705 result.append(buffer);
6706 }
6707
6708 write(fd, result.string(), result.size());
6709 return NO_ERROR;
6710}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006711
6712// --- audio_policy.conf file parsing
6713
Eric Laurente0720872014-03-11 09:30:41 -07006714audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006715{
6716 uint32_t flag = 0;
6717
6718 // it is OK to cast name to non const here as we are not going to use it after
6719 // strtok() modifies it
6720 char *flagName = strtok(name, "|");
6721 while (flagName != NULL) {
6722 if (strlen(flagName) != 0) {
6723 flag |= stringToEnum(sFlagNameToEnumTable,
6724 ARRAY_SIZE(sFlagNameToEnumTable),
6725 flagName);
6726 }
6727 flagName = strtok(NULL, "|");
6728 }
6729 //force direct flag if offload flag is set: offloading implies a direct output stream
6730 // and all common behaviors are driven by checking only the direct flag
6731 // this should normally be set appropriately in the policy configuration file
6732 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6733 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6734 }
6735
6736 return (audio_output_flags_t)flag;
6737}
6738
Eric Laurente0720872014-03-11 09:30:41 -07006739audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006740{
6741 uint32_t device = 0;
6742
6743 char *devName = strtok(name, "|");
6744 while (devName != NULL) {
6745 if (strlen(devName) != 0) {
6746 device |= stringToEnum(sDeviceNameToEnumTable,
6747 ARRAY_SIZE(sDeviceNameToEnumTable),
6748 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006749 }
Eric Laurente552edb2014-03-10 17:42:56 -07006750 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006751 }
Eric Laurente552edb2014-03-10 17:42:56 -07006752 return device;
6753}
6754
Eric Laurente0720872014-03-11 09:30:41 -07006755void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006756{
Eric Laurente552edb2014-03-10 17:42:56 -07006757 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006758 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006759 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006760
Eric Laurent1afeecb2014-05-14 08:52:28 -07006761 node = config_find(root, DEVICES_TAG);
6762 if (node != NULL) {
6763 node = node->first_child;
6764 while (node) {
6765 ALOGV("loadHwModule() loading device %s", node->name);
6766 status_t tmpStatus = module->loadDevice(node);
6767 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6768 status = tmpStatus;
6769 }
6770 node = node->next;
6771 }
6772 }
6773 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006774 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006775 node = node->first_child;
6776 while (node) {
6777 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006778 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006779 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6780 status = tmpStatus;
6781 }
6782 node = node->next;
6783 }
6784 }
6785 node = config_find(root, INPUTS_TAG);
6786 if (node != NULL) {
6787 node = node->first_child;
6788 while (node) {
6789 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006790 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006791 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6792 status = tmpStatus;
6793 }
6794 node = node->next;
6795 }
6796 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006797 loadGlobalConfig(root, module);
6798
Eric Laurente552edb2014-03-10 17:42:56 -07006799 if (status == NO_ERROR) {
6800 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006801 }
6802}
6803
Eric Laurente0720872014-03-11 09:30:41 -07006804void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006805{
6806 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6807 if (node == NULL) {
6808 return;
6809 }
6810
6811 node = node->first_child;
6812 while (node) {
6813 ALOGV("loadHwModules() loading module %s", node->name);
6814 loadHwModule(node);
6815 node = node->next;
6816 }
6817}
6818
Eric Laurent1f2f2232014-06-02 12:01:23 -07006819void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006820{
6821 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006822
Eric Laurente552edb2014-03-10 17:42:56 -07006823 if (node == NULL) {
6824 return;
6825 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006826 DeviceVector declaredDevices;
6827 if (module != NULL) {
6828 declaredDevices = module->mDeclaredDevices;
6829 }
6830
Eric Laurente552edb2014-03-10 17:42:56 -07006831 node = node->first_child;
6832 while (node) {
6833 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006834 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6835 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006836 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6837 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006838 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006839 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006840 ARRAY_SIZE(sDeviceNameToEnumTable),
6841 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006842 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006843 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006844 } else {
6845 ALOGW("loadGlobalConfig() default device not specified");
6846 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006847 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006848 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006849 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6850 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006851 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006852 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6853 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6854 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006855 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6856 uint32_t major, minor;
6857 sscanf((char *)node->value, "%u.%u", &major, &minor);
6858 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6859 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6860 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006861 }
6862 node = node->next;
6863 }
6864}
6865
Eric Laurente0720872014-03-11 09:30:41 -07006866status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006867{
6868 cnode *root;
6869 char *data;
6870
6871 data = (char *)load_file(path, NULL);
6872 if (data == NULL) {
6873 return -ENODEV;
6874 }
6875 root = config_node("", "");
6876 config_load(root, data);
6877
Eric Laurente552edb2014-03-10 17:42:56 -07006878 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006879 // legacy audio_policy.conf files have one global_configuration section
6880 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006881 config_free(root);
6882 free(root);
6883 free(data);
6884
6885 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6886
6887 return NO_ERROR;
6888}
6889
Eric Laurente0720872014-03-11 09:30:41 -07006890void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006891{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006892 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006893 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006894 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6895 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006896 mAvailableOutputDevices.add(mDefaultOutputDevice);
6897 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006898
6899 module = new HwModule("primary");
6900
Eric Laurent1afeecb2014-05-14 08:52:28 -07006901 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006902 profile->mSamplingRates.add(44100);
6903 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6904 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006905 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006906 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6907 module->mOutputProfiles.add(profile);
6908
Eric Laurent1afeecb2014-05-14 08:52:28 -07006909 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006910 profile->mSamplingRates.add(8000);
6911 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6912 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006913 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006914 module->mInputProfiles.add(profile);
6915
6916 mHwModules.add(module);
6917}
6918
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006919audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6920{
6921 // flags to stream type mapping
6922 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6923 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6924 }
6925 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6926 return AUDIO_STREAM_BLUETOOTH_SCO;
6927 }
6928
6929 // usage to stream type mapping
6930 switch (attr->usage) {
6931 case AUDIO_USAGE_MEDIA:
6932 case AUDIO_USAGE_GAME:
6933 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6934 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6935 return AUDIO_STREAM_MUSIC;
6936 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6937 return AUDIO_STREAM_SYSTEM;
6938 case AUDIO_USAGE_VOICE_COMMUNICATION:
6939 return AUDIO_STREAM_VOICE_CALL;
6940
6941 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6942 return AUDIO_STREAM_DTMF;
6943
6944 case AUDIO_USAGE_ALARM:
6945 return AUDIO_STREAM_ALARM;
6946 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6947 return AUDIO_STREAM_RING;
6948
6949 case AUDIO_USAGE_NOTIFICATION:
6950 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6951 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6952 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6953 case AUDIO_USAGE_NOTIFICATION_EVENT:
6954 return AUDIO_STREAM_NOTIFICATION;
6955
6956 case AUDIO_USAGE_UNKNOWN:
6957 default:
6958 return AUDIO_STREAM_MUSIC;
6959 }
6960}
Eric Laurente552edb2014-03-10 17:42:56 -07006961}; // namespace android