blob: 37f85138916bb190cfefaf1f6bff7475fc2b237c [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 Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070047#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070048
Eric Laurent3b73df72014-03-11 09:06:29 -070049namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070050
51// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070052// Definitions for audio_policy.conf file parsing
53// ----------------------------------------------------------------------------
54
55struct StringToEnum {
56 const char *name;
57 uint32_t value;
58};
59
60#define STRING_TO_ENUM(string) { #string, string }
61#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
62
63const StringToEnum sDeviceNameToEnumTable[] = {
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070077 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070084 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070089 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
90 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
91 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
92 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070095 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070096 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
99 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700109};
110
111const StringToEnum sFlagNameToEnumTable[] = {
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
114 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
118};
119
120const StringToEnum sFormatNameToEnumTable[] = {
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
123 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
127 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
128 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530129 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
130 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700139 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700140 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
141 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
142 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
143 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
144 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145};
146
147const StringToEnum sOutChannelsNameToEnumTable[] = {
148 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
149 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
150 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
152};
153
154const StringToEnum sInChannelsNameToEnumTable[] = {
155 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
156 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
157 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
158};
159
Eric Laurent1afeecb2014-05-14 08:52:28 -0700160const StringToEnum sGainModeNameToEnumTable[] = {
161 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
162 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
163 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
164};
165
Eric Laurent3a4311c2014-03-17 12:00:47 -0700166
167uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
168 size_t size,
169 const char *name)
170{
171 for (size_t i = 0; i < size; i++) {
172 if (strcmp(table[i].name, name) == 0) {
173 ALOGV("stringToEnum() found %s", table[i].name);
174 return table[i].value;
175 }
176 }
177 return 0;
178}
179
180const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
181 size_t size,
182 uint32_t value)
183{
184 for (size_t i = 0; i < size; i++) {
185 if (table[i].value == value) {
186 return table[i].name;
187 }
188 }
189 return "";
190}
191
192bool AudioPolicyManager::stringToBool(const char *value)
193{
194 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
195}
196
197
198// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700199// AudioPolicyInterface implementation
200// ----------------------------------------------------------------------------
201
202
Eric Laurente0720872014-03-11 09:30:41 -0700203status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700204 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700205 const char *device_address)
206{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700208
209 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
210
211 // connect/disconnect only 1 device at a time
212 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 // handle output devices
215 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700216 SortedVector <audio_io_handle_t> outputs;
217
Eric Laurent1afeecb2014-05-14 08:52:28 -0700218 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
219 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
221
Eric Laurente552edb2014-03-10 17:42:56 -0700222 // save a copy of the opened output descriptors before any output is opened or closed
223 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
224 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700225 switch (state)
226 {
227 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700228 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700229 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700230 ALOGW("setDeviceConnectionState() device already connected: %x", device);
231 return INVALID_OPERATION;
232 }
233 ALOGV("setDeviceConnectionState() connecting device %x", device);
234
Eric Laurente552edb2014-03-10 17:42:56 -0700235 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 index = mAvailableOutputDevices.add(devDesc);
237 if (index >= 0) {
238 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700239 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700240 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
241 "could not find HW module for device %08x", device);
242 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 } else {
244 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700245 }
246
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700247 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
248 mAvailableOutputDevices.remove(devDesc);
249 return INVALID_OPERATION;
250 }
251 // outputs should never be empty here
252 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
253 "checkOutputsForDevice() returned no outputs but status OK");
254 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
255 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700256 break;
257 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700258 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700260 ALOGW("setDeviceConnectionState() device not connected: %x", device);
261 return INVALID_OPERATION;
262 }
263
264 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
265 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700266 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700267
Eric Laurent3a4311c2014-03-17 12:00:47 -0700268 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700269 } break;
270
271 default:
272 ALOGE("setDeviceConnectionState() invalid state: %x", state);
273 return BAD_VALUE;
274 }
275
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
277 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700278 checkA2dpSuspend();
279 checkOutputForAllStrategies();
280 // outputs must be closed after checkOutputForAllStrategies() is executed
281 if (!outputs.isEmpty()) {
282 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700283 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700284 // close unused outputs after device disconnection or direct outputs that have been
285 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700287 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
288 (desc->mDirectOpenCount == 0))) {
289 closeOutput(outputs[i]);
290 }
291 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 // check again after closing A2DP output to reset mA2dpSuspended if needed
293 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700294 }
295
296 updateDevicesAndOutputs();
297 for (size_t i = 0; i < mOutputs.size(); i++) {
298 // do not force device change on duplicated output because if device is 0, it will
299 // also force a device 0 for the two outputs it is duplicated to which may override
300 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700301 bool force = !mOutputs.valueAt(i)->isDuplicated()
302 && (!deviceDistinguishesOnAddress(device)
303 // always force when disconnecting (a non-duplicated device)
304 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700305 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700306 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700307 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700308 }
309
Eric Laurent72aa32f2014-05-30 18:51:48 -0700310 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700311 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700312 } // end if is output device
313
Eric Laurente552edb2014-03-10 17:42:56 -0700314 // handle input devices
315 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700316 SortedVector <audio_io_handle_t> inputs;
317
Eric Laurent1afeecb2014-05-14 08:52:28 -0700318 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
319 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700320 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700321 switch (state)
322 {
323 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700324 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700326 ALOGW("setDeviceConnectionState() device already connected: %d", device);
327 return INVALID_OPERATION;
328 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700329 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700330 if (module == NULL) {
331 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
332 device);
333 return INVALID_OPERATION;
334 }
Eric Laurentd4692962014-05-05 18:13:44 -0700335 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
336 return INVALID_OPERATION;
337 }
338
Eric Laurent3a4311c2014-03-17 12:00:47 -0700339 index = mAvailableInputDevices.add(devDesc);
340 if (index >= 0) {
341 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700342 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 } else {
344 return NO_MEMORY;
345 }
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700347
348 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700349 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700350 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700351 ALOGW("setDeviceConnectionState() device not connected: %d", device);
352 return INVALID_OPERATION;
353 }
Eric Laurentd4692962014-05-05 18:13:44 -0700354 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700355 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700356 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700357
358 default:
359 ALOGE("setDeviceConnectionState() invalid state: %x", state);
360 return BAD_VALUE;
361 }
362
Eric Laurentd4692962014-05-05 18:13:44 -0700363 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700364
Eric Laurentb52c1522014-05-20 11:27:36 -0700365 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700366 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700367 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700368
369 ALOGW("setDeviceConnectionState() invalid device: %x", device);
370 return BAD_VALUE;
371}
372
Eric Laurente0720872014-03-11 09:30:41 -0700373audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700374 const char *device_address)
375{
Eric Laurent3b73df72014-03-11 09:06:29 -0700376 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700377 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700378 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
379 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 ssize_t index;
381 DeviceVector *deviceVector;
382
Eric Laurente552edb2014-03-10 17:42:56 -0700383 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700385 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 deviceVector = &mAvailableInputDevices;
387 } else {
388 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
389 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700390 }
391
Eric Laurent3a4311c2014-03-17 12:00:47 -0700392 index = deviceVector->indexOf(devDesc);
393 if (index >= 0) {
394 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
395 } else {
396 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
397 }
Eric Laurente552edb2014-03-10 17:42:56 -0700398}
399
Eric Laurente0720872014-03-11 09:30:41 -0700400void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700401{
402 ALOGV("setPhoneState() state %d", state);
403 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700404 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700405 ALOGW("setPhoneState() invalid state %d", state);
406 return;
407 }
408
409 if (state == mPhoneState ) {
410 ALOGW("setPhoneState() setting same state %d", state);
411 return;
412 }
413
414 // if leaving call state, handle special case of active streams
415 // pertaining to sonification strategy see handleIncallSonification()
416 if (isInCall()) {
417 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700418 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
419 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700420 }
421 }
422
423 // store previous phone state for management of sonification strategy below
424 int oldState = mPhoneState;
425 mPhoneState = state;
426 bool force = false;
427
428 // are we entering or starting a call
429 if (!isStateInCall(oldState) && isStateInCall(state)) {
430 ALOGV(" Entering call in setPhoneState()");
431 // force routing command to audio hardware when starting a call
432 // even if no device change is needed
433 force = true;
434 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
435 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
436 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
437 }
438 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
439 ALOGV(" Exiting call in setPhoneState()");
440 // force routing command to audio hardware when exiting a call
441 // even if no device change is needed
442 force = true;
443 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
444 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
445 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
446 }
447 } else if (isStateInCall(state) && (state != oldState)) {
448 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
449 // force routing command to audio hardware when switching between telephony and VoIP
450 // even if no device change is needed
451 force = true;
452 }
453
454 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700455 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700456 checkA2dpSuspend();
457 checkOutputForAllStrategies();
458 updateDevicesAndOutputs();
459
Eric Laurent1f2f2232014-06-02 12:01:23 -0700460 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700461
462 // force routing command to audio hardware when ending call
463 // even if no device change is needed
464 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
465 newDevice = hwOutputDesc->device();
466 }
467
468 int delayMs = 0;
469 if (isStateInCall(state)) {
470 nsecs_t sysTime = systemTime();
471 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700472 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700473 // mute media and sonification strategies and delay device switch by the largest
474 // latency of any output where either strategy is active.
475 // This avoid sending the ring tone or music tail into the earpiece or headset.
476 if ((desc->isStrategyActive(STRATEGY_MEDIA,
477 SONIFICATION_HEADSET_MUSIC_DELAY,
478 sysTime) ||
479 desc->isStrategyActive(STRATEGY_SONIFICATION,
480 SONIFICATION_HEADSET_MUSIC_DELAY,
481 sysTime)) &&
482 (delayMs < (int)desc->mLatency*2)) {
483 delayMs = desc->mLatency*2;
484 }
485 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
486 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
487 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
488 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
489 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
490 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
491 }
492 }
493
494 // change routing is necessary
495 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
496
497 // if entering in call state, handle special case of active streams
498 // pertaining to sonification strategy see handleIncallSonification()
499 if (isStateInCall(state)) {
500 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700501 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
502 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700503 }
504 }
505
506 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700507 if (state == AUDIO_MODE_RINGTONE &&
508 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700509 mLimitRingtoneVolume = true;
510 } else {
511 mLimitRingtoneVolume = false;
512 }
513}
514
Eric Laurente0720872014-03-11 09:30:41 -0700515void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700517{
518 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
519
520 bool forceVolumeReeval = false;
521 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700522 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
523 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
524 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700525 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
526 return;
527 }
528 forceVolumeReeval = true;
529 mForceUse[usage] = config;
530 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700531 case AUDIO_POLICY_FORCE_FOR_MEDIA:
532 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
533 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
534 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
535 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900536 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700537 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
538 return;
539 }
540 mForceUse[usage] = config;
541 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700542 case AUDIO_POLICY_FORCE_FOR_RECORD:
543 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
544 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700545 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
546 return;
547 }
548 mForceUse[usage] = config;
549 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700550 case AUDIO_POLICY_FORCE_FOR_DOCK:
551 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
552 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
553 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
554 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
555 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700556 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
557 }
558 forceVolumeReeval = true;
559 mForceUse[usage] = config;
560 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700561 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
562 if (config != AUDIO_POLICY_FORCE_NONE &&
563 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700564 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
565 }
566 forceVolumeReeval = true;
567 mForceUse[usage] = config;
568 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900569 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
570 if (config != AUDIO_POLICY_FORCE_NONE &&
571 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
572 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
573 }
574 mForceUse[usage] = config;
575 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700576 default:
577 ALOGW("setForceUse() invalid usage %d", usage);
578 break;
579 }
580
581 // check for device and output changes triggered by new force usage
582 checkA2dpSuspend();
583 checkOutputForAllStrategies();
584 updateDevicesAndOutputs();
585 for (size_t i = 0; i < mOutputs.size(); i++) {
586 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700587 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700588 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
589 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
590 applyStreamVolumes(output, newDevice, 0, true);
591 }
592 }
593
594 audio_io_handle_t activeInput = getActiveInput();
595 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700596 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700597 }
598
599}
600
Eric Laurente0720872014-03-11 09:30:41 -0700601audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700602{
603 return mForceUse[usage];
604}
605
Eric Laurente0720872014-03-11 09:30:41 -0700606void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700607{
608 ALOGV("setSystemProperty() property %s, value %s", property, value);
609}
610
611// Find a direct output profile compatible with the parameters passed, even if the input flags do
612// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700613sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700614 audio_devices_t device,
615 uint32_t samplingRate,
616 audio_format_t format,
617 audio_channel_mask_t channelMask,
618 audio_output_flags_t flags)
619{
620 for (size_t i = 0; i < mHwModules.size(); i++) {
621 if (mHwModules[i]->mHandle == 0) {
622 continue;
623 }
624 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700625 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700626 bool found = profile->isCompatibleProfile(device, samplingRate,
627 NULL /*updatedSamplingRate*/, format, channelMask,
628 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
629 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700630 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
631 return profile;
632 }
Eric Laurente552edb2014-03-10 17:42:56 -0700633 }
634 }
635 return 0;
636}
637
Eric Laurente0720872014-03-11 09:30:41 -0700638audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700639 uint32_t samplingRate,
640 audio_format_t format,
641 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700642 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700643 const audio_offload_info_t *offloadInfo)
644{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700645
Eric Laurent3b73df72014-03-11 09:06:29 -0700646 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700647 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
648 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
649 device, stream, samplingRate, format, channelMask, flags);
650
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700651 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
652 offloadInfo);
653}
654
655audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
656 uint32_t samplingRate,
657 audio_format_t format,
658 audio_channel_mask_t channelMask,
659 audio_output_flags_t flags,
660 const audio_offload_info_t *offloadInfo)
661{
662 if (attr == NULL) {
663 ALOGE("getOutputForAttr() called with NULL audio attributes");
664 return 0;
665 }
666 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
667 attr->usage, attr->content_type, attr->tags);
668
669 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
670 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
671 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
672 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
673 device, samplingRate, format, channelMask, flags);
674
675 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
676 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
677 offloadInfo);
678}
679
680audio_io_handle_t AudioPolicyManager::getOutputForDevice(
681 audio_devices_t device,
682 audio_stream_type_t stream,
683 uint32_t samplingRate,
684 audio_format_t format,
685 audio_channel_mask_t channelMask,
686 audio_output_flags_t flags,
687 const audio_offload_info_t *offloadInfo)
688{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700689 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700690 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700691 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700692
Eric Laurente552edb2014-03-10 17:42:56 -0700693#ifdef AUDIO_POLICY_TEST
694 if (mCurOutput != 0) {
695 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
696 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
697
698 if (mTestOutputs[mCurOutput] == 0) {
699 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700700 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700701 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700702 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700703 outputDesc->mFlags =
704 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700705 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700706 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
707 config.sample_rate = mTestSamplingRate;
708 config.channel_mask = mTestChannels;
709 config.format = mTestFormat;
710 config.offload_info = *offloadInfo;
711 status = mpClientInterface->openOutput(0,
712 &mTestOutputs[mCurOutput],
713 &config,
714 &outputDesc->mDevice,
715 String8(""),
716 &outputDesc->mLatency,
717 outputDesc->mFlags);
718 if (status == NO_ERROR) {
719 outputDesc->mSamplingRate = config.sample_rate;
720 outputDesc->mFormat = config.format;
721 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700722 AudioParameter outputCmd = AudioParameter();
723 outputCmd.addInt(String8("set_id"),mCurOutput);
724 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
725 addOutput(mTestOutputs[mCurOutput], outputDesc);
726 }
727 }
728 return mTestOutputs[mCurOutput];
729 }
730#endif //AUDIO_POLICY_TEST
731
732 // open a direct output if required by specified parameters
733 //force direct flag if offload flag is set: offloading implies a direct output stream
734 // and all common behaviors are driven by checking only the direct flag
735 // this should normally be set appropriately in the policy configuration file
736 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700737 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700738 }
739
740 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
741 // creating an offloaded track and tearing it down immediately after start when audioflinger
742 // detects there is an active non offloadable effect.
743 // FIXME: We should check the audio session here but we do not have it in this context.
744 // This may prevent offloading in rare situations where effects are left active by apps
745 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700746 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700747 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
748 !isNonOffloadableEffectEnabled()) {
749 profile = getProfileForDirectOutput(device,
750 samplingRate,
751 format,
752 channelMask,
753 (audio_output_flags_t)flags);
754 }
755
Eric Laurent1c333e22014-05-20 10:48:17 -0700756 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700757 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700758
759 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700760 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700761 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
762 outputDesc = desc;
763 // reuse direct output if currently open and configured with same parameters
764 if ((samplingRate == outputDesc->mSamplingRate) &&
765 (format == outputDesc->mFormat) &&
766 (channelMask == outputDesc->mChannelMask)) {
767 outputDesc->mDirectOpenCount++;
768 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
769 return mOutputs.keyAt(i);
770 }
771 }
772 }
773 // close direct output if currently open and configured with different parameters
774 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700775 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700776 }
777 outputDesc = new AudioOutputDescriptor(profile);
778 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700779 outputDesc->mLatency = 0;
780 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700781 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
782 config.sample_rate = samplingRate;
783 config.channel_mask = channelMask;
784 config.format = format;
785 config.offload_info = *offloadInfo;
786 status = mpClientInterface->openOutput(profile->mModule->mHandle,
787 &output,
788 &config,
789 &outputDesc->mDevice,
790 String8(""),
791 &outputDesc->mLatency,
792 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700793
794 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700795 if (status != NO_ERROR ||
796 (samplingRate != 0 && samplingRate != config.sample_rate) ||
797 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
798 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700799 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
800 "format %d %d, channelMask %04x %04x", output, samplingRate,
801 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
802 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700803 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700804 mpClientInterface->closeOutput(output);
805 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700806 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700807 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700808 outputDesc->mSamplingRate = config.sample_rate;
809 outputDesc->mChannelMask = config.channel_mask;
810 outputDesc->mFormat = config.format;
811 outputDesc->mRefCount[stream] = 0;
812 outputDesc->mStopTime[stream] = 0;
813 outputDesc->mDirectOpenCount = 1;
814
Eric Laurente552edb2014-03-10 17:42:56 -0700815 audio_io_handle_t srcOutput = getOutputForEffect();
816 addOutput(output, outputDesc);
817 audio_io_handle_t dstOutput = getOutputForEffect();
818 if (dstOutput == output) {
819 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
820 }
821 mPreviousOutputs = mOutputs;
822 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700823 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700824 return output;
825 }
826
827 // ignoring channel mask due to downmix capability in mixer
828
829 // open a non direct output
830
831 // for non direct outputs, only PCM is supported
832 if (audio_is_linear_pcm(format)) {
833 // get which output is suitable for the specified stream. The actual
834 // routing change will happen when startOutput() will be called
835 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
836
837 output = selectOutput(outputs, flags);
838 }
839 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
840 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
841
842 ALOGV("getOutput() returns output %d", output);
843
844 return output;
845}
846
Eric Laurente0720872014-03-11 09:30:41 -0700847audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700848 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700849{
850 // select one output among several that provide a path to a particular device or set of
851 // devices (the list was previously build by getOutputsForDevice()).
852 // The priority is as follows:
853 // 1: the output with the highest number of requested policy flags
854 // 2: the primary output
855 // 3: the first output in the list
856
857 if (outputs.size() == 0) {
858 return 0;
859 }
860 if (outputs.size() == 1) {
861 return outputs[0];
862 }
863
864 int maxCommonFlags = 0;
865 audio_io_handle_t outputFlags = 0;
866 audio_io_handle_t outputPrimary = 0;
867
868 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700869 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700870 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700871 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 if (commonFlags > maxCommonFlags) {
873 outputFlags = outputs[i];
874 maxCommonFlags = commonFlags;
875 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
876 }
877 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
878 outputPrimary = outputs[i];
879 }
880 }
881 }
882
883 if (outputFlags != 0) {
884 return outputFlags;
885 }
886 if (outputPrimary != 0) {
887 return outputPrimary;
888 }
889
890 return outputs[0];
891}
892
Eric Laurente0720872014-03-11 09:30:41 -0700893status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700894 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700895 int session)
896{
897 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
898 ssize_t index = mOutputs.indexOfKey(output);
899 if (index < 0) {
900 ALOGW("startOutput() unknown output %d", output);
901 return BAD_VALUE;
902 }
903
Eric Laurent1f2f2232014-06-02 12:01:23 -0700904 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700905
906 // increment usage count for this stream on the requested output:
907 // NOTE that the usage count is the same for duplicated output and hardware output which is
908 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
909 outputDesc->changeRefCount(stream, 1);
910
911 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700912 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700913 routing_strategy strategy = getStrategy(stream);
914 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
915 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
916 uint32_t waitMs = 0;
917 bool force = false;
918 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700919 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700920 if (desc != outputDesc) {
921 // force a device change if any other output is managed by the same hw
922 // module and has a current device selection that differs from selected device.
923 // In this case, the audio HAL must receive the new device selection so that it can
924 // change the device currently selected by the other active output.
925 if (outputDesc->sharesHwModuleWith(desc) &&
926 desc->device() != newDevice) {
927 force = true;
928 }
929 // wait for audio on other active outputs to be presented when starting
930 // a notification so that audio focus effect can propagate.
931 uint32_t latency = desc->latency();
932 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
933 waitMs = latency;
934 }
935 }
936 }
937 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
938
939 // handle special case for sonification while in call
940 if (isInCall()) {
941 handleIncallSonification(stream, true, false);
942 }
943
944 // apply volume rules for current stream and device if necessary
945 checkAndSetVolume(stream,
946 mStreams[stream].getVolumeIndex(newDevice),
947 output,
948 newDevice);
949
950 // update the outputs if starting an output with a stream that can affect notification
951 // routing
952 handleNotificationRoutingForStream(stream);
953 if (waitMs > muteWaitMs) {
954 usleep((waitMs - muteWaitMs) * 2 * 1000);
955 }
956 }
957 return NO_ERROR;
958}
959
960
Eric Laurente0720872014-03-11 09:30:41 -0700961status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700962 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700963 int session)
964{
965 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
966 ssize_t index = mOutputs.indexOfKey(output);
967 if (index < 0) {
968 ALOGW("stopOutput() unknown output %d", output);
969 return BAD_VALUE;
970 }
971
Eric Laurent1f2f2232014-06-02 12:01:23 -0700972 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700973
974 // handle special case for sonification while in call
975 if (isInCall()) {
976 handleIncallSonification(stream, false, false);
977 }
978
979 if (outputDesc->mRefCount[stream] > 0) {
980 // decrement usage count of this stream on the output
981 outputDesc->changeRefCount(stream, -1);
982 // store time at which the stream was stopped - see isStreamActive()
983 if (outputDesc->mRefCount[stream] == 0) {
984 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700985 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700986 // delay the device switch by twice the latency because stopOutput() is executed when
987 // the track stop() command is received and at that time the audio track buffer can
988 // still contain data that needs to be drained. The latency only covers the audio HAL
989 // and kernel buffers. Also the latency does not always include additional delay in the
990 // audio path (audio DSP, CODEC ...)
991 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
992
993 // force restoring the device selection on other active outputs if it differs from the
994 // one being selected for this output
995 for (size_t i = 0; i < mOutputs.size(); i++) {
996 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700997 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700998 if (curOutput != output &&
999 desc->isActive() &&
1000 outputDesc->sharesHwModuleWith(desc) &&
1001 (newDevice != desc->device())) {
1002 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001003 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001004 true,
1005 outputDesc->mLatency*2);
1006 }
1007 }
1008 // update the outputs if stopping one with a stream that can affect notification routing
1009 handleNotificationRoutingForStream(stream);
1010 }
1011 return NO_ERROR;
1012 } else {
1013 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1014 return INVALID_OPERATION;
1015 }
1016}
1017
Eric Laurente0720872014-03-11 09:30:41 -07001018void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001019{
1020 ALOGV("releaseOutput() %d", output);
1021 ssize_t index = mOutputs.indexOfKey(output);
1022 if (index < 0) {
1023 ALOGW("releaseOutput() releasing unknown output %d", output);
1024 return;
1025 }
1026
1027#ifdef AUDIO_POLICY_TEST
1028 int testIndex = testOutputIndex(output);
1029 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001030 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001031 if (outputDesc->isActive()) {
1032 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001033 mOutputs.removeItem(output);
1034 mTestOutputs[testIndex] = 0;
1035 }
1036 return;
1037 }
1038#endif //AUDIO_POLICY_TEST
1039
Eric Laurent1f2f2232014-06-02 12:01:23 -07001040 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001041 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001042 if (desc->mDirectOpenCount <= 0) {
1043 ALOGW("releaseOutput() invalid open count %d for output %d",
1044 desc->mDirectOpenCount, output);
1045 return;
1046 }
1047 if (--desc->mDirectOpenCount == 0) {
1048 closeOutput(output);
1049 // If effects where present on the output, audioflinger moved them to the primary
1050 // output by default: move them back to the appropriate output.
1051 audio_io_handle_t dstOutput = getOutputForEffect();
1052 if (dstOutput != mPrimaryOutput) {
1053 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1054 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001055 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001056 }
1057 }
1058}
1059
1060
Eric Laurente0720872014-03-11 09:30:41 -07001061audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001062 uint32_t samplingRate,
1063 audio_format_t format,
1064 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001065 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001066 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001067{
Eric Laurent4dc68062014-07-28 17:26:49 -07001068 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001069 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001070 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001071
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001072 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001073
1074 if (device == AUDIO_DEVICE_NONE) {
1075 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001076 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001077 }
1078
1079 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001080 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001081 case AUDIO_SOURCE_VOICE_UPLINK:
1082 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1083 break;
1084 case AUDIO_SOURCE_VOICE_DOWNLINK:
1085 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1086 break;
1087 case AUDIO_SOURCE_VOICE_CALL:
1088 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1089 break;
1090 default:
1091 break;
1092 }
1093
Eric Laurent1c333e22014-05-20 10:48:17 -07001094 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001095 samplingRate,
1096 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001097 channelMask,
1098 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001099 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001100 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1101 "channelMask 0x%X, flags %#x",
1102 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001103 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001104 }
1105
1106 if (profile->mModule->mHandle == 0) {
1107 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001108 return AUDIO_IO_HANDLE_NONE;
1109 }
1110
1111 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1112 config.sample_rate = samplingRate;
1113 config.channel_mask = channelMask;
1114 config.format = format;
1115 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1116 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1117 &input,
1118 &config,
1119 &device,
1120 String8(""),
1121 inputSource,
1122 flags);
1123
1124 // only accept input with the exact requested set of parameters
1125 if (status != NO_ERROR ||
1126 (samplingRate != config.sample_rate) ||
1127 (format != config.format) ||
1128 (channelMask != config.channel_mask)) {
1129 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1130 samplingRate, format, channelMask);
1131 if (input != AUDIO_IO_HANDLE_NONE) {
1132 mpClientInterface->closeInput(input);
1133 }
1134 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001135 }
1136
Eric Laurent1f2f2232014-06-02 12:01:23 -07001137 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001138 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001139 inputDesc->mRefCount = 0;
1140 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001141 inputDesc->mSamplingRate = samplingRate;
1142 inputDesc->mFormat = format;
1143 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001144 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001145 inputDesc->mSessions.add(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001146
Eric Laurentd4692962014-05-05 18:13:44 -07001147 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001148 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001149 return input;
1150}
1151
Eric Laurent4dc68062014-07-28 17:26:49 -07001152status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1153 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001154{
1155 ALOGV("startInput() input %d", input);
1156 ssize_t index = mInputs.indexOfKey(input);
1157 if (index < 0) {
1158 ALOGW("startInput() unknown input %d", input);
1159 return BAD_VALUE;
1160 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001161 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001162
Eric Laurent4dc68062014-07-28 17:26:49 -07001163 index = inputDesc->mSessions.indexOf(session);
1164 if (index < 0) {
1165 ALOGW("startInput() unknown session %d on input %d", session, input);
1166 return BAD_VALUE;
1167 }
1168
Glenn Kasten74a8e252014-07-24 14:09:55 -07001169 // virtual input devices are compatible with other input devices
1170 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1171
1172 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001173 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001174 if (activeInput != 0 && activeInput != input) {
1175
1176 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1177 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001178 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001179 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001180 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001181 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1182 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001183 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001184 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001185 return INVALID_OPERATION;
1186 }
1187 }
1188 }
1189
Glenn Kasten74a8e252014-07-24 14:09:55 -07001190 if (inputDesc->mRefCount == 0) {
1191 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001192
Glenn Kasten74a8e252014-07-24 14:09:55 -07001193 // Automatically enable the remote submix output when input is started.
1194 // For remote submix (a virtual device), we open only one input per capture request.
1195 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1196 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1197 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1198 }
Eric Laurente552edb2014-03-10 17:42:56 -07001199 }
1200
Eric Laurente552edb2014-03-10 17:42:56 -07001201 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1202
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001203 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001204 return NO_ERROR;
1205}
1206
Eric Laurent4dc68062014-07-28 17:26:49 -07001207status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1208 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001209{
1210 ALOGV("stopInput() input %d", input);
1211 ssize_t index = mInputs.indexOfKey(input);
1212 if (index < 0) {
1213 ALOGW("stopInput() unknown input %d", input);
1214 return BAD_VALUE;
1215 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001216 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001217
Eric Laurent4dc68062014-07-28 17:26:49 -07001218 index = inputDesc->mSessions.indexOf(session);
1219 if (index < 0) {
1220 ALOGW("stopInput() unknown session %d on input %d", session, input);
1221 return BAD_VALUE;
1222 }
1223
Eric Laurente552edb2014-03-10 17:42:56 -07001224 if (inputDesc->mRefCount == 0) {
1225 ALOGW("stopInput() input %d already stopped", input);
1226 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001227 }
1228
1229 inputDesc->mRefCount--;
1230 if (inputDesc->mRefCount == 0) {
1231
Eric Laurente552edb2014-03-10 17:42:56 -07001232 // automatically disable the remote submix output when input is stopped
1233 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1234 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001235 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001236 }
1237
Eric Laurent1c333e22014-05-20 10:48:17 -07001238 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001239 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001240 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001241}
1242
Eric Laurent4dc68062014-07-28 17:26:49 -07001243void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1244 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001245{
1246 ALOGV("releaseInput() %d", input);
1247 ssize_t index = mInputs.indexOfKey(input);
1248 if (index < 0) {
1249 ALOGW("releaseInput() releasing unknown input %d", input);
1250 return;
1251 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001252 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1253 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001254
1255 index = inputDesc->mSessions.indexOf(session);
1256 if (index < 0) {
1257 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1258 return;
1259 }
1260 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001261 if (inputDesc->mOpenRefCount == 0) {
1262 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1263 return;
1264 }
1265 inputDesc->mOpenRefCount--;
1266 if (inputDesc->mOpenRefCount > 0) {
1267 ALOGV("releaseInput() exit > 0");
1268 return;
1269 }
1270
Eric Laurente552edb2014-03-10 17:42:56 -07001271 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001272 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001273 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001274 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001275 ALOGV("releaseInput() exit");
1276}
1277
Eric Laurentd4692962014-05-05 18:13:44 -07001278void AudioPolicyManager::closeAllInputs() {
1279 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1280 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1281 }
1282 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001283 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001284}
1285
Eric Laurente0720872014-03-11 09:30:41 -07001286void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001287 int indexMin,
1288 int indexMax)
1289{
1290 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1291 if (indexMin < 0 || indexMin >= indexMax) {
1292 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1293 return;
1294 }
1295 mStreams[stream].mIndexMin = indexMin;
1296 mStreams[stream].mIndexMax = indexMax;
1297}
1298
Eric Laurente0720872014-03-11 09:30:41 -07001299status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001300 int index,
1301 audio_devices_t device)
1302{
1303
1304 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1305 return BAD_VALUE;
1306 }
1307 if (!audio_is_output_device(device)) {
1308 return BAD_VALUE;
1309 }
1310
1311 // Force max volume if stream cannot be muted
1312 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1313
1314 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1315 stream, device, index);
1316
1317 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1318 // clear all device specific values
1319 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1320 mStreams[stream].mIndexCur.clear();
1321 }
1322 mStreams[stream].mIndexCur.add(device, index);
1323
1324 // compute and apply stream volume on all outputs according to connected device
1325 status_t status = NO_ERROR;
1326 for (size_t i = 0; i < mOutputs.size(); i++) {
1327 audio_devices_t curDevice =
1328 getDeviceForVolume(mOutputs.valueAt(i)->device());
1329 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1330 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1331 if (volStatus != NO_ERROR) {
1332 status = volStatus;
1333 }
1334 }
1335 }
1336 return status;
1337}
1338
Eric Laurente0720872014-03-11 09:30:41 -07001339status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001340 int *index,
1341 audio_devices_t device)
1342{
1343 if (index == NULL) {
1344 return BAD_VALUE;
1345 }
1346 if (!audio_is_output_device(device)) {
1347 return BAD_VALUE;
1348 }
1349 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1350 // the strategy the stream belongs to.
1351 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1352 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1353 }
1354 device = getDeviceForVolume(device);
1355
1356 *index = mStreams[stream].getVolumeIndex(device);
1357 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1358 return NO_ERROR;
1359}
1360
Eric Laurente0720872014-03-11 09:30:41 -07001361audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001362 const SortedVector<audio_io_handle_t>& outputs)
1363{
1364 // select one output among several suitable for global effects.
1365 // The priority is as follows:
1366 // 1: An offloaded output. If the effect ends up not being offloadable,
1367 // AudioFlinger will invalidate the track and the offloaded output
1368 // will be closed causing the effect to be moved to a PCM output.
1369 // 2: A deep buffer output
1370 // 3: the first output in the list
1371
1372 if (outputs.size() == 0) {
1373 return 0;
1374 }
1375
1376 audio_io_handle_t outputOffloaded = 0;
1377 audio_io_handle_t outputDeepBuffer = 0;
1378
1379 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001380 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001381 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001382 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1383 outputOffloaded = outputs[i];
1384 }
1385 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1386 outputDeepBuffer = outputs[i];
1387 }
1388 }
1389
1390 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1391 outputOffloaded, outputDeepBuffer);
1392 if (outputOffloaded != 0) {
1393 return outputOffloaded;
1394 }
1395 if (outputDeepBuffer != 0) {
1396 return outputDeepBuffer;
1397 }
1398
1399 return outputs[0];
1400}
1401
Eric Laurente0720872014-03-11 09:30:41 -07001402audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001403{
1404 // apply simple rule where global effects are attached to the same output as MUSIC streams
1405
Eric Laurent3b73df72014-03-11 09:06:29 -07001406 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001407 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1408 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1409
1410 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1411 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1412 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1413
1414 return output;
1415}
1416
Eric Laurente0720872014-03-11 09:30:41 -07001417status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001418 audio_io_handle_t io,
1419 uint32_t strategy,
1420 int session,
1421 int id)
1422{
1423 ssize_t index = mOutputs.indexOfKey(io);
1424 if (index < 0) {
1425 index = mInputs.indexOfKey(io);
1426 if (index < 0) {
1427 ALOGW("registerEffect() unknown io %d", io);
1428 return INVALID_OPERATION;
1429 }
1430 }
1431
1432 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1433 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1434 desc->name, desc->memoryUsage);
1435 return INVALID_OPERATION;
1436 }
1437 mTotalEffectsMemory += desc->memoryUsage;
1438 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1439 desc->name, io, strategy, session, id);
1440 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1441
Eric Laurent1f2f2232014-06-02 12:01:23 -07001442 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1443 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1444 effectDesc->mIo = io;
1445 effectDesc->mStrategy = (routing_strategy)strategy;
1446 effectDesc->mSession = session;
1447 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001448
Eric Laurent1f2f2232014-06-02 12:01:23 -07001449 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001450
1451 return NO_ERROR;
1452}
1453
Eric Laurente0720872014-03-11 09:30:41 -07001454status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001455{
1456 ssize_t index = mEffects.indexOfKey(id);
1457 if (index < 0) {
1458 ALOGW("unregisterEffect() unknown effect ID %d", id);
1459 return INVALID_OPERATION;
1460 }
1461
Eric Laurent1f2f2232014-06-02 12:01:23 -07001462 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001463
Eric Laurent1f2f2232014-06-02 12:01:23 -07001464 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001465
Eric Laurent1f2f2232014-06-02 12:01:23 -07001466 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001467 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001468 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1469 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001470 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001471 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001472 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001473 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001474
1475 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001476
1477 return NO_ERROR;
1478}
1479
Eric Laurente0720872014-03-11 09:30:41 -07001480status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001481{
1482 ssize_t index = mEffects.indexOfKey(id);
1483 if (index < 0) {
1484 ALOGW("unregisterEffect() unknown effect ID %d", id);
1485 return INVALID_OPERATION;
1486 }
1487
1488 return setEffectEnabled(mEffects.valueAt(index), enabled);
1489}
1490
Eric Laurent1f2f2232014-06-02 12:01:23 -07001491status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001492{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001494 ALOGV("setEffectEnabled(%s) effect already %s",
1495 enabled?"true":"false", enabled?"enabled":"disabled");
1496 return INVALID_OPERATION;
1497 }
1498
1499 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001500 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001501 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001502 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001503 return INVALID_OPERATION;
1504 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001505 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001506 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1507 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001508 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001509 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001510 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1511 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001512 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001513 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001514 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1515 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001516 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001517 return NO_ERROR;
1518}
1519
Eric Laurente0720872014-03-11 09:30:41 -07001520bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
1522 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001523 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1524 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1525 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001526 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001527 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001528 return true;
1529 }
1530 }
1531 return false;
1532}
1533
Eric Laurente0720872014-03-11 09:30:41 -07001534bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001535{
1536 nsecs_t sysTime = systemTime();
1537 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001538 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001539 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001540 return true;
1541 }
1542 }
1543 return false;
1544}
1545
Eric Laurente0720872014-03-11 09:30:41 -07001546bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001547 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001548{
1549 nsecs_t sysTime = systemTime();
1550 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001551 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001552 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001553 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001554 return true;
1555 }
1556 }
1557 return false;
1558}
1559
Eric Laurente0720872014-03-11 09:30:41 -07001560bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001561{
1562 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001563 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001564 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001565 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001566 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1567 && (inputDescriptor->mRefCount > 0)) {
1568 return true;
1569 }
1570 }
1571 return false;
1572}
1573
1574
Eric Laurente0720872014-03-11 09:30:41 -07001575status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001576{
1577 const size_t SIZE = 256;
1578 char buffer[SIZE];
1579 String8 result;
1580
1581 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1582 result.append(buffer);
1583
1584 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1585 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001586 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1587 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001588 snprintf(buffer, SIZE, " Force use for communications %d\n",
1589 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001590 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001591 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001592 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001593 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001594 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001595 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001596 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001597 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001598 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001599 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1600 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1601 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001602
Eric Laurent3a4311c2014-03-17 12:00:47 -07001603 snprintf(buffer, SIZE, " Available output devices:\n");
1604 result.append(buffer);
1605 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001606 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001607 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001608 }
1609 snprintf(buffer, SIZE, "\n Available input devices:\n");
1610 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001611 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001612 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001613 }
Eric Laurente552edb2014-03-10 17:42:56 -07001614
1615 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1616 write(fd, buffer, strlen(buffer));
1617 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001618 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001619 write(fd, buffer, strlen(buffer));
1620 mHwModules[i]->dump(fd);
1621 }
1622
1623 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1624 write(fd, buffer, strlen(buffer));
1625 for (size_t i = 0; i < mOutputs.size(); i++) {
1626 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1627 write(fd, buffer, strlen(buffer));
1628 mOutputs.valueAt(i)->dump(fd);
1629 }
1630
1631 snprintf(buffer, SIZE, "\nInputs dump:\n");
1632 write(fd, buffer, strlen(buffer));
1633 for (size_t i = 0; i < mInputs.size(); i++) {
1634 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1635 write(fd, buffer, strlen(buffer));
1636 mInputs.valueAt(i)->dump(fd);
1637 }
1638
1639 snprintf(buffer, SIZE, "\nStreams dump:\n");
1640 write(fd, buffer, strlen(buffer));
1641 snprintf(buffer, SIZE,
1642 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1643 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001644 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001645 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001646 write(fd, buffer, strlen(buffer));
1647 mStreams[i].dump(fd);
1648 }
1649
1650 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1651 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1652 write(fd, buffer, strlen(buffer));
1653
1654 snprintf(buffer, SIZE, "Registered effects:\n");
1655 write(fd, buffer, strlen(buffer));
1656 for (size_t i = 0; i < mEffects.size(); i++) {
1657 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1658 write(fd, buffer, strlen(buffer));
1659 mEffects.valueAt(i)->dump(fd);
1660 }
1661
1662
1663 return NO_ERROR;
1664}
1665
1666// This function checks for the parameters which can be offloaded.
1667// This can be enhanced depending on the capability of the DSP and policy
1668// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001669bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001670{
1671 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001672 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001673 offloadInfo.sample_rate, offloadInfo.channel_mask,
1674 offloadInfo.format,
1675 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1676 offloadInfo.has_video);
1677
1678 // Check if offload has been disabled
1679 char propValue[PROPERTY_VALUE_MAX];
1680 if (property_get("audio.offload.disable", propValue, "0")) {
1681 if (atoi(propValue) != 0) {
1682 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1683 return false;
1684 }
1685 }
1686
1687 // Check if stream type is music, then only allow offload as of now.
1688 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1689 {
1690 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1691 return false;
1692 }
1693
1694 //TODO: enable audio offloading with video when ready
1695 if (offloadInfo.has_video)
1696 {
1697 ALOGV("isOffloadSupported: has_video == true, returning false");
1698 return false;
1699 }
1700
1701 //If duration is less than minimum value defined in property, return false
1702 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1703 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1704 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1705 return false;
1706 }
1707 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1708 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1709 return false;
1710 }
1711
1712 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1713 // creating an offloaded track and tearing it down immediately after start when audioflinger
1714 // detects there is an active non offloadable effect.
1715 // FIXME: We should check the audio session here but we do not have it in this context.
1716 // This may prevent offloading in rare situations where effects are left active by apps
1717 // in the background.
1718 if (isNonOffloadableEffectEnabled()) {
1719 return false;
1720 }
1721
1722 // See if there is a profile to support this.
1723 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001724 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001725 offloadInfo.sample_rate,
1726 offloadInfo.format,
1727 offloadInfo.channel_mask,
1728 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001729 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1730 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001731}
1732
Eric Laurent6a94d692014-05-20 11:18:06 -07001733status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1734 audio_port_type_t type,
1735 unsigned int *num_ports,
1736 struct audio_port *ports,
1737 unsigned int *generation)
1738{
1739 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1740 generation == NULL) {
1741 return BAD_VALUE;
1742 }
1743 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1744 if (ports == NULL) {
1745 *num_ports = 0;
1746 }
1747
1748 size_t portsWritten = 0;
1749 size_t portsMax = *num_ports;
1750 *num_ports = 0;
1751 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1752 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1753 for (size_t i = 0;
1754 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1755 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1756 }
1757 *num_ports += mAvailableOutputDevices.size();
1758 }
1759 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1760 for (size_t i = 0;
1761 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1762 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1763 }
1764 *num_ports += mAvailableInputDevices.size();
1765 }
1766 }
1767 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1768 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1769 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1770 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1771 }
1772 *num_ports += mInputs.size();
1773 }
1774 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001775 size_t numOutputs = 0;
1776 for (size_t i = 0; i < mOutputs.size(); i++) {
1777 if (!mOutputs[i]->isDuplicated()) {
1778 numOutputs++;
1779 if (portsWritten < portsMax) {
1780 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1781 }
1782 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001783 }
Eric Laurent84c70242014-06-23 08:46:27 -07001784 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001785 }
1786 }
1787 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001788 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001789 return NO_ERROR;
1790}
1791
1792status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1793{
1794 return NO_ERROR;
1795}
1796
Eric Laurent1f2f2232014-06-02 12:01:23 -07001797sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001798 audio_port_handle_t id) const
1799{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001800 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001801 for (size_t i = 0; i < mOutputs.size(); i++) {
1802 outputDesc = mOutputs.valueAt(i);
1803 if (outputDesc->mId == id) {
1804 break;
1805 }
1806 }
1807 return outputDesc;
1808}
1809
Eric Laurent1f2f2232014-06-02 12:01:23 -07001810sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001811 audio_port_handle_t id) const
1812{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001813 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001814 for (size_t i = 0; i < mInputs.size(); i++) {
1815 inputDesc = mInputs.valueAt(i);
1816 if (inputDesc->mId == id) {
1817 break;
1818 }
1819 }
1820 return inputDesc;
1821}
1822
Eric Laurent1f2f2232014-06-02 12:01:23 -07001823sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1824 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001825{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001826 sp <HwModule> module;
1827
Eric Laurent6a94d692014-05-20 11:18:06 -07001828 for (size_t i = 0; i < mHwModules.size(); i++) {
1829 if (mHwModules[i]->mHandle == 0) {
1830 continue;
1831 }
1832 if (audio_is_output_device(device)) {
1833 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1834 {
1835 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1836 return mHwModules[i];
1837 }
1838 }
1839 } else {
1840 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1841 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1842 device & ~AUDIO_DEVICE_BIT_IN) {
1843 return mHwModules[i];
1844 }
1845 }
1846 }
1847 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001848 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001849}
1850
Eric Laurent1f2f2232014-06-02 12:01:23 -07001851sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001852{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853 sp <HwModule> module;
1854
Eric Laurent1afeecb2014-05-14 08:52:28 -07001855 for (size_t i = 0; i < mHwModules.size(); i++)
1856 {
1857 if (strcmp(mHwModules[i]->mName, name) == 0) {
1858 return mHwModules[i];
1859 }
1860 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001861 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001862}
1863
1864
Eric Laurent6a94d692014-05-20 11:18:06 -07001865status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1866 audio_patch_handle_t *handle,
1867 uid_t uid)
1868{
1869 ALOGV("createAudioPatch()");
1870
1871 if (handle == NULL || patch == NULL) {
1872 return BAD_VALUE;
1873 }
1874 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1875
1876 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1877 return INVALID_OPERATION;
1878 }
1879 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1880 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1881 return INVALID_OPERATION;
1882 }
1883
1884 sp<AudioPatch> patchDesc;
1885 ssize_t index = mAudioPatches.indexOfKey(*handle);
1886
1887 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1888 patch->sinks[0].type);
1889 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1890 patch->sources[0].role,
1891 patch->sources[0].type);
1892
1893 if (index >= 0) {
1894 patchDesc = mAudioPatches.valueAt(index);
1895 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1896 mUidCached, patchDesc->mUid, uid);
1897 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1898 return INVALID_OPERATION;
1899 }
1900 } else {
1901 *handle = 0;
1902 }
1903
1904 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1905 // TODO add support for mix to mix connection
1906 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1907 ALOGV("createAudioPatch() source mix sink not device");
1908 return BAD_VALUE;
1909 }
1910 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001911 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001912 if (outputDesc == NULL) {
1913 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1914 return BAD_VALUE;
1915 }
Eric Laurent84c70242014-06-23 08:46:27 -07001916 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1917 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001918 if (patchDesc != 0) {
1919 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1920 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1921 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1922 return BAD_VALUE;
1923 }
1924 }
1925 sp<DeviceDescriptor> devDesc =
1926 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1927 if (devDesc == 0) {
1928 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1929 return BAD_VALUE;
1930 }
1931
Eric Laurent84c70242014-06-23 08:46:27 -07001932 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001933 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001934 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001935 patch->sources[0].format,
1936 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001937 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001938 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001939 return INVALID_OPERATION;
1940 }
1941 // TODO: reconfigure output format and channels here
1942 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001943 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001944 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001945 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001946 true,
1947 0,
1948 handle);
1949 index = mAudioPatches.indexOfKey(*handle);
1950 if (index >= 0) {
1951 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1952 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1953 }
1954 patchDesc = mAudioPatches.valueAt(index);
1955 patchDesc->mUid = uid;
1956 ALOGV("createAudioPatch() success");
1957 } else {
1958 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1959 return INVALID_OPERATION;
1960 }
1961 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1962 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1963 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001964 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001965 if (inputDesc == NULL) {
1966 return BAD_VALUE;
1967 }
1968 if (patchDesc != 0) {
1969 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1970 return BAD_VALUE;
1971 }
1972 }
1973 sp<DeviceDescriptor> devDesc =
1974 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1975 if (devDesc == 0) {
1976 return BAD_VALUE;
1977 }
1978
Eric Laurent84c70242014-06-23 08:46:27 -07001979 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07001980 patch->sinks[0].sample_rate,
1981 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07001982 patch->sinks[0].format,
1983 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001984 // FIXME for the parameter type,
1985 // and the NONE
1986 (audio_output_flags_t)
1987 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07001988 return INVALID_OPERATION;
1989 }
1990 // TODO: reconfigure output format and channels here
1991 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001992 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001993 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001994 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001995 true,
1996 handle);
1997 index = mAudioPatches.indexOfKey(*handle);
1998 if (index >= 0) {
1999 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2000 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2001 }
2002 patchDesc = mAudioPatches.valueAt(index);
2003 patchDesc->mUid = uid;
2004 ALOGV("createAudioPatch() success");
2005 } else {
2006 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2007 return INVALID_OPERATION;
2008 }
2009 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2010 // device to device connection
2011 if (patchDesc != 0) {
2012 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2013 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2014 return BAD_VALUE;
2015 }
2016 }
2017
2018 sp<DeviceDescriptor> srcDeviceDesc =
2019 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2020 sp<DeviceDescriptor> sinkDeviceDesc =
2021 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2022 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2023 return BAD_VALUE;
2024 }
2025 //update source and sink with our own data as the data passed in the patch may
2026 // be incomplete.
2027 struct audio_patch newPatch = *patch;
2028 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2029 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2030
Eric Laurent6a94d692014-05-20 11:18:06 -07002031 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002032 SortedVector<audio_io_handle_t> outputs =
2033 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2034 // if the sink device is reachable via an opened output stream, request to go via
2035 // this output stream by adding a second source to the patch description
2036 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2037 if (output != AUDIO_IO_HANDLE_NONE) {
2038 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2039 if (outputDesc->isDuplicated()) {
2040 return INVALID_OPERATION;
2041 }
2042 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2043 newPatch.num_sources = 2;
2044 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002045 }
2046 // TODO: check from routing capabilities in config file and other conflicting patches
2047
2048 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2049 if (index >= 0) {
2050 afPatchHandle = patchDesc->mAfPatchHandle;
2051 }
2052
2053 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2054 &afPatchHandle,
2055 0);
2056 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2057 status, afPatchHandle);
2058 if (status == NO_ERROR) {
2059 if (index < 0) {
2060 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2061 &newPatch, uid);
2062 addAudioPatch(patchDesc->mHandle, patchDesc);
2063 } else {
2064 patchDesc->mPatch = newPatch;
2065 }
2066 patchDesc->mAfPatchHandle = afPatchHandle;
2067 *handle = patchDesc->mHandle;
2068 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002069 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002070 } else {
2071 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2072 status);
2073 return INVALID_OPERATION;
2074 }
2075 } else {
2076 return BAD_VALUE;
2077 }
2078 } else {
2079 return BAD_VALUE;
2080 }
2081 return NO_ERROR;
2082}
2083
2084status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2085 uid_t uid)
2086{
2087 ALOGV("releaseAudioPatch() patch %d", handle);
2088
2089 ssize_t index = mAudioPatches.indexOfKey(handle);
2090
2091 if (index < 0) {
2092 return BAD_VALUE;
2093 }
2094 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2095 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2096 mUidCached, patchDesc->mUid, uid);
2097 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2098 return INVALID_OPERATION;
2099 }
2100
2101 struct audio_patch *patch = &patchDesc->mPatch;
2102 patchDesc->mUid = mUidCached;
2103 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002104 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002105 if (outputDesc == NULL) {
2106 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2107 return BAD_VALUE;
2108 }
2109
2110 setOutputDevice(outputDesc->mIoHandle,
2111 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2112 true,
2113 0,
2114 NULL);
2115 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2116 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002117 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002118 if (inputDesc == NULL) {
2119 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2120 return BAD_VALUE;
2121 }
2122 setInputDevice(inputDesc->mIoHandle,
2123 getNewInputDevice(inputDesc->mIoHandle),
2124 true,
2125 NULL);
2126 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2127 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2128 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2129 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2130 status, patchDesc->mAfPatchHandle);
2131 removeAudioPatch(patchDesc->mHandle);
2132 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002133 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002134 } else {
2135 return BAD_VALUE;
2136 }
2137 } else {
2138 return BAD_VALUE;
2139 }
2140 return NO_ERROR;
2141}
2142
2143status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2144 struct audio_patch *patches,
2145 unsigned int *generation)
2146{
2147 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2148 generation == NULL) {
2149 return BAD_VALUE;
2150 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002151 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002152 *num_patches, patches, mAudioPatches.size());
2153 if (patches == NULL) {
2154 *num_patches = 0;
2155 }
2156
2157 size_t patchesWritten = 0;
2158 size_t patchesMax = *num_patches;
2159 for (size_t i = 0;
2160 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2161 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2162 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002163 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002164 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2165 }
2166 *num_patches = mAudioPatches.size();
2167
2168 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002169 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002170 return NO_ERROR;
2171}
2172
Eric Laurente1715a42014-05-20 11:30:42 -07002173status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002174{
Eric Laurente1715a42014-05-20 11:30:42 -07002175 ALOGV("setAudioPortConfig()");
2176
2177 if (config == NULL) {
2178 return BAD_VALUE;
2179 }
2180 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2181 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002182 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2183 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002184 }
2185
Eric Laurenta121f902014-06-03 13:32:54 -07002186 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002187 if (config->type == AUDIO_PORT_TYPE_MIX) {
2188 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002189 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002190 if (outputDesc == NULL) {
2191 return BAD_VALUE;
2192 }
Eric Laurent84c70242014-06-23 08:46:27 -07002193 ALOG_ASSERT(!outputDesc->isDuplicated(),
2194 "setAudioPortConfig() called on duplicated output %d",
2195 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002196 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002197 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002198 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002199 if (inputDesc == NULL) {
2200 return BAD_VALUE;
2201 }
Eric Laurenta121f902014-06-03 13:32:54 -07002202 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002203 } else {
2204 return BAD_VALUE;
2205 }
2206 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2207 sp<DeviceDescriptor> deviceDesc;
2208 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2209 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2210 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2211 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2212 } else {
2213 return BAD_VALUE;
2214 }
2215 if (deviceDesc == NULL) {
2216 return BAD_VALUE;
2217 }
Eric Laurenta121f902014-06-03 13:32:54 -07002218 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002219 } else {
2220 return BAD_VALUE;
2221 }
2222
Eric Laurenta121f902014-06-03 13:32:54 -07002223 struct audio_port_config backupConfig;
2224 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2225 if (status == NO_ERROR) {
2226 struct audio_port_config newConfig;
2227 audioPortConfig->toAudioPortConfig(&newConfig, config);
2228 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002229 }
Eric Laurenta121f902014-06-03 13:32:54 -07002230 if (status != NO_ERROR) {
2231 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002232 }
Eric Laurente1715a42014-05-20 11:30:42 -07002233
2234 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002235}
2236
2237void AudioPolicyManager::clearAudioPatches(uid_t uid)
2238{
2239 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2240 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2241 if (patchDesc->mUid == uid) {
2242 // releaseAudioPatch() removes the patch from mAudioPatches
2243 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2244 i--;
2245 }
2246 }
2247 }
2248}
2249
2250status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2251 const sp<AudioPatch>& patch)
2252{
2253 ssize_t index = mAudioPatches.indexOfKey(handle);
2254
2255 if (index >= 0) {
2256 ALOGW("addAudioPatch() patch %d already in", handle);
2257 return ALREADY_EXISTS;
2258 }
2259 mAudioPatches.add(handle, patch);
2260 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2261 "sink handle %d",
2262 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2263 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2264 return NO_ERROR;
2265}
2266
2267status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2268{
2269 ssize_t index = mAudioPatches.indexOfKey(handle);
2270
2271 if (index < 0) {
2272 ALOGW("removeAudioPatch() patch %d not in", handle);
2273 return ALREADY_EXISTS;
2274 }
2275 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2276 mAudioPatches.valueAt(index)->mAfPatchHandle);
2277 mAudioPatches.removeItemsAt(index);
2278 return NO_ERROR;
2279}
2280
Eric Laurente552edb2014-03-10 17:42:56 -07002281// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002282// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002283// ----------------------------------------------------------------------------
2284
Eric Laurent3a4311c2014-03-17 12:00:47 -07002285uint32_t AudioPolicyManager::nextUniqueId()
2286{
2287 return android_atomic_inc(&mNextUniqueId);
2288}
2289
Eric Laurent6a94d692014-05-20 11:18:06 -07002290uint32_t AudioPolicyManager::nextAudioPortGeneration()
2291{
2292 return android_atomic_inc(&mAudioPortGeneration);
2293}
2294
Eric Laurente0720872014-03-11 09:30:41 -07002295AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002296 :
2297#ifdef AUDIO_POLICY_TEST
2298 Thread(false),
2299#endif //AUDIO_POLICY_TEST
2300 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002301 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002302 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2303 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002304 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002305 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2306 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002307{
Eric Laurent6a94d692014-05-20 11:18:06 -07002308 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002309 mpClientInterface = clientInterface;
2310
Eric Laurent3b73df72014-03-11 09:06:29 -07002311 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2312 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002313 }
2314
Eric Laurent1afeecb2014-05-14 08:52:28 -07002315 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002316 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2317 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2318 ALOGE("could not load audio policy configuration file, setting defaults");
2319 defaultAudioPolicyConfig();
2320 }
2321 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002322 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002323
2324 // must be done after reading the policy
2325 initializeVolumeCurves();
2326
2327 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002328 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2329 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002330 for (size_t i = 0; i < mHwModules.size(); i++) {
2331 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2332 if (mHwModules[i]->mHandle == 0) {
2333 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2334 continue;
2335 }
2336 // open all output streams needed to access attached devices
2337 // except for direct output streams that are only opened when they are actually
2338 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002339 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002340 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2341 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002342 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002343
Eric Laurent3a4311c2014-03-17 12:00:47 -07002344 if (outProfile->mSupportedDevices.isEmpty()) {
2345 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2346 continue;
2347 }
2348
Eric Laurent83b88082014-06-20 18:31:16 -07002349 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2350 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2351 profileType = mDefaultOutputDevice->mDeviceType;
2352 } else {
2353 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2354 }
2355 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002356 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002357 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002358
Eric Laurent83b88082014-06-20 18:31:16 -07002359 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002360 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2361 config.sample_rate = outputDesc->mSamplingRate;
2362 config.channel_mask = outputDesc->mChannelMask;
2363 config.format = outputDesc->mFormat;
2364 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2365 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2366 &output,
2367 &config,
2368 &outputDesc->mDevice,
2369 String8(""),
2370 &outputDesc->mLatency,
2371 outputDesc->mFlags);
2372
2373 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002374 ALOGW("Cannot open output stream for device %08x on hw module %s",
2375 outputDesc->mDevice,
2376 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002377 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002378 outputDesc->mSamplingRate = config.sample_rate;
2379 outputDesc->mChannelMask = config.channel_mask;
2380 outputDesc->mFormat = config.format;
2381
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002382 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002383 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002384 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002385 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002386 // give a valid ID to an attached device once confirmed it is reachable
2387 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2388 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002389 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002390 }
2391 }
Eric Laurente552edb2014-03-10 17:42:56 -07002392 if (mPrimaryOutput == 0 &&
2393 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2394 mPrimaryOutput = output;
2395 }
2396 addOutput(output, outputDesc);
2397 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002398 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002399 true);
2400 }
2401 }
2402 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002403 // open input streams needed to access attached devices to validate
2404 // mAvailableInputDevices list
2405 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2406 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002407 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002408
Eric Laurent3a4311c2014-03-17 12:00:47 -07002409 if (inProfile->mSupportedDevices.isEmpty()) {
2410 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2411 continue;
2412 }
2413
Eric Laurent83b88082014-06-20 18:31:16 -07002414 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2415 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002416 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002417
2418 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002419 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002420
Eric Laurentcf2c0212014-07-25 16:20:43 -07002421 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2422 config.sample_rate = inputDesc->mSamplingRate;
2423 config.channel_mask = inputDesc->mChannelMask;
2424 config.format = inputDesc->mFormat;
2425 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2426 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2427 &input,
2428 &config,
2429 &inputDesc->mDevice,
2430 String8(""),
2431 AUDIO_SOURCE_MIC,
2432 AUDIO_INPUT_FLAG_NONE);
2433
2434 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002435 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002436 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002437 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002438 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002439 // give a valid ID to an attached device once confirmed it is reachable
2440 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2441 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002442 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002443 }
2444 }
2445 mpClientInterface->closeInput(input);
2446 } else {
2447 ALOGW("Cannot open input stream for device %08x on hw module %s",
2448 inputDesc->mDevice,
2449 mHwModules[i]->mName);
2450 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002451 }
2452 }
2453 }
2454 // make sure all attached devices have been allocated a unique ID
2455 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2456 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002457 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002458 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2459 continue;
2460 }
2461 i++;
2462 }
2463 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2464 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002465 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002466 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2467 continue;
2468 }
2469 i++;
2470 }
2471 // make sure default device is reachable
2472 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002473 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002474 }
Eric Laurente552edb2014-03-10 17:42:56 -07002475
2476 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2477
2478 updateDevicesAndOutputs();
2479
2480#ifdef AUDIO_POLICY_TEST
2481 if (mPrimaryOutput != 0) {
2482 AudioParameter outputCmd = AudioParameter();
2483 outputCmd.addInt(String8("set_id"), 0);
2484 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2485
2486 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2487 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002488 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2489 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002490 mTestLatencyMs = 0;
2491 mCurOutput = 0;
2492 mDirectOutput = false;
2493 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2494 mTestOutputs[i] = 0;
2495 }
2496
2497 const size_t SIZE = 256;
2498 char buffer[SIZE];
2499 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2500 run(buffer, ANDROID_PRIORITY_AUDIO);
2501 }
2502#endif //AUDIO_POLICY_TEST
2503}
2504
Eric Laurente0720872014-03-11 09:30:41 -07002505AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002506{
2507#ifdef AUDIO_POLICY_TEST
2508 exit();
2509#endif //AUDIO_POLICY_TEST
2510 for (size_t i = 0; i < mOutputs.size(); i++) {
2511 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002512 }
2513 for (size_t i = 0; i < mInputs.size(); i++) {
2514 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002515 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002516 mAvailableOutputDevices.clear();
2517 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002518 mOutputs.clear();
2519 mInputs.clear();
2520 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002521}
2522
Eric Laurente0720872014-03-11 09:30:41 -07002523status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002524{
2525 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2526}
2527
2528#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002529bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002530{
2531 ALOGV("entering threadLoop()");
2532 while (!exitPending())
2533 {
2534 String8 command;
2535 int valueInt;
2536 String8 value;
2537
2538 Mutex::Autolock _l(mLock);
2539 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2540
2541 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2542 AudioParameter param = AudioParameter(command);
2543
2544 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2545 valueInt != 0) {
2546 ALOGV("Test command %s received", command.string());
2547 String8 target;
2548 if (param.get(String8("target"), target) != NO_ERROR) {
2549 target = "Manager";
2550 }
2551 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2552 param.remove(String8("test_cmd_policy_output"));
2553 mCurOutput = valueInt;
2554 }
2555 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2556 param.remove(String8("test_cmd_policy_direct"));
2557 if (value == "false") {
2558 mDirectOutput = false;
2559 } else if (value == "true") {
2560 mDirectOutput = true;
2561 }
2562 }
2563 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2564 param.remove(String8("test_cmd_policy_input"));
2565 mTestInput = valueInt;
2566 }
2567
2568 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2569 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002570 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002571 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002572 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002573 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002574 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002575 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002576 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002577 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002578 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002579 if (target == "Manager") {
2580 mTestFormat = format;
2581 } else if (mTestOutputs[mCurOutput] != 0) {
2582 AudioParameter outputParam = AudioParameter();
2583 outputParam.addInt(String8("format"), format);
2584 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2585 }
2586 }
2587 }
2588 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2589 param.remove(String8("test_cmd_policy_channels"));
2590 int channels = 0;
2591
2592 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002593 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002594 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002595 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002596 }
2597 if (channels != 0) {
2598 if (target == "Manager") {
2599 mTestChannels = channels;
2600 } else if (mTestOutputs[mCurOutput] != 0) {
2601 AudioParameter outputParam = AudioParameter();
2602 outputParam.addInt(String8("channels"), channels);
2603 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2604 }
2605 }
2606 }
2607 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2608 param.remove(String8("test_cmd_policy_sampleRate"));
2609 if (valueInt >= 0 && valueInt <= 96000) {
2610 int samplingRate = valueInt;
2611 if (target == "Manager") {
2612 mTestSamplingRate = samplingRate;
2613 } else if (mTestOutputs[mCurOutput] != 0) {
2614 AudioParameter outputParam = AudioParameter();
2615 outputParam.addInt(String8("sampling_rate"), samplingRate);
2616 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2617 }
2618 }
2619 }
2620
2621 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2622 param.remove(String8("test_cmd_policy_reopen"));
2623
Eric Laurent1f2f2232014-06-02 12:01:23 -07002624 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002625 mpClientInterface->closeOutput(mPrimaryOutput);
2626
2627 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2628
Eric Laurente552edb2014-03-10 17:42:56 -07002629 mOutputs.removeItem(mPrimaryOutput);
2630
Eric Laurent1f2f2232014-06-02 12:01:23 -07002631 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002632 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002633 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2634 config.sample_rate = outputDesc->mSamplingRate;
2635 config.channel_mask = outputDesc->mChannelMask;
2636 config.format = outputDesc->mFormat;
2637 status_t status = mpClientInterface->openOutput(moduleHandle,
2638 &mPrimaryOutput,
2639 &config,
2640 &outputDesc->mDevice,
2641 String8(""),
2642 &outputDesc->mLatency,
2643 outputDesc->mFlags);
2644 if (status != NO_ERROR) {
2645 ALOGE("Failed to reopen hardware output stream, "
2646 "samplingRate: %d, format %d, channels %d",
2647 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002648 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002649 outputDesc->mSamplingRate = config.sample_rate;
2650 outputDesc->mChannelMask = config.channel_mask;
2651 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002652 AudioParameter outputCmd = AudioParameter();
2653 outputCmd.addInt(String8("set_id"), 0);
2654 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2655 addOutput(mPrimaryOutput, outputDesc);
2656 }
2657 }
2658
2659
2660 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2661 }
2662 }
2663 return false;
2664}
2665
Eric Laurente0720872014-03-11 09:30:41 -07002666void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002667{
2668 {
2669 AutoMutex _l(mLock);
2670 requestExit();
2671 mWaitWorkCV.signal();
2672 }
2673 requestExitAndWait();
2674}
2675
Eric Laurente0720872014-03-11 09:30:41 -07002676int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002677{
2678 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2679 if (output == mTestOutputs[i]) return i;
2680 }
2681 return 0;
2682}
2683#endif //AUDIO_POLICY_TEST
2684
2685// ---
2686
Eric Laurent1f2f2232014-06-02 12:01:23 -07002687void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002688{
Eric Laurent1c333e22014-05-20 10:48:17 -07002689 outputDesc->mIoHandle = output;
2690 outputDesc->mId = nextUniqueId();
2691 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002692 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002693}
2694
Eric Laurent1f2f2232014-06-02 12:01:23 -07002695void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002696{
Eric Laurent1c333e22014-05-20 10:48:17 -07002697 inputDesc->mIoHandle = input;
2698 inputDesc->mId = nextUniqueId();
2699 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002700 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002701}
Eric Laurente552edb2014-03-10 17:42:56 -07002702
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002703void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2704 const String8 address /*in*/,
2705 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2706 // look for a match on the given address on the addresses of the outputs:
2707 // find the address by finding the patch that maps to this output
2708 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2709 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2710 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2711 if (patchIdx >= 0) {
2712 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2713 const int numSinks = patchDesc->mPatch.num_sinks;
2714 for (ssize_t j=0; j < numSinks; j++) {
2715 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2716 const char* patchAddr =
2717 patchDesc->mPatch.sinks[j].ext.device.address;
2718 if (strncmp(patchAddr,
2719 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2720 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2721 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2722 outputs.add(desc->mIoHandle);
2723 break;
2724 }
2725 }
2726 }
2727 }
2728}
2729
Eric Laurente0720872014-03-11 09:30:41 -07002730status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002731 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002732 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002733 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002734{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002735 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002736
Eric Laurent3b73df72014-03-11 09:06:29 -07002737 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002738 // first list already open outputs that can be routed to this device
2739 for (size_t i = 0; i < mOutputs.size(); i++) {
2740 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002741 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002742 if (!deviceDistinguishesOnAddress(device)) {
2743 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2744 outputs.add(mOutputs.keyAt(i));
2745 } else {
2746 ALOGV(" checking address match due to device 0x%x", device);
2747 findIoHandlesByAddress(desc, address, outputs);
2748 }
Eric Laurente552edb2014-03-10 17:42:56 -07002749 }
2750 }
2751 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002752 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002753 for (size_t i = 0; i < mHwModules.size(); i++)
2754 {
2755 if (mHwModules[i]->mHandle == 0) {
2756 continue;
2757 }
2758 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2759 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002760 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002761 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002762 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2763 }
2764 }
2765 }
2766
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002767 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2768
Eric Laurente552edb2014-03-10 17:42:56 -07002769 if (profiles.isEmpty() && outputs.isEmpty()) {
2770 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2771 return BAD_VALUE;
2772 }
2773
2774 // open outputs for matching profiles if needed. Direct outputs are also opened to
2775 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2776 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002777 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002778
2779 // nothing to do if one output is already opened for this profile
2780 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002781 for (j = 0; j < outputs.size(); j++) {
2782 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002783 if (!desc->isDuplicated() && desc->mProfile == profile) {
2784 break;
2785 }
2786 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002787 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002788 continue;
2789 }
2790
Eric Laurent83b88082014-06-20 18:31:16 -07002791 ALOGV("opening output for device %08x with params %s profile %p",
2792 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002793 desc = new AudioOutputDescriptor(profile);
2794 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002795 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2796 config.sample_rate = desc->mSamplingRate;
2797 config.channel_mask = desc->mChannelMask;
2798 config.format = desc->mFormat;
2799 config.offload_info.sample_rate = desc->mSamplingRate;
2800 config.offload_info.channel_mask = desc->mChannelMask;
2801 config.offload_info.format = desc->mFormat;
2802 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2803 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2804 &output,
2805 &config,
2806 &desc->mDevice,
2807 address,
2808 &desc->mLatency,
2809 desc->mFlags);
2810 if (status == NO_ERROR) {
2811 desc->mSamplingRate = config.sample_rate;
2812 desc->mChannelMask = config.channel_mask;
2813 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002814
Eric Laurentd4692962014-05-05 18:13:44 -07002815 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002816 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002817 char *param = audio_device_address_to_parameter(device, address);
2818 mpClientInterface->setParameters(output, String8(param));
2819 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002820 }
2821
Eric Laurentd4692962014-05-05 18:13:44 -07002822 // Here is where we step through and resolve any "dynamic" fields
2823 String8 reply;
2824 char *value;
2825 if (profile->mSamplingRates[0] == 0) {
2826 reply = mpClientInterface->getParameters(output,
2827 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002828 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002829 reply.string());
2830 value = strpbrk((char *)reply.string(), "=");
2831 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002832 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002833 }
Eric Laurentd4692962014-05-05 18:13:44 -07002834 }
2835 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2836 reply = mpClientInterface->getParameters(output,
2837 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002838 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002839 reply.string());
2840 value = strpbrk((char *)reply.string(), "=");
2841 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002842 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002843 }
Eric Laurentd4692962014-05-05 18:13:44 -07002844 }
2845 if (profile->mChannelMasks[0] == 0) {
2846 reply = mpClientInterface->getParameters(output,
2847 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002848 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002849 reply.string());
2850 value = strpbrk((char *)reply.string(), "=");
2851 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002852 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
Eric Laurentd4692962014-05-05 18:13:44 -07002854 }
2855 if (((profile->mSamplingRates[0] == 0) &&
2856 (profile->mSamplingRates.size() < 2)) ||
2857 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2858 (profile->mFormats.size() < 2)) ||
2859 ((profile->mChannelMasks[0] == 0) &&
2860 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002861 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002862 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002863 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002864 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2865 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002866 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002867 config.sample_rate = profile->pickSamplingRate();
2868 config.channel_mask = profile->pickChannelMask();
2869 config.format = profile->pickFormat();
2870 config.offload_info.sample_rate = config.sample_rate;
2871 config.offload_info.channel_mask = config.channel_mask;
2872 config.offload_info.format = config.format;
2873 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2874 &output,
2875 &config,
2876 &desc->mDevice,
2877 address,
2878 &desc->mLatency,
2879 desc->mFlags);
2880 if (status == NO_ERROR) {
2881 desc->mSamplingRate = config.sample_rate;
2882 desc->mChannelMask = config.channel_mask;
2883 desc->mFormat = config.format;
2884 } else {
2885 output = AUDIO_IO_HANDLE_NONE;
2886 }
Eric Laurentd4692962014-05-05 18:13:44 -07002887 }
2888
Eric Laurentcf2c0212014-07-25 16:20:43 -07002889 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002890 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002891 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002892 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002893
Eric Laurentd4692962014-05-05 18:13:44 -07002894 // set initial stream volume for device
2895 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002896
Eric Laurentd4692962014-05-05 18:13:44 -07002897 //TODO: configure audio effect output stage here
2898
2899 // open a duplicating output thread for the new output and the primary output
2900 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2901 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002902 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002903 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002904 sp<AudioOutputDescriptor> dupOutputDesc =
2905 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002906 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2907 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2908 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2909 dupOutputDesc->mFormat = desc->mFormat;
2910 dupOutputDesc->mChannelMask = desc->mChannelMask;
2911 dupOutputDesc->mLatency = desc->mLatency;
2912 addOutput(duplicatedOutput, dupOutputDesc);
2913 applyStreamVolumes(duplicatedOutput, device, 0, true);
2914 } else {
2915 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2916 mPrimaryOutput, output);
2917 mpClientInterface->closeOutput(output);
2918 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002920 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002921 }
Eric Laurente552edb2014-03-10 17:42:56 -07002922 }
2923 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002924 } else {
2925 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002926 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002927 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002928 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002929 profiles.removeAt(profile_index);
2930 profile_index--;
2931 } else {
2932 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002933 if (deviceDistinguishesOnAddress(device)) {
2934 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2935 device, address.string());
2936 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2937 NULL/*patch handle*/, address.string());
2938 }
Eric Laurente552edb2014-03-10 17:42:56 -07002939 ALOGV("checkOutputsForDevice(): adding output %d", output);
2940 }
2941 }
2942
2943 if (profiles.isEmpty()) {
2944 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2945 return BAD_VALUE;
2946 }
Eric Laurentd4692962014-05-05 18:13:44 -07002947 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002948 // check if one opened output is not needed any more after disconnecting one device
2949 for (size_t i = 0; i < mOutputs.size(); i++) {
2950 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002951 if (!desc->isDuplicated()) {
2952 if (!(desc->mProfile->mSupportedDevices.types()
2953 & mAvailableOutputDevices.types())) {
2954 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
2955 mOutputs.keyAt(i));
2956 outputs.add(mOutputs.keyAt(i));
2957 } else if (deviceDistinguishesOnAddress(device) &&
2958 // exact match on device
2959 (desc->mProfile->mSupportedDevices.types() == device)) {
2960 findIoHandlesByAddress(desc, address, outputs);
2961 }
Eric Laurente552edb2014-03-10 17:42:56 -07002962 }
2963 }
Eric Laurentd4692962014-05-05 18:13:44 -07002964 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002965 for (size_t i = 0; i < mHwModules.size(); i++)
2966 {
2967 if (mHwModules[i]->mHandle == 0) {
2968 continue;
2969 }
2970 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2971 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002972 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002973 if (profile->mSupportedDevices.types() & device) {
2974 ALOGV("checkOutputsForDevice(): "
2975 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002976 if (profile->mSamplingRates[0] == 0) {
2977 profile->mSamplingRates.clear();
2978 profile->mSamplingRates.add(0);
2979 }
2980 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2981 profile->mFormats.clear();
2982 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2983 }
2984 if (profile->mChannelMasks[0] == 0) {
2985 profile->mChannelMasks.clear();
2986 profile->mChannelMasks.add(0);
2987 }
2988 }
2989 }
2990 }
2991 }
2992 return NO_ERROR;
2993}
2994
Eric Laurentd4692962014-05-05 18:13:44 -07002995status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2996 audio_policy_dev_state_t state,
2997 SortedVector<audio_io_handle_t>& inputs,
2998 const String8 address)
2999{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003000 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003001 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3002 // first list already open inputs that can be routed to this device
3003 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3004 desc = mInputs.valueAt(input_index);
3005 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3006 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3007 inputs.add(mInputs.keyAt(input_index));
3008 }
3009 }
3010
3011 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003012 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003013 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3014 {
3015 if (mHwModules[module_idx]->mHandle == 0) {
3016 continue;
3017 }
3018 for (size_t profile_index = 0;
3019 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3020 profile_index++)
3021 {
3022 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3023 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003024 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003025 profile_index, module_idx);
3026 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3027 }
3028 }
3029 }
3030
3031 if (profiles.isEmpty() && inputs.isEmpty()) {
3032 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3033 return BAD_VALUE;
3034 }
3035
3036 // open inputs for matching profiles if needed. Direct inputs are also opened to
3037 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3038 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3039
Eric Laurent1c333e22014-05-20 10:48:17 -07003040 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003041 // nothing to do if one input is already opened for this profile
3042 size_t input_index;
3043 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3044 desc = mInputs.valueAt(input_index);
3045 if (desc->mProfile == profile) {
3046 break;
3047 }
3048 }
3049 if (input_index != mInputs.size()) {
3050 continue;
3051 }
3052
3053 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3054 desc = new AudioInputDescriptor(profile);
3055 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003056 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3057 config.sample_rate = desc->mSamplingRate;
3058 config.channel_mask = desc->mChannelMask;
3059 config.format = desc->mFormat;
3060 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3061 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3062 &input,
3063 &config,
3064 &desc->mDevice,
3065 address,
3066 AUDIO_SOURCE_MIC,
3067 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003068
Eric Laurentcf2c0212014-07-25 16:20:43 -07003069 if (status == NO_ERROR) {
3070 desc->mSamplingRate = config.sample_rate;
3071 desc->mChannelMask = config.channel_mask;
3072 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003073
Eric Laurentd4692962014-05-05 18:13:44 -07003074 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003075 char *param = audio_device_address_to_parameter(device, address);
3076 mpClientInterface->setParameters(input, String8(param));
3077 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003078 }
3079
3080 // Here is where we step through and resolve any "dynamic" fields
3081 String8 reply;
3082 char *value;
3083 if (profile->mSamplingRates[0] == 0) {
3084 reply = mpClientInterface->getParameters(input,
3085 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3086 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3087 reply.string());
3088 value = strpbrk((char *)reply.string(), "=");
3089 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003090 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003091 }
3092 }
3093 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3094 reply = mpClientInterface->getParameters(input,
3095 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3096 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3097 value = strpbrk((char *)reply.string(), "=");
3098 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003099 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003100 }
3101 }
3102 if (profile->mChannelMasks[0] == 0) {
3103 reply = mpClientInterface->getParameters(input,
3104 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3105 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3106 reply.string());
3107 value = strpbrk((char *)reply.string(), "=");
3108 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003109 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003110 }
3111 }
3112 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3113 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3114 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3115 ALOGW("checkInputsForDevice() direct input missing param");
3116 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003117 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003118 }
3119
3120 if (input != 0) {
3121 addInput(input, desc);
3122 }
3123 } // endif input != 0
3124
Eric Laurentcf2c0212014-07-25 16:20:43 -07003125 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003126 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003127 profiles.removeAt(profile_index);
3128 profile_index--;
3129 } else {
3130 inputs.add(input);
3131 ALOGV("checkInputsForDevice(): adding input %d", input);
3132 }
3133 } // end scan profiles
3134
3135 if (profiles.isEmpty()) {
3136 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3137 return BAD_VALUE;
3138 }
3139 } else {
3140 // Disconnect
3141 // check if one opened input is not needed any more after disconnecting one device
3142 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3143 desc = mInputs.valueAt(input_index);
3144 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3145 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3146 mInputs.keyAt(input_index));
3147 inputs.add(mInputs.keyAt(input_index));
3148 }
3149 }
3150 // Clear any profiles associated with the disconnected device.
3151 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3152 if (mHwModules[module_index]->mHandle == 0) {
3153 continue;
3154 }
3155 for (size_t profile_index = 0;
3156 profile_index < mHwModules[module_index]->mInputProfiles.size();
3157 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003158 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003159 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003160 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003161 profile_index, module_index);
3162 if (profile->mSamplingRates[0] == 0) {
3163 profile->mSamplingRates.clear();
3164 profile->mSamplingRates.add(0);
3165 }
3166 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3167 profile->mFormats.clear();
3168 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3169 }
3170 if (profile->mChannelMasks[0] == 0) {
3171 profile->mChannelMasks.clear();
3172 profile->mChannelMasks.add(0);
3173 }
3174 }
3175 }
3176 }
3177 } // end disconnect
3178
3179 return NO_ERROR;
3180}
3181
3182
Eric Laurente0720872014-03-11 09:30:41 -07003183void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003184{
3185 ALOGV("closeOutput(%d)", output);
3186
Eric Laurent1f2f2232014-06-02 12:01:23 -07003187 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003188 if (outputDesc == NULL) {
3189 ALOGW("closeOutput() unknown output %d", output);
3190 return;
3191 }
3192
3193 // look for duplicated outputs connected to the output being removed.
3194 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003195 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003196 if (dupOutputDesc->isDuplicated() &&
3197 (dupOutputDesc->mOutput1 == outputDesc ||
3198 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003199 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003200 if (dupOutputDesc->mOutput1 == outputDesc) {
3201 outputDesc2 = dupOutputDesc->mOutput2;
3202 } else {
3203 outputDesc2 = dupOutputDesc->mOutput1;
3204 }
3205 // As all active tracks on duplicated output will be deleted,
3206 // and as they were also referenced on the other output, the reference
3207 // count for their stream type must be adjusted accordingly on
3208 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003209 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003210 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003211 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003212 }
3213 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3214 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3215
3216 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003217 mOutputs.removeItem(duplicatedOutput);
3218 }
3219 }
3220
3221 AudioParameter param;
3222 param.add(String8("closing"), String8("true"));
3223 mpClientInterface->setParameters(output, param.toString());
3224
3225 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003226 mOutputs.removeItem(output);
3227 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003228 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003229}
3230
Eric Laurente0720872014-03-11 09:30:41 -07003231SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003232 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003233{
3234 SortedVector<audio_io_handle_t> outputs;
3235
3236 ALOGVV("getOutputsForDevice() device %04x", device);
3237 for (size_t i = 0; i < openOutputs.size(); i++) {
3238 ALOGVV("output %d isDuplicated=%d device=%04x",
3239 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3240 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3241 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3242 outputs.add(openOutputs.keyAt(i));
3243 }
3244 }
3245 return outputs;
3246}
3247
Eric Laurente0720872014-03-11 09:30:41 -07003248bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003249 SortedVector<audio_io_handle_t>& outputs2)
3250{
3251 if (outputs1.size() != outputs2.size()) {
3252 return false;
3253 }
3254 for (size_t i = 0; i < outputs1.size(); i++) {
3255 if (outputs1[i] != outputs2[i]) {
3256 return false;
3257 }
3258 }
3259 return true;
3260}
3261
Eric Laurente0720872014-03-11 09:30:41 -07003262void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003263{
3264 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3265 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3266 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3267 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3268
3269 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3270 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3271 strategy, srcOutputs[0], dstOutputs[0]);
3272 // mute strategy while moving tracks from one output to another
3273 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003274 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003275 if (desc->isStrategyActive(strategy)) {
3276 setStrategyMute(strategy, true, srcOutputs[i]);
3277 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3278 }
3279 }
3280
3281 // Move effects associated to this strategy from previous output to new output
3282 if (strategy == STRATEGY_MEDIA) {
3283 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3284 SortedVector<audio_io_handle_t> moved;
3285 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003286 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3287 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3288 effectDesc->mIo != fxOutput) {
3289 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003290 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3291 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003292 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003293 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003294 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003295 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003296 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003297 }
3298 }
3299 }
3300 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003301 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3302 if (getStrategy((audio_stream_type_t)i) == strategy) {
3303 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003304 }
3305 }
3306 }
3307}
3308
Eric Laurente0720872014-03-11 09:30:41 -07003309void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003310{
3311 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3312 checkOutputForStrategy(STRATEGY_PHONE);
3313 checkOutputForStrategy(STRATEGY_SONIFICATION);
3314 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3315 checkOutputForStrategy(STRATEGY_MEDIA);
3316 checkOutputForStrategy(STRATEGY_DTMF);
3317}
3318
Eric Laurente0720872014-03-11 09:30:41 -07003319audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003320{
Eric Laurente552edb2014-03-10 17:42:56 -07003321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003322 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003323 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3324 return mOutputs.keyAt(i);
3325 }
3326 }
3327
3328 return 0;
3329}
3330
Eric Laurente0720872014-03-11 09:30:41 -07003331void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003332{
Eric Laurente552edb2014-03-10 17:42:56 -07003333 audio_io_handle_t a2dpOutput = getA2dpOutput();
3334 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003335 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003336 return;
3337 }
3338
Eric Laurent3a4311c2014-03-17 12:00:47 -07003339 bool isScoConnected =
3340 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003341 // suspend A2DP output if:
3342 // (NOT already suspended) &&
3343 // ((SCO device is connected &&
3344 // (forced usage for communication || for record is SCO))) ||
3345 // (phone state is ringing || in call)
3346 //
3347 // restore A2DP output if:
3348 // (Already suspended) &&
3349 // ((SCO device is NOT connected ||
3350 // (forced usage NOT for communication && NOT for record is SCO))) &&
3351 // (phone state is NOT ringing && NOT in call)
3352 //
3353 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003354 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003355 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3356 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3357 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3358 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003359
3360 mpClientInterface->restoreOutput(a2dpOutput);
3361 mA2dpSuspended = false;
3362 }
3363 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003364 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003365 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3366 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3367 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3368 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003369
3370 mpClientInterface->suspendOutput(a2dpOutput);
3371 mA2dpSuspended = true;
3372 }
3373 }
3374}
3375
Eric Laurent1c333e22014-05-20 10:48:17 -07003376audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003377{
3378 audio_devices_t device = AUDIO_DEVICE_NONE;
3379
Eric Laurent1f2f2232014-06-02 12:01:23 -07003380 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003381
3382 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3383 if (index >= 0) {
3384 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3385 if (patchDesc->mUid != mUidCached) {
3386 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3387 outputDesc->device(), outputDesc->mPatchHandle);
3388 return outputDesc->device();
3389 }
3390 }
3391
Eric Laurente552edb2014-03-10 17:42:56 -07003392 // check the following by order of priority to request a routing change if necessary:
3393 // 1: the strategy enforced audible is active on the output:
3394 // use device for strategy enforced audible
3395 // 2: we are in call or the strategy phone is active on the output:
3396 // use device for strategy phone
3397 // 3: the strategy sonification is active on the output:
3398 // use device for strategy sonification
3399 // 4: the strategy "respectful" sonification is active on the output:
3400 // use device for strategy "respectful" sonification
3401 // 5: the strategy media is active on the output:
3402 // use device for strategy media
3403 // 6: the strategy DTMF is active on the output:
3404 // use device for strategy DTMF
3405 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3406 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3407 } else if (isInCall() ||
3408 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3409 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3410 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3411 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3412 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3413 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3414 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3415 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3416 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3417 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3418 }
3419
Eric Laurent1c333e22014-05-20 10:48:17 -07003420 ALOGV("getNewOutputDevice() selected device %x", device);
3421 return device;
3422}
3423
3424audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3425{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003426 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003427
3428 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3429 if (index >= 0) {
3430 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3431 if (patchDesc->mUid != mUidCached) {
3432 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3433 inputDesc->mDevice, inputDesc->mPatchHandle);
3434 return inputDesc->mDevice;
3435 }
3436 }
3437
Eric Laurent1c333e22014-05-20 10:48:17 -07003438 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3439
3440 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003441 return device;
3442}
3443
Eric Laurente0720872014-03-11 09:30:41 -07003444uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003445 return (uint32_t)getStrategy(stream);
3446}
3447
Eric Laurente0720872014-03-11 09:30:41 -07003448audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003449 // By checking the range of stream before calling getStrategy, we avoid
3450 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3451 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003452 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003453 return AUDIO_DEVICE_NONE;
3454 }
3455 audio_devices_t devices;
3456 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3457 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3458 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3459 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003461 if (outputDesc->isStrategyActive(strategy)) {
3462 devices = outputDesc->device();
3463 break;
3464 }
Eric Laurente552edb2014-03-10 17:42:56 -07003465 }
3466 return devices;
3467}
3468
Eric Laurente0720872014-03-11 09:30:41 -07003469AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003470 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003471 // stream to strategy mapping
3472 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003473 case AUDIO_STREAM_VOICE_CALL:
3474 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003475 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003476 case AUDIO_STREAM_RING:
3477 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003478 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003479 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003480 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003481 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003482 return STRATEGY_DTMF;
3483 default:
3484 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003485 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003486 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3487 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003488 case AUDIO_STREAM_TTS:
3489 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003490 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003491 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003492 return STRATEGY_ENFORCED_AUDIBLE;
3493 }
3494}
3495
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003496uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3497 // flags to strategy mapping
3498 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3499 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3500 }
3501
3502 // usage to strategy mapping
3503 switch (attr->usage) {
3504 case AUDIO_USAGE_MEDIA:
3505 case AUDIO_USAGE_GAME:
3506 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3507 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3508 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3509 return (uint32_t) STRATEGY_MEDIA;
3510
3511 case AUDIO_USAGE_VOICE_COMMUNICATION:
3512 return (uint32_t) STRATEGY_PHONE;
3513
3514 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3515 return (uint32_t) STRATEGY_DTMF;
3516
3517 case AUDIO_USAGE_ALARM:
3518 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3519 return (uint32_t) STRATEGY_SONIFICATION;
3520
3521 case AUDIO_USAGE_NOTIFICATION:
3522 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3523 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3524 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3525 case AUDIO_USAGE_NOTIFICATION_EVENT:
3526 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3527
3528 case AUDIO_USAGE_UNKNOWN:
3529 default:
3530 return (uint32_t) STRATEGY_MEDIA;
3531 }
3532}
3533
Eric Laurente0720872014-03-11 09:30:41 -07003534void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003535 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003536 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003537 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3538 updateDevicesAndOutputs();
3539 break;
3540 default:
3541 break;
3542 }
3543}
3544
Eric Laurente0720872014-03-11 09:30:41 -07003545audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003546 bool fromCache)
3547{
3548 uint32_t device = AUDIO_DEVICE_NONE;
3549
3550 if (fromCache) {
3551 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3552 strategy, mDeviceForStrategy[strategy]);
3553 return mDeviceForStrategy[strategy];
3554 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003555 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003556 switch (strategy) {
3557
3558 case STRATEGY_SONIFICATION_RESPECTFUL:
3559 if (isInCall()) {
3560 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003561 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003562 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3563 // while media is playing on a remote device, use the the sonification behavior.
3564 // Note that we test this usecase before testing if media is playing because
3565 // the isStreamActive() method only informs about the activity of a stream, not
3566 // if it's for local playback. Note also that we use the same delay between both tests
3567 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003568 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003569 // while media is playing (or has recently played), use the same device
3570 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3571 } else {
3572 // when media is not playing anymore, fall back on the sonification behavior
3573 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3574 }
3575
3576 break;
3577
3578 case STRATEGY_DTMF:
3579 if (!isInCall()) {
3580 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3581 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3582 break;
3583 }
3584 // when in call, DTMF and PHONE strategies follow the same rules
3585 // FALL THROUGH
3586
3587 case STRATEGY_PHONE:
3588 // for phone strategy, we first consider the forced use and then the available devices by order
3589 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003590 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3591 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003592 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003593 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003594 if (device) break;
3595 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003596 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003597 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003598 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003599 if (device) break;
3600 // if SCO device is requested but no SCO device is available, fall back to default case
3601 // FALL THROUGH
3602
3603 default: // FORCE_NONE
3604 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003605 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003606 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003607 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003608 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003609 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003610 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003611 if (device) break;
3612 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003613 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003614 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003615 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003616 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003617 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003618 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003619 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003620 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003621 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003623 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003624 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003625 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003626 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003627 if (device) break;
3628 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003629 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003630 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003631 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003632 if (device == AUDIO_DEVICE_NONE) {
3633 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3634 }
3635 break;
3636
Eric Laurent3b73df72014-03-11 09:06:29 -07003637 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003638 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3639 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003640 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003641 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003642 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003643 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003644 if (device) break;
3645 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003646 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003647 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003648 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003651 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003652 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003654 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003656 if (device) break;
3657 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003658 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003659 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003660 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 if (device == AUDIO_DEVICE_NONE) {
3662 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3663 }
3664 break;
3665 }
3666 break;
3667
3668 case STRATEGY_SONIFICATION:
3669
3670 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3671 // handleIncallSonification().
3672 if (isInCall()) {
3673 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3674 break;
3675 }
3676 // FALL THROUGH
3677
3678 case STRATEGY_ENFORCED_AUDIBLE:
3679 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3680 // except:
3681 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3682 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3683
3684 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003685 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003686 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003687 if (device == AUDIO_DEVICE_NONE) {
3688 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3689 }
3690 }
3691 // The second device used for sonification is the same as the device used by media strategy
3692 // FALL THROUGH
3693
3694 case STRATEGY_MEDIA: {
3695 uint32_t device2 = AUDIO_DEVICE_NONE;
3696 if (strategy != STRATEGY_SONIFICATION) {
3697 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003698 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003699 }
3700 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003701 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003702 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003703 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003704 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003705 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003706 }
3707 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003708 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003709 }
3710 }
3711 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003712 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003713 }
3714 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003715 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003716 }
3717 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003718 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003719 }
3720 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003721 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
3723 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003724 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003725 }
3726 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3727 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003728 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003729 }
3730 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003731 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003732 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003733 }
3734 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003735 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003736 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003737 int device3 = AUDIO_DEVICE_NONE;
3738 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003739 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003740 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3741 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003742 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003743 }
Eric Laurente552edb2014-03-10 17:42:56 -07003744
Jungshik Jang839e4f32014-06-26 17:23:40 +09003745 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003746 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3747 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3748 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003749
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003750 // If hdmi system audio mode is on, remove speaker out of output list.
3751 if ((strategy == STRATEGY_MEDIA) &&
3752 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3753 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3754 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3755 }
3756
Eric Laurente552edb2014-03-10 17:42:56 -07003757 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003758 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003759 if (device == AUDIO_DEVICE_NONE) {
3760 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3761 }
3762 } break;
3763
3764 default:
3765 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3766 break;
3767 }
3768
3769 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3770 return device;
3771}
3772
Eric Laurente0720872014-03-11 09:30:41 -07003773void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003774{
3775 for (int i = 0; i < NUM_STRATEGIES; i++) {
3776 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3777 }
3778 mPreviousOutputs = mOutputs;
3779}
3780
Eric Laurent1f2f2232014-06-02 12:01:23 -07003781uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003782 audio_devices_t prevDevice,
3783 uint32_t delayMs)
3784{
3785 // mute/unmute strategies using an incompatible device combination
3786 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3787 // if unmuting, unmute only after the specified delay
3788 if (outputDesc->isDuplicated()) {
3789 return 0;
3790 }
3791
3792 uint32_t muteWaitMs = 0;
3793 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003794 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003795
3796 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3797 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3798 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3799 bool doMute = false;
3800
3801 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3802 doMute = true;
3803 outputDesc->mStrategyMutedByDevice[i] = true;
3804 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3805 doMute = true;
3806 outputDesc->mStrategyMutedByDevice[i] = false;
3807 }
Eric Laurent99401132014-05-07 19:48:15 -07003808 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003809 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003810 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003811 // skip output if it does not share any device with current output
3812 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3813 == AUDIO_DEVICE_NONE) {
3814 continue;
3815 }
3816 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3817 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3818 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3819 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3820 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003821 if (mute) {
3822 // FIXME: should not need to double latency if volume could be applied
3823 // immediately by the audioflinger mixer. We must account for the delay
3824 // between now and the next time the audioflinger thread for this output
3825 // will process a buffer (which corresponds to one buffer size,
3826 // usually 1/2 or 1/4 of the latency).
3827 if (muteWaitMs < desc->latency() * 2) {
3828 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003829 }
3830 }
3831 }
3832 }
3833 }
3834 }
3835
Eric Laurent99401132014-05-07 19:48:15 -07003836 // temporary mute output if device selection changes to avoid volume bursts due to
3837 // different per device volumes
3838 if (outputDesc->isActive() && (device != prevDevice)) {
3839 if (muteWaitMs < outputDesc->latency() * 2) {
3840 muteWaitMs = outputDesc->latency() * 2;
3841 }
3842 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3843 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003844 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003845 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003846 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003847 muteWaitMs *2, device);
3848 }
3849 }
3850 }
3851
Eric Laurente552edb2014-03-10 17:42:56 -07003852 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3853 if (muteWaitMs > delayMs) {
3854 muteWaitMs -= delayMs;
3855 usleep(muteWaitMs * 1000);
3856 return muteWaitMs;
3857 }
3858 return 0;
3859}
3860
Eric Laurente0720872014-03-11 09:30:41 -07003861uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003862 audio_devices_t device,
3863 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003865 audio_patch_handle_t *patchHandle,
3866 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003867{
3868 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003869 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003870 AudioParameter param;
3871 uint32_t muteWaitMs;
3872
3873 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003874 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3875 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003876 return muteWaitMs;
3877 }
3878 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3879 // output profile
3880 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003881 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003882 return 0;
3883 }
3884
3885 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003886 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003887
3888 audio_devices_t prevDevice = outputDesc->mDevice;
3889
3890 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3891
3892 if (device != AUDIO_DEVICE_NONE) {
3893 outputDesc->mDevice = device;
3894 }
3895 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3896
3897 // Do not change the routing if:
3898 // - the requested device is AUDIO_DEVICE_NONE
3899 // - the requested device is the same as current device and force is not specified.
3900 // Doing this check here allows the caller to call setOutputDevice() without conditions
3901 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3902 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3903 return muteWaitMs;
3904 }
3905
3906 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003907
Eric Laurente552edb2014-03-10 17:42:56 -07003908 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003909 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003910 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003911 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003912 DeviceVector deviceList = (address == NULL) ?
3913 mAvailableOutputDevices.getDevicesFromType(device)
3914 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003915 if (!deviceList.isEmpty()) {
3916 struct audio_patch patch;
3917 outputDesc->toAudioPortConfig(&patch.sources[0]);
3918 patch.num_sources = 1;
3919 patch.num_sinks = 0;
3920 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3921 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003922 patch.num_sinks++;
3923 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003924 ssize_t index;
3925 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3926 index = mAudioPatches.indexOfKey(*patchHandle);
3927 } else {
3928 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3929 }
3930 sp< AudioPatch> patchDesc;
3931 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3932 if (index >= 0) {
3933 patchDesc = mAudioPatches.valueAt(index);
3934 afPatchHandle = patchDesc->mAfPatchHandle;
3935 }
3936
Eric Laurent1c333e22014-05-20 10:48:17 -07003937 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003938 &afPatchHandle,
3939 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003940 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3941 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003942 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003943 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 if (index < 0) {
3945 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3946 &patch, mUidCached);
3947 addAudioPatch(patchDesc->mHandle, patchDesc);
3948 } else {
3949 patchDesc->mPatch = patch;
3950 }
3951 patchDesc->mAfPatchHandle = afPatchHandle;
3952 patchDesc->mUid = mUidCached;
3953 if (patchHandle) {
3954 *patchHandle = patchDesc->mHandle;
3955 }
3956 outputDesc->mPatchHandle = patchDesc->mHandle;
3957 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003958 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003959 }
3960 }
3961 }
Eric Laurente552edb2014-03-10 17:42:56 -07003962
3963 // update stream volumes according to new device
3964 applyStreamVolumes(output, device, delayMs);
3965
3966 return muteWaitMs;
3967}
3968
Eric Laurent1c333e22014-05-20 10:48:17 -07003969status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003970 int delayMs,
3971 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003972{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003973 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003974 ssize_t index;
3975 if (patchHandle) {
3976 index = mAudioPatches.indexOfKey(*patchHandle);
3977 } else {
3978 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3979 }
3980 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003981 return INVALID_OPERATION;
3982 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003983 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3984 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003985 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3986 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003987 removeAudioPatch(patchDesc->mHandle);
3988 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003989 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003990 return status;
3991}
3992
3993status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3994 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 bool force,
3996 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003997{
3998 status_t status = NO_ERROR;
3999
Eric Laurent1f2f2232014-06-02 12:01:23 -07004000 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004001 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4002 inputDesc->mDevice = device;
4003
4004 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4005 if (!deviceList.isEmpty()) {
4006 struct audio_patch patch;
4007 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004008 // AUDIO_SOURCE_HOTWORD is for internal use only:
4009 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
4010 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD) {
4011 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4012 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004013 patch.num_sinks = 1;
4014 //only one input device for now
4015 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004016 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004017 ssize_t index;
4018 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4019 index = mAudioPatches.indexOfKey(*patchHandle);
4020 } else {
4021 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4022 }
4023 sp< AudioPatch> patchDesc;
4024 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4025 if (index >= 0) {
4026 patchDesc = mAudioPatches.valueAt(index);
4027 afPatchHandle = patchDesc->mAfPatchHandle;
4028 }
4029
Eric Laurent1c333e22014-05-20 10:48:17 -07004030 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004031 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004032 0);
4033 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004034 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004035 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 if (index < 0) {
4037 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4038 &patch, mUidCached);
4039 addAudioPatch(patchDesc->mHandle, patchDesc);
4040 } else {
4041 patchDesc->mPatch = patch;
4042 }
4043 patchDesc->mAfPatchHandle = afPatchHandle;
4044 patchDesc->mUid = mUidCached;
4045 if (patchHandle) {
4046 *patchHandle = patchDesc->mHandle;
4047 }
4048 inputDesc->mPatchHandle = patchDesc->mHandle;
4049 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004050 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004051 }
4052 }
4053 }
4054 return status;
4055}
4056
Eric Laurent6a94d692014-05-20 11:18:06 -07004057status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4058 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004059{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004060 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004061 ssize_t index;
4062 if (patchHandle) {
4063 index = mAudioPatches.indexOfKey(*patchHandle);
4064 } else {
4065 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4066 }
4067 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004068 return INVALID_OPERATION;
4069 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004070 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4071 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004072 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4073 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004074 removeAudioPatch(patchDesc->mHandle);
4075 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004076 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004077 return status;
4078}
4079
4080sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004081 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004082 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004083 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004084 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004085{
4086 // Choose an input profile based on the requested capture parameters: select the first available
4087 // profile supporting all requested parameters.
4088
4089 for (size_t i = 0; i < mHwModules.size(); i++)
4090 {
4091 if (mHwModules[i]->mHandle == 0) {
4092 continue;
4093 }
4094 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4095 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004096 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004097 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004098 if (profile->isCompatibleProfile(device, samplingRate,
4099 &samplingRate /*updatedSamplingRate*/,
4100 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004101 return profile;
4102 }
4103 }
4104 }
4105 return NULL;
4106}
4107
Eric Laurente0720872014-03-11 09:30:41 -07004108audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004109{
4110 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4112 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004113 switch (inputSource) {
4114 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004115 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004116 device = AUDIO_DEVICE_IN_VOICE_CALL;
4117 break;
4118 }
4119 // FALL THROUGH
4120
4121 case AUDIO_SOURCE_DEFAULT:
4122 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004123 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4124 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4125 break;
4126 }
4127 // FALL THROUGH
4128
Eric Laurente552edb2014-03-10 17:42:56 -07004129 case AUDIO_SOURCE_VOICE_RECOGNITION:
4130 case AUDIO_SOURCE_HOTWORD:
4131 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004132 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004133 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004134 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004135 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004136 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004137 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4138 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004139 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004140 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4141 }
4142 break;
4143 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004144 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004145 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004147 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4148 }
4149 break;
4150 case AUDIO_SOURCE_VOICE_DOWNLINK:
4151 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004152 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004153 device = AUDIO_DEVICE_IN_VOICE_CALL;
4154 }
4155 break;
4156 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004157 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004158 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4159 }
4160 break;
4161 default:
4162 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4163 break;
4164 }
4165 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4166 return device;
4167}
4168
Eric Laurente0720872014-03-11 09:30:41 -07004169bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004170{
4171 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4172 device &= ~AUDIO_DEVICE_BIT_IN;
4173 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4174 return true;
4175 }
4176 return false;
4177}
4178
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004179bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4180 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4181}
4182
Eric Laurente0720872014-03-11 09:30:41 -07004183audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004184{
4185 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004186 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004187 if ((input_descriptor->mRefCount > 0)
4188 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4189 return mInputs.keyAt(i);
4190 }
4191 }
4192 return 0;
4193}
4194
4195
Eric Laurente0720872014-03-11 09:30:41 -07004196audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004197{
4198 if (device == AUDIO_DEVICE_NONE) {
4199 // this happens when forcing a route update and no track is active on an output.
4200 // In this case the returned category is not important.
4201 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004202 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004203 // Multiple device selection is either:
4204 // - speaker + one other device: give priority to speaker in this case.
4205 // - one A2DP device + another device: happens with duplicated output. In this case
4206 // retain the device on the A2DP output as the other must not correspond to an active
4207 // selection if not the speaker.
4208 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4209 device = AUDIO_DEVICE_OUT_SPEAKER;
4210 } else {
4211 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4212 }
4213 }
4214
Eric Laurent3b73df72014-03-11 09:06:29 -07004215 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004216 "getDeviceForVolume() invalid device combination: %08x",
4217 device);
4218
4219 return device;
4220}
4221
Eric Laurente0720872014-03-11 09:30:41 -07004222AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004223{
4224 switch(getDeviceForVolume(device)) {
4225 case AUDIO_DEVICE_OUT_EARPIECE:
4226 return DEVICE_CATEGORY_EARPIECE;
4227 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4228 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4229 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4230 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4231 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4232 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4233 return DEVICE_CATEGORY_HEADSET;
4234 case AUDIO_DEVICE_OUT_SPEAKER:
4235 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4236 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4237 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4238 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4239 case AUDIO_DEVICE_OUT_USB_DEVICE:
4240 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4241 default:
4242 return DEVICE_CATEGORY_SPEAKER;
4243 }
4244}
4245
Eric Laurente0720872014-03-11 09:30:41 -07004246float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004247 int indexInUi)
4248{
4249 device_category deviceCategory = getDeviceCategory(device);
4250 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4251
4252 // the volume index in the UI is relative to the min and max volume indices for this stream type
4253 int nbSteps = 1 + curve[VOLMAX].mIndex -
4254 curve[VOLMIN].mIndex;
4255 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4256 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4257
4258 // find what part of the curve this index volume belongs to, or if it's out of bounds
4259 int segment = 0;
4260 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4261 return 0.0f;
4262 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4263 segment = 0;
4264 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4265 segment = 1;
4266 } else if (volIdx <= curve[VOLMAX].mIndex) {
4267 segment = 2;
4268 } else { // out of bounds
4269 return 1.0f;
4270 }
4271
4272 // linear interpolation in the attenuation table in dB
4273 float decibels = curve[segment].mDBAttenuation +
4274 ((float)(volIdx - curve[segment].mIndex)) *
4275 ( (curve[segment+1].mDBAttenuation -
4276 curve[segment].mDBAttenuation) /
4277 ((float)(curve[segment+1].mIndex -
4278 curve[segment].mIndex)) );
4279
4280 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4281
4282 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4283 curve[segment].mIndex, volIdx,
4284 curve[segment+1].mIndex,
4285 curve[segment].mDBAttenuation,
4286 decibels,
4287 curve[segment+1].mDBAttenuation,
4288 amplification);
4289
4290 return amplification;
4291}
4292
Eric Laurente0720872014-03-11 09:30:41 -07004293const AudioPolicyManager::VolumeCurvePoint
4294 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004295 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4296};
4297
Eric Laurente0720872014-03-11 09:30:41 -07004298const AudioPolicyManager::VolumeCurvePoint
4299 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004300 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4301};
4302
Eric Laurente0720872014-03-11 09:30:41 -07004303const AudioPolicyManager::VolumeCurvePoint
4304 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004305 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4306};
4307
Eric Laurente0720872014-03-11 09:30:41 -07004308const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004309 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004310 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004311};
4312
4313const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004314 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004315 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4316};
4317
Eric Laurente0720872014-03-11 09:30:41 -07004318const AudioPolicyManager::VolumeCurvePoint
4319 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004320 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4321};
4322
4323// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4324// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4325// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4326// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4327
Eric Laurente0720872014-03-11 09:30:41 -07004328const AudioPolicyManager::VolumeCurvePoint
4329 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004330 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4331};
4332
Eric Laurente0720872014-03-11 09:30:41 -07004333const AudioPolicyManager::VolumeCurvePoint
4334 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004335 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4336};
4337
Eric Laurente0720872014-03-11 09:30:41 -07004338const AudioPolicyManager::VolumeCurvePoint
4339 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004340 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4341};
4342
Eric Laurente0720872014-03-11 09:30:41 -07004343const AudioPolicyManager::VolumeCurvePoint
4344 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004345 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4346};
4347
Eric Laurente0720872014-03-11 09:30:41 -07004348const AudioPolicyManager::VolumeCurvePoint
4349 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004350 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4351};
4352
Eric Laurente0720872014-03-11 09:30:41 -07004353const AudioPolicyManager::VolumeCurvePoint
4354 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4355 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004356 { // AUDIO_STREAM_VOICE_CALL
4357 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4358 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4359 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4360 },
4361 { // AUDIO_STREAM_SYSTEM
4362 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4363 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4364 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4365 },
4366 { // AUDIO_STREAM_RING
4367 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4368 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4369 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4370 },
4371 { // AUDIO_STREAM_MUSIC
4372 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4373 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4374 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4375 },
4376 { // AUDIO_STREAM_ALARM
4377 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4378 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4379 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4380 },
4381 { // AUDIO_STREAM_NOTIFICATION
4382 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4383 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4384 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4385 },
4386 { // AUDIO_STREAM_BLUETOOTH_SCO
4387 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4388 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4389 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4390 },
4391 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4392 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4393 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4394 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4395 },
4396 { // AUDIO_STREAM_DTMF
4397 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4398 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4399 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4400 },
4401 { // AUDIO_STREAM_TTS
4402 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4403 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4404 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4405 },
4406};
4407
Eric Laurente0720872014-03-11 09:30:41 -07004408void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004409{
4410 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4411 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4412 mStreams[i].mVolumeCurve[j] =
4413 sVolumeProfiles[i][j];
4414 }
4415 }
4416
4417 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4418 if (mSpeakerDrcEnabled) {
4419 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4420 sDefaultSystemVolumeCurveDrc;
4421 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4422 sSpeakerSonificationVolumeCurveDrc;
4423 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4424 sSpeakerSonificationVolumeCurveDrc;
4425 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4426 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004427 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4428 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004429 }
4430}
4431
Eric Laurente0720872014-03-11 09:30:41 -07004432float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004433 int index,
4434 audio_io_handle_t output,
4435 audio_devices_t device)
4436{
4437 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004438 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004439 StreamDescriptor &streamDesc = mStreams[stream];
4440
4441 if (device == AUDIO_DEVICE_NONE) {
4442 device = outputDesc->device();
4443 }
4444
Eric Laurente552edb2014-03-10 17:42:56 -07004445 volume = volIndexToAmpl(device, streamDesc, index);
4446
4447 // if a headset is connected, apply the following rules to ring tones and notifications
4448 // to avoid sound level bursts in user's ears:
4449 // - always attenuate ring tones and notifications volume by 6dB
4450 // - if music is playing, always limit the volume to current music volume,
4451 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004452 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004453 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4454 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4455 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4456 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4457 ((stream_strategy == STRATEGY_SONIFICATION)
4458 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004459 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004460 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004461 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004462 streamDesc.mCanBeMuted) {
4463 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4464 // when the phone is ringing we must consider that music could have been paused just before
4465 // by the music application and behave as if music was active if the last music track was
4466 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004467 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004468 mLimitRingtoneVolume) {
4469 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004470 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4471 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004472 output,
4473 musicDevice);
4474 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4475 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4476 if (volume > minVol) {
4477 volume = minVol;
4478 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4479 }
4480 }
4481 }
4482
4483 return volume;
4484}
4485
Eric Laurente0720872014-03-11 09:30:41 -07004486status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004487 int index,
4488 audio_io_handle_t output,
4489 audio_devices_t device,
4490 int delayMs,
4491 bool force)
4492{
4493
4494 // do not change actual stream volume if the stream is muted
4495 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4496 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4497 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4498 return NO_ERROR;
4499 }
4500
4501 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004502 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4503 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4504 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4505 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004506 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004507 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004508 return INVALID_OPERATION;
4509 }
4510
4511 float volume = computeVolume(stream, index, output, device);
4512 // We actually change the volume if:
4513 // - the float value returned by computeVolume() changed
4514 // - the force flag is set
4515 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4516 force) {
4517 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4518 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4519 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4520 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004521 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4522 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004523 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004524 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004525 }
4526
Eric Laurent3b73df72014-03-11 09:06:29 -07004527 if (stream == AUDIO_STREAM_VOICE_CALL ||
4528 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004529 float voiceVolume;
4530 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004531 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004532 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4533 } else {
4534 voiceVolume = 1.0;
4535 }
4536
4537 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4538 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4539 mLastVoiceVolume = voiceVolume;
4540 }
4541 }
4542
4543 return NO_ERROR;
4544}
4545
Eric Laurente0720872014-03-11 09:30:41 -07004546void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004547 audio_devices_t device,
4548 int delayMs,
4549 bool force)
4550{
4551 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4552
Eric Laurent3b73df72014-03-11 09:06:29 -07004553 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4554 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004555 mStreams[stream].getVolumeIndex(device),
4556 output,
4557 device,
4558 delayMs,
4559 force);
4560 }
4561}
4562
Eric Laurente0720872014-03-11 09:30:41 -07004563void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004564 bool on,
4565 audio_io_handle_t output,
4566 int delayMs,
4567 audio_devices_t device)
4568{
4569 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004570 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4571 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4572 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004573 }
4574 }
4575}
4576
Eric Laurente0720872014-03-11 09:30:41 -07004577void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004578 bool on,
4579 audio_io_handle_t output,
4580 int delayMs,
4581 audio_devices_t device)
4582{
4583 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004584 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004585 if (device == AUDIO_DEVICE_NONE) {
4586 device = outputDesc->device();
4587 }
4588
4589 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4590 stream, on, output, outputDesc->mMuteCount[stream], device);
4591
4592 if (on) {
4593 if (outputDesc->mMuteCount[stream] == 0) {
4594 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004595 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4596 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004597 checkAndSetVolume(stream, 0, output, device, delayMs);
4598 }
4599 }
4600 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4601 outputDesc->mMuteCount[stream]++;
4602 } else {
4603 if (outputDesc->mMuteCount[stream] == 0) {
4604 ALOGV("setStreamMute() unmuting non muted stream!");
4605 return;
4606 }
4607 if (--outputDesc->mMuteCount[stream] == 0) {
4608 checkAndSetVolume(stream,
4609 streamDesc.getVolumeIndex(device),
4610 output,
4611 device,
4612 delayMs);
4613 }
4614 }
4615}
4616
Eric Laurente0720872014-03-11 09:30:41 -07004617void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004618 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004619{
4620 // if the stream pertains to sonification strategy and we are in call we must
4621 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4622 // in the device used for phone strategy and play the tone if the selected device does not
4623 // interfere with the device used for phone strategy
4624 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4625 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004626 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4628 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004629 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004630 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4631 stream, starting, outputDesc->mDevice, stateChange);
4632 if (outputDesc->mRefCount[stream]) {
4633 int muteCount = 1;
4634 if (stateChange) {
4635 muteCount = outputDesc->mRefCount[stream];
4636 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004637 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004638 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4639 for (int i = 0; i < muteCount; i++) {
4640 setStreamMute(stream, starting, mPrimaryOutput);
4641 }
4642 } else {
4643 ALOGV("handleIncallSonification() high visibility");
4644 if (outputDesc->device() &
4645 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4646 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4647 for (int i = 0; i < muteCount; i++) {
4648 setStreamMute(stream, starting, mPrimaryOutput);
4649 }
4650 }
4651 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004652 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4653 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004654 } else {
4655 mpClientInterface->stopTone();
4656 }
4657 }
4658 }
4659 }
4660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
4664 return isStateInCall(mPhoneState);
4665}
4666
Eric Laurente0720872014-03-11 09:30:41 -07004667bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004668 return ((state == AUDIO_MODE_IN_CALL) ||
4669 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004670}
4671
Eric Laurente0720872014-03-11 09:30:41 -07004672uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004673{
4674 return MAX_EFFECTS_CPU_LOAD;
4675}
4676
Eric Laurente0720872014-03-11 09:30:41 -07004677uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004678{
4679 return MAX_EFFECTS_MEMORY;
4680}
4681
Eric Laurent6a94d692014-05-20 11:18:06 -07004682
Eric Laurente552edb2014-03-10 17:42:56 -07004683// --- AudioOutputDescriptor class implementation
4684
Eric Laurente0720872014-03-11 09:30:41 -07004685AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004686 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004687 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004688 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004689 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4690{
4691 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004692 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004693 mRefCount[i] = 0;
4694 mCurVolume[i] = -1.0;
4695 mMuteCount[i] = 0;
4696 mStopTime[i] = 0;
4697 }
4698 for (int i = 0; i < NUM_STRATEGIES; i++) {
4699 mStrategyMutedByDevice[i] = false;
4700 }
4701 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004702 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004703 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004704 mSamplingRate = profile->pickSamplingRate();
4705 mFormat = profile->pickFormat();
4706 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004707 if (profile->mGains.size() > 0) {
4708 profile->mGains[0]->getDefaultConfig(&mGain);
4709 }
Eric Laurente552edb2014-03-10 17:42:56 -07004710 }
4711}
4712
Eric Laurente0720872014-03-11 09:30:41 -07004713audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004714{
4715 if (isDuplicated()) {
4716 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4717 } else {
4718 return mDevice;
4719 }
4720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
4724 if (isDuplicated()) {
4725 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4726 } else {
4727 return mLatency;
4728 }
4729}
4730
Eric Laurente0720872014-03-11 09:30:41 -07004731bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004732 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004733{
4734 if (isDuplicated()) {
4735 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4736 } else if (outputDesc->isDuplicated()){
4737 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4738 } else {
4739 return (mProfile->mModule == outputDesc->mProfile->mModule);
4740 }
4741}
4742
Eric Laurente0720872014-03-11 09:30:41 -07004743void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004744 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004745{
4746 // forward usage count change to attached outputs
4747 if (isDuplicated()) {
4748 mOutput1->changeRefCount(stream, delta);
4749 mOutput2->changeRefCount(stream, delta);
4750 }
4751 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004752 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4753 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004754 mRefCount[stream] = 0;
4755 return;
4756 }
4757 mRefCount[stream] += delta;
4758 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4759}
4760
Eric Laurente0720872014-03-11 09:30:41 -07004761audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004762{
4763 if (isDuplicated()) {
4764 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4765 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004766 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004767 }
4768}
4769
Eric Laurente0720872014-03-11 09:30:41 -07004770bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004771{
4772 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4773}
4774
Eric Laurente0720872014-03-11 09:30:41 -07004775bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004776 uint32_t inPastMs,
4777 nsecs_t sysTime) const
4778{
4779 if ((sysTime == 0) && (inPastMs != 0)) {
4780 sysTime = systemTime();
4781 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004782 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4783 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004784 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004785 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004786 return true;
4787 }
4788 }
4789 return false;
4790}
4791
Eric Laurente0720872014-03-11 09:30:41 -07004792bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004793 uint32_t inPastMs,
4794 nsecs_t sysTime) const
4795{
4796 if (mRefCount[stream] != 0) {
4797 return true;
4798 }
4799 if (inPastMs == 0) {
4800 return false;
4801 }
4802 if (sysTime == 0) {
4803 sysTime = systemTime();
4804 }
4805 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4806 return true;
4807 }
4808 return false;
4809}
4810
Eric Laurent1c333e22014-05-20 10:48:17 -07004811void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 struct audio_port_config *dstConfig,
4813 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004814{
Eric Laurent84c70242014-06-23 08:46:27 -07004815 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4816
Eric Laurent1f2f2232014-06-02 12:01:23 -07004817 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4818 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4819 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004820 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004821 }
4822 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4823
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 dstConfig->id = mId;
4825 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4826 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4828 dstConfig->ext.mix.handle = mIoHandle;
4829 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004830}
4831
4832void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4833 struct audio_port *port) const
4834{
Eric Laurent84c70242014-06-23 08:46:27 -07004835 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004836 mProfile->toAudioPort(port);
4837 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 toAudioPortConfig(&port->active_config);
4839 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004840 port->ext.mix.handle = mIoHandle;
4841 port->ext.mix.latency_class =
4842 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4843}
Eric Laurente552edb2014-03-10 17:42:56 -07004844
Eric Laurente0720872014-03-11 09:30:41 -07004845status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004846{
4847 const size_t SIZE = 256;
4848 char buffer[SIZE];
4849 String8 result;
4850
4851 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4852 result.append(buffer);
4853 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4854 result.append(buffer);
4855 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4856 result.append(buffer);
4857 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4858 result.append(buffer);
4859 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4860 result.append(buffer);
4861 snprintf(buffer, SIZE, " Devices %08x\n", device());
4862 result.append(buffer);
4863 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4864 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004865 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4866 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4867 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004868 result.append(buffer);
4869 }
4870 write(fd, result.string(), result.size());
4871
4872 return NO_ERROR;
4873}
4874
4875// --- AudioInputDescriptor class implementation
4876
Eric Laurent1c333e22014-05-20 10:48:17 -07004877AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004878 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004879 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004880 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004881{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004882 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004883 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004884 mSamplingRate = profile->pickSamplingRate();
4885 mFormat = profile->pickFormat();
4886 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004887 if (profile->mGains.size() > 0) {
4888 profile->mGains[0]->getDefaultConfig(&mGain);
4889 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004890 }
Eric Laurente552edb2014-03-10 17:42:56 -07004891}
4892
Eric Laurent1c333e22014-05-20 10:48:17 -07004893void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 struct audio_port_config *dstConfig,
4895 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004896{
Eric Laurent84c70242014-06-23 08:46:27 -07004897 ALOG_ASSERT(mProfile != 0,
4898 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004899 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4900 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4901 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004902 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004903 }
4904
4905 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4906
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 dstConfig->id = mId;
4908 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4909 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004910 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4911 dstConfig->ext.mix.handle = mIoHandle;
4912 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004913}
4914
4915void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4916 struct audio_port *port) const
4917{
Eric Laurent84c70242014-06-23 08:46:27 -07004918 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4919
Eric Laurent1c333e22014-05-20 10:48:17 -07004920 mProfile->toAudioPort(port);
4921 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 toAudioPortConfig(&port->active_config);
4923 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004924 port->ext.mix.handle = mIoHandle;
4925 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4926}
4927
Eric Laurente0720872014-03-11 09:30:41 -07004928status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004929{
4930 const size_t SIZE = 256;
4931 char buffer[SIZE];
4932 String8 result;
4933
4934 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4935 result.append(buffer);
4936 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4937 result.append(buffer);
4938 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4939 result.append(buffer);
4940 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4941 result.append(buffer);
4942 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4943 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004944 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
4945 result.append(buffer);
4946
Eric Laurente552edb2014-03-10 17:42:56 -07004947 write(fd, result.string(), result.size());
4948
4949 return NO_ERROR;
4950}
4951
4952// --- StreamDescriptor class implementation
4953
Eric Laurente0720872014-03-11 09:30:41 -07004954AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004955 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4956{
4957 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4958}
4959
Eric Laurente0720872014-03-11 09:30:41 -07004960int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004961{
Eric Laurente0720872014-03-11 09:30:41 -07004962 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004963 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4964 if (mIndexCur.indexOfKey(device) < 0) {
4965 device = AUDIO_DEVICE_OUT_DEFAULT;
4966 }
4967 return mIndexCur.valueFor(device);
4968}
4969
Eric Laurente0720872014-03-11 09:30:41 -07004970void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004971{
4972 const size_t SIZE = 256;
4973 char buffer[SIZE];
4974 String8 result;
4975
4976 snprintf(buffer, SIZE, "%s %02d %02d ",
4977 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4978 result.append(buffer);
4979 for (size_t i = 0; i < mIndexCur.size(); i++) {
4980 snprintf(buffer, SIZE, "%04x : %02d, ",
4981 mIndexCur.keyAt(i),
4982 mIndexCur.valueAt(i));
4983 result.append(buffer);
4984 }
4985 result.append("\n");
4986
4987 write(fd, result.string(), result.size());
4988}
4989
4990// --- EffectDescriptor class implementation
4991
Eric Laurente0720872014-03-11 09:30:41 -07004992status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004993{
4994 const size_t SIZE = 256;
4995 char buffer[SIZE];
4996 String8 result;
4997
4998 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4999 result.append(buffer);
5000 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5001 result.append(buffer);
5002 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5003 result.append(buffer);
5004 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5005 result.append(buffer);
5006 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5007 result.append(buffer);
5008 write(fd, result.string(), result.size());
5009
5010 return NO_ERROR;
5011}
5012
Eric Laurent1c333e22014-05-20 10:48:17 -07005013// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005014
Eric Laurente0720872014-03-11 09:30:41 -07005015AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005016 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5017 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005018{
5019}
5020
Eric Laurente0720872014-03-11 09:30:41 -07005021AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005022{
5023 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005024 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005025 }
5026 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005027 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005028 }
5029 free((void *)mName);
5030}
5031
Eric Laurent1afeecb2014-05-14 08:52:28 -07005032status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5033{
5034 cnode *node = root->first_child;
5035
5036 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5037
5038 while (node) {
5039 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5040 profile->loadSamplingRates((char *)node->value);
5041 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5042 profile->loadFormats((char *)node->value);
5043 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5044 profile->loadInChannels((char *)node->value);
5045 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5046 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5047 mDeclaredDevices);
5048 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5049 profile->loadGains(node);
5050 }
5051 node = node->next;
5052 }
5053 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5054 "loadInput() invalid supported devices");
5055 ALOGW_IF(profile->mChannelMasks.size() == 0,
5056 "loadInput() invalid supported channel masks");
5057 ALOGW_IF(profile->mSamplingRates.size() == 0,
5058 "loadInput() invalid supported sampling rates");
5059 ALOGW_IF(profile->mFormats.size() == 0,
5060 "loadInput() invalid supported formats");
5061 if (!profile->mSupportedDevices.isEmpty() &&
5062 (profile->mChannelMasks.size() != 0) &&
5063 (profile->mSamplingRates.size() != 0) &&
5064 (profile->mFormats.size() != 0)) {
5065
5066 ALOGV("loadInput() adding input Supported Devices %04x",
5067 profile->mSupportedDevices.types());
5068
5069 mInputProfiles.add(profile);
5070 return NO_ERROR;
5071 } else {
5072 return BAD_VALUE;
5073 }
5074}
5075
5076status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5077{
5078 cnode *node = root->first_child;
5079
5080 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5081
5082 while (node) {
5083 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5084 profile->loadSamplingRates((char *)node->value);
5085 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5086 profile->loadFormats((char *)node->value);
5087 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5088 profile->loadOutChannels((char *)node->value);
5089 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5090 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5091 mDeclaredDevices);
5092 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5093 profile->mFlags = parseFlagNames((char *)node->value);
5094 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5095 profile->loadGains(node);
5096 }
5097 node = node->next;
5098 }
5099 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5100 "loadOutput() invalid supported devices");
5101 ALOGW_IF(profile->mChannelMasks.size() == 0,
5102 "loadOutput() invalid supported channel masks");
5103 ALOGW_IF(profile->mSamplingRates.size() == 0,
5104 "loadOutput() invalid supported sampling rates");
5105 ALOGW_IF(profile->mFormats.size() == 0,
5106 "loadOutput() invalid supported formats");
5107 if (!profile->mSupportedDevices.isEmpty() &&
5108 (profile->mChannelMasks.size() != 0) &&
5109 (profile->mSamplingRates.size() != 0) &&
5110 (profile->mFormats.size() != 0)) {
5111
5112 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5113 profile->mSupportedDevices.types(), profile->mFlags);
5114
5115 mOutputProfiles.add(profile);
5116 return NO_ERROR;
5117 } else {
5118 return BAD_VALUE;
5119 }
5120}
5121
5122status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5123{
5124 cnode *node = root->first_child;
5125
5126 audio_devices_t type = AUDIO_DEVICE_NONE;
5127 while (node) {
5128 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5129 type = parseDeviceNames((char *)node->value);
5130 break;
5131 }
5132 node = node->next;
5133 }
5134 if (type == AUDIO_DEVICE_NONE ||
5135 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5136 ALOGW("loadDevice() bad type %08x", type);
5137 return BAD_VALUE;
5138 }
5139 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5140 deviceDesc->mModule = this;
5141
5142 node = root->first_child;
5143 while (node) {
5144 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5145 deviceDesc->mAddress = String8((char *)node->value);
5146 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5147 if (audio_is_input_device(type)) {
5148 deviceDesc->loadInChannels((char *)node->value);
5149 } else {
5150 deviceDesc->loadOutChannels((char *)node->value);
5151 }
5152 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5153 deviceDesc->loadGains(node);
5154 }
5155 node = node->next;
5156 }
5157
5158 ALOGV("loadDevice() adding device name %s type %08x address %s",
5159 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5160
5161 mDeclaredDevices.add(deviceDesc);
5162
5163 return NO_ERROR;
5164}
5165
Eric Laurente0720872014-03-11 09:30:41 -07005166void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005167{
5168 const size_t SIZE = 256;
5169 char buffer[SIZE];
5170 String8 result;
5171
5172 snprintf(buffer, SIZE, " - name: %s\n", mName);
5173 result.append(buffer);
5174 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5175 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005176 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5177 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005178 write(fd, result.string(), result.size());
5179 if (mOutputProfiles.size()) {
5180 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5181 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005182 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005183 write(fd, buffer, strlen(buffer));
5184 mOutputProfiles[i]->dump(fd);
5185 }
5186 }
5187 if (mInputProfiles.size()) {
5188 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5189 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005190 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005191 write(fd, buffer, strlen(buffer));
5192 mInputProfiles[i]->dump(fd);
5193 }
5194 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005195 if (mDeclaredDevices.size()) {
5196 write(fd, " - devices:\n", strlen(" - devices:\n"));
5197 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5198 mDeclaredDevices[i]->dump(fd, 4, i);
5199 }
5200 }
Eric Laurente552edb2014-03-10 17:42:56 -07005201}
5202
Eric Laurent1c333e22014-05-20 10:48:17 -07005203// --- AudioPort class implementation
5204
Eric Laurenta121f902014-06-03 13:32:54 -07005205
5206AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5207 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005208 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005209{
5210 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5211 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5212}
5213
Eric Laurent1c333e22014-05-20 10:48:17 -07005214void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5215{
5216 port->role = mRole;
5217 port->type = mType;
5218 unsigned int i;
5219 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5220 port->sample_rates[i] = mSamplingRates[i];
5221 }
5222 port->num_sample_rates = i;
5223 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5224 port->channel_masks[i] = mChannelMasks[i];
5225 }
5226 port->num_channel_masks = i;
5227 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5228 port->formats[i] = mFormats[i];
5229 }
5230 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005231
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005232 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005233
5234 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5235 port->gains[i] = mGains[i]->mGain;
5236 }
5237 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005238}
5239
5240
5241void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5242{
5243 char *str = strtok(name, "|");
5244
5245 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5246 // rates should be read from the output stream after it is opened for the first time
5247 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5248 mSamplingRates.add(0);
5249 return;
5250 }
5251
5252 while (str != NULL) {
5253 uint32_t rate = atoi(str);
5254 if (rate != 0) {
5255 ALOGV("loadSamplingRates() adding rate %d", rate);
5256 mSamplingRates.add(rate);
5257 }
5258 str = strtok(NULL, "|");
5259 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005260}
5261
5262void AudioPolicyManager::AudioPort::loadFormats(char *name)
5263{
5264 char *str = strtok(name, "|");
5265
5266 // by convention, "0' in the first entry in mFormats indicates the supported formats
5267 // should be read from the output stream after it is opened for the first time
5268 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5269 mFormats.add(AUDIO_FORMAT_DEFAULT);
5270 return;
5271 }
5272
5273 while (str != NULL) {
5274 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5275 ARRAY_SIZE(sFormatNameToEnumTable),
5276 str);
5277 if (format != AUDIO_FORMAT_DEFAULT) {
5278 mFormats.add(format);
5279 }
5280 str = strtok(NULL, "|");
5281 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005282}
5283
5284void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5285{
5286 const char *str = strtok(name, "|");
5287
5288 ALOGV("loadInChannels() %s", name);
5289
5290 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5291 mChannelMasks.add(0);
5292 return;
5293 }
5294
5295 while (str != NULL) {
5296 audio_channel_mask_t channelMask =
5297 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5298 ARRAY_SIZE(sInChannelsNameToEnumTable),
5299 str);
5300 if (channelMask != 0) {
5301 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5302 mChannelMasks.add(channelMask);
5303 }
5304 str = strtok(NULL, "|");
5305 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005306}
5307
5308void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5309{
5310 const char *str = strtok(name, "|");
5311
5312 ALOGV("loadOutChannels() %s", name);
5313
5314 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5315 // masks should be read from the output stream after it is opened for the first time
5316 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5317 mChannelMasks.add(0);
5318 return;
5319 }
5320
5321 while (str != NULL) {
5322 audio_channel_mask_t channelMask =
5323 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5324 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5325 str);
5326 if (channelMask != 0) {
5327 mChannelMasks.add(channelMask);
5328 }
5329 str = strtok(NULL, "|");
5330 }
5331 return;
5332}
5333
Eric Laurent1afeecb2014-05-14 08:52:28 -07005334audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5335{
5336 const char *str = strtok(name, "|");
5337
5338 ALOGV("loadGainMode() %s", name);
5339 audio_gain_mode_t mode = 0;
5340 while (str != NULL) {
5341 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5342 ARRAY_SIZE(sGainModeNameToEnumTable),
5343 str);
5344 str = strtok(NULL, "|");
5345 }
5346 return mode;
5347}
5348
Eric Laurenta121f902014-06-03 13:32:54 -07005349void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005350{
5351 cnode *node = root->first_child;
5352
Eric Laurenta121f902014-06-03 13:32:54 -07005353 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005354
5355 while (node) {
5356 if (strcmp(node->name, GAIN_MODE) == 0) {
5357 gain->mGain.mode = loadGainMode((char *)node->value);
5358 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005359 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005360 gain->mGain.channel_mask =
5361 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5362 ARRAY_SIZE(sInChannelsNameToEnumTable),
5363 (char *)node->value);
5364 } else {
5365 gain->mGain.channel_mask =
5366 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5367 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5368 (char *)node->value);
5369 }
5370 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5371 gain->mGain.min_value = atoi((char *)node->value);
5372 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5373 gain->mGain.max_value = atoi((char *)node->value);
5374 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5375 gain->mGain.default_value = atoi((char *)node->value);
5376 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5377 gain->mGain.step_value = atoi((char *)node->value);
5378 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5379 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5380 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5381 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5382 }
5383 node = node->next;
5384 }
5385
5386 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5387 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5388
5389 if (gain->mGain.mode == 0) {
5390 return;
5391 }
5392 mGains.add(gain);
5393}
5394
5395void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5396{
5397 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005398 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005399 while (node) {
5400 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005401 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005402 node = node->next;
5403 }
5404}
5405
Glenn Kastencbd48022014-07-24 13:46:44 -07005406status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005407{
5408 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5409 if (mSamplingRates[i] == samplingRate) {
5410 return NO_ERROR;
5411 }
5412 }
5413 return BAD_VALUE;
5414}
5415
Glenn Kastencbd48022014-07-24 13:46:44 -07005416status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5417 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005418{
Glenn Kastencbd48022014-07-24 13:46:44 -07005419 // Search for the closest supported sampling rate that is above (preferred)
5420 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5421 // The sampling rates do not need to be sorted in ascending order.
5422 ssize_t maxBelow = -1;
5423 ssize_t minAbove = -1;
5424 uint32_t candidate;
5425 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5426 candidate = mSamplingRates[i];
5427 if (candidate == samplingRate) {
5428 if (updatedSamplingRate != NULL) {
5429 *updatedSamplingRate = candidate;
5430 }
5431 return NO_ERROR;
5432 }
5433 // candidate < desired
5434 if (candidate < samplingRate) {
5435 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5436 maxBelow = i;
5437 }
5438 // candidate > desired
5439 } else {
5440 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5441 minAbove = i;
5442 }
5443 }
5444 }
5445 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5446 // TODO Move these assumptions out.
5447 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5448 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5449 // due to approximation by an int32_t of the
5450 // phase increments
5451 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5452 if (minAbove >= 0) {
5453 candidate = mSamplingRates[minAbove];
5454 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5455 if (updatedSamplingRate != NULL) {
5456 *updatedSamplingRate = candidate;
5457 }
5458 return NO_ERROR;
5459 }
5460 }
5461 // But if we have to up-sample from a lower sampling rate, that's OK.
5462 if (maxBelow >= 0) {
5463 candidate = mSamplingRates[maxBelow];
5464 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5465 if (updatedSamplingRate != NULL) {
5466 *updatedSamplingRate = candidate;
5467 }
5468 return NO_ERROR;
5469 }
5470 }
5471 // leave updatedSamplingRate unmodified
5472 return BAD_VALUE;
5473}
5474
5475status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5476{
5477 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005478 if (mChannelMasks[i] == channelMask) {
5479 return NO_ERROR;
5480 }
5481 }
5482 return BAD_VALUE;
5483}
5484
Glenn Kastencbd48022014-07-24 13:46:44 -07005485status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5486 const
5487{
5488 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5489 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5490 // FIXME Does not handle multi-channel automatic conversions yet
5491 audio_channel_mask_t supported = mChannelMasks[i];
5492 if (supported == channelMask) {
5493 return NO_ERROR;
5494 }
5495 if (isRecordThread) {
5496 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5497 // FIXME Abstract this out to a table.
5498 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5499 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5500 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5501 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5502 return NO_ERROR;
5503 }
5504 }
5505 }
5506 return BAD_VALUE;
5507}
5508
Eric Laurenta121f902014-06-03 13:32:54 -07005509status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5510{
5511 for (size_t i = 0; i < mFormats.size(); i ++) {
5512 if (mFormats[i] == format) {
5513 return NO_ERROR;
5514 }
5515 }
5516 return BAD_VALUE;
5517}
5518
Eric Laurent1e693b52014-07-09 15:03:28 -07005519
5520uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5521{
5522 // special case for uninitialized dynamic profile
5523 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5524 return 0;
5525 }
5526
5527 uint32_t samplingRate = 0;
5528 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5529
5530 // For mixed output and inputs, use max mixer sampling rates. Do not
5531 // limit sampling rate otherwise
5532 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5533 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5534 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5535 maxRate = UINT_MAX;
5536 }
5537 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5538 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5539 samplingRate = mSamplingRates[i];
5540 }
5541 }
5542 return samplingRate;
5543}
5544
5545audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5546{
5547 // special case for uninitialized dynamic profile
5548 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5549 return AUDIO_CHANNEL_NONE;
5550 }
5551
5552 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5553 uint32_t channelCount = 0;
5554 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5555
5556 // For mixed output and inputs, use max mixer channel count. Do not
5557 // limit channel count otherwise
5558 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5559 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5560 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5561 maxCount = UINT_MAX;
5562 }
5563 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5564 uint32_t cnlCount;
5565 if (mUseInChannelMask) {
5566 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5567 } else {
5568 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5569 }
5570 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5571 channelMask = mChannelMasks[i];
5572 }
5573 }
5574 return channelMask;
5575}
5576
5577const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5578 AUDIO_FORMAT_DEFAULT,
5579 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005580 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005581 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005582 AUDIO_FORMAT_PCM_32_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005583};
5584
5585int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5586 audio_format_t format2)
5587{
5588 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5589 // compressed format and better than any PCM format. This is by design of pickFormat()
5590 if (!audio_is_linear_pcm(format1)) {
5591 if (!audio_is_linear_pcm(format2)) {
5592 return 0;
5593 }
5594 return 1;
5595 }
5596 if (!audio_is_linear_pcm(format2)) {
5597 return -1;
5598 }
5599
5600 int index1 = -1, index2 = -1;
5601 for (size_t i = 0;
5602 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5603 i ++) {
5604 if (sPcmFormatCompareTable[i] == format1) {
5605 index1 = i;
5606 }
5607 if (sPcmFormatCompareTable[i] == format2) {
5608 index2 = i;
5609 }
5610 }
5611 // format1 not found => index1 < 0 => format2 > format1
5612 // format2 not found => index2 < 0 => format2 < format1
5613 return index1 - index2;
5614}
5615
5616audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5617{
5618 // special case for uninitialized dynamic profile
5619 if (mFormats.size() == 1 && mFormats[0] == 0) {
5620 return AUDIO_FORMAT_DEFAULT;
5621 }
5622
5623 audio_format_t format = AUDIO_FORMAT_DEFAULT;
5624 audio_format_t bestFormat = BEST_MIXER_FORMAT;
5625 // For mixed output and inputs, use best mixer output format. Do not
5626 // limit format otherwise
5627 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5628 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005629 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005630 bestFormat = AUDIO_FORMAT_INVALID;
5631 }
5632
5633 for (size_t i = 0; i < mFormats.size(); i ++) {
5634 if ((compareFormats(mFormats[i], format) > 0) &&
5635 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5636 format = mFormats[i];
5637 }
5638 }
5639 return format;
5640}
5641
Eric Laurenta121f902014-06-03 13:32:54 -07005642status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5643 int index) const
5644{
5645 if (index < 0 || (size_t)index >= mGains.size()) {
5646 return BAD_VALUE;
5647 }
5648 return mGains[index]->checkConfig(gainConfig);
5649}
5650
Eric Laurent1afeecb2014-05-14 08:52:28 -07005651void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5652{
5653 const size_t SIZE = 256;
5654 char buffer[SIZE];
5655 String8 result;
5656
5657 if (mName.size() != 0) {
5658 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5659 result.append(buffer);
5660 }
5661
5662 if (mSamplingRates.size() != 0) {
5663 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5664 result.append(buffer);
5665 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005666 if (i == 0 && mSamplingRates[i] == 0) {
5667 snprintf(buffer, SIZE, "Dynamic");
5668 } else {
5669 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5670 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005671 result.append(buffer);
5672 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5673 }
5674 result.append("\n");
5675 }
5676
5677 if (mChannelMasks.size() != 0) {
5678 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5679 result.append(buffer);
5680 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005681 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5682
5683 if (i == 0 && mChannelMasks[i] == 0) {
5684 snprintf(buffer, SIZE, "Dynamic");
5685 } else {
5686 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5687 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005688 result.append(buffer);
5689 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5690 }
5691 result.append("\n");
5692 }
5693
5694 if (mFormats.size() != 0) {
5695 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5696 result.append(buffer);
5697 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005698 const char *formatStr = enumToString(sFormatNameToEnumTable,
5699 ARRAY_SIZE(sFormatNameToEnumTable),
5700 mFormats[i]);
5701 if (i == 0 && strcmp(formatStr, "") == 0) {
5702 snprintf(buffer, SIZE, "Dynamic");
5703 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005704 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005705 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005706 result.append(buffer);
5707 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5708 }
5709 result.append("\n");
5710 }
5711 write(fd, result.string(), result.size());
5712 if (mGains.size() != 0) {
5713 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5714 write(fd, buffer, strlen(buffer) + 1);
5715 result.append(buffer);
5716 for (size_t i = 0; i < mGains.size(); i++) {
5717 mGains[i]->dump(fd, spaces + 2, i);
5718 }
5719 }
5720}
5721
5722// --- AudioGain class implementation
5723
Eric Laurenta121f902014-06-03 13:32:54 -07005724AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005725{
Eric Laurenta121f902014-06-03 13:32:54 -07005726 mIndex = index;
5727 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005728 memset(&mGain, 0, sizeof(struct audio_gain));
5729}
5730
Eric Laurenta121f902014-06-03 13:32:54 -07005731void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5732{
5733 config->index = mIndex;
5734 config->mode = mGain.mode;
5735 config->channel_mask = mGain.channel_mask;
5736 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5737 config->values[0] = mGain.default_value;
5738 } else {
5739 uint32_t numValues;
5740 if (mUseInChannelMask) {
5741 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5742 } else {
5743 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5744 }
5745 for (size_t i = 0; i < numValues; i++) {
5746 config->values[i] = mGain.default_value;
5747 }
5748 }
5749 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5750 config->ramp_duration_ms = mGain.min_ramp_ms;
5751 }
5752}
5753
5754status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5755{
5756 if ((config->mode & ~mGain.mode) != 0) {
5757 return BAD_VALUE;
5758 }
5759 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5760 if ((config->values[0] < mGain.min_value) ||
5761 (config->values[0] > mGain.max_value)) {
5762 return BAD_VALUE;
5763 }
5764 } else {
5765 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5766 return BAD_VALUE;
5767 }
5768 uint32_t numValues;
5769 if (mUseInChannelMask) {
5770 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5771 } else {
5772 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5773 }
5774 for (size_t i = 0; i < numValues; i++) {
5775 if ((config->values[i] < mGain.min_value) ||
5776 (config->values[i] > mGain.max_value)) {
5777 return BAD_VALUE;
5778 }
5779 }
5780 }
5781 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5782 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5783 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5784 return BAD_VALUE;
5785 }
5786 }
5787 return NO_ERROR;
5788}
5789
Eric Laurent1afeecb2014-05-14 08:52:28 -07005790void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5791{
5792 const size_t SIZE = 256;
5793 char buffer[SIZE];
5794 String8 result;
5795
5796 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5797 result.append(buffer);
5798 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5799 result.append(buffer);
5800 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5801 result.append(buffer);
5802 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5803 result.append(buffer);
5804 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5805 result.append(buffer);
5806 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5807 result.append(buffer);
5808 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5809 result.append(buffer);
5810 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5811 result.append(buffer);
5812 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5813 result.append(buffer);
5814
5815 write(fd, result.string(), result.size());
5816}
5817
Eric Laurent1f2f2232014-06-02 12:01:23 -07005818// --- AudioPortConfig class implementation
5819
5820AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5821{
5822 mSamplingRate = 0;
5823 mChannelMask = AUDIO_CHANNEL_NONE;
5824 mFormat = AUDIO_FORMAT_INVALID;
5825 mGain.index = -1;
5826}
5827
Eric Laurenta121f902014-06-03 13:32:54 -07005828status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5829 const struct audio_port_config *config,
5830 struct audio_port_config *backupConfig)
5831{
5832 struct audio_port_config localBackupConfig;
5833 status_t status = NO_ERROR;
5834
5835 localBackupConfig.config_mask = config->config_mask;
5836 toAudioPortConfig(&localBackupConfig);
5837
5838 if (mAudioPort == 0) {
5839 status = NO_INIT;
5840 goto exit;
5841 }
5842 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005843 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005844 if (status != NO_ERROR) {
5845 goto exit;
5846 }
5847 mSamplingRate = config->sample_rate;
5848 }
5849 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005850 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005851 if (status != NO_ERROR) {
5852 goto exit;
5853 }
5854 mChannelMask = config->channel_mask;
5855 }
5856 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5857 status = mAudioPort->checkFormat(config->format);
5858 if (status != NO_ERROR) {
5859 goto exit;
5860 }
5861 mFormat = config->format;
5862 }
5863 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5864 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5865 if (status != NO_ERROR) {
5866 goto exit;
5867 }
5868 mGain = config->gain;
5869 }
5870
5871exit:
5872 if (status != NO_ERROR) {
5873 applyAudioPortConfig(&localBackupConfig);
5874 }
5875 if (backupConfig != NULL) {
5876 *backupConfig = localBackupConfig;
5877 }
5878 return status;
5879}
5880
Eric Laurent1f2f2232014-06-02 12:01:23 -07005881void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5882 struct audio_port_config *dstConfig,
5883 const struct audio_port_config *srcConfig) const
5884{
5885 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5886 dstConfig->sample_rate = mSamplingRate;
5887 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5888 dstConfig->sample_rate = srcConfig->sample_rate;
5889 }
5890 } else {
5891 dstConfig->sample_rate = 0;
5892 }
5893 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5894 dstConfig->channel_mask = mChannelMask;
5895 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5896 dstConfig->channel_mask = srcConfig->channel_mask;
5897 }
5898 } else {
5899 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5900 }
5901 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5902 dstConfig->format = mFormat;
5903 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5904 dstConfig->format = srcConfig->format;
5905 }
5906 } else {
5907 dstConfig->format = AUDIO_FORMAT_INVALID;
5908 }
5909 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5910 dstConfig->gain = mGain;
5911 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5912 dstConfig->gain = srcConfig->gain;
5913 }
5914 } else {
5915 dstConfig->gain.index = -1;
5916 }
5917 if (dstConfig->gain.index != -1) {
5918 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5919 } else {
5920 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5921 }
5922}
5923
Eric Laurent1c333e22014-05-20 10:48:17 -07005924// --- IOProfile class implementation
5925
Eric Laurent1afeecb2014-05-14 08:52:28 -07005926AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005927 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07005928 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07005929{
5930}
5931
Eric Laurente0720872014-03-11 09:30:41 -07005932AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005933{
5934}
5935
5936// checks if the IO profile is compatible with specified parameters.
5937// Sampling rate, format and channel mask must be specified in order to
5938// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005939bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005940 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005941 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005942 audio_format_t format,
5943 audio_channel_mask_t channelMask,
5944 audio_output_flags_t flags) const
5945{
Glenn Kastencbd48022014-07-24 13:46:44 -07005946 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
5947 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5948 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07005949
Glenn Kastencbd48022014-07-24 13:46:44 -07005950 if ((mSupportedDevices.types() & device) != device) {
5951 return false;
5952 }
5953
5954 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005955 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005956 }
5957 uint32_t myUpdatedSamplingRate = samplingRate;
5958 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005959 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005960 }
5961 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
5962 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005963 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005964 }
5965
5966 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
5967 return false;
5968 }
5969
5970 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
5971 checkExactChannelMask(channelMask) != NO_ERROR)) {
5972 return false;
5973 }
5974 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
5975 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
5976 return false;
5977 }
5978
5979 if (isPlaybackThread && (mFlags & flags) != flags) {
5980 return false;
5981 }
5982 // The only input flag that is allowed to be different is the fast flag.
5983 // An existing fast stream is compatible with a normal track request.
5984 // An existing normal stream is compatible with a fast track request,
5985 // but the fast request will be denied by AudioFlinger and converted to normal track.
5986 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
5987 ~AUDIO_INPUT_FLAG_FAST)) {
5988 return false;
5989 }
5990
5991 if (updatedSamplingRate != NULL) {
5992 *updatedSamplingRate = myUpdatedSamplingRate;
5993 }
5994 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07005995}
5996
Eric Laurente0720872014-03-11 09:30:41 -07005997void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005998{
5999 const size_t SIZE = 256;
6000 char buffer[SIZE];
6001 String8 result;
6002
Eric Laurent1afeecb2014-05-14 08:52:28 -07006003 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006004
Eric Laurente552edb2014-03-10 17:42:56 -07006005 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6006 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006007 snprintf(buffer, SIZE, " - devices:\n");
6008 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006009 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006010 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6011 mSupportedDevices[i]->dump(fd, 6, i);
6012 }
Eric Laurente552edb2014-03-10 17:42:56 -07006013}
6014
Eric Laurentd4692962014-05-05 18:13:44 -07006015void AudioPolicyManager::IOProfile::log()
6016{
6017 const size_t SIZE = 256;
6018 char buffer[SIZE];
6019 String8 result;
6020
6021 ALOGV(" - sampling rates: ");
6022 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6023 ALOGV(" %d", mSamplingRates[i]);
6024 }
6025
6026 ALOGV(" - channel masks: ");
6027 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6028 ALOGV(" 0x%04x", mChannelMasks[i]);
6029 }
6030
6031 ALOGV(" - formats: ");
6032 for (size_t i = 0; i < mFormats.size(); i++) {
6033 ALOGV(" 0x%08x", mFormats[i]);
6034 }
6035
6036 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6037 ALOGV(" - flags: 0x%04x\n", mFlags);
6038}
6039
6040
Eric Laurent3a4311c2014-03-17 12:00:47 -07006041// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006042
Eric Laurent1f2f2232014-06-02 12:01:23 -07006043
6044AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6045 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6046 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6047 AUDIO_PORT_ROLE_SOURCE,
6048 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006049 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006050{
6051 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006052 if (mGains.size() > 0) {
6053 mGains[0]->getDefaultConfig(&mGain);
6054 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006055}
6056
Eric Laurent3a4311c2014-03-17 12:00:47 -07006057bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006058{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006059 // Devices are considered equal if they:
6060 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6061 // - have the same address or one device does not specify the address
6062 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006063 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006064 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006065 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006066 mChannelMask == other->mChannelMask);
6067}
6068
6069void AudioPolicyManager::DeviceVector::refreshTypes()
6070{
Eric Laurent1c333e22014-05-20 10:48:17 -07006071 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006072 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006073 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006074 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006075 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006076}
6077
6078ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6079{
6080 for(size_t i = 0; i < size(); i++) {
6081 if (item->equals(itemAt(i))) {
6082 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006083 }
6084 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006085 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006086}
6087
Eric Laurent3a4311c2014-03-17 12:00:47 -07006088ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006089{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006090 ssize_t ret = indexOf(item);
6091
6092 if (ret < 0) {
6093 ret = SortedVector::add(item);
6094 if (ret >= 0) {
6095 refreshTypes();
6096 }
6097 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006098 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006099 ret = -1;
6100 }
6101 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006102}
6103
Eric Laurent3a4311c2014-03-17 12:00:47 -07006104ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6105{
6106 size_t i;
6107 ssize_t ret = indexOf(item);
6108
6109 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006110 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006111 } else {
6112 ret = SortedVector::removeAt(ret);
6113 if (ret >= 0) {
6114 refreshTypes();
6115 }
6116 }
6117 return ret;
6118}
6119
6120void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6121{
6122 DeviceVector deviceList;
6123
6124 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6125 types &= ~role_bit;
6126
6127 while (types) {
6128 uint32_t i = 31 - __builtin_clz(types);
6129 uint32_t type = 1 << i;
6130 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006131 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006132 }
6133}
6134
Eric Laurent1afeecb2014-05-14 08:52:28 -07006135void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6136 const DeviceVector& declaredDevices)
6137{
6138 char *devName = strtok(name, "|");
6139 while (devName != NULL) {
6140 if (strlen(devName) != 0) {
6141 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6142 ARRAY_SIZE(sDeviceNameToEnumTable),
6143 devName);
6144 if (type != AUDIO_DEVICE_NONE) {
6145 add(new DeviceDescriptor(String8(""), type));
6146 } else {
6147 sp<DeviceDescriptor> deviceDesc =
6148 declaredDevices.getDeviceFromName(String8(devName));
6149 if (deviceDesc != 0) {
6150 add(deviceDesc);
6151 }
6152 }
6153 }
6154 devName = strtok(NULL, "|");
6155 }
6156}
6157
Eric Laurent1c333e22014-05-20 10:48:17 -07006158sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6159 audio_devices_t type, String8 address) const
6160{
6161 sp<DeviceDescriptor> device;
6162 for (size_t i = 0; i < size(); i++) {
6163 if (itemAt(i)->mDeviceType == type) {
6164 device = itemAt(i);
6165 if (itemAt(i)->mAddress = address) {
6166 break;
6167 }
6168 }
6169 }
6170 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6171 type, address.string(), device.get());
6172 return device;
6173}
6174
Eric Laurent6a94d692014-05-20 11:18:06 -07006175sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6176 audio_port_handle_t id) const
6177{
6178 sp<DeviceDescriptor> device;
6179 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006180 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006181 if (itemAt(i)->mId == id) {
6182 device = itemAt(i);
6183 break;
6184 }
6185 }
6186 return device;
6187}
6188
Eric Laurent1c333e22014-05-20 10:48:17 -07006189AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6190 audio_devices_t type) const
6191{
6192 DeviceVector devices;
6193 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6194 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6195 devices.add(itemAt(i));
6196 type &= ~itemAt(i)->mDeviceType;
6197 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6198 itemAt(i)->mDeviceType, itemAt(i).get());
6199 }
6200 }
6201 return devices;
6202}
6203
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006204AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6205 audio_devices_t type, String8 address) const
6206{
6207 DeviceVector devices;
6208 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6209 for (size_t i = 0; i < size(); i++) {
6210 //ALOGV(" at i=%d: device=%x, addr=%s",
6211 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6212 if (itemAt(i)->mDeviceType == type) {
6213 if (itemAt(i)->mAddress == address) {
6214 //ALOGV(" found matching address %s", address.string());
6215 devices.add(itemAt(i));
6216 }
6217 }
6218 }
6219 return devices;
6220}
6221
Eric Laurent1afeecb2014-05-14 08:52:28 -07006222sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6223 const String8& name) const
6224{
6225 sp<DeviceDescriptor> device;
6226 for (size_t i = 0; i < size(); i++) {
6227 if (itemAt(i)->mName == name) {
6228 device = itemAt(i);
6229 break;
6230 }
6231 }
6232 return device;
6233}
6234
Eric Laurent6a94d692014-05-20 11:18:06 -07006235void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6236 struct audio_port_config *dstConfig,
6237 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006238{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006239 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6240 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006241 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006242 }
6243
6244 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6245
Eric Laurent6a94d692014-05-20 11:18:06 -07006246 dstConfig->id = mId;
6247 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006248 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006249 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006250 dstConfig->ext.device.type = mDeviceType;
6251 dstConfig->ext.device.hw_module = mModule->mHandle;
6252 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006253}
6254
6255void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6256{
Eric Laurent83b88082014-06-20 18:31:16 -07006257 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006258 AudioPort::toAudioPort(port);
6259 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006260 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006261 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006262 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006263 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6264}
6265
Eric Laurent1afeecb2014-05-14 08:52:28 -07006266status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006267{
6268 const size_t SIZE = 256;
6269 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006270 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006271
Eric Laurent1afeecb2014-05-14 08:52:28 -07006272 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6273 result.append(buffer);
6274 if (mId != 0) {
6275 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6276 result.append(buffer);
6277 }
6278 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6279 enumToString(sDeviceNameToEnumTable,
6280 ARRAY_SIZE(sDeviceNameToEnumTable),
6281 mDeviceType));
6282 result.append(buffer);
6283 if (mAddress.size() != 0) {
6284 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6285 result.append(buffer);
6286 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006287 write(fd, result.string(), result.size());
6288 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006289
6290 return NO_ERROR;
6291}
6292
6293
6294// --- audio_policy.conf file parsing
6295
Eric Laurente0720872014-03-11 09:30:41 -07006296audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006297{
6298 uint32_t flag = 0;
6299
6300 // it is OK to cast name to non const here as we are not going to use it after
6301 // strtok() modifies it
6302 char *flagName = strtok(name, "|");
6303 while (flagName != NULL) {
6304 if (strlen(flagName) != 0) {
6305 flag |= stringToEnum(sFlagNameToEnumTable,
6306 ARRAY_SIZE(sFlagNameToEnumTable),
6307 flagName);
6308 }
6309 flagName = strtok(NULL, "|");
6310 }
6311 //force direct flag if offload flag is set: offloading implies a direct output stream
6312 // and all common behaviors are driven by checking only the direct flag
6313 // this should normally be set appropriately in the policy configuration file
6314 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6315 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6316 }
6317
6318 return (audio_output_flags_t)flag;
6319}
6320
Eric Laurente0720872014-03-11 09:30:41 -07006321audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006322{
6323 uint32_t device = 0;
6324
6325 char *devName = strtok(name, "|");
6326 while (devName != NULL) {
6327 if (strlen(devName) != 0) {
6328 device |= stringToEnum(sDeviceNameToEnumTable,
6329 ARRAY_SIZE(sDeviceNameToEnumTable),
6330 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006331 }
Eric Laurente552edb2014-03-10 17:42:56 -07006332 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006333 }
Eric Laurente552edb2014-03-10 17:42:56 -07006334 return device;
6335}
6336
Eric Laurente0720872014-03-11 09:30:41 -07006337void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006338{
Eric Laurente552edb2014-03-10 17:42:56 -07006339 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006340 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006341 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006342
Eric Laurent1afeecb2014-05-14 08:52:28 -07006343 node = config_find(root, DEVICES_TAG);
6344 if (node != NULL) {
6345 node = node->first_child;
6346 while (node) {
6347 ALOGV("loadHwModule() loading device %s", node->name);
6348 status_t tmpStatus = module->loadDevice(node);
6349 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6350 status = tmpStatus;
6351 }
6352 node = node->next;
6353 }
6354 }
6355 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006356 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006357 node = node->first_child;
6358 while (node) {
6359 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006360 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006361 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6362 status = tmpStatus;
6363 }
6364 node = node->next;
6365 }
6366 }
6367 node = config_find(root, INPUTS_TAG);
6368 if (node != NULL) {
6369 node = node->first_child;
6370 while (node) {
6371 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006372 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006373 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6374 status = tmpStatus;
6375 }
6376 node = node->next;
6377 }
6378 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006379 loadGlobalConfig(root, module);
6380
Eric Laurente552edb2014-03-10 17:42:56 -07006381 if (status == NO_ERROR) {
6382 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006383 }
6384}
6385
Eric Laurente0720872014-03-11 09:30:41 -07006386void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006387{
6388 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6389 if (node == NULL) {
6390 return;
6391 }
6392
6393 node = node->first_child;
6394 while (node) {
6395 ALOGV("loadHwModules() loading module %s", node->name);
6396 loadHwModule(node);
6397 node = node->next;
6398 }
6399}
6400
Eric Laurent1f2f2232014-06-02 12:01:23 -07006401void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006402{
6403 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006404
Eric Laurente552edb2014-03-10 17:42:56 -07006405 if (node == NULL) {
6406 return;
6407 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006408 DeviceVector declaredDevices;
6409 if (module != NULL) {
6410 declaredDevices = module->mDeclaredDevices;
6411 }
6412
Eric Laurente552edb2014-03-10 17:42:56 -07006413 node = node->first_child;
6414 while (node) {
6415 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006416 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6417 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006418 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6419 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006420 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006421 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006422 ARRAY_SIZE(sDeviceNameToEnumTable),
6423 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006424 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006425 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006426 } else {
6427 ALOGW("loadGlobalConfig() default device not specified");
6428 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006429 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006430 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006431 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6432 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006433 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006434 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6435 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6436 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006437 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6438 uint32_t major, minor;
6439 sscanf((char *)node->value, "%u.%u", &major, &minor);
6440 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6441 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6442 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006443 }
6444 node = node->next;
6445 }
6446}
6447
Eric Laurente0720872014-03-11 09:30:41 -07006448status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006449{
6450 cnode *root;
6451 char *data;
6452
6453 data = (char *)load_file(path, NULL);
6454 if (data == NULL) {
6455 return -ENODEV;
6456 }
6457 root = config_node("", "");
6458 config_load(root, data);
6459
Eric Laurente552edb2014-03-10 17:42:56 -07006460 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006461 // legacy audio_policy.conf files have one global_configuration section
6462 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006463 config_free(root);
6464 free(root);
6465 free(data);
6466
6467 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6468
6469 return NO_ERROR;
6470}
6471
Eric Laurente0720872014-03-11 09:30:41 -07006472void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006473{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006474 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006475 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006476 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6477 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006478 mAvailableOutputDevices.add(mDefaultOutputDevice);
6479 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006480
6481 module = new HwModule("primary");
6482
Eric Laurent1afeecb2014-05-14 08:52:28 -07006483 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006484 profile->mSamplingRates.add(44100);
6485 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6486 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006487 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006488 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6489 module->mOutputProfiles.add(profile);
6490
Eric Laurent1afeecb2014-05-14 08:52:28 -07006491 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006492 profile->mSamplingRates.add(8000);
6493 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6494 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006495 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006496 module->mInputProfiles.add(profile);
6497
6498 mHwModules.add(module);
6499}
6500
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006501audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6502{
6503 // flags to stream type mapping
6504 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6505 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6506 }
6507 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6508 return AUDIO_STREAM_BLUETOOTH_SCO;
6509 }
6510
6511 // usage to stream type mapping
6512 switch (attr->usage) {
6513 case AUDIO_USAGE_MEDIA:
6514 case AUDIO_USAGE_GAME:
6515 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6516 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6517 return AUDIO_STREAM_MUSIC;
6518 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6519 return AUDIO_STREAM_SYSTEM;
6520 case AUDIO_USAGE_VOICE_COMMUNICATION:
6521 return AUDIO_STREAM_VOICE_CALL;
6522
6523 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6524 return AUDIO_STREAM_DTMF;
6525
6526 case AUDIO_USAGE_ALARM:
6527 return AUDIO_STREAM_ALARM;
6528 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6529 return AUDIO_STREAM_RING;
6530
6531 case AUDIO_USAGE_NOTIFICATION:
6532 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6533 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6534 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6535 case AUDIO_USAGE_NOTIFICATION_EVENT:
6536 return AUDIO_STREAM_NOTIFICATION;
6537
6538 case AUDIO_USAGE_UNKNOWN:
6539 default:
6540 return AUDIO_STREAM_MUSIC;
6541 }
6542}
Eric Laurente552edb2014-03-10 17:42:56 -07006543}; // namespace android