blob: 6adcde443f627bbf08b0640cb91be797bd450989 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070085 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070090 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050091 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700110 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900111 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122};
123
124const StringToEnum sFormatNameToEnumTable[] = {
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
130 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
131 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700143 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700144 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
146 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
147 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
148 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149};
150
151const StringToEnum sOutChannelsNameToEnumTable[] = {
152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
156 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
157};
158
159const StringToEnum sInChannelsNameToEnumTable[] = {
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
162 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
163};
164
Eric Laurent1afeecb2014-05-14 08:52:28 -0700165const StringToEnum sGainModeNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
168 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
169};
170
Eric Laurent3a4311c2014-03-17 12:00:47 -0700171
172uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
173 size_t size,
174 const char *name)
175{
176 for (size_t i = 0; i < size; i++) {
177 if (strcmp(table[i].name, name) == 0) {
178 ALOGV("stringToEnum() found %s", table[i].name);
179 return table[i].value;
180 }
181 }
182 return 0;
183}
184
185const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
186 size_t size,
187 uint32_t value)
188{
189 for (size_t i = 0; i < size; i++) {
190 if (table[i].value == value) {
191 return table[i].name;
192 }
193 }
194 return "";
195}
196
197bool AudioPolicyManager::stringToBool(const char *value)
198{
199 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
200}
201
202
203// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700204// AudioPolicyInterface implementation
205// ----------------------------------------------------------------------------
206
207
Eric Laurente0720872014-03-11 09:30:41 -0700208status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700209 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700210 const char *device_address)
211{
Eric Laurent22226012014-08-01 17:00:54 -0700212 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurent22226012014-08-01 17:00:54 -0700214 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
215 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700216
217 // connect/disconnect only 1 device at a time
218 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
219
Eric Laurente552edb2014-03-10 17:42:56 -0700220 // handle output devices
221 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700222 SortedVector <audio_io_handle_t> outputs;
223
Eric Laurent1afeecb2014-05-14 08:52:28 -0700224 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
225 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // save a copy of the opened output descriptors before any output is opened or closed
229 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
230 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 switch (state)
232 {
233 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700234 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700235 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700236 ALOGW("setDeviceConnectionState() device already connected: %x", device);
237 return INVALID_OPERATION;
238 }
239 ALOGV("setDeviceConnectionState() connecting device %x", device);
240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700242 index = mAvailableOutputDevices.add(devDesc);
243 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700244 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700245 if (module == 0) {
246 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
247 device);
248 mAvailableOutputDevices.remove(devDesc);
249 return INVALID_OPERATION;
250 }
251 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700252 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 } else {
254 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
256
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700257 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 // outputs should never be empty here
262 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
263 "checkOutputsForDevice() returned no outputs but status OK");
264 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
265 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700266 break;
267 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700268 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700269 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700270 ALOGW("setDeviceConnectionState() device not connected: %x", device);
271 return INVALID_OPERATION;
272 }
273
Paul McLean5c477aa2014-08-20 16:47:57 -0700274 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
275
276 // Set Disconnect to HALs
277 AudioParameter param = AudioParameter(address);
278 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
279 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
280
Eric Laurente552edb2014-03-10 17:42:56 -0700281 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700283
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700284 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700285 } break;
286
287 default:
288 ALOGE("setDeviceConnectionState() invalid state: %x", state);
289 return BAD_VALUE;
290 }
291
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
293 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700294 checkA2dpSuspend();
295 checkOutputForAllStrategies();
296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700299 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700300 // close unused outputs after device disconnection or direct outputs that have been
301 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700302 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700303 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
304 (desc->mDirectOpenCount == 0))) {
305 closeOutput(outputs[i]);
306 }
307 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700308 // check again after closing A2DP output to reset mA2dpSuspended if needed
309 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700310 }
311
312 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700313 if (mPhoneState == AUDIO_MODE_IN_CALL) {
314 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
315 updateCallRouting(newDevice);
316 }
Eric Laurente552edb2014-03-10 17:42:56 -0700317 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 audio_io_handle_t output = mOutputs.keyAt(i);
319 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
320 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
321 true /*fromCache*/);
322 // do not force device change on duplicated output because if device is 0, it will
323 // also force a device 0 for the two outputs it is duplicated to which may override
324 // a valid device selection on those outputs.
325 bool force = !mOutputs.valueAt(i)->isDuplicated()
326 && (!deviceDistinguishesOnAddress(device)
327 // always force when disconnecting (a non-duplicated device)
328 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
329 setOutputDevice(output, newDevice, force, 0);
330 }
Eric Laurente552edb2014-03-10 17:42:56 -0700331 }
332
Eric Laurent72aa32f2014-05-30 18:51:48 -0700333 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700334 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700335 } // end if is output device
336
Eric Laurente552edb2014-03-10 17:42:56 -0700337 // handle input devices
338 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700339 SortedVector <audio_io_handle_t> inputs;
340
Eric Laurent1afeecb2014-05-14 08:52:28 -0700341 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
342 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700344 switch (state)
345 {
346 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700347 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700349 ALOGW("setDeviceConnectionState() device already connected: %d", device);
350 return INVALID_OPERATION;
351 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700352 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700353 if (module == NULL) {
354 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
355 device);
356 return INVALID_OPERATION;
357 }
Eric Laurentd4692962014-05-05 18:13:44 -0700358 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
359 return INVALID_OPERATION;
360 }
361
Eric Laurent3a4311c2014-03-17 12:00:47 -0700362 index = mAvailableInputDevices.add(devDesc);
363 if (index >= 0) {
364 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700365 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 } else {
367 return NO_MEMORY;
368 }
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700372 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700373 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700374 ALOGW("setDeviceConnectionState() device not connected: %d", device);
375 return INVALID_OPERATION;
376 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700377
378 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
379
380 // Set Disconnect to HALs
381 AudioParameter param = AudioParameter(address);
382 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
383 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
384
Eric Laurentd4692962014-05-05 18:13:44 -0700385 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700387
Eric Laurentd4692962014-05-05 18:13:44 -0700388 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700389
390 default:
391 ALOGE("setDeviceConnectionState() invalid state: %x", state);
392 return BAD_VALUE;
393 }
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700396
Eric Laurentc2730ba2014-07-20 15:47:07 -0700397 if (mPhoneState == AUDIO_MODE_IN_CALL) {
398 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
399 updateCallRouting(newDevice);
400 }
401
Eric Laurentb52c1522014-05-20 11:27:36 -0700402 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700403 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700404 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700405
406 ALOGW("setDeviceConnectionState() invalid device: %x", device);
407 return BAD_VALUE;
408}
409
Eric Laurente0720872014-03-11 09:30:41 -0700410audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700411 const char *device_address)
412{
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700414 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700415 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700416 ssize_t index;
417 DeviceVector *deviceVector;
418
Eric Laurente552edb2014-03-10 17:42:56 -0700419 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700420 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700421 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 deviceVector = &mAvailableInputDevices;
423 } else {
424 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
425 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700426 }
427
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 index = deviceVector->indexOf(devDesc);
429 if (index >= 0) {
430 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
431 } else {
432 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
433 }
Eric Laurente552edb2014-03-10 17:42:56 -0700434}
435
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
437{
438 bool createTxPatch = false;
439 struct audio_patch patch;
440 patch.num_sources = 1;
441 patch.num_sinks = 1;
442 status_t status;
443 audio_patch_handle_t afPatchHandle;
444 DeviceVector deviceList;
445
446 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
447 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
448
449 // release existing RX patch if any
450 if (mCallRxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
452 mCallRxPatch.clear();
453 }
454 // release TX patch if any
455 if (mCallTxPatch != 0) {
456 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
457 mCallTxPatch.clear();
458 }
459
460 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
461 // via setOutputDevice() on primary output.
462 // Otherwise, create two audio patches for TX and RX path.
463 if (availablePrimaryOutputDevices() & rxDevice) {
464 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
465 // If the TX device is also on the primary HW module, setOutputDevice() will take care
466 // of it due to legacy implementation. If not, create a patch.
467 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
468 == AUDIO_DEVICE_NONE) {
469 createTxPatch = true;
470 }
471 } else {
472 // create RX path audio patch
473 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
474 ALOG_ASSERT(!deviceList.isEmpty(),
475 "updateCallRouting() selected device not in output device list");
476 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
477 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
478 ALOG_ASSERT(!deviceList.isEmpty(),
479 "updateCallRouting() no telephony RX device");
480 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
481
482 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
483 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
484
485 // request to reuse existing output stream if one is already opened to reach the RX device
486 SortedVector<audio_io_handle_t> outputs =
487 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700488 audio_io_handle_t output = selectOutput(outputs,
489 AUDIO_OUTPUT_FLAG_NONE,
490 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700491 if (output != AUDIO_IO_HANDLE_NONE) {
492 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
493 ALOG_ASSERT(!outputDesc->isDuplicated(),
494 "updateCallRouting() RX device output is duplicated");
495 outputDesc->toAudioPortConfig(&patch.sources[1]);
496 patch.num_sources = 2;
497 }
498
499 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
500 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
501 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
502 status);
503 if (status == NO_ERROR) {
504 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
505 &patch, mUidCached);
506 mCallRxPatch->mAfPatchHandle = afPatchHandle;
507 mCallRxPatch->mUid = mUidCached;
508 }
509 createTxPatch = true;
510 }
511 if (createTxPatch) {
512
513 struct audio_patch patch;
514 patch.num_sources = 1;
515 patch.num_sinks = 1;
516 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
517 ALOG_ASSERT(!deviceList.isEmpty(),
518 "updateCallRouting() selected device not in input device list");
519 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
520 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
521 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
522 ALOG_ASSERT(!deviceList.isEmpty(),
523 "updateCallRouting() no telephony TX device");
524 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
525 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
526
527 SortedVector<audio_io_handle_t> outputs =
528 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700529 audio_io_handle_t output = selectOutput(outputs,
530 AUDIO_OUTPUT_FLAG_NONE,
531 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700532 // request to reuse existing output stream if one is already opened to reach the TX
533 // path output device
534 if (output != AUDIO_IO_HANDLE_NONE) {
535 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
536 ALOG_ASSERT(!outputDesc->isDuplicated(),
537 "updateCallRouting() RX device output is duplicated");
538 outputDesc->toAudioPortConfig(&patch.sources[1]);
539 patch.num_sources = 2;
540 }
541
542 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
543 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
544 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
545 status);
546 if (status == NO_ERROR) {
547 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
548 &patch, mUidCached);
549 mCallTxPatch->mAfPatchHandle = afPatchHandle;
550 mCallTxPatch->mUid = mUidCached;
551 }
552 }
553}
554
Eric Laurente0720872014-03-11 09:30:41 -0700555void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700556{
557 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700558 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700559 ALOGW("setPhoneState() invalid state %d", state);
560 return;
561 }
562
563 if (state == mPhoneState ) {
564 ALOGW("setPhoneState() setting same state %d", state);
565 return;
566 }
567
568 // if leaving call state, handle special case of active streams
569 // pertaining to sonification strategy see handleIncallSonification()
570 if (isInCall()) {
571 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700572 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
573 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700574 }
575 }
576
577 // store previous phone state for management of sonification strategy below
578 int oldState = mPhoneState;
579 mPhoneState = state;
580 bool force = false;
581
582 // are we entering or starting a call
583 if (!isStateInCall(oldState) && isStateInCall(state)) {
584 ALOGV(" Entering call in setPhoneState()");
585 // force routing command to audio hardware when starting a call
586 // even if no device change is needed
587 force = true;
588 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
589 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
590 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
591 }
592 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
593 ALOGV(" Exiting call in setPhoneState()");
594 // force routing command to audio hardware when exiting a call
595 // even if no device change is needed
596 force = true;
597 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
598 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
599 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
600 }
601 } else if (isStateInCall(state) && (state != oldState)) {
602 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
603 // force routing command to audio hardware when switching between telephony and VoIP
604 // even if no device change is needed
605 force = true;
606 }
607
608 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700609 checkA2dpSuspend();
610 checkOutputForAllStrategies();
611 updateDevicesAndOutputs();
612
Eric Laurent1f2f2232014-06-02 12:01:23 -0700613 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700614
Eric Laurente552edb2014-03-10 17:42:56 -0700615 int delayMs = 0;
616 if (isStateInCall(state)) {
617 nsecs_t sysTime = systemTime();
618 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700619 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700620 // mute media and sonification strategies and delay device switch by the largest
621 // latency of any output where either strategy is active.
622 // This avoid sending the ring tone or music tail into the earpiece or headset.
623 if ((desc->isStrategyActive(STRATEGY_MEDIA,
624 SONIFICATION_HEADSET_MUSIC_DELAY,
625 sysTime) ||
626 desc->isStrategyActive(STRATEGY_SONIFICATION,
627 SONIFICATION_HEADSET_MUSIC_DELAY,
628 sysTime)) &&
629 (delayMs < (int)desc->mLatency*2)) {
630 delayMs = desc->mLatency*2;
631 }
632 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
633 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
634 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
635 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
636 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
637 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
638 }
639 }
640
Eric Laurentc2730ba2014-07-20 15:47:07 -0700641 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
642 // the device returned is not necessarily reachable via this output
643 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
644 // force routing command to audio hardware when ending call
645 // even if no device change is needed
646 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
647 rxDevice = hwOutputDesc->device();
648 }
Eric Laurente552edb2014-03-10 17:42:56 -0700649
Eric Laurentc2730ba2014-07-20 15:47:07 -0700650 if (state == AUDIO_MODE_IN_CALL) {
651 updateCallRouting(rxDevice, delayMs);
652 } else if (oldState == AUDIO_MODE_IN_CALL) {
653 if (mCallRxPatch != 0) {
654 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
655 mCallRxPatch.clear();
656 }
657 if (mCallTxPatch != 0) {
658 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
659 mCallTxPatch.clear();
660 }
661 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
662 } else {
663 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
664 }
Eric Laurente552edb2014-03-10 17:42:56 -0700665 // if entering in call state, handle special case of active streams
666 // pertaining to sonification strategy see handleIncallSonification()
667 if (isStateInCall(state)) {
668 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700669 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
670 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700671 }
672 }
673
674 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700675 if (state == AUDIO_MODE_RINGTONE &&
676 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700677 mLimitRingtoneVolume = true;
678 } else {
679 mLimitRingtoneVolume = false;
680 }
681}
682
Eric Laurente0720872014-03-11 09:30:41 -0700683void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700684 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700685{
686 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
687
688 bool forceVolumeReeval = false;
689 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700690 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
691 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
692 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700693 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
694 return;
695 }
696 forceVolumeReeval = true;
697 mForceUse[usage] = config;
698 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700699 case AUDIO_POLICY_FORCE_FOR_MEDIA:
700 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
701 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
702 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
703 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900704 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700705 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
706 return;
707 }
708 mForceUse[usage] = config;
709 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700710 case AUDIO_POLICY_FORCE_FOR_RECORD:
711 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
712 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
714 return;
715 }
716 mForceUse[usage] = config;
717 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700718 case AUDIO_POLICY_FORCE_FOR_DOCK:
719 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
720 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
721 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
722 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
723 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700724 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
725 }
726 forceVolumeReeval = true;
727 mForceUse[usage] = config;
728 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700729 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
730 if (config != AUDIO_POLICY_FORCE_NONE &&
731 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700732 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
733 }
734 forceVolumeReeval = true;
735 mForceUse[usage] = config;
736 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900737 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
738 if (config != AUDIO_POLICY_FORCE_NONE &&
739 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
740 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
741 }
742 mForceUse[usage] = config;
743 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700744 default:
745 ALOGW("setForceUse() invalid usage %d", usage);
746 break;
747 }
748
749 // check for device and output changes triggered by new force usage
750 checkA2dpSuspend();
751 checkOutputForAllStrategies();
752 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700753 if (mPhoneState == AUDIO_MODE_IN_CALL) {
754 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
755 updateCallRouting(newDevice);
756 }
Eric Laurente552edb2014-03-10 17:42:56 -0700757 for (size_t i = 0; i < mOutputs.size(); i++) {
758 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700759 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
761 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
762 }
Eric Laurente552edb2014-03-10 17:42:56 -0700763 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
764 applyStreamVolumes(output, newDevice, 0, true);
765 }
766 }
767
768 audio_io_handle_t activeInput = getActiveInput();
769 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700770 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700771 }
772
773}
774
Eric Laurente0720872014-03-11 09:30:41 -0700775audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700776{
777 return mForceUse[usage];
778}
779
Eric Laurente0720872014-03-11 09:30:41 -0700780void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700781{
782 ALOGV("setSystemProperty() property %s, value %s", property, value);
783}
784
785// Find a direct output profile compatible with the parameters passed, even if the input flags do
786// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700787sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700788 audio_devices_t device,
789 uint32_t samplingRate,
790 audio_format_t format,
791 audio_channel_mask_t channelMask,
792 audio_output_flags_t flags)
793{
794 for (size_t i = 0; i < mHwModules.size(); i++) {
795 if (mHwModules[i]->mHandle == 0) {
796 continue;
797 }
798 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700800 bool found = profile->isCompatibleProfile(device, samplingRate,
801 NULL /*updatedSamplingRate*/, format, channelMask,
802 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
803 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700804 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
805 return profile;
806 }
Eric Laurente552edb2014-03-10 17:42:56 -0700807 }
808 }
809 return 0;
810}
811
Eric Laurente0720872014-03-11 09:30:41 -0700812audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700813 uint32_t samplingRate,
814 audio_format_t format,
815 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700816 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700817 const audio_offload_info_t *offloadInfo)
818{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700819
Eric Laurent3b73df72014-03-11 09:06:29 -0700820 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
822 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
823 device, stream, samplingRate, format, channelMask, flags);
824
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700825 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
826 offloadInfo);
827}
828
829audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
830 uint32_t samplingRate,
831 audio_format_t format,
832 audio_channel_mask_t channelMask,
833 audio_output_flags_t flags,
834 const audio_offload_info_t *offloadInfo)
835{
836 if (attr == NULL) {
837 ALOGE("getOutputForAttr() called with NULL audio attributes");
838 return 0;
839 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700840 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
841 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700842
843 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
844 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
845 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700846
847 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
848 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
849 }
850
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700851 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
852 device, samplingRate, format, channelMask, flags);
853
854 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
855 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
856 offloadInfo);
857}
858
859audio_io_handle_t AudioPolicyManager::getOutputForDevice(
860 audio_devices_t device,
861 audio_stream_type_t stream,
862 uint32_t samplingRate,
863 audio_format_t format,
864 audio_channel_mask_t channelMask,
865 audio_output_flags_t flags,
866 const audio_offload_info_t *offloadInfo)
867{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700868 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700869 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700870 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871
Eric Laurente552edb2014-03-10 17:42:56 -0700872#ifdef AUDIO_POLICY_TEST
873 if (mCurOutput != 0) {
874 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
875 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
876
877 if (mTestOutputs[mCurOutput] == 0) {
878 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700879 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700880 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700881 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700882 outputDesc->mFlags =
883 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700884 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700885 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
886 config.sample_rate = mTestSamplingRate;
887 config.channel_mask = mTestChannels;
888 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700889 if (offloadInfo != NULL) {
890 config.offload_info = *offloadInfo;
891 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700892 status = mpClientInterface->openOutput(0,
893 &mTestOutputs[mCurOutput],
894 &config,
895 &outputDesc->mDevice,
896 String8(""),
897 &outputDesc->mLatency,
898 outputDesc->mFlags);
899 if (status == NO_ERROR) {
900 outputDesc->mSamplingRate = config.sample_rate;
901 outputDesc->mFormat = config.format;
902 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700903 AudioParameter outputCmd = AudioParameter();
904 outputCmd.addInt(String8("set_id"),mCurOutput);
905 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
906 addOutput(mTestOutputs[mCurOutput], outputDesc);
907 }
908 }
909 return mTestOutputs[mCurOutput];
910 }
911#endif //AUDIO_POLICY_TEST
912
913 // open a direct output if required by specified parameters
914 //force direct flag if offload flag is set: offloading implies a direct output stream
915 // and all common behaviors are driven by checking only the direct flag
916 // this should normally be set appropriately in the policy configuration file
917 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700918 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700920 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
921 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
922 }
Eric Laurente552edb2014-03-10 17:42:56 -0700923
924 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
925 // creating an offloaded track and tearing it down immediately after start when audioflinger
926 // detects there is an active non offloadable effect.
927 // FIXME: We should check the audio session here but we do not have it in this context.
928 // This may prevent offloading in rare situations where effects are left active by apps
929 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700930 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700931 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
932 !isNonOffloadableEffectEnabled()) {
933 profile = getProfileForDirectOutput(device,
934 samplingRate,
935 format,
936 channelMask,
937 (audio_output_flags_t)flags);
938 }
939
Eric Laurent1c333e22014-05-20 10:48:17 -0700940 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700941 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700942
943 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700944 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
946 outputDesc = desc;
947 // reuse direct output if currently open and configured with same parameters
948 if ((samplingRate == outputDesc->mSamplingRate) &&
949 (format == outputDesc->mFormat) &&
950 (channelMask == outputDesc->mChannelMask)) {
951 outputDesc->mDirectOpenCount++;
952 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
953 return mOutputs.keyAt(i);
954 }
955 }
956 }
957 // close direct output if currently open and configured with different parameters
958 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700959 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 }
961 outputDesc = new AudioOutputDescriptor(profile);
962 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700963 outputDesc->mLatency = 0;
964 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700965 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
966 config.sample_rate = samplingRate;
967 config.channel_mask = channelMask;
968 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700969 if (offloadInfo != NULL) {
970 config.offload_info = *offloadInfo;
971 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 status = mpClientInterface->openOutput(profile->mModule->mHandle,
973 &output,
974 &config,
975 &outputDesc->mDevice,
976 String8(""),
977 &outputDesc->mLatency,
978 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700979
980 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700981 if (status != NO_ERROR ||
982 (samplingRate != 0 && samplingRate != config.sample_rate) ||
983 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
984 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700985 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
986 "format %d %d, channelMask %04x %04x", output, samplingRate,
987 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
988 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700989 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700990 mpClientInterface->closeOutput(output);
991 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700992 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700993 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700994 outputDesc->mSamplingRate = config.sample_rate;
995 outputDesc->mChannelMask = config.channel_mask;
996 outputDesc->mFormat = config.format;
997 outputDesc->mRefCount[stream] = 0;
998 outputDesc->mStopTime[stream] = 0;
999 outputDesc->mDirectOpenCount = 1;
1000
Eric Laurente552edb2014-03-10 17:42:56 -07001001 audio_io_handle_t srcOutput = getOutputForEffect();
1002 addOutput(output, outputDesc);
1003 audio_io_handle_t dstOutput = getOutputForEffect();
1004 if (dstOutput == output) {
1005 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1006 }
1007 mPreviousOutputs = mOutputs;
1008 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001009 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001010 return output;
1011 }
1012
1013 // ignoring channel mask due to downmix capability in mixer
1014
1015 // open a non direct output
1016
1017 // for non direct outputs, only PCM is supported
1018 if (audio_is_linear_pcm(format)) {
1019 // get which output is suitable for the specified stream. The actual
1020 // routing change will happen when startOutput() will be called
1021 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1022
Eric Laurent8838a382014-09-08 16:44:28 -07001023 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1024 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1025 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1028 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1029
1030 ALOGV("getOutput() returns output %d", output);
1031
1032 return output;
1033}
1034
Eric Laurente0720872014-03-11 09:30:41 -07001035audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001036 audio_output_flags_t flags,
1037 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001038{
1039 // select one output among several that provide a path to a particular device or set of
1040 // devices (the list was previously build by getOutputsForDevice()).
1041 // The priority is as follows:
1042 // 1: the output with the highest number of requested policy flags
1043 // 2: the primary output
1044 // 3: the first output in the list
1045
1046 if (outputs.size() == 0) {
1047 return 0;
1048 }
1049 if (outputs.size() == 1) {
1050 return outputs[0];
1051 }
1052
1053 int maxCommonFlags = 0;
1054 audio_io_handle_t outputFlags = 0;
1055 audio_io_handle_t outputPrimary = 0;
1056
1057 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001058 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001059 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001060 // if a valid format is specified, skip output if not compatible
1061 if (format != AUDIO_FORMAT_INVALID) {
1062 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1063 if (format != outputDesc->mFormat) {
1064 continue;
1065 }
1066 } else if (!audio_is_linear_pcm(format)) {
1067 continue;
1068 }
1069 }
1070
Eric Laurent3b73df72014-03-11 09:06:29 -07001071 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001072 if (commonFlags > maxCommonFlags) {
1073 outputFlags = outputs[i];
1074 maxCommonFlags = commonFlags;
1075 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1076 }
1077 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1078 outputPrimary = outputs[i];
1079 }
1080 }
1081 }
1082
1083 if (outputFlags != 0) {
1084 return outputFlags;
1085 }
1086 if (outputPrimary != 0) {
1087 return outputPrimary;
1088 }
1089
1090 return outputs[0];
1091}
1092
Eric Laurente0720872014-03-11 09:30:41 -07001093status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001094 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001095 int session)
1096{
1097 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1098 ssize_t index = mOutputs.indexOfKey(output);
1099 if (index < 0) {
1100 ALOGW("startOutput() unknown output %d", output);
1101 return BAD_VALUE;
1102 }
1103
Eric Laurent1f2f2232014-06-02 12:01:23 -07001104 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001105
1106 // increment usage count for this stream on the requested output:
1107 // NOTE that the usage count is the same for duplicated output and hardware output which is
1108 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1109 outputDesc->changeRefCount(stream, 1);
1110
1111 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001112 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001113 routing_strategy strategy = getStrategy(stream);
1114 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1115 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1116 uint32_t waitMs = 0;
1117 bool force = false;
1118 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001119 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001120 if (desc != outputDesc) {
1121 // force a device change if any other output is managed by the same hw
1122 // module and has a current device selection that differs from selected device.
1123 // In this case, the audio HAL must receive the new device selection so that it can
1124 // change the device currently selected by the other active output.
1125 if (outputDesc->sharesHwModuleWith(desc) &&
1126 desc->device() != newDevice) {
1127 force = true;
1128 }
1129 // wait for audio on other active outputs to be presented when starting
1130 // a notification so that audio focus effect can propagate.
1131 uint32_t latency = desc->latency();
1132 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1133 waitMs = latency;
1134 }
1135 }
1136 }
1137 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1138
1139 // handle special case for sonification while in call
1140 if (isInCall()) {
1141 handleIncallSonification(stream, true, false);
1142 }
1143
1144 // apply volume rules for current stream and device if necessary
1145 checkAndSetVolume(stream,
1146 mStreams[stream].getVolumeIndex(newDevice),
1147 output,
1148 newDevice);
1149
1150 // update the outputs if starting an output with a stream that can affect notification
1151 // routing
1152 handleNotificationRoutingForStream(stream);
1153 if (waitMs > muteWaitMs) {
1154 usleep((waitMs - muteWaitMs) * 2 * 1000);
1155 }
1156 }
1157 return NO_ERROR;
1158}
1159
1160
Eric Laurente0720872014-03-11 09:30:41 -07001161status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001162 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001163 int session)
1164{
1165 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1166 ssize_t index = mOutputs.indexOfKey(output);
1167 if (index < 0) {
1168 ALOGW("stopOutput() unknown output %d", output);
1169 return BAD_VALUE;
1170 }
1171
Eric Laurent1f2f2232014-06-02 12:01:23 -07001172 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001173
1174 // handle special case for sonification while in call
1175 if (isInCall()) {
1176 handleIncallSonification(stream, false, false);
1177 }
1178
1179 if (outputDesc->mRefCount[stream] > 0) {
1180 // decrement usage count of this stream on the output
1181 outputDesc->changeRefCount(stream, -1);
1182 // store time at which the stream was stopped - see isStreamActive()
1183 if (outputDesc->mRefCount[stream] == 0) {
1184 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001185 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001186 // delay the device switch by twice the latency because stopOutput() is executed when
1187 // the track stop() command is received and at that time the audio track buffer can
1188 // still contain data that needs to be drained. The latency only covers the audio HAL
1189 // and kernel buffers. Also the latency does not always include additional delay in the
1190 // audio path (audio DSP, CODEC ...)
1191 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1192
1193 // force restoring the device selection on other active outputs if it differs from the
1194 // one being selected for this output
1195 for (size_t i = 0; i < mOutputs.size(); i++) {
1196 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001197 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001198 if (curOutput != output &&
1199 desc->isActive() &&
1200 outputDesc->sharesHwModuleWith(desc) &&
1201 (newDevice != desc->device())) {
1202 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001203 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001204 true,
1205 outputDesc->mLatency*2);
1206 }
1207 }
1208 // update the outputs if stopping one with a stream that can affect notification routing
1209 handleNotificationRoutingForStream(stream);
1210 }
1211 return NO_ERROR;
1212 } else {
1213 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1214 return INVALID_OPERATION;
1215 }
1216}
1217
Eric Laurente0720872014-03-11 09:30:41 -07001218void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001219{
1220 ALOGV("releaseOutput() %d", output);
1221 ssize_t index = mOutputs.indexOfKey(output);
1222 if (index < 0) {
1223 ALOGW("releaseOutput() releasing unknown output %d", output);
1224 return;
1225 }
1226
1227#ifdef AUDIO_POLICY_TEST
1228 int testIndex = testOutputIndex(output);
1229 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001230 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001231 if (outputDesc->isActive()) {
1232 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001233 mOutputs.removeItem(output);
1234 mTestOutputs[testIndex] = 0;
1235 }
1236 return;
1237 }
1238#endif //AUDIO_POLICY_TEST
1239
Eric Laurent1f2f2232014-06-02 12:01:23 -07001240 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001241 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001242 if (desc->mDirectOpenCount <= 0) {
1243 ALOGW("releaseOutput() invalid open count %d for output %d",
1244 desc->mDirectOpenCount, output);
1245 return;
1246 }
1247 if (--desc->mDirectOpenCount == 0) {
1248 closeOutput(output);
1249 // If effects where present on the output, audioflinger moved them to the primary
1250 // output by default: move them back to the appropriate output.
1251 audio_io_handle_t dstOutput = getOutputForEffect();
1252 if (dstOutput != mPrimaryOutput) {
1253 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1254 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001255 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001256 }
1257 }
1258}
1259
1260
Eric Laurente0720872014-03-11 09:30:41 -07001261audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001262 uint32_t samplingRate,
1263 audio_format_t format,
1264 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001265 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001266 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001267{
Eric Laurent4dc68062014-07-28 17:26:49 -07001268 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001269 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001270 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001271
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001272 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001273
1274 if (device == AUDIO_DEVICE_NONE) {
1275 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001276 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001277 }
1278
1279 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001280 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001281 case AUDIO_SOURCE_VOICE_UPLINK:
1282 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1283 break;
1284 case AUDIO_SOURCE_VOICE_DOWNLINK:
1285 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1286 break;
1287 case AUDIO_SOURCE_VOICE_CALL:
1288 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1289 break;
1290 default:
1291 break;
1292 }
1293
Eric Laurent1c333e22014-05-20 10:48:17 -07001294 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001295 samplingRate,
1296 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001297 channelMask,
1298 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001299 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001300 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1301 "channelMask 0x%X, flags %#x",
1302 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001303 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
1305
1306 if (profile->mModule->mHandle == 0) {
1307 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001308 return AUDIO_IO_HANDLE_NONE;
1309 }
1310
1311 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1312 config.sample_rate = samplingRate;
1313 config.channel_mask = channelMask;
1314 config.format = format;
1315 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001316
1317 bool isSoundTrigger = false;
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001318 audio_source_t halInputSource = inputSource;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001319 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1320 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1321 if (index >= 0) {
1322 input = mSoundTriggerSessions.valueFor(session);
1323 isSoundTrigger = true;
1324 ALOGV("SoundTrigger capture on session %d input %d", session, input);
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001325 } else {
1326 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001327 }
1328 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001329 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1330 &input,
1331 &config,
1332 &device,
1333 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001334 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001335 flags);
1336
1337 // only accept input with the exact requested set of parameters
1338 if (status != NO_ERROR ||
1339 (samplingRate != config.sample_rate) ||
1340 (format != config.format) ||
1341 (channelMask != config.channel_mask)) {
1342 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1343 samplingRate, format, channelMask);
1344 if (input != AUDIO_IO_HANDLE_NONE) {
1345 mpClientInterface->closeInput(input);
1346 }
1347 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001348 }
1349
Eric Laurent1f2f2232014-06-02 12:01:23 -07001350 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001351 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001352 inputDesc->mRefCount = 0;
1353 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001354 inputDesc->mSamplingRate = samplingRate;
1355 inputDesc->mFormat = format;
1356 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001357 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001358 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001359 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001360
Eric Laurentd4692962014-05-05 18:13:44 -07001361 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001362 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001363 return input;
1364}
1365
Eric Laurent4dc68062014-07-28 17:26:49 -07001366status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1367 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001368{
1369 ALOGV("startInput() input %d", input);
1370 ssize_t index = mInputs.indexOfKey(input);
1371 if (index < 0) {
1372 ALOGW("startInput() unknown input %d", input);
1373 return BAD_VALUE;
1374 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001375 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001376
Eric Laurent4dc68062014-07-28 17:26:49 -07001377 index = inputDesc->mSessions.indexOf(session);
1378 if (index < 0) {
1379 ALOGW("startInput() unknown session %d on input %d", session, input);
1380 return BAD_VALUE;
1381 }
1382
Glenn Kasten74a8e252014-07-24 14:09:55 -07001383 // virtual input devices are compatible with other input devices
1384 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1385
1386 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001387 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001388 if (activeInput != 0 && activeInput != input) {
1389
1390 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1391 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001392 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001393 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001394 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001395 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1396 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001397 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001398 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001399 return INVALID_OPERATION;
1400 }
1401 }
1402 }
1403
Glenn Kasten74a8e252014-07-24 14:09:55 -07001404 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001405 if (activeInputsCount() == 0) {
1406 SoundTrigger::setCaptureState(true);
1407 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001408 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001409
Glenn Kasten74a8e252014-07-24 14:09:55 -07001410 // Automatically enable the remote submix output when input is started.
1411 // For remote submix (a virtual device), we open only one input per capture request.
1412 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1413 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1414 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1415 }
Eric Laurente552edb2014-03-10 17:42:56 -07001416 }
1417
Eric Laurente552edb2014-03-10 17:42:56 -07001418 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1419
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001420 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001421 return NO_ERROR;
1422}
1423
Eric Laurent4dc68062014-07-28 17:26:49 -07001424status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1425 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001426{
1427 ALOGV("stopInput() input %d", input);
1428 ssize_t index = mInputs.indexOfKey(input);
1429 if (index < 0) {
1430 ALOGW("stopInput() unknown input %d", input);
1431 return BAD_VALUE;
1432 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001434
Eric Laurent4dc68062014-07-28 17:26:49 -07001435 index = inputDesc->mSessions.indexOf(session);
1436 if (index < 0) {
1437 ALOGW("stopInput() unknown session %d on input %d", session, input);
1438 return BAD_VALUE;
1439 }
1440
Eric Laurente552edb2014-03-10 17:42:56 -07001441 if (inputDesc->mRefCount == 0) {
1442 ALOGW("stopInput() input %d already stopped", input);
1443 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001444 }
1445
1446 inputDesc->mRefCount--;
1447 if (inputDesc->mRefCount == 0) {
1448
Eric Laurente552edb2014-03-10 17:42:56 -07001449 // automatically disable the remote submix output when input is stopped
1450 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1451 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001452 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001453 }
1454
Eric Laurent1c333e22014-05-20 10:48:17 -07001455 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001456
1457 if (activeInputsCount() == 0) {
1458 SoundTrigger::setCaptureState(false);
1459 }
Eric Laurente552edb2014-03-10 17:42:56 -07001460 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001461 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001462}
1463
Eric Laurent4dc68062014-07-28 17:26:49 -07001464void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1465 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001466{
1467 ALOGV("releaseInput() %d", input);
1468 ssize_t index = mInputs.indexOfKey(input);
1469 if (index < 0) {
1470 ALOGW("releaseInput() releasing unknown input %d", input);
1471 return;
1472 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001473 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1474 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001475
1476 index = inputDesc->mSessions.indexOf(session);
1477 if (index < 0) {
1478 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1479 return;
1480 }
1481 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001482 if (inputDesc->mOpenRefCount == 0) {
1483 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1484 return;
1485 }
1486 inputDesc->mOpenRefCount--;
1487 if (inputDesc->mOpenRefCount > 0) {
1488 ALOGV("releaseInput() exit > 0");
1489 return;
1490 }
1491
Eric Laurent05b90f82014-08-27 15:32:29 -07001492 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001493 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001494 ALOGV("releaseInput() exit");
1495}
1496
Eric Laurentd4692962014-05-05 18:13:44 -07001497void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001498 bool patchRemoved = false;
1499
Eric Laurentd4692962014-05-05 18:13:44 -07001500 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001501 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1502 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1503 if (patch_index >= 0) {
1504 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1505 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1506 mAudioPatches.removeItemsAt(patch_index);
1507 patchRemoved = true;
1508 }
Eric Laurentd4692962014-05-05 18:13:44 -07001509 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1510 }
1511 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001512 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001513
1514 if (patchRemoved) {
1515 mpClientInterface->onAudioPatchListUpdate();
1516 }
Eric Laurentd4692962014-05-05 18:13:44 -07001517}
1518
Eric Laurente0720872014-03-11 09:30:41 -07001519void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001520 int indexMin,
1521 int indexMax)
1522{
1523 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1524 if (indexMin < 0 || indexMin >= indexMax) {
1525 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1526 return;
1527 }
1528 mStreams[stream].mIndexMin = indexMin;
1529 mStreams[stream].mIndexMax = indexMax;
1530}
1531
Eric Laurente0720872014-03-11 09:30:41 -07001532status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001533 int index,
1534 audio_devices_t device)
1535{
1536
1537 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1538 return BAD_VALUE;
1539 }
1540 if (!audio_is_output_device(device)) {
1541 return BAD_VALUE;
1542 }
1543
1544 // Force max volume if stream cannot be muted
1545 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1546
1547 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1548 stream, device, index);
1549
1550 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1551 // clear all device specific values
1552 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1553 mStreams[stream].mIndexCur.clear();
1554 }
1555 mStreams[stream].mIndexCur.add(device, index);
1556
1557 // compute and apply stream volume on all outputs according to connected device
1558 status_t status = NO_ERROR;
1559 for (size_t i = 0; i < mOutputs.size(); i++) {
1560 audio_devices_t curDevice =
1561 getDeviceForVolume(mOutputs.valueAt(i)->device());
1562 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1563 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1564 if (volStatus != NO_ERROR) {
1565 status = volStatus;
1566 }
1567 }
1568 }
1569 return status;
1570}
1571
Eric Laurente0720872014-03-11 09:30:41 -07001572status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001573 int *index,
1574 audio_devices_t device)
1575{
1576 if (index == NULL) {
1577 return BAD_VALUE;
1578 }
1579 if (!audio_is_output_device(device)) {
1580 return BAD_VALUE;
1581 }
1582 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1583 // the strategy the stream belongs to.
1584 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1585 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1586 }
1587 device = getDeviceForVolume(device);
1588
1589 *index = mStreams[stream].getVolumeIndex(device);
1590 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1591 return NO_ERROR;
1592}
1593
Eric Laurente0720872014-03-11 09:30:41 -07001594audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001595 const SortedVector<audio_io_handle_t>& outputs)
1596{
1597 // select one output among several suitable for global effects.
1598 // The priority is as follows:
1599 // 1: An offloaded output. If the effect ends up not being offloadable,
1600 // AudioFlinger will invalidate the track and the offloaded output
1601 // will be closed causing the effect to be moved to a PCM output.
1602 // 2: A deep buffer output
1603 // 3: the first output in the list
1604
1605 if (outputs.size() == 0) {
1606 return 0;
1607 }
1608
1609 audio_io_handle_t outputOffloaded = 0;
1610 audio_io_handle_t outputDeepBuffer = 0;
1611
1612 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001613 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001614 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001615 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1616 outputOffloaded = outputs[i];
1617 }
1618 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1619 outputDeepBuffer = outputs[i];
1620 }
1621 }
1622
1623 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1624 outputOffloaded, outputDeepBuffer);
1625 if (outputOffloaded != 0) {
1626 return outputOffloaded;
1627 }
1628 if (outputDeepBuffer != 0) {
1629 return outputDeepBuffer;
1630 }
1631
1632 return outputs[0];
1633}
1634
Eric Laurente0720872014-03-11 09:30:41 -07001635audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001636{
1637 // apply simple rule where global effects are attached to the same output as MUSIC streams
1638
Eric Laurent3b73df72014-03-11 09:06:29 -07001639 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001640 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1641 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1642
1643 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1644 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1645 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1646
1647 return output;
1648}
1649
Eric Laurente0720872014-03-11 09:30:41 -07001650status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001651 audio_io_handle_t io,
1652 uint32_t strategy,
1653 int session,
1654 int id)
1655{
1656 ssize_t index = mOutputs.indexOfKey(io);
1657 if (index < 0) {
1658 index = mInputs.indexOfKey(io);
1659 if (index < 0) {
1660 ALOGW("registerEffect() unknown io %d", io);
1661 return INVALID_OPERATION;
1662 }
1663 }
1664
1665 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1666 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1667 desc->name, desc->memoryUsage);
1668 return INVALID_OPERATION;
1669 }
1670 mTotalEffectsMemory += desc->memoryUsage;
1671 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1672 desc->name, io, strategy, session, id);
1673 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1674
Eric Laurent1f2f2232014-06-02 12:01:23 -07001675 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1676 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1677 effectDesc->mIo = io;
1678 effectDesc->mStrategy = (routing_strategy)strategy;
1679 effectDesc->mSession = session;
1680 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001681
Eric Laurent1f2f2232014-06-02 12:01:23 -07001682 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001683
1684 return NO_ERROR;
1685}
1686
Eric Laurente0720872014-03-11 09:30:41 -07001687status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001688{
1689 ssize_t index = mEffects.indexOfKey(id);
1690 if (index < 0) {
1691 ALOGW("unregisterEffect() unknown effect ID %d", id);
1692 return INVALID_OPERATION;
1693 }
1694
Eric Laurent1f2f2232014-06-02 12:01:23 -07001695 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001696
Eric Laurent1f2f2232014-06-02 12:01:23 -07001697 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001698
Eric Laurent1f2f2232014-06-02 12:01:23 -07001699 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001700 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001701 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1702 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001703 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001704 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001705 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001706 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001707
1708 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001709
1710 return NO_ERROR;
1711}
1712
Eric Laurente0720872014-03-11 09:30:41 -07001713status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001714{
1715 ssize_t index = mEffects.indexOfKey(id);
1716 if (index < 0) {
1717 ALOGW("unregisterEffect() unknown effect ID %d", id);
1718 return INVALID_OPERATION;
1719 }
1720
1721 return setEffectEnabled(mEffects.valueAt(index), enabled);
1722}
1723
Eric Laurent1f2f2232014-06-02 12:01:23 -07001724status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001725{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001726 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001727 ALOGV("setEffectEnabled(%s) effect already %s",
1728 enabled?"true":"false", enabled?"enabled":"disabled");
1729 return INVALID_OPERATION;
1730 }
1731
1732 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001733 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001734 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001735 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001736 return INVALID_OPERATION;
1737 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001738 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001739 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1740 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001741 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001742 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001743 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1744 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001745 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001746 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001747 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1748 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001749 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001750 return NO_ERROR;
1751}
1752
Eric Laurente0720872014-03-11 09:30:41 -07001753bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001754{
1755 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001756 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1757 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1758 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001759 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001760 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001761 return true;
1762 }
1763 }
1764 return false;
1765}
1766
Eric Laurente0720872014-03-11 09:30:41 -07001767bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001768{
1769 nsecs_t sysTime = systemTime();
1770 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001772 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001773 return true;
1774 }
1775 }
1776 return false;
1777}
1778
Eric Laurente0720872014-03-11 09:30:41 -07001779bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001780 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001781{
1782 nsecs_t sysTime = systemTime();
1783 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001784 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001785 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001786 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001787 return true;
1788 }
1789 }
1790 return false;
1791}
1792
Eric Laurente0720872014-03-11 09:30:41 -07001793bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001794{
1795 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001796 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001797 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001798 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001799 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1800 && (inputDescriptor->mRefCount > 0)) {
1801 return true;
1802 }
1803 }
1804 return false;
1805}
1806
1807
Eric Laurente0720872014-03-11 09:30:41 -07001808status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001809{
1810 const size_t SIZE = 256;
1811 char buffer[SIZE];
1812 String8 result;
1813
1814 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1815 result.append(buffer);
1816
1817 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1818 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001819 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1820 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001821 snprintf(buffer, SIZE, " Force use for communications %d\n",
1822 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001823 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001824 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001825 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001826 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001827 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001828 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001829 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001830 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001831 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001832 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1833 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1834 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001835
Eric Laurent3a4311c2014-03-17 12:00:47 -07001836 snprintf(buffer, SIZE, " Available output devices:\n");
1837 result.append(buffer);
1838 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001839 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001840 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001841 }
1842 snprintf(buffer, SIZE, "\n Available input devices:\n");
1843 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001844 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001845 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001846 }
Eric Laurente552edb2014-03-10 17:42:56 -07001847
1848 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1849 write(fd, buffer, strlen(buffer));
1850 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001851 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001852 write(fd, buffer, strlen(buffer));
1853 mHwModules[i]->dump(fd);
1854 }
1855
1856 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1857 write(fd, buffer, strlen(buffer));
1858 for (size_t i = 0; i < mOutputs.size(); i++) {
1859 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1860 write(fd, buffer, strlen(buffer));
1861 mOutputs.valueAt(i)->dump(fd);
1862 }
1863
1864 snprintf(buffer, SIZE, "\nInputs dump:\n");
1865 write(fd, buffer, strlen(buffer));
1866 for (size_t i = 0; i < mInputs.size(); i++) {
1867 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1868 write(fd, buffer, strlen(buffer));
1869 mInputs.valueAt(i)->dump(fd);
1870 }
1871
1872 snprintf(buffer, SIZE, "\nStreams dump:\n");
1873 write(fd, buffer, strlen(buffer));
1874 snprintf(buffer, SIZE,
1875 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1876 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001877 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001878 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001879 write(fd, buffer, strlen(buffer));
1880 mStreams[i].dump(fd);
1881 }
1882
1883 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1884 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1885 write(fd, buffer, strlen(buffer));
1886
1887 snprintf(buffer, SIZE, "Registered effects:\n");
1888 write(fd, buffer, strlen(buffer));
1889 for (size_t i = 0; i < mEffects.size(); i++) {
1890 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1891 write(fd, buffer, strlen(buffer));
1892 mEffects.valueAt(i)->dump(fd);
1893 }
1894
Eric Laurent4d416952014-08-10 14:07:09 -07001895 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1896 write(fd, buffer, strlen(buffer));
1897 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1898 mAudioPatches[i]->dump(fd, 2, i);
1899 }
Eric Laurente552edb2014-03-10 17:42:56 -07001900
1901 return NO_ERROR;
1902}
1903
1904// This function checks for the parameters which can be offloaded.
1905// This can be enhanced depending on the capability of the DSP and policy
1906// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001907bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
1909 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001910 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001911 offloadInfo.sample_rate, offloadInfo.channel_mask,
1912 offloadInfo.format,
1913 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1914 offloadInfo.has_video);
1915
1916 // Check if offload has been disabled
1917 char propValue[PROPERTY_VALUE_MAX];
1918 if (property_get("audio.offload.disable", propValue, "0")) {
1919 if (atoi(propValue) != 0) {
1920 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1921 return false;
1922 }
1923 }
1924
1925 // Check if stream type is music, then only allow offload as of now.
1926 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1927 {
1928 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1929 return false;
1930 }
1931
1932 //TODO: enable audio offloading with video when ready
1933 if (offloadInfo.has_video)
1934 {
1935 ALOGV("isOffloadSupported: has_video == true, returning false");
1936 return false;
1937 }
1938
1939 //If duration is less than minimum value defined in property, return false
1940 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1941 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1942 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1943 return false;
1944 }
1945 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1946 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1947 return false;
1948 }
1949
1950 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1951 // creating an offloaded track and tearing it down immediately after start when audioflinger
1952 // detects there is an active non offloadable effect.
1953 // FIXME: We should check the audio session here but we do not have it in this context.
1954 // This may prevent offloading in rare situations where effects are left active by apps
1955 // in the background.
1956 if (isNonOffloadableEffectEnabled()) {
1957 return false;
1958 }
1959
1960 // See if there is a profile to support this.
1961 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001962 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001963 offloadInfo.sample_rate,
1964 offloadInfo.format,
1965 offloadInfo.channel_mask,
1966 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001967 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1968 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001969}
1970
Eric Laurent6a94d692014-05-20 11:18:06 -07001971status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1972 audio_port_type_t type,
1973 unsigned int *num_ports,
1974 struct audio_port *ports,
1975 unsigned int *generation)
1976{
1977 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1978 generation == NULL) {
1979 return BAD_VALUE;
1980 }
1981 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1982 if (ports == NULL) {
1983 *num_ports = 0;
1984 }
1985
1986 size_t portsWritten = 0;
1987 size_t portsMax = *num_ports;
1988 *num_ports = 0;
1989 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1990 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1991 for (size_t i = 0;
1992 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1993 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1994 }
1995 *num_ports += mAvailableOutputDevices.size();
1996 }
1997 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1998 for (size_t i = 0;
1999 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2000 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2001 }
2002 *num_ports += mAvailableInputDevices.size();
2003 }
2004 }
2005 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2006 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2007 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2008 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2009 }
2010 *num_ports += mInputs.size();
2011 }
2012 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002013 size_t numOutputs = 0;
2014 for (size_t i = 0; i < mOutputs.size(); i++) {
2015 if (!mOutputs[i]->isDuplicated()) {
2016 numOutputs++;
2017 if (portsWritten < portsMax) {
2018 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2019 }
2020 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002021 }
Eric Laurent84c70242014-06-23 08:46:27 -07002022 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002023 }
2024 }
2025 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002026 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002027 return NO_ERROR;
2028}
2029
2030status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2031{
2032 return NO_ERROR;
2033}
2034
Eric Laurent1f2f2232014-06-02 12:01:23 -07002035sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002036 audio_port_handle_t id) const
2037{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002038 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002039 for (size_t i = 0; i < mOutputs.size(); i++) {
2040 outputDesc = mOutputs.valueAt(i);
2041 if (outputDesc->mId == id) {
2042 break;
2043 }
2044 }
2045 return outputDesc;
2046}
2047
Eric Laurent1f2f2232014-06-02 12:01:23 -07002048sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002049 audio_port_handle_t id) const
2050{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002051 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002052 for (size_t i = 0; i < mInputs.size(); i++) {
2053 inputDesc = mInputs.valueAt(i);
2054 if (inputDesc->mId == id) {
2055 break;
2056 }
2057 }
2058 return inputDesc;
2059}
2060
Eric Laurent1f2f2232014-06-02 12:01:23 -07002061sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2062 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002063{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002064 sp <HwModule> module;
2065
Eric Laurent6a94d692014-05-20 11:18:06 -07002066 for (size_t i = 0; i < mHwModules.size(); i++) {
2067 if (mHwModules[i]->mHandle == 0) {
2068 continue;
2069 }
2070 if (audio_is_output_device(device)) {
2071 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2072 {
2073 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2074 return mHwModules[i];
2075 }
2076 }
2077 } else {
2078 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2079 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2080 device & ~AUDIO_DEVICE_BIT_IN) {
2081 return mHwModules[i];
2082 }
2083 }
2084 }
2085 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002086 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002087}
2088
Eric Laurent1f2f2232014-06-02 12:01:23 -07002089sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002090{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002091 sp <HwModule> module;
2092
Eric Laurent1afeecb2014-05-14 08:52:28 -07002093 for (size_t i = 0; i < mHwModules.size(); i++)
2094 {
2095 if (strcmp(mHwModules[i]->mName, name) == 0) {
2096 return mHwModules[i];
2097 }
2098 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002099 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002100}
2101
Eric Laurentc2730ba2014-07-20 15:47:07 -07002102audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2103{
2104 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2105 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2106 return devices & mAvailableOutputDevices.types();
2107}
2108
2109audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2110{
2111 audio_module_handle_t primaryHandle =
2112 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2113 audio_devices_t devices = AUDIO_DEVICE_NONE;
2114 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2115 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2116 devices |= mAvailableInputDevices[i]->mDeviceType;
2117 }
2118 }
2119 return devices;
2120}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002121
Eric Laurent6a94d692014-05-20 11:18:06 -07002122status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2123 audio_patch_handle_t *handle,
2124 uid_t uid)
2125{
2126 ALOGV("createAudioPatch()");
2127
2128 if (handle == NULL || patch == NULL) {
2129 return BAD_VALUE;
2130 }
2131 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2132
Eric Laurent874c42872014-08-08 15:13:39 -07002133 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2134 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2135 return BAD_VALUE;
2136 }
2137 // only one source per audio patch supported for now
2138 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002139 return INVALID_OPERATION;
2140 }
Eric Laurent874c42872014-08-08 15:13:39 -07002141
2142 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002143 return INVALID_OPERATION;
2144 }
Eric Laurent874c42872014-08-08 15:13:39 -07002145 for (size_t i = 0; i < patch->num_sinks; i++) {
2146 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2147 return INVALID_OPERATION;
2148 }
2149 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002150
2151 sp<AudioPatch> patchDesc;
2152 ssize_t index = mAudioPatches.indexOfKey(*handle);
2153
Eric Laurent6a94d692014-05-20 11:18:06 -07002154 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2155 patch->sources[0].role,
2156 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002157#if LOG_NDEBUG == 0
2158 for (size_t i = 0; i < patch->num_sinks; i++) {
2159 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2160 patch->sinks[i].role,
2161 patch->sinks[i].type);
2162 }
2163#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002164
2165 if (index >= 0) {
2166 patchDesc = mAudioPatches.valueAt(index);
2167 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2168 mUidCached, patchDesc->mUid, uid);
2169 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2170 return INVALID_OPERATION;
2171 }
2172 } else {
2173 *handle = 0;
2174 }
2175
2176 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002177 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002178 if (outputDesc == NULL) {
2179 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2180 return BAD_VALUE;
2181 }
Eric Laurent84c70242014-06-23 08:46:27 -07002182 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2183 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002184 if (patchDesc != 0) {
2185 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2186 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2187 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2188 return BAD_VALUE;
2189 }
2190 }
Eric Laurent874c42872014-08-08 15:13:39 -07002191 DeviceVector devices;
2192 for (size_t i = 0; i < patch->num_sinks; i++) {
2193 // Only support mix to devices connection
2194 // TODO add support for mix to mix connection
2195 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2196 ALOGV("createAudioPatch() source mix but sink is not a device");
2197 return INVALID_OPERATION;
2198 }
2199 sp<DeviceDescriptor> devDesc =
2200 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2201 if (devDesc == 0) {
2202 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2203 return BAD_VALUE;
2204 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002205
Eric Laurent874c42872014-08-08 15:13:39 -07002206 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2207 patch->sources[0].sample_rate,
2208 NULL, // updatedSamplingRate
2209 patch->sources[0].format,
2210 patch->sources[0].channel_mask,
2211 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2212 ALOGV("createAudioPatch() profile not supported for device %08x",
2213 devDesc->mDeviceType);
2214 return INVALID_OPERATION;
2215 }
2216 devices.add(devDesc);
2217 }
2218 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002219 return INVALID_OPERATION;
2220 }
Eric Laurent874c42872014-08-08 15:13:39 -07002221
Eric Laurent6a94d692014-05-20 11:18:06 -07002222 // TODO: reconfigure output format and channels here
2223 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002224 devices.types(), outputDesc->mIoHandle);
2225 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002226 index = mAudioPatches.indexOfKey(*handle);
2227 if (index >= 0) {
2228 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2229 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2230 }
2231 patchDesc = mAudioPatches.valueAt(index);
2232 patchDesc->mUid = uid;
2233 ALOGV("createAudioPatch() success");
2234 } else {
2235 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2236 return INVALID_OPERATION;
2237 }
2238 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2239 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2240 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002241 // only one sink supported when connecting an input device to a mix
2242 if (patch->num_sinks > 1) {
2243 return INVALID_OPERATION;
2244 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002245 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002246 if (inputDesc == NULL) {
2247 return BAD_VALUE;
2248 }
2249 if (patchDesc != 0) {
2250 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2251 return BAD_VALUE;
2252 }
2253 }
2254 sp<DeviceDescriptor> devDesc =
2255 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2256 if (devDesc == 0) {
2257 return BAD_VALUE;
2258 }
2259
Eric Laurent84c70242014-06-23 08:46:27 -07002260 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002261 patch->sinks[0].sample_rate,
2262 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002263 patch->sinks[0].format,
2264 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002265 // FIXME for the parameter type,
2266 // and the NONE
2267 (audio_output_flags_t)
2268 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002269 return INVALID_OPERATION;
2270 }
2271 // TODO: reconfigure output format and channels here
2272 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002273 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002274 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002275 index = mAudioPatches.indexOfKey(*handle);
2276 if (index >= 0) {
2277 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2278 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2279 }
2280 patchDesc = mAudioPatches.valueAt(index);
2281 patchDesc->mUid = uid;
2282 ALOGV("createAudioPatch() success");
2283 } else {
2284 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2285 return INVALID_OPERATION;
2286 }
2287 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2288 // device to device connection
2289 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002290 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002291 return BAD_VALUE;
2292 }
2293 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002294 sp<DeviceDescriptor> srcDeviceDesc =
2295 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent874c42872014-08-08 15:13:39 -07002296
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 //update source and sink with our own data as the data passed in the patch may
2298 // be incomplete.
2299 struct audio_patch newPatch = *patch;
2300 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent874c42872014-08-08 15:13:39 -07002301 if (srcDeviceDesc == 0) {
2302 return BAD_VALUE;
2303 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002304
Eric Laurent874c42872014-08-08 15:13:39 -07002305 for (size_t i = 0; i < patch->num_sinks; i++) {
2306 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2307 ALOGV("createAudioPatch() source device but one sink is not a device");
2308 return INVALID_OPERATION;
2309 }
2310
2311 sp<DeviceDescriptor> sinkDeviceDesc =
2312 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2313 if (sinkDeviceDesc == 0) {
2314 return BAD_VALUE;
2315 }
2316 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2317
2318 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2319 // only one sink supported when connected devices across HW modules
2320 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002321 return INVALID_OPERATION;
2322 }
Eric Laurent874c42872014-08-08 15:13:39 -07002323 SortedVector<audio_io_handle_t> outputs =
2324 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2325 mOutputs);
2326 // if the sink device is reachable via an opened output stream, request to go via
2327 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002328 audio_io_handle_t output = selectOutput(outputs,
2329 AUDIO_OUTPUT_FLAG_NONE,
2330 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002331 if (output != AUDIO_IO_HANDLE_NONE) {
2332 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2333 if (outputDesc->isDuplicated()) {
2334 return INVALID_OPERATION;
2335 }
2336 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2337 newPatch.num_sources = 2;
2338 }
Eric Laurent83b88082014-06-20 18:31:16 -07002339 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002340 }
2341 // TODO: check from routing capabilities in config file and other conflicting patches
2342
2343 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2344 if (index >= 0) {
2345 afPatchHandle = patchDesc->mAfPatchHandle;
2346 }
2347
2348 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2349 &afPatchHandle,
2350 0);
2351 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2352 status, afPatchHandle);
2353 if (status == NO_ERROR) {
2354 if (index < 0) {
2355 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2356 &newPatch, uid);
2357 addAudioPatch(patchDesc->mHandle, patchDesc);
2358 } else {
2359 patchDesc->mPatch = newPatch;
2360 }
2361 patchDesc->mAfPatchHandle = afPatchHandle;
2362 *handle = patchDesc->mHandle;
2363 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002364 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002365 } else {
2366 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2367 status);
2368 return INVALID_OPERATION;
2369 }
2370 } else {
2371 return BAD_VALUE;
2372 }
2373 } else {
2374 return BAD_VALUE;
2375 }
2376 return NO_ERROR;
2377}
2378
2379status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2380 uid_t uid)
2381{
2382 ALOGV("releaseAudioPatch() patch %d", handle);
2383
2384 ssize_t index = mAudioPatches.indexOfKey(handle);
2385
2386 if (index < 0) {
2387 return BAD_VALUE;
2388 }
2389 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2390 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2391 mUidCached, patchDesc->mUid, uid);
2392 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2393 return INVALID_OPERATION;
2394 }
2395
2396 struct audio_patch *patch = &patchDesc->mPatch;
2397 patchDesc->mUid = mUidCached;
2398 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002399 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002400 if (outputDesc == NULL) {
2401 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2402 return BAD_VALUE;
2403 }
2404
2405 setOutputDevice(outputDesc->mIoHandle,
2406 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2407 true,
2408 0,
2409 NULL);
2410 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2411 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002412 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002413 if (inputDesc == NULL) {
2414 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2415 return BAD_VALUE;
2416 }
2417 setInputDevice(inputDesc->mIoHandle,
2418 getNewInputDevice(inputDesc->mIoHandle),
2419 true,
2420 NULL);
2421 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2422 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2423 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2424 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2425 status, patchDesc->mAfPatchHandle);
2426 removeAudioPatch(patchDesc->mHandle);
2427 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002428 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002429 } else {
2430 return BAD_VALUE;
2431 }
2432 } else {
2433 return BAD_VALUE;
2434 }
2435 return NO_ERROR;
2436}
2437
2438status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2439 struct audio_patch *patches,
2440 unsigned int *generation)
2441{
2442 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2443 generation == NULL) {
2444 return BAD_VALUE;
2445 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002446 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002447 *num_patches, patches, mAudioPatches.size());
2448 if (patches == NULL) {
2449 *num_patches = 0;
2450 }
2451
2452 size_t patchesWritten = 0;
2453 size_t patchesMax = *num_patches;
2454 for (size_t i = 0;
2455 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2456 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2457 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002458 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002459 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2460 }
2461 *num_patches = mAudioPatches.size();
2462
2463 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002464 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002465 return NO_ERROR;
2466}
2467
Eric Laurente1715a42014-05-20 11:30:42 -07002468status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002469{
Eric Laurente1715a42014-05-20 11:30:42 -07002470 ALOGV("setAudioPortConfig()");
2471
2472 if (config == NULL) {
2473 return BAD_VALUE;
2474 }
2475 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2476 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002477 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2478 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002479 }
2480
Eric Laurenta121f902014-06-03 13:32:54 -07002481 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002482 if (config->type == AUDIO_PORT_TYPE_MIX) {
2483 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002484 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002485 if (outputDesc == NULL) {
2486 return BAD_VALUE;
2487 }
Eric Laurent84c70242014-06-23 08:46:27 -07002488 ALOG_ASSERT(!outputDesc->isDuplicated(),
2489 "setAudioPortConfig() called on duplicated output %d",
2490 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002491 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002492 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002493 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002494 if (inputDesc == NULL) {
2495 return BAD_VALUE;
2496 }
Eric Laurenta121f902014-06-03 13:32:54 -07002497 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002498 } else {
2499 return BAD_VALUE;
2500 }
2501 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2502 sp<DeviceDescriptor> deviceDesc;
2503 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2504 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2505 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2506 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2507 } else {
2508 return BAD_VALUE;
2509 }
2510 if (deviceDesc == NULL) {
2511 return BAD_VALUE;
2512 }
Eric Laurenta121f902014-06-03 13:32:54 -07002513 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002514 } else {
2515 return BAD_VALUE;
2516 }
2517
Eric Laurenta121f902014-06-03 13:32:54 -07002518 struct audio_port_config backupConfig;
2519 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2520 if (status == NO_ERROR) {
2521 struct audio_port_config newConfig;
2522 audioPortConfig->toAudioPortConfig(&newConfig, config);
2523 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002524 }
Eric Laurenta121f902014-06-03 13:32:54 -07002525 if (status != NO_ERROR) {
2526 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002527 }
Eric Laurente1715a42014-05-20 11:30:42 -07002528
2529 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002530}
2531
2532void AudioPolicyManager::clearAudioPatches(uid_t uid)
2533{
2534 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2535 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2536 if (patchDesc->mUid == uid) {
2537 // releaseAudioPatch() removes the patch from mAudioPatches
2538 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2539 i--;
2540 }
2541 }
2542 }
2543}
2544
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002545status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2546 audio_io_handle_t *ioHandle,
2547 audio_devices_t *device)
2548{
2549 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2550 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2551 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2552
2553 mSoundTriggerSessions.add(*session, *ioHandle);
2554
2555 return NO_ERROR;
2556}
2557
2558status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2559{
2560 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2561 if (index < 0) {
2562 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2563 return BAD_VALUE;
2564 }
2565
2566 mSoundTriggerSessions.removeItem(session);
2567 return NO_ERROR;
2568}
2569
Eric Laurent6a94d692014-05-20 11:18:06 -07002570status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2571 const sp<AudioPatch>& patch)
2572{
2573 ssize_t index = mAudioPatches.indexOfKey(handle);
2574
2575 if (index >= 0) {
2576 ALOGW("addAudioPatch() patch %d already in", handle);
2577 return ALREADY_EXISTS;
2578 }
2579 mAudioPatches.add(handle, patch);
2580 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2581 "sink handle %d",
2582 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2583 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2584 return NO_ERROR;
2585}
2586
2587status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2588{
2589 ssize_t index = mAudioPatches.indexOfKey(handle);
2590
2591 if (index < 0) {
2592 ALOGW("removeAudioPatch() patch %d not in", handle);
2593 return ALREADY_EXISTS;
2594 }
2595 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2596 mAudioPatches.valueAt(index)->mAfPatchHandle);
2597 mAudioPatches.removeItemsAt(index);
2598 return NO_ERROR;
2599}
2600
Eric Laurente552edb2014-03-10 17:42:56 -07002601// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002602// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002603// ----------------------------------------------------------------------------
2604
Eric Laurent3a4311c2014-03-17 12:00:47 -07002605uint32_t AudioPolicyManager::nextUniqueId()
2606{
2607 return android_atomic_inc(&mNextUniqueId);
2608}
2609
Eric Laurent6a94d692014-05-20 11:18:06 -07002610uint32_t AudioPolicyManager::nextAudioPortGeneration()
2611{
2612 return android_atomic_inc(&mAudioPortGeneration);
2613}
2614
Eric Laurente0720872014-03-11 09:30:41 -07002615AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002616 :
2617#ifdef AUDIO_POLICY_TEST
2618 Thread(false),
2619#endif //AUDIO_POLICY_TEST
2620 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002621 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002622 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2623 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002624 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002625 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2626 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002627{
Eric Laurent6a94d692014-05-20 11:18:06 -07002628 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002629 mpClientInterface = clientInterface;
2630
Eric Laurent3b73df72014-03-11 09:06:29 -07002631 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2632 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002633 }
2634
Eric Laurent1afeecb2014-05-14 08:52:28 -07002635 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002636 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2637 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2638 ALOGE("could not load audio policy configuration file, setting defaults");
2639 defaultAudioPolicyConfig();
2640 }
2641 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002642 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002643
2644 // must be done after reading the policy
2645 initializeVolumeCurves();
2646
2647 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002648 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2649 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002650 for (size_t i = 0; i < mHwModules.size(); i++) {
2651 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2652 if (mHwModules[i]->mHandle == 0) {
2653 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2654 continue;
2655 }
2656 // open all output streams needed to access attached devices
2657 // except for direct output streams that are only opened when they are actually
2658 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002659 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002660 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2661 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002662 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002663
Eric Laurent3a4311c2014-03-17 12:00:47 -07002664 if (outProfile->mSupportedDevices.isEmpty()) {
2665 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2666 continue;
2667 }
2668
Eric Laurent83b88082014-06-20 18:31:16 -07002669 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2670 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2671 profileType = mDefaultOutputDevice->mDeviceType;
2672 } else {
2673 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2674 }
2675 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002676 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002677 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002678
Eric Laurent83b88082014-06-20 18:31:16 -07002679 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002680 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2681 config.sample_rate = outputDesc->mSamplingRate;
2682 config.channel_mask = outputDesc->mChannelMask;
2683 config.format = outputDesc->mFormat;
2684 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2685 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2686 &output,
2687 &config,
2688 &outputDesc->mDevice,
2689 String8(""),
2690 &outputDesc->mLatency,
2691 outputDesc->mFlags);
2692
2693 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002694 ALOGW("Cannot open output stream for device %08x on hw module %s",
2695 outputDesc->mDevice,
2696 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002697 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002698 outputDesc->mSamplingRate = config.sample_rate;
2699 outputDesc->mChannelMask = config.channel_mask;
2700 outputDesc->mFormat = config.format;
2701
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002702 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002703 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002704 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002705 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002706 // give a valid ID to an attached device once confirmed it is reachable
2707 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2708 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002709 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002710 }
2711 }
Eric Laurente552edb2014-03-10 17:42:56 -07002712 if (mPrimaryOutput == 0 &&
2713 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2714 mPrimaryOutput = output;
2715 }
2716 addOutput(output, outputDesc);
2717 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002718 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002719 true);
2720 }
2721 }
2722 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002723 // open input streams needed to access attached devices to validate
2724 // mAvailableInputDevices list
2725 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2726 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002727 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002728
Eric Laurent3a4311c2014-03-17 12:00:47 -07002729 if (inProfile->mSupportedDevices.isEmpty()) {
2730 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2731 continue;
2732 }
2733
Eric Laurent83b88082014-06-20 18:31:16 -07002734 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2735 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002736 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002737
2738 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002739 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002740
Eric Laurentcf2c0212014-07-25 16:20:43 -07002741 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2742 config.sample_rate = inputDesc->mSamplingRate;
2743 config.channel_mask = inputDesc->mChannelMask;
2744 config.format = inputDesc->mFormat;
2745 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2746 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2747 &input,
2748 &config,
2749 &inputDesc->mDevice,
2750 String8(""),
2751 AUDIO_SOURCE_MIC,
2752 AUDIO_INPUT_FLAG_NONE);
2753
2754 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002755 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002756 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002757 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002758 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002759 // give a valid ID to an attached device once confirmed it is reachable
2760 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2761 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002762 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002763 }
2764 }
2765 mpClientInterface->closeInput(input);
2766 } else {
2767 ALOGW("Cannot open input stream for device %08x on hw module %s",
2768 inputDesc->mDevice,
2769 mHwModules[i]->mName);
2770 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002771 }
2772 }
2773 }
2774 // make sure all attached devices have been allocated a unique ID
2775 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2776 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002777 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002778 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2779 continue;
2780 }
2781 i++;
2782 }
2783 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2784 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002785 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002786 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2787 continue;
2788 }
2789 i++;
2790 }
2791 // make sure default device is reachable
2792 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002793 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002794 }
Eric Laurente552edb2014-03-10 17:42:56 -07002795
2796 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2797
2798 updateDevicesAndOutputs();
2799
2800#ifdef AUDIO_POLICY_TEST
2801 if (mPrimaryOutput != 0) {
2802 AudioParameter outputCmd = AudioParameter();
2803 outputCmd.addInt(String8("set_id"), 0);
2804 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2805
2806 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2807 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002808 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2809 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002810 mTestLatencyMs = 0;
2811 mCurOutput = 0;
2812 mDirectOutput = false;
2813 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2814 mTestOutputs[i] = 0;
2815 }
2816
2817 const size_t SIZE = 256;
2818 char buffer[SIZE];
2819 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2820 run(buffer, ANDROID_PRIORITY_AUDIO);
2821 }
2822#endif //AUDIO_POLICY_TEST
2823}
2824
Eric Laurente0720872014-03-11 09:30:41 -07002825AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002826{
2827#ifdef AUDIO_POLICY_TEST
2828 exit();
2829#endif //AUDIO_POLICY_TEST
2830 for (size_t i = 0; i < mOutputs.size(); i++) {
2831 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002832 }
2833 for (size_t i = 0; i < mInputs.size(); i++) {
2834 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002835 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002836 mAvailableOutputDevices.clear();
2837 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002838 mOutputs.clear();
2839 mInputs.clear();
2840 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002841}
2842
Eric Laurente0720872014-03-11 09:30:41 -07002843status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002844{
2845 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2846}
2847
2848#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002849bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002850{
2851 ALOGV("entering threadLoop()");
2852 while (!exitPending())
2853 {
2854 String8 command;
2855 int valueInt;
2856 String8 value;
2857
2858 Mutex::Autolock _l(mLock);
2859 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2860
2861 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2862 AudioParameter param = AudioParameter(command);
2863
2864 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2865 valueInt != 0) {
2866 ALOGV("Test command %s received", command.string());
2867 String8 target;
2868 if (param.get(String8("target"), target) != NO_ERROR) {
2869 target = "Manager";
2870 }
2871 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2872 param.remove(String8("test_cmd_policy_output"));
2873 mCurOutput = valueInt;
2874 }
2875 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2876 param.remove(String8("test_cmd_policy_direct"));
2877 if (value == "false") {
2878 mDirectOutput = false;
2879 } else if (value == "true") {
2880 mDirectOutput = true;
2881 }
2882 }
2883 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2884 param.remove(String8("test_cmd_policy_input"));
2885 mTestInput = valueInt;
2886 }
2887
2888 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2889 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002890 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002891 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002892 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002893 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002894 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002895 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002896 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002897 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002898 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002899 if (target == "Manager") {
2900 mTestFormat = format;
2901 } else if (mTestOutputs[mCurOutput] != 0) {
2902 AudioParameter outputParam = AudioParameter();
2903 outputParam.addInt(String8("format"), format);
2904 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2905 }
2906 }
2907 }
2908 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2909 param.remove(String8("test_cmd_policy_channels"));
2910 int channels = 0;
2911
2912 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002913 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002914 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002915 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002916 }
2917 if (channels != 0) {
2918 if (target == "Manager") {
2919 mTestChannels = channels;
2920 } else if (mTestOutputs[mCurOutput] != 0) {
2921 AudioParameter outputParam = AudioParameter();
2922 outputParam.addInt(String8("channels"), channels);
2923 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2924 }
2925 }
2926 }
2927 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2928 param.remove(String8("test_cmd_policy_sampleRate"));
2929 if (valueInt >= 0 && valueInt <= 96000) {
2930 int samplingRate = valueInt;
2931 if (target == "Manager") {
2932 mTestSamplingRate = samplingRate;
2933 } else if (mTestOutputs[mCurOutput] != 0) {
2934 AudioParameter outputParam = AudioParameter();
2935 outputParam.addInt(String8("sampling_rate"), samplingRate);
2936 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2937 }
2938 }
2939 }
2940
2941 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2942 param.remove(String8("test_cmd_policy_reopen"));
2943
Eric Laurent1f2f2232014-06-02 12:01:23 -07002944 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002945 mpClientInterface->closeOutput(mPrimaryOutput);
2946
2947 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2948
Eric Laurente552edb2014-03-10 17:42:56 -07002949 mOutputs.removeItem(mPrimaryOutput);
2950
Eric Laurent1f2f2232014-06-02 12:01:23 -07002951 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002952 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002953 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2954 config.sample_rate = outputDesc->mSamplingRate;
2955 config.channel_mask = outputDesc->mChannelMask;
2956 config.format = outputDesc->mFormat;
2957 status_t status = mpClientInterface->openOutput(moduleHandle,
2958 &mPrimaryOutput,
2959 &config,
2960 &outputDesc->mDevice,
2961 String8(""),
2962 &outputDesc->mLatency,
2963 outputDesc->mFlags);
2964 if (status != NO_ERROR) {
2965 ALOGE("Failed to reopen hardware output stream, "
2966 "samplingRate: %d, format %d, channels %d",
2967 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002968 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002969 outputDesc->mSamplingRate = config.sample_rate;
2970 outputDesc->mChannelMask = config.channel_mask;
2971 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002972 AudioParameter outputCmd = AudioParameter();
2973 outputCmd.addInt(String8("set_id"), 0);
2974 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2975 addOutput(mPrimaryOutput, outputDesc);
2976 }
2977 }
2978
2979
2980 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2981 }
2982 }
2983 return false;
2984}
2985
Eric Laurente0720872014-03-11 09:30:41 -07002986void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002987{
2988 {
2989 AutoMutex _l(mLock);
2990 requestExit();
2991 mWaitWorkCV.signal();
2992 }
2993 requestExitAndWait();
2994}
2995
Eric Laurente0720872014-03-11 09:30:41 -07002996int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
2998 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2999 if (output == mTestOutputs[i]) return i;
3000 }
3001 return 0;
3002}
3003#endif //AUDIO_POLICY_TEST
3004
3005// ---
3006
Eric Laurent1f2f2232014-06-02 12:01:23 -07003007void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003008{
Eric Laurent1c333e22014-05-20 10:48:17 -07003009 outputDesc->mIoHandle = output;
3010 outputDesc->mId = nextUniqueId();
3011 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003012 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003013}
3014
Eric Laurent1f2f2232014-06-02 12:01:23 -07003015void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003016{
Eric Laurent1c333e22014-05-20 10:48:17 -07003017 inputDesc->mIoHandle = input;
3018 inputDesc->mId = nextUniqueId();
3019 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003021}
Eric Laurente552edb2014-03-10 17:42:56 -07003022
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003023void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3024 const String8 address /*in*/,
3025 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3026 // look for a match on the given address on the addresses of the outputs:
3027 // find the address by finding the patch that maps to this output
3028 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3029 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3030 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3031 if (patchIdx >= 0) {
3032 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3033 const int numSinks = patchDesc->mPatch.num_sinks;
3034 for (ssize_t j=0; j < numSinks; j++) {
3035 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3036 const char* patchAddr =
3037 patchDesc->mPatch.sinks[j].ext.device.address;
3038 if (strncmp(patchAddr,
3039 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003040 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003041 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3042 outputs.add(desc->mIoHandle);
3043 break;
3044 }
3045 }
3046 }
3047 }
3048}
3049
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003050status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003051 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003052 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003053 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003054{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003055 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003056 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003057 // erase all current sample rates, formats and channel masks
3058 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003059
Eric Laurent3b73df72014-03-11 09:06:29 -07003060 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003061 // first list already open outputs that can be routed to this device
3062 for (size_t i = 0; i < mOutputs.size(); i++) {
3063 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003064 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003065 if (!deviceDistinguishesOnAddress(device)) {
3066 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3067 outputs.add(mOutputs.keyAt(i));
3068 } else {
3069 ALOGV(" checking address match due to device 0x%x", device);
3070 findIoHandlesByAddress(desc, address, outputs);
3071 }
Eric Laurente552edb2014-03-10 17:42:56 -07003072 }
3073 }
3074 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003075 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003076 for (size_t i = 0; i < mHwModules.size(); i++)
3077 {
3078 if (mHwModules[i]->mHandle == 0) {
3079 continue;
3080 }
3081 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3082 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003083 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003084 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003085 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3086 }
3087 }
3088 }
3089
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003090 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3091
Eric Laurente552edb2014-03-10 17:42:56 -07003092 if (profiles.isEmpty() && outputs.isEmpty()) {
3093 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3094 return BAD_VALUE;
3095 }
3096
3097 // open outputs for matching profiles if needed. Direct outputs are also opened to
3098 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3099 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003100 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003101
3102 // nothing to do if one output is already opened for this profile
3103 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003104 for (j = 0; j < outputs.size(); j++) {
3105 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003106 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003107 // matching profile: save the sample rates, format and channel masks supported
3108 // by the profile in our device descriptor
3109 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003110 break;
3111 }
3112 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003113 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003114 continue;
3115 }
3116
Eric Laurent83b88082014-06-20 18:31:16 -07003117 ALOGV("opening output for device %08x with params %s profile %p",
3118 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003119 desc = new AudioOutputDescriptor(profile);
3120 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003121 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3122 config.sample_rate = desc->mSamplingRate;
3123 config.channel_mask = desc->mChannelMask;
3124 config.format = desc->mFormat;
3125 config.offload_info.sample_rate = desc->mSamplingRate;
3126 config.offload_info.channel_mask = desc->mChannelMask;
3127 config.offload_info.format = desc->mFormat;
3128 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3129 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3130 &output,
3131 &config,
3132 &desc->mDevice,
3133 address,
3134 &desc->mLatency,
3135 desc->mFlags);
3136 if (status == NO_ERROR) {
3137 desc->mSamplingRate = config.sample_rate;
3138 desc->mChannelMask = config.channel_mask;
3139 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003140
Eric Laurentd4692962014-05-05 18:13:44 -07003141 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003142 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003143 char *param = audio_device_address_to_parameter(device, address);
3144 mpClientInterface->setParameters(output, String8(param));
3145 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003146 }
3147
Eric Laurentd4692962014-05-05 18:13:44 -07003148 // Here is where we step through and resolve any "dynamic" fields
3149 String8 reply;
3150 char *value;
3151 if (profile->mSamplingRates[0] == 0) {
3152 reply = mpClientInterface->getParameters(output,
3153 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003154 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003155 reply.string());
3156 value = strpbrk((char *)reply.string(), "=");
3157 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003158 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003159 }
Eric Laurentd4692962014-05-05 18:13:44 -07003160 }
3161 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3162 reply = mpClientInterface->getParameters(output,
3163 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003164 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003165 reply.string());
3166 value = strpbrk((char *)reply.string(), "=");
3167 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003168 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003169 }
Eric Laurentd4692962014-05-05 18:13:44 -07003170 }
3171 if (profile->mChannelMasks[0] == 0) {
3172 reply = mpClientInterface->getParameters(output,
3173 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003174 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003175 reply.string());
3176 value = strpbrk((char *)reply.string(), "=");
3177 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003178 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003179 }
Eric Laurentd4692962014-05-05 18:13:44 -07003180 }
3181 if (((profile->mSamplingRates[0] == 0) &&
3182 (profile->mSamplingRates.size() < 2)) ||
3183 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3184 (profile->mFormats.size() < 2)) ||
3185 ((profile->mChannelMasks[0] == 0) &&
3186 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003187 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003188 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003189 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003190 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3191 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003192 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003193 config.sample_rate = profile->pickSamplingRate();
3194 config.channel_mask = profile->pickChannelMask();
3195 config.format = profile->pickFormat();
3196 config.offload_info.sample_rate = config.sample_rate;
3197 config.offload_info.channel_mask = config.channel_mask;
3198 config.offload_info.format = config.format;
3199 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3200 &output,
3201 &config,
3202 &desc->mDevice,
3203 address,
3204 &desc->mLatency,
3205 desc->mFlags);
3206 if (status == NO_ERROR) {
3207 desc->mSamplingRate = config.sample_rate;
3208 desc->mChannelMask = config.channel_mask;
3209 desc->mFormat = config.format;
3210 } else {
3211 output = AUDIO_IO_HANDLE_NONE;
3212 }
Eric Laurentd4692962014-05-05 18:13:44 -07003213 }
3214
Eric Laurentcf2c0212014-07-25 16:20:43 -07003215 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003216 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003217 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003218 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003219
Eric Laurentd4692962014-05-05 18:13:44 -07003220 // set initial stream volume for device
3221 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003222
Eric Laurentd4692962014-05-05 18:13:44 -07003223 //TODO: configure audio effect output stage here
3224
3225 // open a duplicating output thread for the new output and the primary output
3226 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3227 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003228 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003229 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003230 sp<AudioOutputDescriptor> dupOutputDesc =
3231 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003232 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3233 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3234 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3235 dupOutputDesc->mFormat = desc->mFormat;
3236 dupOutputDesc->mChannelMask = desc->mChannelMask;
3237 dupOutputDesc->mLatency = desc->mLatency;
3238 addOutput(duplicatedOutput, dupOutputDesc);
3239 applyStreamVolumes(duplicatedOutput, device, 0, true);
3240 } else {
3241 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3242 mPrimaryOutput, output);
3243 mpClientInterface->closeOutput(output);
3244 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003245 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003246 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003247 }
Eric Laurente552edb2014-03-10 17:42:56 -07003248 }
3249 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003250 } else {
3251 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003252 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003253 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003254 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003255 profiles.removeAt(profile_index);
3256 profile_index--;
3257 } else {
3258 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003259 devDesc->importAudioPort(profile);
3260
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003261 if (deviceDistinguishesOnAddress(device)) {
3262 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3263 device, address.string());
3264 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3265 NULL/*patch handle*/, address.string());
3266 }
Eric Laurente552edb2014-03-10 17:42:56 -07003267 ALOGV("checkOutputsForDevice(): adding output %d", output);
3268 }
3269 }
3270
3271 if (profiles.isEmpty()) {
3272 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3273 return BAD_VALUE;
3274 }
Eric Laurentd4692962014-05-05 18:13:44 -07003275 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003276 // check if one opened output is not needed any more after disconnecting one device
3277 for (size_t i = 0; i < mOutputs.size(); i++) {
3278 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003279 if (!desc->isDuplicated()) {
3280 if (!(desc->mProfile->mSupportedDevices.types()
3281 & mAvailableOutputDevices.types())) {
3282 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3283 mOutputs.keyAt(i));
3284 outputs.add(mOutputs.keyAt(i));
3285 } else if (deviceDistinguishesOnAddress(device) &&
3286 // exact match on device
3287 (desc->mProfile->mSupportedDevices.types() == device)) {
3288 findIoHandlesByAddress(desc, address, outputs);
3289 }
Eric Laurente552edb2014-03-10 17:42:56 -07003290 }
3291 }
Eric Laurentd4692962014-05-05 18:13:44 -07003292 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003293 for (size_t i = 0; i < mHwModules.size(); i++)
3294 {
3295 if (mHwModules[i]->mHandle == 0) {
3296 continue;
3297 }
3298 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3299 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003300 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003301 if (profile->mSupportedDevices.types() & device) {
3302 ALOGV("checkOutputsForDevice(): "
3303 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003304 if (profile->mSamplingRates[0] == 0) {
3305 profile->mSamplingRates.clear();
3306 profile->mSamplingRates.add(0);
3307 }
3308 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3309 profile->mFormats.clear();
3310 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3311 }
3312 if (profile->mChannelMasks[0] == 0) {
3313 profile->mChannelMasks.clear();
3314 profile->mChannelMasks.add(0);
3315 }
3316 }
3317 }
3318 }
3319 }
3320 return NO_ERROR;
3321}
3322
Eric Laurentd4692962014-05-05 18:13:44 -07003323status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3324 audio_policy_dev_state_t state,
3325 SortedVector<audio_io_handle_t>& inputs,
3326 const String8 address)
3327{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003328 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003329 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3330 // first list already open inputs that can be routed to this device
3331 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3332 desc = mInputs.valueAt(input_index);
3333 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3334 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3335 inputs.add(mInputs.keyAt(input_index));
3336 }
3337 }
3338
3339 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003340 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003341 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3342 {
3343 if (mHwModules[module_idx]->mHandle == 0) {
3344 continue;
3345 }
3346 for (size_t profile_index = 0;
3347 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3348 profile_index++)
3349 {
3350 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3351 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003352 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003353 profile_index, module_idx);
3354 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3355 }
3356 }
3357 }
3358
3359 if (profiles.isEmpty() && inputs.isEmpty()) {
3360 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3361 return BAD_VALUE;
3362 }
3363
3364 // open inputs for matching profiles if needed. Direct inputs are also opened to
3365 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3366 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3367
Eric Laurent1c333e22014-05-20 10:48:17 -07003368 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003369 // nothing to do if one input is already opened for this profile
3370 size_t input_index;
3371 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3372 desc = mInputs.valueAt(input_index);
3373 if (desc->mProfile == profile) {
3374 break;
3375 }
3376 }
3377 if (input_index != mInputs.size()) {
3378 continue;
3379 }
3380
3381 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3382 desc = new AudioInputDescriptor(profile);
3383 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003384 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3385 config.sample_rate = desc->mSamplingRate;
3386 config.channel_mask = desc->mChannelMask;
3387 config.format = desc->mFormat;
3388 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3389 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3390 &input,
3391 &config,
3392 &desc->mDevice,
3393 address,
3394 AUDIO_SOURCE_MIC,
3395 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003396
Eric Laurentcf2c0212014-07-25 16:20:43 -07003397 if (status == NO_ERROR) {
3398 desc->mSamplingRate = config.sample_rate;
3399 desc->mChannelMask = config.channel_mask;
3400 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003401
Eric Laurentd4692962014-05-05 18:13:44 -07003402 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003403 char *param = audio_device_address_to_parameter(device, address);
3404 mpClientInterface->setParameters(input, String8(param));
3405 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003406 }
3407
3408 // Here is where we step through and resolve any "dynamic" fields
3409 String8 reply;
3410 char *value;
3411 if (profile->mSamplingRates[0] == 0) {
3412 reply = mpClientInterface->getParameters(input,
3413 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3414 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3415 reply.string());
3416 value = strpbrk((char *)reply.string(), "=");
3417 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003418 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003419 }
3420 }
3421 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3422 reply = mpClientInterface->getParameters(input,
3423 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3424 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3425 value = strpbrk((char *)reply.string(), "=");
3426 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003427 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003428 }
3429 }
3430 if (profile->mChannelMasks[0] == 0) {
3431 reply = mpClientInterface->getParameters(input,
3432 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3433 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3434 reply.string());
3435 value = strpbrk((char *)reply.string(), "=");
3436 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003437 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003438 }
3439 }
3440 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3441 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3442 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3443 ALOGW("checkInputsForDevice() direct input missing param");
3444 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003445 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003446 }
3447
3448 if (input != 0) {
3449 addInput(input, desc);
3450 }
3451 } // endif input != 0
3452
Eric Laurentcf2c0212014-07-25 16:20:43 -07003453 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003454 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003455 profiles.removeAt(profile_index);
3456 profile_index--;
3457 } else {
3458 inputs.add(input);
3459 ALOGV("checkInputsForDevice(): adding input %d", input);
3460 }
3461 } // end scan profiles
3462
3463 if (profiles.isEmpty()) {
3464 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3465 return BAD_VALUE;
3466 }
3467 } else {
3468 // Disconnect
3469 // check if one opened input is not needed any more after disconnecting one device
3470 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3471 desc = mInputs.valueAt(input_index);
3472 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3473 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3474 mInputs.keyAt(input_index));
3475 inputs.add(mInputs.keyAt(input_index));
3476 }
3477 }
3478 // Clear any profiles associated with the disconnected device.
3479 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3480 if (mHwModules[module_index]->mHandle == 0) {
3481 continue;
3482 }
3483 for (size_t profile_index = 0;
3484 profile_index < mHwModules[module_index]->mInputProfiles.size();
3485 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003486 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003487 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003488 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003489 profile_index, module_index);
3490 if (profile->mSamplingRates[0] == 0) {
3491 profile->mSamplingRates.clear();
3492 profile->mSamplingRates.add(0);
3493 }
3494 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3495 profile->mFormats.clear();
3496 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3497 }
3498 if (profile->mChannelMasks[0] == 0) {
3499 profile->mChannelMasks.clear();
3500 profile->mChannelMasks.add(0);
3501 }
3502 }
3503 }
3504 }
3505 } // end disconnect
3506
3507 return NO_ERROR;
3508}
3509
3510
Eric Laurente0720872014-03-11 09:30:41 -07003511void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003512{
3513 ALOGV("closeOutput(%d)", output);
3514
Eric Laurent1f2f2232014-06-02 12:01:23 -07003515 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003516 if (outputDesc == NULL) {
3517 ALOGW("closeOutput() unknown output %d", output);
3518 return;
3519 }
3520
3521 // look for duplicated outputs connected to the output being removed.
3522 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003523 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003524 if (dupOutputDesc->isDuplicated() &&
3525 (dupOutputDesc->mOutput1 == outputDesc ||
3526 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003527 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003528 if (dupOutputDesc->mOutput1 == outputDesc) {
3529 outputDesc2 = dupOutputDesc->mOutput2;
3530 } else {
3531 outputDesc2 = dupOutputDesc->mOutput1;
3532 }
3533 // As all active tracks on duplicated output will be deleted,
3534 // and as they were also referenced on the other output, the reference
3535 // count for their stream type must be adjusted accordingly on
3536 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003537 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003538 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003539 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003540 }
3541 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3542 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3543
3544 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003545 mOutputs.removeItem(duplicatedOutput);
3546 }
3547 }
3548
Eric Laurent05b90f82014-08-27 15:32:29 -07003549 nextAudioPortGeneration();
3550
3551 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3552 if (index >= 0) {
3553 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3554 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3555 mAudioPatches.removeItemsAt(index);
3556 mpClientInterface->onAudioPatchListUpdate();
3557 }
3558
Eric Laurente552edb2014-03-10 17:42:56 -07003559 AudioParameter param;
3560 param.add(String8("closing"), String8("true"));
3561 mpClientInterface->setParameters(output, param.toString());
3562
3563 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003564 mOutputs.removeItem(output);
3565 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003566}
3567
3568void AudioPolicyManager::closeInput(audio_io_handle_t input)
3569{
3570 ALOGV("closeInput(%d)", input);
3571
3572 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3573 if (inputDesc == NULL) {
3574 ALOGW("closeInput() unknown input %d", input);
3575 return;
3576 }
3577
Eric Laurent6a94d692014-05-20 11:18:06 -07003578 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003579
3580 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3581 if (index >= 0) {
3582 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3583 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3584 mAudioPatches.removeItemsAt(index);
3585 mpClientInterface->onAudioPatchListUpdate();
3586 }
3587
3588 mpClientInterface->closeInput(input);
3589 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003590}
3591
Eric Laurente0720872014-03-11 09:30:41 -07003592SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003593 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003594{
3595 SortedVector<audio_io_handle_t> outputs;
3596
3597 ALOGVV("getOutputsForDevice() device %04x", device);
3598 for (size_t i = 0; i < openOutputs.size(); i++) {
3599 ALOGVV("output %d isDuplicated=%d device=%04x",
3600 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3601 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3602 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3603 outputs.add(openOutputs.keyAt(i));
3604 }
3605 }
3606 return outputs;
3607}
3608
Eric Laurente0720872014-03-11 09:30:41 -07003609bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003610 SortedVector<audio_io_handle_t>& outputs2)
3611{
3612 if (outputs1.size() != outputs2.size()) {
3613 return false;
3614 }
3615 for (size_t i = 0; i < outputs1.size(); i++) {
3616 if (outputs1[i] != outputs2[i]) {
3617 return false;
3618 }
3619 }
3620 return true;
3621}
3622
Eric Laurente0720872014-03-11 09:30:41 -07003623void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003624{
3625 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3626 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3627 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3628 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3629
3630 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3631 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3632 strategy, srcOutputs[0], dstOutputs[0]);
3633 // mute strategy while moving tracks from one output to another
3634 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003635 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003636 if (desc->isStrategyActive(strategy)) {
3637 setStrategyMute(strategy, true, srcOutputs[i]);
3638 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3639 }
3640 }
3641
3642 // Move effects associated to this strategy from previous output to new output
3643 if (strategy == STRATEGY_MEDIA) {
3644 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3645 SortedVector<audio_io_handle_t> moved;
3646 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003647 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3648 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3649 effectDesc->mIo != fxOutput) {
3650 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003651 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3652 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003653 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003654 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003655 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003656 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003657 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003658 }
3659 }
3660 }
3661 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003662 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3663 if (getStrategy((audio_stream_type_t)i) == strategy) {
3664 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003665 }
3666 }
3667 }
3668}
3669
Eric Laurente0720872014-03-11 09:30:41 -07003670void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003671{
3672 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3673 checkOutputForStrategy(STRATEGY_PHONE);
3674 checkOutputForStrategy(STRATEGY_SONIFICATION);
3675 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3676 checkOutputForStrategy(STRATEGY_MEDIA);
3677 checkOutputForStrategy(STRATEGY_DTMF);
3678}
3679
Eric Laurente0720872014-03-11 09:30:41 -07003680audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003681{
Eric Laurente552edb2014-03-10 17:42:56 -07003682 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003683 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003684 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3685 return mOutputs.keyAt(i);
3686 }
3687 }
3688
3689 return 0;
3690}
3691
Eric Laurente0720872014-03-11 09:30:41 -07003692void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003693{
Eric Laurente552edb2014-03-10 17:42:56 -07003694 audio_io_handle_t a2dpOutput = getA2dpOutput();
3695 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003696 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003697 return;
3698 }
3699
Eric Laurent3a4311c2014-03-17 12:00:47 -07003700 bool isScoConnected =
3701 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003702 // suspend A2DP output if:
3703 // (NOT already suspended) &&
3704 // ((SCO device is connected &&
3705 // (forced usage for communication || for record is SCO))) ||
3706 // (phone state is ringing || in call)
3707 //
3708 // restore A2DP output if:
3709 // (Already suspended) &&
3710 // ((SCO device is NOT connected ||
3711 // (forced usage NOT for communication && NOT for record is SCO))) &&
3712 // (phone state is NOT ringing && NOT in call)
3713 //
3714 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003715 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003716 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3717 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3718 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3719 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003720
3721 mpClientInterface->restoreOutput(a2dpOutput);
3722 mA2dpSuspended = false;
3723 }
3724 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003725 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003726 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3727 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3728 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3729 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003730
3731 mpClientInterface->suspendOutput(a2dpOutput);
3732 mA2dpSuspended = true;
3733 }
3734 }
3735}
3736
Eric Laurent1c333e22014-05-20 10:48:17 -07003737audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003738{
3739 audio_devices_t device = AUDIO_DEVICE_NONE;
3740
Eric Laurent1f2f2232014-06-02 12:01:23 -07003741 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003742
3743 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3744 if (index >= 0) {
3745 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3746 if (patchDesc->mUid != mUidCached) {
3747 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3748 outputDesc->device(), outputDesc->mPatchHandle);
3749 return outputDesc->device();
3750 }
3751 }
3752
Eric Laurente552edb2014-03-10 17:42:56 -07003753 // check the following by order of priority to request a routing change if necessary:
3754 // 1: the strategy enforced audible is active on the output:
3755 // use device for strategy enforced audible
3756 // 2: we are in call or the strategy phone is active on the output:
3757 // use device for strategy phone
3758 // 3: the strategy sonification is active on the output:
3759 // use device for strategy sonification
3760 // 4: the strategy "respectful" sonification is active on the output:
3761 // use device for strategy "respectful" sonification
3762 // 5: the strategy media is active on the output:
3763 // use device for strategy media
3764 // 6: the strategy DTMF is active on the output:
3765 // use device for strategy DTMF
3766 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3767 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3768 } else if (isInCall() ||
3769 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3770 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3771 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3772 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3773 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3774 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3775 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3776 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3777 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3778 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3779 }
3780
Eric Laurent1c333e22014-05-20 10:48:17 -07003781 ALOGV("getNewOutputDevice() selected device %x", device);
3782 return device;
3783}
3784
3785audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3786{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003787 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003788
3789 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3790 if (index >= 0) {
3791 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3792 if (patchDesc->mUid != mUidCached) {
3793 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3794 inputDesc->mDevice, inputDesc->mPatchHandle);
3795 return inputDesc->mDevice;
3796 }
3797 }
3798
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3800
3801 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003802 return device;
3803}
3804
Eric Laurente0720872014-03-11 09:30:41 -07003805uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003806 return (uint32_t)getStrategy(stream);
3807}
3808
Eric Laurente0720872014-03-11 09:30:41 -07003809audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003810 // By checking the range of stream before calling getStrategy, we avoid
3811 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3812 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003813 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003814 return AUDIO_DEVICE_NONE;
3815 }
3816 audio_devices_t devices;
3817 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3818 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3819 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3820 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003821 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003822 if (outputDesc->isStrategyActive(strategy)) {
3823 devices = outputDesc->device();
3824 break;
3825 }
Eric Laurente552edb2014-03-10 17:42:56 -07003826 }
3827 return devices;
3828}
3829
Eric Laurente0720872014-03-11 09:30:41 -07003830AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003831 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003832 // stream to strategy mapping
3833 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003834 case AUDIO_STREAM_VOICE_CALL:
3835 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003836 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003837 case AUDIO_STREAM_RING:
3838 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003839 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003840 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003841 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003842 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003843 return STRATEGY_DTMF;
3844 default:
3845 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003846 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003847 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3848 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003849 case AUDIO_STREAM_TTS:
3850 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003851 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003852 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003853 return STRATEGY_ENFORCED_AUDIBLE;
3854 }
3855}
3856
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003857uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3858 // flags to strategy mapping
3859 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3860 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3861 }
3862
3863 // usage to strategy mapping
3864 switch (attr->usage) {
3865 case AUDIO_USAGE_MEDIA:
3866 case AUDIO_USAGE_GAME:
3867 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3868 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3869 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3870 return (uint32_t) STRATEGY_MEDIA;
3871
3872 case AUDIO_USAGE_VOICE_COMMUNICATION:
3873 return (uint32_t) STRATEGY_PHONE;
3874
3875 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3876 return (uint32_t) STRATEGY_DTMF;
3877
3878 case AUDIO_USAGE_ALARM:
3879 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3880 return (uint32_t) STRATEGY_SONIFICATION;
3881
3882 case AUDIO_USAGE_NOTIFICATION:
3883 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3884 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3885 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3886 case AUDIO_USAGE_NOTIFICATION_EVENT:
3887 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3888
3889 case AUDIO_USAGE_UNKNOWN:
3890 default:
3891 return (uint32_t) STRATEGY_MEDIA;
3892 }
3893}
3894
Eric Laurente0720872014-03-11 09:30:41 -07003895void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003896 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003897 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003898 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3899 updateDevicesAndOutputs();
3900 break;
3901 default:
3902 break;
3903 }
3904}
3905
Eric Laurente0720872014-03-11 09:30:41 -07003906audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003907 bool fromCache)
3908{
3909 uint32_t device = AUDIO_DEVICE_NONE;
3910
3911 if (fromCache) {
3912 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3913 strategy, mDeviceForStrategy[strategy]);
3914 return mDeviceForStrategy[strategy];
3915 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003916 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003917 switch (strategy) {
3918
3919 case STRATEGY_SONIFICATION_RESPECTFUL:
3920 if (isInCall()) {
3921 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003923 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3924 // while media is playing on a remote device, use the the sonification behavior.
3925 // Note that we test this usecase before testing if media is playing because
3926 // the isStreamActive() method only informs about the activity of a stream, not
3927 // if it's for local playback. Note also that we use the same delay between both tests
3928 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003929 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003930 // while media is playing (or has recently played), use the same device
3931 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3932 } else {
3933 // when media is not playing anymore, fall back on the sonification behavior
3934 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3935 }
3936
3937 break;
3938
3939 case STRATEGY_DTMF:
3940 if (!isInCall()) {
3941 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3942 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3943 break;
3944 }
3945 // when in call, DTMF and PHONE strategies follow the same rules
3946 // FALL THROUGH
3947
3948 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003949 // Force use of only devices on primary output if:
3950 // - in call AND
3951 // - cannot route from voice call RX OR
3952 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3953 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3954 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3955 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3956 if (((mAvailableInputDevices.types() &
3957 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3958 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07003959 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07003960 AUDIO_DEVICE_API_VERSION_3_0))) {
3961 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3962 }
3963 }
Eric Laurente552edb2014-03-10 17:42:56 -07003964 // for phone strategy, we first consider the forced use and then the available devices by order
3965 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003966 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3967 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003968 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003969 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003970 if (device) break;
3971 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003972 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003973 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003974 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003975 if (device) break;
3976 // if SCO device is requested but no SCO device is available, fall back to default case
3977 // FALL THROUGH
3978
3979 default: // FORCE_NONE
3980 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003981 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003982 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003983 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003984 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003985 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003986 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003987 if (device) break;
3988 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003989 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003990 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003991 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003992 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07003993 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3994 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003995 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003996 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003997 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003998 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003999 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004000 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004001 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004002 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004003 if (device) break;
4004 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004005 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004006 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004007 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004008 if (device == AUDIO_DEVICE_NONE) {
4009 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4010 }
4011 break;
4012
Eric Laurent3b73df72014-03-11 09:06:29 -07004013 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004014 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4015 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004016 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004017 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004018 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004019 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004020 if (device) break;
4021 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004022 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004023 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004024 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004025 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004026 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004027 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004028 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004029 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004030 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004031 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004032 if (device) break;
4033 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004034 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4035 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004036 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004037 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004038 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004039 if (device == AUDIO_DEVICE_NONE) {
4040 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4041 }
4042 break;
4043 }
4044 break;
4045
4046 case STRATEGY_SONIFICATION:
4047
4048 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4049 // handleIncallSonification().
4050 if (isInCall()) {
4051 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4052 break;
4053 }
4054 // FALL THROUGH
4055
4056 case STRATEGY_ENFORCED_AUDIBLE:
4057 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4058 // except:
4059 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4060 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4061
4062 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004063 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004065 if (device == AUDIO_DEVICE_NONE) {
4066 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4067 }
4068 }
4069 // The second device used for sonification is the same as the device used by media strategy
4070 // FALL THROUGH
4071
4072 case STRATEGY_MEDIA: {
4073 uint32_t device2 = AUDIO_DEVICE_NONE;
4074 if (strategy != STRATEGY_SONIFICATION) {
4075 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004077 }
4078 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004079 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004080 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004082 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004083 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
4085 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004087 }
4088 }
4089 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004090 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004091 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004092 if ((device2 == AUDIO_DEVICE_NONE)) {
4093 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4094 }
Eric Laurente552edb2014-03-10 17:42:56 -07004095 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004096 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004097 }
4098 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004099 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004100 }
4101 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004102 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004103 }
4104 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004105 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004106 }
4107 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4108 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004109 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004110 }
4111 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004112 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004114 }
4115 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004116 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004117 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004118 int device3 = AUDIO_DEVICE_NONE;
4119 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004120 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004121 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4122 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004123 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004124 }
Eric Laurente552edb2014-03-10 17:42:56 -07004125
Jungshik Jang839e4f32014-06-26 17:23:40 +09004126 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004127 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4128 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4129 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004130
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004131 // If hdmi system audio mode is on, remove speaker out of output list.
4132 if ((strategy == STRATEGY_MEDIA) &&
4133 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4134 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4135 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4136 }
4137
Eric Laurente552edb2014-03-10 17:42:56 -07004138 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004139 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004140 if (device == AUDIO_DEVICE_NONE) {
4141 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4142 }
4143 } break;
4144
4145 default:
4146 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4147 break;
4148 }
4149
4150 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4151 return device;
4152}
4153
Eric Laurente0720872014-03-11 09:30:41 -07004154void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004155{
4156 for (int i = 0; i < NUM_STRATEGIES; i++) {
4157 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4158 }
4159 mPreviousOutputs = mOutputs;
4160}
4161
Eric Laurent1f2f2232014-06-02 12:01:23 -07004162uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004163 audio_devices_t prevDevice,
4164 uint32_t delayMs)
4165{
4166 // mute/unmute strategies using an incompatible device combination
4167 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4168 // if unmuting, unmute only after the specified delay
4169 if (outputDesc->isDuplicated()) {
4170 return 0;
4171 }
4172
4173 uint32_t muteWaitMs = 0;
4174 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004175 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004176
4177 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4178 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4179 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4180 bool doMute = false;
4181
4182 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4183 doMute = true;
4184 outputDesc->mStrategyMutedByDevice[i] = true;
4185 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4186 doMute = true;
4187 outputDesc->mStrategyMutedByDevice[i] = false;
4188 }
Eric Laurent99401132014-05-07 19:48:15 -07004189 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004190 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004191 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004192 // skip output if it does not share any device with current output
4193 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4194 == AUDIO_DEVICE_NONE) {
4195 continue;
4196 }
4197 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4198 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4199 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4200 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4201 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004202 if (mute) {
4203 // FIXME: should not need to double latency if volume could be applied
4204 // immediately by the audioflinger mixer. We must account for the delay
4205 // between now and the next time the audioflinger thread for this output
4206 // will process a buffer (which corresponds to one buffer size,
4207 // usually 1/2 or 1/4 of the latency).
4208 if (muteWaitMs < desc->latency() * 2) {
4209 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004210 }
4211 }
4212 }
4213 }
4214 }
4215 }
4216
Eric Laurent99401132014-05-07 19:48:15 -07004217 // temporary mute output if device selection changes to avoid volume bursts due to
4218 // different per device volumes
4219 if (outputDesc->isActive() && (device != prevDevice)) {
4220 if (muteWaitMs < outputDesc->latency() * 2) {
4221 muteWaitMs = outputDesc->latency() * 2;
4222 }
4223 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4224 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004225 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004226 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004227 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004228 muteWaitMs *2, device);
4229 }
4230 }
4231 }
4232
Eric Laurente552edb2014-03-10 17:42:56 -07004233 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4234 if (muteWaitMs > delayMs) {
4235 muteWaitMs -= delayMs;
4236 usleep(muteWaitMs * 1000);
4237 return muteWaitMs;
4238 }
4239 return 0;
4240}
4241
Eric Laurente0720872014-03-11 09:30:41 -07004242uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004243 audio_devices_t device,
4244 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004245 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004246 audio_patch_handle_t *patchHandle,
4247 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004248{
4249 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004250 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004251 AudioParameter param;
4252 uint32_t muteWaitMs;
4253
4254 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004255 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4256 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004257 return muteWaitMs;
4258 }
4259 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4260 // output profile
4261 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004262 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004263 return 0;
4264 }
4265
4266 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004267 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004268
4269 audio_devices_t prevDevice = outputDesc->mDevice;
4270
4271 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4272
4273 if (device != AUDIO_DEVICE_NONE) {
4274 outputDesc->mDevice = device;
4275 }
4276 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4277
4278 // Do not change the routing if:
4279 // - the requested device is AUDIO_DEVICE_NONE
4280 // - the requested device is the same as current device and force is not specified.
4281 // Doing this check here allows the caller to call setOutputDevice() without conditions
4282 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4283 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4284 return muteWaitMs;
4285 }
4286
4287 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004288
Eric Laurente552edb2014-03-10 17:42:56 -07004289 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004290 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004291 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004292 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004293 DeviceVector deviceList = (address == NULL) ?
4294 mAvailableOutputDevices.getDevicesFromType(device)
4295 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004296 if (!deviceList.isEmpty()) {
4297 struct audio_patch patch;
4298 outputDesc->toAudioPortConfig(&patch.sources[0]);
4299 patch.num_sources = 1;
4300 patch.num_sinks = 0;
4301 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4302 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004303 patch.num_sinks++;
4304 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004305 ssize_t index;
4306 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4307 index = mAudioPatches.indexOfKey(*patchHandle);
4308 } else {
4309 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4310 }
4311 sp< AudioPatch> patchDesc;
4312 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4313 if (index >= 0) {
4314 patchDesc = mAudioPatches.valueAt(index);
4315 afPatchHandle = patchDesc->mAfPatchHandle;
4316 }
4317
Eric Laurent1c333e22014-05-20 10:48:17 -07004318 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004319 &afPatchHandle,
4320 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004321 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4322 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004324 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004325 if (index < 0) {
4326 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4327 &patch, mUidCached);
4328 addAudioPatch(patchDesc->mHandle, patchDesc);
4329 } else {
4330 patchDesc->mPatch = patch;
4331 }
4332 patchDesc->mAfPatchHandle = afPatchHandle;
4333 patchDesc->mUid = mUidCached;
4334 if (patchHandle) {
4335 *patchHandle = patchDesc->mHandle;
4336 }
4337 outputDesc->mPatchHandle = patchDesc->mHandle;
4338 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004339 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004340 }
4341 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004342
4343 // inform all input as well
4344 for (size_t i = 0; i < mInputs.size(); i++) {
4345 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4346 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4347 AudioParameter inputCmd = AudioParameter();
4348 ALOGV("%s: inform input %d of device:%d", __func__,
4349 inputDescriptor->mIoHandle, device);
4350 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4351 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4352 inputCmd.toString(),
4353 delayMs);
4354 }
4355 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004356 }
Eric Laurente552edb2014-03-10 17:42:56 -07004357
4358 // update stream volumes according to new device
4359 applyStreamVolumes(output, device, delayMs);
4360
4361 return muteWaitMs;
4362}
4363
Eric Laurent1c333e22014-05-20 10:48:17 -07004364status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004365 int delayMs,
4366 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004367{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004368 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004369 ssize_t index;
4370 if (patchHandle) {
4371 index = mAudioPatches.indexOfKey(*patchHandle);
4372 } else {
4373 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4374 }
4375 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004376 return INVALID_OPERATION;
4377 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004378 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4379 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004380 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4381 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004382 removeAudioPatch(patchDesc->mHandle);
4383 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004384 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004385 return status;
4386}
4387
4388status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4389 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004390 bool force,
4391 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004392{
4393 status_t status = NO_ERROR;
4394
Eric Laurent1f2f2232014-06-02 12:01:23 -07004395 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004396 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4397 inputDesc->mDevice = device;
4398
4399 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4400 if (!deviceList.isEmpty()) {
4401 struct audio_patch patch;
4402 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004403 // AUDIO_SOURCE_HOTWORD is for internal use only:
4404 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004405 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4406 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004407 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4408 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004409 patch.num_sinks = 1;
4410 //only one input device for now
4411 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004412 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004413 ssize_t index;
4414 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4415 index = mAudioPatches.indexOfKey(*patchHandle);
4416 } else {
4417 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4418 }
4419 sp< AudioPatch> patchDesc;
4420 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4421 if (index >= 0) {
4422 patchDesc = mAudioPatches.valueAt(index);
4423 afPatchHandle = patchDesc->mAfPatchHandle;
4424 }
4425
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004427 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004428 0);
4429 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004430 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004431 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 if (index < 0) {
4433 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4434 &patch, mUidCached);
4435 addAudioPatch(patchDesc->mHandle, patchDesc);
4436 } else {
4437 patchDesc->mPatch = patch;
4438 }
4439 patchDesc->mAfPatchHandle = afPatchHandle;
4440 patchDesc->mUid = mUidCached;
4441 if (patchHandle) {
4442 *patchHandle = patchDesc->mHandle;
4443 }
4444 inputDesc->mPatchHandle = patchDesc->mHandle;
4445 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004446 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004447 }
4448 }
4449 }
4450 return status;
4451}
4452
Eric Laurent6a94d692014-05-20 11:18:06 -07004453status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4454 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004455{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004456 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 ssize_t index;
4458 if (patchHandle) {
4459 index = mAudioPatches.indexOfKey(*patchHandle);
4460 } else {
4461 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4462 }
4463 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004464 return INVALID_OPERATION;
4465 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4467 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004468 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4469 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 removeAudioPatch(patchDesc->mHandle);
4471 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004472 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004473 return status;
4474}
4475
4476sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004477 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004478 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004479 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004480 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004481{
4482 // Choose an input profile based on the requested capture parameters: select the first available
4483 // profile supporting all requested parameters.
4484
4485 for (size_t i = 0; i < mHwModules.size(); i++)
4486 {
4487 if (mHwModules[i]->mHandle == 0) {
4488 continue;
4489 }
4490 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4491 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004492 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004493 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004494 if (profile->isCompatibleProfile(device, samplingRate,
4495 &samplingRate /*updatedSamplingRate*/,
4496 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004497 return profile;
4498 }
4499 }
4500 }
4501 return NULL;
4502}
4503
Eric Laurente0720872014-03-11 09:30:41 -07004504audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004505{
4506 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004507 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4508 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004509 switch (inputSource) {
4510 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004511 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004512 device = AUDIO_DEVICE_IN_VOICE_CALL;
4513 break;
4514 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004515 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004516
4517 case AUDIO_SOURCE_DEFAULT:
4518 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004519 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4520 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004521 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4522 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4523 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4524 device = AUDIO_DEVICE_IN_USB_DEVICE;
4525 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4526 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004527 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004528 break;
4529
4530 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4531 // Allow only use of devices on primary input if in call and HAL does not support routing
4532 // to voice call path.
4533 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4534 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4535 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4536 }
4537
4538 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4539 case AUDIO_POLICY_FORCE_BT_SCO:
4540 // if SCO device is requested but no SCO device is available, fall back to default case
4541 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4542 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4543 break;
4544 }
4545 // FALL THROUGH
4546
4547 default: // FORCE_NONE
4548 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4549 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4550 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4551 device = AUDIO_DEVICE_IN_USB_DEVICE;
4552 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4553 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4554 }
4555 break;
4556
4557 case AUDIO_POLICY_FORCE_SPEAKER:
4558 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4559 device = AUDIO_DEVICE_IN_BACK_MIC;
4560 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4561 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4562 }
4563 break;
4564 }
4565 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004566
Eric Laurente552edb2014-03-10 17:42:56 -07004567 case AUDIO_SOURCE_VOICE_RECOGNITION:
4568 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004569 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004571 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004573 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004574 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4575 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004576 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004577 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4578 }
4579 break;
4580 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004581 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004582 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004584 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4585 }
4586 break;
4587 case AUDIO_SOURCE_VOICE_DOWNLINK:
4588 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004589 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004590 device = AUDIO_DEVICE_IN_VOICE_CALL;
4591 }
4592 break;
4593 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004594 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004595 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4596 }
4597 break;
4598 default:
4599 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4600 break;
4601 }
4602 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4603 return device;
4604}
4605
Eric Laurente0720872014-03-11 09:30:41 -07004606bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004607{
4608 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4609 device &= ~AUDIO_DEVICE_BIT_IN;
4610 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4611 return true;
4612 }
4613 return false;
4614}
4615
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004616bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4617 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4618}
4619
Eric Laurente0720872014-03-11 09:30:41 -07004620audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004621{
4622 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004623 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004624 if ((input_descriptor->mRefCount > 0)
4625 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4626 return mInputs.keyAt(i);
4627 }
4628 }
4629 return 0;
4630}
4631
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004632uint32_t AudioPolicyManager::activeInputsCount() const
4633{
4634 uint32_t count = 0;
4635 for (size_t i = 0; i < mInputs.size(); i++) {
4636 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4637 if (desc->mRefCount > 0) {
4638 return count++;
4639 }
4640 }
4641 return count;
4642}
4643
Eric Laurente552edb2014-03-10 17:42:56 -07004644
Eric Laurente0720872014-03-11 09:30:41 -07004645audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004646{
4647 if (device == AUDIO_DEVICE_NONE) {
4648 // this happens when forcing a route update and no track is active on an output.
4649 // In this case the returned category is not important.
4650 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004651 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004652 // Multiple device selection is either:
4653 // - speaker + one other device: give priority to speaker in this case.
4654 // - one A2DP device + another device: happens with duplicated output. In this case
4655 // retain the device on the A2DP output as the other must not correspond to an active
4656 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004657 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004658 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4659 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004660 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4661 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4662 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4663 device = AUDIO_DEVICE_OUT_AUX_LINE;
4664 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4665 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004666 } else {
4667 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4668 }
4669 }
4670
Eric Laurent3b73df72014-03-11 09:06:29 -07004671 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004672 "getDeviceForVolume() invalid device combination: %08x",
4673 device);
4674
4675 return device;
4676}
4677
Eric Laurente0720872014-03-11 09:30:41 -07004678AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004679{
4680 switch(getDeviceForVolume(device)) {
4681 case AUDIO_DEVICE_OUT_EARPIECE:
4682 return DEVICE_CATEGORY_EARPIECE;
4683 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4684 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4685 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4686 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4687 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4688 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4689 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004690 case AUDIO_DEVICE_OUT_LINE:
4691 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4692 /*USB? Remote submix?*/
4693 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004694 case AUDIO_DEVICE_OUT_SPEAKER:
4695 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4696 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004697 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4698 case AUDIO_DEVICE_OUT_USB_DEVICE:
4699 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4700 default:
4701 return DEVICE_CATEGORY_SPEAKER;
4702 }
4703}
4704
Eric Laurente0720872014-03-11 09:30:41 -07004705float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004706 int indexInUi)
4707{
4708 device_category deviceCategory = getDeviceCategory(device);
4709 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4710
4711 // the volume index in the UI is relative to the min and max volume indices for this stream type
4712 int nbSteps = 1 + curve[VOLMAX].mIndex -
4713 curve[VOLMIN].mIndex;
4714 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4715 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4716
4717 // find what part of the curve this index volume belongs to, or if it's out of bounds
4718 int segment = 0;
4719 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4720 return 0.0f;
4721 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4722 segment = 0;
4723 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4724 segment = 1;
4725 } else if (volIdx <= curve[VOLMAX].mIndex) {
4726 segment = 2;
4727 } else { // out of bounds
4728 return 1.0f;
4729 }
4730
4731 // linear interpolation in the attenuation table in dB
4732 float decibels = curve[segment].mDBAttenuation +
4733 ((float)(volIdx - curve[segment].mIndex)) *
4734 ( (curve[segment+1].mDBAttenuation -
4735 curve[segment].mDBAttenuation) /
4736 ((float)(curve[segment+1].mIndex -
4737 curve[segment].mIndex)) );
4738
4739 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4740
4741 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4742 curve[segment].mIndex, volIdx,
4743 curve[segment+1].mIndex,
4744 curve[segment].mDBAttenuation,
4745 decibels,
4746 curve[segment+1].mDBAttenuation,
4747 amplification);
4748
4749 return amplification;
4750}
4751
Eric Laurente0720872014-03-11 09:30:41 -07004752const AudioPolicyManager::VolumeCurvePoint
4753 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004754 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4755};
4756
Eric Laurente0720872014-03-11 09:30:41 -07004757const AudioPolicyManager::VolumeCurvePoint
4758 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004759 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4760};
4761
Eric Laurente0720872014-03-11 09:30:41 -07004762const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004763 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4764 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4765};
4766
4767const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004768 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004769 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4770};
4771
Eric Laurente0720872014-03-11 09:30:41 -07004772const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004773 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004774 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004775};
4776
4777const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004778 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004779 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4780};
4781
Eric Laurente0720872014-03-11 09:30:41 -07004782const AudioPolicyManager::VolumeCurvePoint
4783 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004784 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4785};
4786
4787// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4788// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4789// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4790// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4791
Eric Laurente0720872014-03-11 09:30:41 -07004792const AudioPolicyManager::VolumeCurvePoint
4793 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004794 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4795};
4796
Eric Laurente0720872014-03-11 09:30:41 -07004797const AudioPolicyManager::VolumeCurvePoint
4798 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004799 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4800};
4801
Eric Laurente0720872014-03-11 09:30:41 -07004802const AudioPolicyManager::VolumeCurvePoint
4803 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004804 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4805};
4806
Eric Laurente0720872014-03-11 09:30:41 -07004807const AudioPolicyManager::VolumeCurvePoint
4808 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004809 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4810};
4811
Eric Laurente0720872014-03-11 09:30:41 -07004812const AudioPolicyManager::VolumeCurvePoint
4813 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004814 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4815};
4816
Eric Laurente0720872014-03-11 09:30:41 -07004817const AudioPolicyManager::VolumeCurvePoint
4818 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4819 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004820 { // AUDIO_STREAM_VOICE_CALL
4821 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4822 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004823 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4824 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004825 },
4826 { // AUDIO_STREAM_SYSTEM
4827 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4828 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004829 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4830 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004831 },
4832 { // AUDIO_STREAM_RING
4833 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4834 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004835 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4836 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004837 },
4838 { // AUDIO_STREAM_MUSIC
4839 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4840 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004841 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4842 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004843 },
4844 { // AUDIO_STREAM_ALARM
4845 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4846 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004847 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4848 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004849 },
4850 { // AUDIO_STREAM_NOTIFICATION
4851 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4852 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004853 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4854 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004855 },
4856 { // AUDIO_STREAM_BLUETOOTH_SCO
4857 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4858 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004859 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4860 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004861 },
4862 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4863 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4864 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004865 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4866 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004867 },
4868 { // AUDIO_STREAM_DTMF
4869 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4870 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004871 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4872 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004873 },
4874 { // AUDIO_STREAM_TTS
4875 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4876 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004877 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4878 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004879 },
4880};
4881
Eric Laurente0720872014-03-11 09:30:41 -07004882void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004883{
4884 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4885 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4886 mStreams[i].mVolumeCurve[j] =
4887 sVolumeProfiles[i][j];
4888 }
4889 }
4890
4891 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4892 if (mSpeakerDrcEnabled) {
4893 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4894 sDefaultSystemVolumeCurveDrc;
4895 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4896 sSpeakerSonificationVolumeCurveDrc;
4897 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4898 sSpeakerSonificationVolumeCurveDrc;
4899 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4900 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004901 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4902 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004903 }
4904}
4905
Eric Laurente0720872014-03-11 09:30:41 -07004906float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004907 int index,
4908 audio_io_handle_t output,
4909 audio_devices_t device)
4910{
4911 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004912 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004913 StreamDescriptor &streamDesc = mStreams[stream];
4914
4915 if (device == AUDIO_DEVICE_NONE) {
4916 device = outputDesc->device();
4917 }
4918
Eric Laurente552edb2014-03-10 17:42:56 -07004919 volume = volIndexToAmpl(device, streamDesc, index);
4920
4921 // if a headset is connected, apply the following rules to ring tones and notifications
4922 // to avoid sound level bursts in user's ears:
4923 // - always attenuate ring tones and notifications volume by 6dB
4924 // - if music is playing, always limit the volume to current music volume,
4925 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004926 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004927 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4928 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4929 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4930 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4931 ((stream_strategy == STRATEGY_SONIFICATION)
4932 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004933 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004934 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004935 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004936 streamDesc.mCanBeMuted) {
4937 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4938 // when the phone is ringing we must consider that music could have been paused just before
4939 // by the music application and behave as if music was active if the last music track was
4940 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004941 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004942 mLimitRingtoneVolume) {
4943 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004944 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4945 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004946 output,
4947 musicDevice);
4948 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4949 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4950 if (volume > minVol) {
4951 volume = minVol;
4952 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4953 }
4954 }
4955 }
4956
4957 return volume;
4958}
4959
Eric Laurente0720872014-03-11 09:30:41 -07004960status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004961 int index,
4962 audio_io_handle_t output,
4963 audio_devices_t device,
4964 int delayMs,
4965 bool force)
4966{
4967
4968 // do not change actual stream volume if the stream is muted
4969 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4970 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4971 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4972 return NO_ERROR;
4973 }
4974
4975 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004976 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4977 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4978 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4979 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004980 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004981 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004982 return INVALID_OPERATION;
4983 }
4984
4985 float volume = computeVolume(stream, index, output, device);
4986 // We actually change the volume if:
4987 // - the float value returned by computeVolume() changed
4988 // - the force flag is set
4989 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4990 force) {
4991 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4992 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4993 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4994 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004995 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4996 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004997 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004998 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004999 }
5000
Eric Laurent3b73df72014-03-11 09:06:29 -07005001 if (stream == AUDIO_STREAM_VOICE_CALL ||
5002 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005003 float voiceVolume;
5004 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005005 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005006 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5007 } else {
5008 voiceVolume = 1.0;
5009 }
5010
5011 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5012 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5013 mLastVoiceVolume = voiceVolume;
5014 }
5015 }
5016
5017 return NO_ERROR;
5018}
5019
Eric Laurente0720872014-03-11 09:30:41 -07005020void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005021 audio_devices_t device,
5022 int delayMs,
5023 bool force)
5024{
5025 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5026
Eric Laurent3b73df72014-03-11 09:06:29 -07005027 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5028 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005029 mStreams[stream].getVolumeIndex(device),
5030 output,
5031 device,
5032 delayMs,
5033 force);
5034 }
5035}
5036
Eric Laurente0720872014-03-11 09:30:41 -07005037void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005038 bool on,
5039 audio_io_handle_t output,
5040 int delayMs,
5041 audio_devices_t device)
5042{
5043 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005044 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5045 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5046 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005047 }
5048 }
5049}
5050
Eric Laurente0720872014-03-11 09:30:41 -07005051void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005052 bool on,
5053 audio_io_handle_t output,
5054 int delayMs,
5055 audio_devices_t device)
5056{
5057 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005058 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005059 if (device == AUDIO_DEVICE_NONE) {
5060 device = outputDesc->device();
5061 }
5062
5063 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5064 stream, on, output, outputDesc->mMuteCount[stream], device);
5065
5066 if (on) {
5067 if (outputDesc->mMuteCount[stream] == 0) {
5068 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005069 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5070 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005071 checkAndSetVolume(stream, 0, output, device, delayMs);
5072 }
5073 }
5074 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5075 outputDesc->mMuteCount[stream]++;
5076 } else {
5077 if (outputDesc->mMuteCount[stream] == 0) {
5078 ALOGV("setStreamMute() unmuting non muted stream!");
5079 return;
5080 }
5081 if (--outputDesc->mMuteCount[stream] == 0) {
5082 checkAndSetVolume(stream,
5083 streamDesc.getVolumeIndex(device),
5084 output,
5085 device,
5086 delayMs);
5087 }
5088 }
5089}
5090
Eric Laurente0720872014-03-11 09:30:41 -07005091void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005092 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005093{
5094 // if the stream pertains to sonification strategy and we are in call we must
5095 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5096 // in the device used for phone strategy and play the tone if the selected device does not
5097 // interfere with the device used for phone strategy
5098 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5099 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005100 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005101 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5102 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005103 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005104 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5105 stream, starting, outputDesc->mDevice, stateChange);
5106 if (outputDesc->mRefCount[stream]) {
5107 int muteCount = 1;
5108 if (stateChange) {
5109 muteCount = outputDesc->mRefCount[stream];
5110 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005111 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005112 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5113 for (int i = 0; i < muteCount; i++) {
5114 setStreamMute(stream, starting, mPrimaryOutput);
5115 }
5116 } else {
5117 ALOGV("handleIncallSonification() high visibility");
5118 if (outputDesc->device() &
5119 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5120 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5121 for (int i = 0; i < muteCount; i++) {
5122 setStreamMute(stream, starting, mPrimaryOutput);
5123 }
5124 }
5125 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005126 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5127 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005128 } else {
5129 mpClientInterface->stopTone();
5130 }
5131 }
5132 }
5133 }
5134}
5135
Eric Laurente0720872014-03-11 09:30:41 -07005136bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005137{
5138 return isStateInCall(mPhoneState);
5139}
5140
Eric Laurente0720872014-03-11 09:30:41 -07005141bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005142 return ((state == AUDIO_MODE_IN_CALL) ||
5143 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005144}
5145
Eric Laurente0720872014-03-11 09:30:41 -07005146uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005147{
5148 return MAX_EFFECTS_CPU_LOAD;
5149}
5150
Eric Laurente0720872014-03-11 09:30:41 -07005151uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005152{
5153 return MAX_EFFECTS_MEMORY;
5154}
5155
Eric Laurent6a94d692014-05-20 11:18:06 -07005156
Eric Laurente552edb2014-03-10 17:42:56 -07005157// --- AudioOutputDescriptor class implementation
5158
Eric Laurente0720872014-03-11 09:30:41 -07005159AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005160 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005161 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005162 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005163 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5164{
5165 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005166 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005167 mRefCount[i] = 0;
5168 mCurVolume[i] = -1.0;
5169 mMuteCount[i] = 0;
5170 mStopTime[i] = 0;
5171 }
5172 for (int i = 0; i < NUM_STRATEGIES; i++) {
5173 mStrategyMutedByDevice[i] = false;
5174 }
5175 if (profile != NULL) {
Eric Laurentd8622372014-07-27 13:47:31 -07005176 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005177 mSamplingRate = profile->pickSamplingRate();
5178 mFormat = profile->pickFormat();
5179 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005180 if (profile->mGains.size() > 0) {
5181 profile->mGains[0]->getDefaultConfig(&mGain);
5182 }
Eric Laurente552edb2014-03-10 17:42:56 -07005183 }
5184}
5185
Eric Laurente0720872014-03-11 09:30:41 -07005186audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005187{
5188 if (isDuplicated()) {
5189 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5190 } else {
5191 return mDevice;
5192 }
5193}
5194
Eric Laurente0720872014-03-11 09:30:41 -07005195uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005196{
5197 if (isDuplicated()) {
5198 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5199 } else {
5200 return mLatency;
5201 }
5202}
5203
Eric Laurente0720872014-03-11 09:30:41 -07005204bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005205 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005206{
5207 if (isDuplicated()) {
5208 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5209 } else if (outputDesc->isDuplicated()){
5210 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5211 } else {
5212 return (mProfile->mModule == outputDesc->mProfile->mModule);
5213 }
5214}
5215
Eric Laurente0720872014-03-11 09:30:41 -07005216void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005217 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005218{
5219 // forward usage count change to attached outputs
5220 if (isDuplicated()) {
5221 mOutput1->changeRefCount(stream, delta);
5222 mOutput2->changeRefCount(stream, delta);
5223 }
5224 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005225 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5226 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005227 mRefCount[stream] = 0;
5228 return;
5229 }
5230 mRefCount[stream] += delta;
5231 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5232}
5233
Eric Laurente0720872014-03-11 09:30:41 -07005234audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005235{
5236 if (isDuplicated()) {
5237 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5238 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005239 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005240 }
5241}
5242
Eric Laurente0720872014-03-11 09:30:41 -07005243bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005244{
5245 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5246}
5247
Eric Laurente0720872014-03-11 09:30:41 -07005248bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005249 uint32_t inPastMs,
5250 nsecs_t sysTime) const
5251{
5252 if ((sysTime == 0) && (inPastMs != 0)) {
5253 sysTime = systemTime();
5254 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005255 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5256 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005257 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005258 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005259 return true;
5260 }
5261 }
5262 return false;
5263}
5264
Eric Laurente0720872014-03-11 09:30:41 -07005265bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005266 uint32_t inPastMs,
5267 nsecs_t sysTime) const
5268{
5269 if (mRefCount[stream] != 0) {
5270 return true;
5271 }
5272 if (inPastMs == 0) {
5273 return false;
5274 }
5275 if (sysTime == 0) {
5276 sysTime = systemTime();
5277 }
5278 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5279 return true;
5280 }
5281 return false;
5282}
5283
Eric Laurent1c333e22014-05-20 10:48:17 -07005284void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 struct audio_port_config *dstConfig,
5286 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005287{
Eric Laurent84c70242014-06-23 08:46:27 -07005288 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5289
Eric Laurent1f2f2232014-06-02 12:01:23 -07005290 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5291 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5292 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005293 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005294 }
5295 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5296
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 dstConfig->id = mId;
5298 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5299 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5301 dstConfig->ext.mix.handle = mIoHandle;
5302 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005303}
5304
5305void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5306 struct audio_port *port) const
5307{
Eric Laurent84c70242014-06-23 08:46:27 -07005308 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005309 mProfile->toAudioPort(port);
5310 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 toAudioPortConfig(&port->active_config);
5312 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 port->ext.mix.handle = mIoHandle;
5314 port->ext.mix.latency_class =
5315 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5316}
Eric Laurente552edb2014-03-10 17:42:56 -07005317
Eric Laurente0720872014-03-11 09:30:41 -07005318status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005319{
5320 const size_t SIZE = 256;
5321 char buffer[SIZE];
5322 String8 result;
5323
Eric Laurent4d416952014-08-10 14:07:09 -07005324 snprintf(buffer, SIZE, " ID: %d\n", mId);
5325 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005326 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5327 result.append(buffer);
5328 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5329 result.append(buffer);
5330 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5331 result.append(buffer);
5332 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5333 result.append(buffer);
5334 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5335 result.append(buffer);
5336 snprintf(buffer, SIZE, " Devices %08x\n", device());
5337 result.append(buffer);
5338 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5339 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005340 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5341 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5342 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005343 result.append(buffer);
5344 }
5345 write(fd, result.string(), result.size());
5346
5347 return NO_ERROR;
5348}
5349
5350// --- AudioInputDescriptor class implementation
5351
Eric Laurent1c333e22014-05-20 10:48:17 -07005352AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005353 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005354 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005355 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005356{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005357 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005358 mSamplingRate = profile->pickSamplingRate();
5359 mFormat = profile->pickFormat();
5360 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005361 if (profile->mGains.size() > 0) {
5362 profile->mGains[0]->getDefaultConfig(&mGain);
5363 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005364 }
Eric Laurente552edb2014-03-10 17:42:56 -07005365}
5366
Eric Laurent1c333e22014-05-20 10:48:17 -07005367void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 struct audio_port_config *dstConfig,
5369 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005370{
Eric Laurent84c70242014-06-23 08:46:27 -07005371 ALOG_ASSERT(mProfile != 0,
5372 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005373 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5374 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5375 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005376 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005377 }
5378
5379 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5380
Eric Laurent6a94d692014-05-20 11:18:06 -07005381 dstConfig->id = mId;
5382 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5383 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005384 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5385 dstConfig->ext.mix.handle = mIoHandle;
5386 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005387}
5388
5389void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5390 struct audio_port *port) const
5391{
Eric Laurent84c70242014-06-23 08:46:27 -07005392 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5393
Eric Laurent1c333e22014-05-20 10:48:17 -07005394 mProfile->toAudioPort(port);
5395 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005396 toAudioPortConfig(&port->active_config);
5397 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005398 port->ext.mix.handle = mIoHandle;
5399 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5400}
5401
Eric Laurente0720872014-03-11 09:30:41 -07005402status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005403{
5404 const size_t SIZE = 256;
5405 char buffer[SIZE];
5406 String8 result;
5407
Eric Laurent4d416952014-08-10 14:07:09 -07005408 snprintf(buffer, SIZE, " ID: %d\n", mId);
5409 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005410 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5411 result.append(buffer);
5412 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5413 result.append(buffer);
5414 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5415 result.append(buffer);
5416 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5417 result.append(buffer);
5418 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5419 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005420 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5421 result.append(buffer);
5422
Eric Laurente552edb2014-03-10 17:42:56 -07005423 write(fd, result.string(), result.size());
5424
5425 return NO_ERROR;
5426}
5427
5428// --- StreamDescriptor class implementation
5429
Eric Laurente0720872014-03-11 09:30:41 -07005430AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005431 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5432{
5433 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5434}
5435
Eric Laurente0720872014-03-11 09:30:41 -07005436int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005437{
Eric Laurente0720872014-03-11 09:30:41 -07005438 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005439 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5440 if (mIndexCur.indexOfKey(device) < 0) {
5441 device = AUDIO_DEVICE_OUT_DEFAULT;
5442 }
5443 return mIndexCur.valueFor(device);
5444}
5445
Eric Laurente0720872014-03-11 09:30:41 -07005446void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005447{
5448 const size_t SIZE = 256;
5449 char buffer[SIZE];
5450 String8 result;
5451
5452 snprintf(buffer, SIZE, "%s %02d %02d ",
5453 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5454 result.append(buffer);
5455 for (size_t i = 0; i < mIndexCur.size(); i++) {
5456 snprintf(buffer, SIZE, "%04x : %02d, ",
5457 mIndexCur.keyAt(i),
5458 mIndexCur.valueAt(i));
5459 result.append(buffer);
5460 }
5461 result.append("\n");
5462
5463 write(fd, result.string(), result.size());
5464}
5465
5466// --- EffectDescriptor class implementation
5467
Eric Laurente0720872014-03-11 09:30:41 -07005468status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005469{
5470 const size_t SIZE = 256;
5471 char buffer[SIZE];
5472 String8 result;
5473
5474 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5475 result.append(buffer);
5476 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5477 result.append(buffer);
5478 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5479 result.append(buffer);
5480 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5481 result.append(buffer);
5482 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5483 result.append(buffer);
5484 write(fd, result.string(), result.size());
5485
5486 return NO_ERROR;
5487}
5488
Eric Laurent1c333e22014-05-20 10:48:17 -07005489// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005490
Eric Laurente0720872014-03-11 09:30:41 -07005491AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005492 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5493 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005494{
5495}
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005498{
5499 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005500 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005501 }
5502 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005503 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005504 }
5505 free((void *)mName);
5506}
5507
Eric Laurent1afeecb2014-05-14 08:52:28 -07005508status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5509{
5510 cnode *node = root->first_child;
5511
5512 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5513
5514 while (node) {
5515 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5516 profile->loadSamplingRates((char *)node->value);
5517 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5518 profile->loadFormats((char *)node->value);
5519 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5520 profile->loadInChannels((char *)node->value);
5521 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5522 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5523 mDeclaredDevices);
5524 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5525 profile->loadGains(node);
5526 }
5527 node = node->next;
5528 }
5529 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5530 "loadInput() invalid supported devices");
5531 ALOGW_IF(profile->mChannelMasks.size() == 0,
5532 "loadInput() invalid supported channel masks");
5533 ALOGW_IF(profile->mSamplingRates.size() == 0,
5534 "loadInput() invalid supported sampling rates");
5535 ALOGW_IF(profile->mFormats.size() == 0,
5536 "loadInput() invalid supported formats");
5537 if (!profile->mSupportedDevices.isEmpty() &&
5538 (profile->mChannelMasks.size() != 0) &&
5539 (profile->mSamplingRates.size() != 0) &&
5540 (profile->mFormats.size() != 0)) {
5541
5542 ALOGV("loadInput() adding input Supported Devices %04x",
5543 profile->mSupportedDevices.types());
5544
5545 mInputProfiles.add(profile);
5546 return NO_ERROR;
5547 } else {
5548 return BAD_VALUE;
5549 }
5550}
5551
5552status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5553{
5554 cnode *node = root->first_child;
5555
5556 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5557
5558 while (node) {
5559 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5560 profile->loadSamplingRates((char *)node->value);
5561 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5562 profile->loadFormats((char *)node->value);
5563 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5564 profile->loadOutChannels((char *)node->value);
5565 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5566 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5567 mDeclaredDevices);
5568 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5569 profile->mFlags = parseFlagNames((char *)node->value);
5570 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5571 profile->loadGains(node);
5572 }
5573 node = node->next;
5574 }
5575 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5576 "loadOutput() invalid supported devices");
5577 ALOGW_IF(profile->mChannelMasks.size() == 0,
5578 "loadOutput() invalid supported channel masks");
5579 ALOGW_IF(profile->mSamplingRates.size() == 0,
5580 "loadOutput() invalid supported sampling rates");
5581 ALOGW_IF(profile->mFormats.size() == 0,
5582 "loadOutput() invalid supported formats");
5583 if (!profile->mSupportedDevices.isEmpty() &&
5584 (profile->mChannelMasks.size() != 0) &&
5585 (profile->mSamplingRates.size() != 0) &&
5586 (profile->mFormats.size() != 0)) {
5587
5588 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5589 profile->mSupportedDevices.types(), profile->mFlags);
5590
5591 mOutputProfiles.add(profile);
5592 return NO_ERROR;
5593 } else {
5594 return BAD_VALUE;
5595 }
5596}
5597
5598status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5599{
5600 cnode *node = root->first_child;
5601
5602 audio_devices_t type = AUDIO_DEVICE_NONE;
5603 while (node) {
5604 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5605 type = parseDeviceNames((char *)node->value);
5606 break;
5607 }
5608 node = node->next;
5609 }
5610 if (type == AUDIO_DEVICE_NONE ||
5611 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5612 ALOGW("loadDevice() bad type %08x", type);
5613 return BAD_VALUE;
5614 }
5615 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5616 deviceDesc->mModule = this;
5617
5618 node = root->first_child;
5619 while (node) {
5620 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5621 deviceDesc->mAddress = String8((char *)node->value);
5622 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5623 if (audio_is_input_device(type)) {
5624 deviceDesc->loadInChannels((char *)node->value);
5625 } else {
5626 deviceDesc->loadOutChannels((char *)node->value);
5627 }
5628 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5629 deviceDesc->loadGains(node);
5630 }
5631 node = node->next;
5632 }
5633
5634 ALOGV("loadDevice() adding device name %s type %08x address %s",
5635 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5636
5637 mDeclaredDevices.add(deviceDesc);
5638
5639 return NO_ERROR;
5640}
5641
Eric Laurente0720872014-03-11 09:30:41 -07005642void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005643{
5644 const size_t SIZE = 256;
5645 char buffer[SIZE];
5646 String8 result;
5647
5648 snprintf(buffer, SIZE, " - name: %s\n", mName);
5649 result.append(buffer);
5650 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5651 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005652 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5653 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005654 write(fd, result.string(), result.size());
5655 if (mOutputProfiles.size()) {
5656 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5657 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005658 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005659 write(fd, buffer, strlen(buffer));
5660 mOutputProfiles[i]->dump(fd);
5661 }
5662 }
5663 if (mInputProfiles.size()) {
5664 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5665 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005666 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005667 write(fd, buffer, strlen(buffer));
5668 mInputProfiles[i]->dump(fd);
5669 }
5670 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005671 if (mDeclaredDevices.size()) {
5672 write(fd, " - devices:\n", strlen(" - devices:\n"));
5673 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5674 mDeclaredDevices[i]->dump(fd, 4, i);
5675 }
5676 }
Eric Laurente552edb2014-03-10 17:42:56 -07005677}
5678
Eric Laurent1c333e22014-05-20 10:48:17 -07005679// --- AudioPort class implementation
5680
Eric Laurenta121f902014-06-03 13:32:54 -07005681
5682AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5683 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005684 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005685{
5686 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5687 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5688}
5689
Eric Laurent1c333e22014-05-20 10:48:17 -07005690void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5691{
5692 port->role = mRole;
5693 port->type = mType;
5694 unsigned int i;
5695 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005696 if (mSamplingRates[i] != 0) {
5697 port->sample_rates[i] = mSamplingRates[i];
5698 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005699 }
5700 port->num_sample_rates = i;
5701 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005702 if (mChannelMasks[i] != 0) {
5703 port->channel_masks[i] = mChannelMasks[i];
5704 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005705 }
5706 port->num_channel_masks = i;
5707 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005708 if (mFormats[i] != 0) {
5709 port->formats[i] = mFormats[i];
5710 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005711 }
5712 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005713
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005714 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005715
5716 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5717 port->gains[i] = mGains[i]->mGain;
5718 }
5719 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005720}
5721
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005722void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5723 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5724 const uint32_t rate = port->mSamplingRates.itemAt(k);
5725 if (rate != 0) { // skip "dynamic" rates
5726 bool hasRate = false;
5727 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5728 if (rate == mSamplingRates.itemAt(l)) {
5729 hasRate = true;
5730 break;
5731 }
5732 }
5733 if (!hasRate) { // never import a sampling rate twice
5734 mSamplingRates.add(rate);
5735 }
5736 }
5737 }
5738 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5739 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5740 if (mask != 0) { // skip "dynamic" masks
5741 bool hasMask = false;
5742 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5743 if (mask == mChannelMasks.itemAt(l)) {
5744 hasMask = true;
5745 break;
5746 }
5747 }
5748 if (!hasMask) { // never import a channel mask twice
5749 mChannelMasks.add(mask);
5750 }
5751 }
5752 }
5753 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5754 const audio_format_t format = port->mFormats.itemAt(k);
5755 if (format != 0) { // skip "dynamic" formats
5756 bool hasFormat = false;
5757 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5758 if (format == mFormats.itemAt(l)) {
5759 hasFormat = true;
5760 break;
5761 }
5762 }
5763 if (!hasFormat) { // never import a channel mask twice
5764 mFormats.add(format);
5765 }
5766 }
5767 }
5768}
5769
5770void AudioPolicyManager::AudioPort::clearCapabilities() {
5771 mChannelMasks.clear();
5772 mFormats.clear();
5773 mSamplingRates.clear();
5774}
Eric Laurent1c333e22014-05-20 10:48:17 -07005775
5776void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5777{
5778 char *str = strtok(name, "|");
5779
5780 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5781 // rates should be read from the output stream after it is opened for the first time
5782 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5783 mSamplingRates.add(0);
5784 return;
5785 }
5786
5787 while (str != NULL) {
5788 uint32_t rate = atoi(str);
5789 if (rate != 0) {
5790 ALOGV("loadSamplingRates() adding rate %d", rate);
5791 mSamplingRates.add(rate);
5792 }
5793 str = strtok(NULL, "|");
5794 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005795}
5796
5797void AudioPolicyManager::AudioPort::loadFormats(char *name)
5798{
5799 char *str = strtok(name, "|");
5800
5801 // by convention, "0' in the first entry in mFormats indicates the supported formats
5802 // should be read from the output stream after it is opened for the first time
5803 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5804 mFormats.add(AUDIO_FORMAT_DEFAULT);
5805 return;
5806 }
5807
5808 while (str != NULL) {
5809 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5810 ARRAY_SIZE(sFormatNameToEnumTable),
5811 str);
5812 if (format != AUDIO_FORMAT_DEFAULT) {
5813 mFormats.add(format);
5814 }
5815 str = strtok(NULL, "|");
5816 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005817}
5818
5819void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5820{
5821 const char *str = strtok(name, "|");
5822
5823 ALOGV("loadInChannels() %s", name);
5824
5825 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5826 mChannelMasks.add(0);
5827 return;
5828 }
5829
5830 while (str != NULL) {
5831 audio_channel_mask_t channelMask =
5832 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5833 ARRAY_SIZE(sInChannelsNameToEnumTable),
5834 str);
5835 if (channelMask != 0) {
5836 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5837 mChannelMasks.add(channelMask);
5838 }
5839 str = strtok(NULL, "|");
5840 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005841}
5842
5843void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5844{
5845 const char *str = strtok(name, "|");
5846
5847 ALOGV("loadOutChannels() %s", name);
5848
5849 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5850 // masks should be read from the output stream after it is opened for the first time
5851 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5852 mChannelMasks.add(0);
5853 return;
5854 }
5855
5856 while (str != NULL) {
5857 audio_channel_mask_t channelMask =
5858 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5859 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5860 str);
5861 if (channelMask != 0) {
5862 mChannelMasks.add(channelMask);
5863 }
5864 str = strtok(NULL, "|");
5865 }
5866 return;
5867}
5868
Eric Laurent1afeecb2014-05-14 08:52:28 -07005869audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5870{
5871 const char *str = strtok(name, "|");
5872
5873 ALOGV("loadGainMode() %s", name);
5874 audio_gain_mode_t mode = 0;
5875 while (str != NULL) {
5876 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5877 ARRAY_SIZE(sGainModeNameToEnumTable),
5878 str);
5879 str = strtok(NULL, "|");
5880 }
5881 return mode;
5882}
5883
Eric Laurenta121f902014-06-03 13:32:54 -07005884void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005885{
5886 cnode *node = root->first_child;
5887
Eric Laurenta121f902014-06-03 13:32:54 -07005888 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005889
5890 while (node) {
5891 if (strcmp(node->name, GAIN_MODE) == 0) {
5892 gain->mGain.mode = loadGainMode((char *)node->value);
5893 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005894 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005895 gain->mGain.channel_mask =
5896 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5897 ARRAY_SIZE(sInChannelsNameToEnumTable),
5898 (char *)node->value);
5899 } else {
5900 gain->mGain.channel_mask =
5901 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5902 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5903 (char *)node->value);
5904 }
5905 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5906 gain->mGain.min_value = atoi((char *)node->value);
5907 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5908 gain->mGain.max_value = atoi((char *)node->value);
5909 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5910 gain->mGain.default_value = atoi((char *)node->value);
5911 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5912 gain->mGain.step_value = atoi((char *)node->value);
5913 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5914 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5915 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5916 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5917 }
5918 node = node->next;
5919 }
5920
5921 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5922 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5923
5924 if (gain->mGain.mode == 0) {
5925 return;
5926 }
5927 mGains.add(gain);
5928}
5929
5930void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5931{
5932 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005933 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005934 while (node) {
5935 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005936 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005937 node = node->next;
5938 }
5939}
5940
Glenn Kastencbd48022014-07-24 13:46:44 -07005941status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005942{
5943 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5944 if (mSamplingRates[i] == samplingRate) {
5945 return NO_ERROR;
5946 }
5947 }
5948 return BAD_VALUE;
5949}
5950
Glenn Kastencbd48022014-07-24 13:46:44 -07005951status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5952 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005953{
Glenn Kastencbd48022014-07-24 13:46:44 -07005954 // Search for the closest supported sampling rate that is above (preferred)
5955 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5956 // The sampling rates do not need to be sorted in ascending order.
5957 ssize_t maxBelow = -1;
5958 ssize_t minAbove = -1;
5959 uint32_t candidate;
5960 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5961 candidate = mSamplingRates[i];
5962 if (candidate == samplingRate) {
5963 if (updatedSamplingRate != NULL) {
5964 *updatedSamplingRate = candidate;
5965 }
5966 return NO_ERROR;
5967 }
5968 // candidate < desired
5969 if (candidate < samplingRate) {
5970 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5971 maxBelow = i;
5972 }
5973 // candidate > desired
5974 } else {
5975 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5976 minAbove = i;
5977 }
5978 }
5979 }
5980 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5981 // TODO Move these assumptions out.
5982 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5983 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5984 // due to approximation by an int32_t of the
5985 // phase increments
5986 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5987 if (minAbove >= 0) {
5988 candidate = mSamplingRates[minAbove];
5989 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5990 if (updatedSamplingRate != NULL) {
5991 *updatedSamplingRate = candidate;
5992 }
5993 return NO_ERROR;
5994 }
5995 }
5996 // But if we have to up-sample from a lower sampling rate, that's OK.
5997 if (maxBelow >= 0) {
5998 candidate = mSamplingRates[maxBelow];
5999 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6000 if (updatedSamplingRate != NULL) {
6001 *updatedSamplingRate = candidate;
6002 }
6003 return NO_ERROR;
6004 }
6005 }
6006 // leave updatedSamplingRate unmodified
6007 return BAD_VALUE;
6008}
6009
6010status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6011{
6012 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006013 if (mChannelMasks[i] == channelMask) {
6014 return NO_ERROR;
6015 }
6016 }
6017 return BAD_VALUE;
6018}
6019
Glenn Kastencbd48022014-07-24 13:46:44 -07006020status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6021 const
6022{
6023 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6024 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6025 // FIXME Does not handle multi-channel automatic conversions yet
6026 audio_channel_mask_t supported = mChannelMasks[i];
6027 if (supported == channelMask) {
6028 return NO_ERROR;
6029 }
6030 if (isRecordThread) {
6031 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6032 // FIXME Abstract this out to a table.
6033 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6034 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6035 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6036 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6037 return NO_ERROR;
6038 }
6039 }
6040 }
6041 return BAD_VALUE;
6042}
6043
Eric Laurenta121f902014-06-03 13:32:54 -07006044status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6045{
6046 for (size_t i = 0; i < mFormats.size(); i ++) {
6047 if (mFormats[i] == format) {
6048 return NO_ERROR;
6049 }
6050 }
6051 return BAD_VALUE;
6052}
6053
Eric Laurent1e693b52014-07-09 15:03:28 -07006054
6055uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6056{
6057 // special case for uninitialized dynamic profile
6058 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6059 return 0;
6060 }
6061
Eric Laurent828bcff2014-09-07 12:26:06 -07006062 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6063 // channel count / sampling rate combination chosen will be supported by the connected
6064 // sink
6065 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6066 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6067 uint32_t samplingRate = UINT_MAX;
6068 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6069 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6070 samplingRate = mSamplingRates[i];
6071 }
6072 }
6073 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6074 }
6075
Eric Laurent1e693b52014-07-09 15:03:28 -07006076 uint32_t samplingRate = 0;
6077 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6078
6079 // For mixed output and inputs, use max mixer sampling rates. Do not
6080 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006081 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006082 maxRate = UINT_MAX;
6083 }
6084 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6085 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6086 samplingRate = mSamplingRates[i];
6087 }
6088 }
6089 return samplingRate;
6090}
6091
6092audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6093{
6094 // special case for uninitialized dynamic profile
6095 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6096 return AUDIO_CHANNEL_NONE;
6097 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006098 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006099
6100 // For direct outputs, pick minimum channel count: this helps ensuring that the
6101 // channel count / sampling rate combination chosen will be supported by the connected
6102 // sink
6103 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6104 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6105 uint32_t channelCount = UINT_MAX;
6106 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6107 uint32_t cnlCount;
6108 if (mUseInChannelMask) {
6109 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6110 } else {
6111 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6112 }
6113 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6114 channelMask = mChannelMasks[i];
6115 channelCount = cnlCount;
6116 }
6117 }
6118 return channelMask;
6119 }
6120
Eric Laurent1e693b52014-07-09 15:03:28 -07006121 uint32_t channelCount = 0;
6122 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6123
6124 // For mixed output and inputs, use max mixer channel count. Do not
6125 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006126 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006127 maxCount = UINT_MAX;
6128 }
6129 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6130 uint32_t cnlCount;
6131 if (mUseInChannelMask) {
6132 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6133 } else {
6134 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6135 }
6136 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6137 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006138 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006139 }
6140 }
6141 return channelMask;
6142}
6143
Andy Hung9a605382014-07-28 16:16:31 -07006144/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006145const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6146 AUDIO_FORMAT_DEFAULT,
6147 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006148 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006149 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006150 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006151 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006152};
6153
6154int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6155 audio_format_t format2)
6156{
6157 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6158 // compressed format and better than any PCM format. This is by design of pickFormat()
6159 if (!audio_is_linear_pcm(format1)) {
6160 if (!audio_is_linear_pcm(format2)) {
6161 return 0;
6162 }
6163 return 1;
6164 }
6165 if (!audio_is_linear_pcm(format2)) {
6166 return -1;
6167 }
6168
6169 int index1 = -1, index2 = -1;
6170 for (size_t i = 0;
6171 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6172 i ++) {
6173 if (sPcmFormatCompareTable[i] == format1) {
6174 index1 = i;
6175 }
6176 if (sPcmFormatCompareTable[i] == format2) {
6177 index2 = i;
6178 }
6179 }
6180 // format1 not found => index1 < 0 => format2 > format1
6181 // format2 not found => index2 < 0 => format2 < format1
6182 return index1 - index2;
6183}
6184
6185audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6186{
6187 // special case for uninitialized dynamic profile
6188 if (mFormats.size() == 1 && mFormats[0] == 0) {
6189 return AUDIO_FORMAT_DEFAULT;
6190 }
6191
6192 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006193 audio_format_t bestFormat =
6194 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6195 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006196 // For mixed output and inputs, use best mixer output format. Do not
6197 // limit format otherwise
6198 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6199 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006200 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006201 bestFormat = AUDIO_FORMAT_INVALID;
6202 }
6203
6204 for (size_t i = 0; i < mFormats.size(); i ++) {
6205 if ((compareFormats(mFormats[i], format) > 0) &&
6206 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6207 format = mFormats[i];
6208 }
6209 }
6210 return format;
6211}
6212
Eric Laurenta121f902014-06-03 13:32:54 -07006213status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6214 int index) const
6215{
6216 if (index < 0 || (size_t)index >= mGains.size()) {
6217 return BAD_VALUE;
6218 }
6219 return mGains[index]->checkConfig(gainConfig);
6220}
6221
Eric Laurent1afeecb2014-05-14 08:52:28 -07006222void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6223{
6224 const size_t SIZE = 256;
6225 char buffer[SIZE];
6226 String8 result;
6227
6228 if (mName.size() != 0) {
6229 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6230 result.append(buffer);
6231 }
6232
6233 if (mSamplingRates.size() != 0) {
6234 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6235 result.append(buffer);
6236 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006237 if (i == 0 && mSamplingRates[i] == 0) {
6238 snprintf(buffer, SIZE, "Dynamic");
6239 } else {
6240 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6241 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006242 result.append(buffer);
6243 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6244 }
6245 result.append("\n");
6246 }
6247
6248 if (mChannelMasks.size() != 0) {
6249 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6250 result.append(buffer);
6251 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006252 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6253
6254 if (i == 0 && mChannelMasks[i] == 0) {
6255 snprintf(buffer, SIZE, "Dynamic");
6256 } else {
6257 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6258 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006259 result.append(buffer);
6260 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6261 }
6262 result.append("\n");
6263 }
6264
6265 if (mFormats.size() != 0) {
6266 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6267 result.append(buffer);
6268 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006269 const char *formatStr = enumToString(sFormatNameToEnumTable,
6270 ARRAY_SIZE(sFormatNameToEnumTable),
6271 mFormats[i]);
6272 if (i == 0 && strcmp(formatStr, "") == 0) {
6273 snprintf(buffer, SIZE, "Dynamic");
6274 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006275 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006276 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006277 result.append(buffer);
6278 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6279 }
6280 result.append("\n");
6281 }
6282 write(fd, result.string(), result.size());
6283 if (mGains.size() != 0) {
6284 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6285 write(fd, buffer, strlen(buffer) + 1);
6286 result.append(buffer);
6287 for (size_t i = 0; i < mGains.size(); i++) {
6288 mGains[i]->dump(fd, spaces + 2, i);
6289 }
6290 }
6291}
6292
6293// --- AudioGain class implementation
6294
Eric Laurenta121f902014-06-03 13:32:54 -07006295AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006296{
Eric Laurenta121f902014-06-03 13:32:54 -07006297 mIndex = index;
6298 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006299 memset(&mGain, 0, sizeof(struct audio_gain));
6300}
6301
Eric Laurenta121f902014-06-03 13:32:54 -07006302void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6303{
6304 config->index = mIndex;
6305 config->mode = mGain.mode;
6306 config->channel_mask = mGain.channel_mask;
6307 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6308 config->values[0] = mGain.default_value;
6309 } else {
6310 uint32_t numValues;
6311 if (mUseInChannelMask) {
6312 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6313 } else {
6314 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6315 }
6316 for (size_t i = 0; i < numValues; i++) {
6317 config->values[i] = mGain.default_value;
6318 }
6319 }
6320 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6321 config->ramp_duration_ms = mGain.min_ramp_ms;
6322 }
6323}
6324
6325status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6326{
6327 if ((config->mode & ~mGain.mode) != 0) {
6328 return BAD_VALUE;
6329 }
6330 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6331 if ((config->values[0] < mGain.min_value) ||
6332 (config->values[0] > mGain.max_value)) {
6333 return BAD_VALUE;
6334 }
6335 } else {
6336 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6337 return BAD_VALUE;
6338 }
6339 uint32_t numValues;
6340 if (mUseInChannelMask) {
6341 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6342 } else {
6343 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6344 }
6345 for (size_t i = 0; i < numValues; i++) {
6346 if ((config->values[i] < mGain.min_value) ||
6347 (config->values[i] > mGain.max_value)) {
6348 return BAD_VALUE;
6349 }
6350 }
6351 }
6352 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6353 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6354 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6355 return BAD_VALUE;
6356 }
6357 }
6358 return NO_ERROR;
6359}
6360
Eric Laurent1afeecb2014-05-14 08:52:28 -07006361void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6362{
6363 const size_t SIZE = 256;
6364 char buffer[SIZE];
6365 String8 result;
6366
6367 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6368 result.append(buffer);
6369 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6370 result.append(buffer);
6371 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6372 result.append(buffer);
6373 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6374 result.append(buffer);
6375 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6376 result.append(buffer);
6377 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6378 result.append(buffer);
6379 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6380 result.append(buffer);
6381 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6382 result.append(buffer);
6383 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6384 result.append(buffer);
6385
6386 write(fd, result.string(), result.size());
6387}
6388
Eric Laurent1f2f2232014-06-02 12:01:23 -07006389// --- AudioPortConfig class implementation
6390
6391AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6392{
6393 mSamplingRate = 0;
6394 mChannelMask = AUDIO_CHANNEL_NONE;
6395 mFormat = AUDIO_FORMAT_INVALID;
6396 mGain.index = -1;
6397}
6398
Eric Laurenta121f902014-06-03 13:32:54 -07006399status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6400 const struct audio_port_config *config,
6401 struct audio_port_config *backupConfig)
6402{
6403 struct audio_port_config localBackupConfig;
6404 status_t status = NO_ERROR;
6405
6406 localBackupConfig.config_mask = config->config_mask;
6407 toAudioPortConfig(&localBackupConfig);
6408
Marco Nelissen961ec212014-08-25 15:58:39 -07006409 sp<AudioPort> audioport = getAudioPort();
6410 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006411 status = NO_INIT;
6412 goto exit;
6413 }
6414 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006415 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006416 if (status != NO_ERROR) {
6417 goto exit;
6418 }
6419 mSamplingRate = config->sample_rate;
6420 }
6421 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006422 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006423 if (status != NO_ERROR) {
6424 goto exit;
6425 }
6426 mChannelMask = config->channel_mask;
6427 }
6428 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006429 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006430 if (status != NO_ERROR) {
6431 goto exit;
6432 }
6433 mFormat = config->format;
6434 }
6435 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006436 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006437 if (status != NO_ERROR) {
6438 goto exit;
6439 }
6440 mGain = config->gain;
6441 }
6442
6443exit:
6444 if (status != NO_ERROR) {
6445 applyAudioPortConfig(&localBackupConfig);
6446 }
6447 if (backupConfig != NULL) {
6448 *backupConfig = localBackupConfig;
6449 }
6450 return status;
6451}
6452
Eric Laurent1f2f2232014-06-02 12:01:23 -07006453void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6454 struct audio_port_config *dstConfig,
6455 const struct audio_port_config *srcConfig) const
6456{
6457 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6458 dstConfig->sample_rate = mSamplingRate;
6459 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6460 dstConfig->sample_rate = srcConfig->sample_rate;
6461 }
6462 } else {
6463 dstConfig->sample_rate = 0;
6464 }
6465 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6466 dstConfig->channel_mask = mChannelMask;
6467 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6468 dstConfig->channel_mask = srcConfig->channel_mask;
6469 }
6470 } else {
6471 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6472 }
6473 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6474 dstConfig->format = mFormat;
6475 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6476 dstConfig->format = srcConfig->format;
6477 }
6478 } else {
6479 dstConfig->format = AUDIO_FORMAT_INVALID;
6480 }
6481 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6482 dstConfig->gain = mGain;
6483 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6484 dstConfig->gain = srcConfig->gain;
6485 }
6486 } else {
6487 dstConfig->gain.index = -1;
6488 }
6489 if (dstConfig->gain.index != -1) {
6490 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6491 } else {
6492 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6493 }
6494}
6495
Eric Laurent1c333e22014-05-20 10:48:17 -07006496// --- IOProfile class implementation
6497
Eric Laurent1afeecb2014-05-14 08:52:28 -07006498AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006499 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006500 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006501{
6502}
6503
Eric Laurente0720872014-03-11 09:30:41 -07006504AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006505{
6506}
6507
6508// checks if the IO profile is compatible with specified parameters.
6509// Sampling rate, format and channel mask must be specified in order to
6510// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006511bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006512 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006513 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006514 audio_format_t format,
6515 audio_channel_mask_t channelMask,
6516 audio_output_flags_t flags) const
6517{
Glenn Kastencbd48022014-07-24 13:46:44 -07006518 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6519 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6520 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006521
Glenn Kastencbd48022014-07-24 13:46:44 -07006522 if ((mSupportedDevices.types() & device) != device) {
6523 return false;
6524 }
6525
6526 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006527 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006528 }
6529 uint32_t myUpdatedSamplingRate = samplingRate;
6530 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006531 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006532 }
6533 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6534 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006535 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006536 }
6537
6538 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6539 return false;
6540 }
6541
6542 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6543 checkExactChannelMask(channelMask) != NO_ERROR)) {
6544 return false;
6545 }
6546 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6547 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6548 return false;
6549 }
6550
6551 if (isPlaybackThread && (mFlags & flags) != flags) {
6552 return false;
6553 }
6554 // The only input flag that is allowed to be different is the fast flag.
6555 // An existing fast stream is compatible with a normal track request.
6556 // An existing normal stream is compatible with a fast track request,
6557 // but the fast request will be denied by AudioFlinger and converted to normal track.
6558 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6559 ~AUDIO_INPUT_FLAG_FAST)) {
6560 return false;
6561 }
6562
6563 if (updatedSamplingRate != NULL) {
6564 *updatedSamplingRate = myUpdatedSamplingRate;
6565 }
6566 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006567}
6568
Eric Laurente0720872014-03-11 09:30:41 -07006569void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006570{
6571 const size_t SIZE = 256;
6572 char buffer[SIZE];
6573 String8 result;
6574
Eric Laurent1afeecb2014-05-14 08:52:28 -07006575 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006576
Eric Laurente552edb2014-03-10 17:42:56 -07006577 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6578 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006579 snprintf(buffer, SIZE, " - devices:\n");
6580 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006581 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006582 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6583 mSupportedDevices[i]->dump(fd, 6, i);
6584 }
Eric Laurente552edb2014-03-10 17:42:56 -07006585}
6586
Eric Laurentd4692962014-05-05 18:13:44 -07006587void AudioPolicyManager::IOProfile::log()
6588{
6589 const size_t SIZE = 256;
6590 char buffer[SIZE];
6591 String8 result;
6592
6593 ALOGV(" - sampling rates: ");
6594 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6595 ALOGV(" %d", mSamplingRates[i]);
6596 }
6597
6598 ALOGV(" - channel masks: ");
6599 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6600 ALOGV(" 0x%04x", mChannelMasks[i]);
6601 }
6602
6603 ALOGV(" - formats: ");
6604 for (size_t i = 0; i < mFormats.size(); i++) {
6605 ALOGV(" 0x%08x", mFormats[i]);
6606 }
6607
6608 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6609 ALOGV(" - flags: 0x%04x\n", mFlags);
6610}
6611
6612
Eric Laurent3a4311c2014-03-17 12:00:47 -07006613// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006614
Eric Laurent1f2f2232014-06-02 12:01:23 -07006615
6616AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6617 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6618 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6619 AUDIO_PORT_ROLE_SOURCE,
6620 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006621 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006622{
Eric Laurenta121f902014-06-03 13:32:54 -07006623 if (mGains.size() > 0) {
6624 mGains[0]->getDefaultConfig(&mGain);
6625 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006626}
6627
Eric Laurent3a4311c2014-03-17 12:00:47 -07006628bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006629{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006630 // Devices are considered equal if they:
6631 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6632 // - have the same address or one device does not specify the address
6633 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006634 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006635 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006636 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006637 mChannelMask == other->mChannelMask);
6638}
6639
6640void AudioPolicyManager::DeviceVector::refreshTypes()
6641{
Eric Laurent1c333e22014-05-20 10:48:17 -07006642 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006643 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006644 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006645 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006646 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006647}
6648
6649ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6650{
6651 for(size_t i = 0; i < size(); i++) {
6652 if (item->equals(itemAt(i))) {
6653 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006654 }
6655 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006656 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006657}
6658
Eric Laurent3a4311c2014-03-17 12:00:47 -07006659ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006660{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006661 ssize_t ret = indexOf(item);
6662
6663 if (ret < 0) {
6664 ret = SortedVector::add(item);
6665 if (ret >= 0) {
6666 refreshTypes();
6667 }
6668 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006669 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006670 ret = -1;
6671 }
6672 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006673}
6674
Eric Laurent3a4311c2014-03-17 12:00:47 -07006675ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6676{
6677 size_t i;
6678 ssize_t ret = indexOf(item);
6679
6680 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006681 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006682 } else {
6683 ret = SortedVector::removeAt(ret);
6684 if (ret >= 0) {
6685 refreshTypes();
6686 }
6687 }
6688 return ret;
6689}
6690
6691void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6692{
6693 DeviceVector deviceList;
6694
6695 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6696 types &= ~role_bit;
6697
6698 while (types) {
6699 uint32_t i = 31 - __builtin_clz(types);
6700 uint32_t type = 1 << i;
6701 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006702 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006703 }
6704}
6705
Eric Laurent1afeecb2014-05-14 08:52:28 -07006706void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6707 const DeviceVector& declaredDevices)
6708{
6709 char *devName = strtok(name, "|");
6710 while (devName != NULL) {
6711 if (strlen(devName) != 0) {
6712 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6713 ARRAY_SIZE(sDeviceNameToEnumTable),
6714 devName);
6715 if (type != AUDIO_DEVICE_NONE) {
6716 add(new DeviceDescriptor(String8(""), type));
6717 } else {
6718 sp<DeviceDescriptor> deviceDesc =
6719 declaredDevices.getDeviceFromName(String8(devName));
6720 if (deviceDesc != 0) {
6721 add(deviceDesc);
6722 }
6723 }
6724 }
6725 devName = strtok(NULL, "|");
6726 }
6727}
6728
Eric Laurent1c333e22014-05-20 10:48:17 -07006729sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6730 audio_devices_t type, String8 address) const
6731{
6732 sp<DeviceDescriptor> device;
6733 for (size_t i = 0; i < size(); i++) {
6734 if (itemAt(i)->mDeviceType == type) {
6735 device = itemAt(i);
6736 if (itemAt(i)->mAddress = address) {
6737 break;
6738 }
6739 }
6740 }
6741 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6742 type, address.string(), device.get());
6743 return device;
6744}
6745
Eric Laurent6a94d692014-05-20 11:18:06 -07006746sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6747 audio_port_handle_t id) const
6748{
6749 sp<DeviceDescriptor> device;
6750 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006751 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006752 if (itemAt(i)->mId == id) {
6753 device = itemAt(i);
6754 break;
6755 }
6756 }
6757 return device;
6758}
6759
Eric Laurent1c333e22014-05-20 10:48:17 -07006760AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6761 audio_devices_t type) const
6762{
6763 DeviceVector devices;
6764 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6765 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6766 devices.add(itemAt(i));
6767 type &= ~itemAt(i)->mDeviceType;
6768 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6769 itemAt(i)->mDeviceType, itemAt(i).get());
6770 }
6771 }
6772 return devices;
6773}
6774
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006775AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6776 audio_devices_t type, String8 address) const
6777{
6778 DeviceVector devices;
6779 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6780 for (size_t i = 0; i < size(); i++) {
6781 //ALOGV(" at i=%d: device=%x, addr=%s",
6782 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6783 if (itemAt(i)->mDeviceType == type) {
6784 if (itemAt(i)->mAddress == address) {
6785 //ALOGV(" found matching address %s", address.string());
6786 devices.add(itemAt(i));
6787 }
6788 }
6789 }
6790 return devices;
6791}
6792
Eric Laurent1afeecb2014-05-14 08:52:28 -07006793sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6794 const String8& name) const
6795{
6796 sp<DeviceDescriptor> device;
6797 for (size_t i = 0; i < size(); i++) {
6798 if (itemAt(i)->mName == name) {
6799 device = itemAt(i);
6800 break;
6801 }
6802 }
6803 return device;
6804}
6805
Eric Laurent6a94d692014-05-20 11:18:06 -07006806void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6807 struct audio_port_config *dstConfig,
6808 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006809{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006810 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6811 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006812 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006813 }
6814
6815 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6816
Eric Laurent6a94d692014-05-20 11:18:06 -07006817 dstConfig->id = mId;
6818 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006819 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006820 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006821 dstConfig->ext.device.type = mDeviceType;
6822 dstConfig->ext.device.hw_module = mModule->mHandle;
6823 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006824}
6825
6826void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6827{
Eric Laurent83b88082014-06-20 18:31:16 -07006828 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006829 AudioPort::toAudioPort(port);
6830 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006831 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006832 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006833 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006834 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6835}
6836
Eric Laurent1afeecb2014-05-14 08:52:28 -07006837status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006838{
6839 const size_t SIZE = 256;
6840 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006841 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006842
Eric Laurent1afeecb2014-05-14 08:52:28 -07006843 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6844 result.append(buffer);
6845 if (mId != 0) {
6846 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6847 result.append(buffer);
6848 }
6849 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6850 enumToString(sDeviceNameToEnumTable,
6851 ARRAY_SIZE(sDeviceNameToEnumTable),
6852 mDeviceType));
6853 result.append(buffer);
6854 if (mAddress.size() != 0) {
6855 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6856 result.append(buffer);
6857 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006858 write(fd, result.string(), result.size());
6859 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006860
6861 return NO_ERROR;
6862}
6863
Eric Laurent4d416952014-08-10 14:07:09 -07006864status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6865{
6866 const size_t SIZE = 256;
6867 char buffer[SIZE];
6868 String8 result;
6869
6870
6871 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6872 result.append(buffer);
6873 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6874 result.append(buffer);
6875 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6876 result.append(buffer);
6877 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6878 result.append(buffer);
6879 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6880 result.append(buffer);
6881 for (size_t i = 0; i < mPatch.num_sources; i++) {
6882 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6883 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6884 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6885 ARRAY_SIZE(sDeviceNameToEnumTable),
6886 mPatch.sources[i].ext.device.type));
6887 } else {
6888 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6889 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6890 }
6891 result.append(buffer);
6892 }
6893 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6894 result.append(buffer);
6895 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6896 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6897 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6898 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6899 ARRAY_SIZE(sDeviceNameToEnumTable),
6900 mPatch.sinks[i].ext.device.type));
6901 } else {
6902 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6903 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6904 }
6905 result.append(buffer);
6906 }
6907
6908 write(fd, result.string(), result.size());
6909 return NO_ERROR;
6910}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006911
6912// --- audio_policy.conf file parsing
6913
Eric Laurente0720872014-03-11 09:30:41 -07006914audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006915{
6916 uint32_t flag = 0;
6917
6918 // it is OK to cast name to non const here as we are not going to use it after
6919 // strtok() modifies it
6920 char *flagName = strtok(name, "|");
6921 while (flagName != NULL) {
6922 if (strlen(flagName) != 0) {
6923 flag |= stringToEnum(sFlagNameToEnumTable,
6924 ARRAY_SIZE(sFlagNameToEnumTable),
6925 flagName);
6926 }
6927 flagName = strtok(NULL, "|");
6928 }
6929 //force direct flag if offload flag is set: offloading implies a direct output stream
6930 // and all common behaviors are driven by checking only the direct flag
6931 // this should normally be set appropriately in the policy configuration file
6932 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6933 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6934 }
6935
6936 return (audio_output_flags_t)flag;
6937}
6938
Eric Laurente0720872014-03-11 09:30:41 -07006939audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006940{
6941 uint32_t device = 0;
6942
6943 char *devName = strtok(name, "|");
6944 while (devName != NULL) {
6945 if (strlen(devName) != 0) {
6946 device |= stringToEnum(sDeviceNameToEnumTable,
6947 ARRAY_SIZE(sDeviceNameToEnumTable),
6948 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006949 }
Eric Laurente552edb2014-03-10 17:42:56 -07006950 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006951 }
Eric Laurente552edb2014-03-10 17:42:56 -07006952 return device;
6953}
6954
Eric Laurente0720872014-03-11 09:30:41 -07006955void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006956{
Eric Laurente552edb2014-03-10 17:42:56 -07006957 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006958 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006959 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006960
Eric Laurent1afeecb2014-05-14 08:52:28 -07006961 node = config_find(root, DEVICES_TAG);
6962 if (node != NULL) {
6963 node = node->first_child;
6964 while (node) {
6965 ALOGV("loadHwModule() loading device %s", node->name);
6966 status_t tmpStatus = module->loadDevice(node);
6967 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6968 status = tmpStatus;
6969 }
6970 node = node->next;
6971 }
6972 }
6973 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006974 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006975 node = node->first_child;
6976 while (node) {
6977 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006978 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006979 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6980 status = tmpStatus;
6981 }
6982 node = node->next;
6983 }
6984 }
6985 node = config_find(root, INPUTS_TAG);
6986 if (node != NULL) {
6987 node = node->first_child;
6988 while (node) {
6989 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006990 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006991 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6992 status = tmpStatus;
6993 }
6994 node = node->next;
6995 }
6996 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006997 loadGlobalConfig(root, module);
6998
Eric Laurente552edb2014-03-10 17:42:56 -07006999 if (status == NO_ERROR) {
7000 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007001 }
7002}
7003
Eric Laurente0720872014-03-11 09:30:41 -07007004void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007005{
7006 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7007 if (node == NULL) {
7008 return;
7009 }
7010
7011 node = node->first_child;
7012 while (node) {
7013 ALOGV("loadHwModules() loading module %s", node->name);
7014 loadHwModule(node);
7015 node = node->next;
7016 }
7017}
7018
Eric Laurent1f2f2232014-06-02 12:01:23 -07007019void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007020{
7021 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007022
Eric Laurente552edb2014-03-10 17:42:56 -07007023 if (node == NULL) {
7024 return;
7025 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007026 DeviceVector declaredDevices;
7027 if (module != NULL) {
7028 declaredDevices = module->mDeclaredDevices;
7029 }
7030
Eric Laurente552edb2014-03-10 17:42:56 -07007031 node = node->first_child;
7032 while (node) {
7033 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007034 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7035 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007036 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7037 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007038 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007039 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007040 ARRAY_SIZE(sDeviceNameToEnumTable),
7041 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007042 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007043 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007044 } else {
7045 ALOGW("loadGlobalConfig() default device not specified");
7046 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007047 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007048 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007049 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7050 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007051 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007052 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7053 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7054 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007055 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7056 uint32_t major, minor;
7057 sscanf((char *)node->value, "%u.%u", &major, &minor);
7058 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7059 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7060 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007061 }
7062 node = node->next;
7063 }
7064}
7065
Eric Laurente0720872014-03-11 09:30:41 -07007066status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007067{
7068 cnode *root;
7069 char *data;
7070
7071 data = (char *)load_file(path, NULL);
7072 if (data == NULL) {
7073 return -ENODEV;
7074 }
7075 root = config_node("", "");
7076 config_load(root, data);
7077
Eric Laurente552edb2014-03-10 17:42:56 -07007078 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007079 // legacy audio_policy.conf files have one global_configuration section
7080 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007081 config_free(root);
7082 free(root);
7083 free(data);
7084
7085 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7086
7087 return NO_ERROR;
7088}
7089
Eric Laurente0720872014-03-11 09:30:41 -07007090void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007091{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007092 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007093 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007094 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7095 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007096 mAvailableOutputDevices.add(mDefaultOutputDevice);
7097 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007098
7099 module = new HwModule("primary");
7100
Eric Laurent1afeecb2014-05-14 08:52:28 -07007101 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007102 profile->mSamplingRates.add(44100);
7103 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7104 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007105 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007106 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7107 module->mOutputProfiles.add(profile);
7108
Eric Laurent1afeecb2014-05-14 08:52:28 -07007109 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007110 profile->mSamplingRates.add(8000);
7111 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7112 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007113 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007114 module->mInputProfiles.add(profile);
7115
7116 mHwModules.add(module);
7117}
7118
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007119audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7120{
7121 // flags to stream type mapping
7122 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7123 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7124 }
7125 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7126 return AUDIO_STREAM_BLUETOOTH_SCO;
7127 }
7128
7129 // usage to stream type mapping
7130 switch (attr->usage) {
7131 case AUDIO_USAGE_MEDIA:
7132 case AUDIO_USAGE_GAME:
7133 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7134 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7135 return AUDIO_STREAM_MUSIC;
7136 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7137 return AUDIO_STREAM_SYSTEM;
7138 case AUDIO_USAGE_VOICE_COMMUNICATION:
7139 return AUDIO_STREAM_VOICE_CALL;
7140
7141 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7142 return AUDIO_STREAM_DTMF;
7143
7144 case AUDIO_USAGE_ALARM:
7145 return AUDIO_STREAM_ALARM;
7146 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7147 return AUDIO_STREAM_RING;
7148
7149 case AUDIO_USAGE_NOTIFICATION:
7150 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7151 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7152 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7153 case AUDIO_USAGE_NOTIFICATION_EVENT:
7154 return AUDIO_STREAM_NOTIFICATION;
7155
7156 case AUDIO_USAGE_UNKNOWN:
7157 default:
7158 return AUDIO_STREAM_MUSIC;
7159 }
7160}
Eric Laurente552edb2014-03-10 17:42:56 -07007161}; // namespace android