blob: aa6a389f92f3c5fc1c2f1f702733a33c0ef168f1 [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];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700626 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700627 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
628 if (profile->isCompatibleProfile(device, samplingRate, format,
629 channelMask,
630 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700631 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700632 }
633 } else {
634 if (profile->isCompatibleProfile(device, samplingRate, format,
635 channelMask,
636 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700637 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700638 }
639 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700640 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
641 return profile;
642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643 }
644 }
645 return 0;
646}
647
Eric Laurente0720872014-03-11 09:30:41 -0700648audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700649 uint32_t samplingRate,
650 audio_format_t format,
651 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700652 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700653 const audio_offload_info_t *offloadInfo)
654{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700655
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700657 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
658 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
659 device, stream, samplingRate, format, channelMask, flags);
660
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700661 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
662 offloadInfo);
663}
664
665audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
666 uint32_t samplingRate,
667 audio_format_t format,
668 audio_channel_mask_t channelMask,
669 audio_output_flags_t flags,
670 const audio_offload_info_t *offloadInfo)
671{
672 if (attr == NULL) {
673 ALOGE("getOutputForAttr() called with NULL audio attributes");
674 return 0;
675 }
676 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
677 attr->usage, attr->content_type, attr->tags);
678
679 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
680 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
681 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
682 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
683 device, samplingRate, format, channelMask, flags);
684
685 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
686 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
687 offloadInfo);
688}
689
690audio_io_handle_t AudioPolicyManager::getOutputForDevice(
691 audio_devices_t device,
692 audio_stream_type_t stream,
693 uint32_t samplingRate,
694 audio_format_t format,
695 audio_channel_mask_t channelMask,
696 audio_output_flags_t flags,
697 const audio_offload_info_t *offloadInfo)
698{
699 audio_io_handle_t output = 0;
700 uint32_t latency = 0;
701
Eric Laurente552edb2014-03-10 17:42:56 -0700702#ifdef AUDIO_POLICY_TEST
703 if (mCurOutput != 0) {
704 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
705 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
706
707 if (mTestOutputs[mCurOutput] == 0) {
708 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700709 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700710 outputDesc->mDevice = mTestDevice;
711 outputDesc->mSamplingRate = mTestSamplingRate;
712 outputDesc->mFormat = mTestFormat;
713 outputDesc->mChannelMask = mTestChannels;
714 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700715 outputDesc->mFlags =
716 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700717 outputDesc->mRefCount[stream] = 0;
718 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
719 &outputDesc->mSamplingRate,
720 &outputDesc->mFormat,
721 &outputDesc->mChannelMask,
722 &outputDesc->mLatency,
723 outputDesc->mFlags,
724 offloadInfo);
725 if (mTestOutputs[mCurOutput]) {
726 AudioParameter outputCmd = AudioParameter();
727 outputCmd.addInt(String8("set_id"),mCurOutput);
728 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
729 addOutput(mTestOutputs[mCurOutput], outputDesc);
730 }
731 }
732 return mTestOutputs[mCurOutput];
733 }
734#endif //AUDIO_POLICY_TEST
735
736 // open a direct output if required by specified parameters
737 //force direct flag if offload flag is set: offloading implies a direct output stream
738 // and all common behaviors are driven by checking only the direct flag
739 // this should normally be set appropriately in the policy configuration file
740 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700741 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 }
743
744 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
745 // creating an offloaded track and tearing it down immediately after start when audioflinger
746 // detects there is an active non offloadable effect.
747 // FIXME: We should check the audio session here but we do not have it in this context.
748 // This may prevent offloading in rare situations where effects are left active by apps
749 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700750 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700751 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
752 !isNonOffloadableEffectEnabled()) {
753 profile = getProfileForDirectOutput(device,
754 samplingRate,
755 format,
756 channelMask,
757 (audio_output_flags_t)flags);
758 }
759
Eric Laurent1c333e22014-05-20 10:48:17 -0700760 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700761 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700762
763 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700764 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700765 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
766 outputDesc = desc;
767 // reuse direct output if currently open and configured with same parameters
768 if ((samplingRate == outputDesc->mSamplingRate) &&
769 (format == outputDesc->mFormat) &&
770 (channelMask == outputDesc->mChannelMask)) {
771 outputDesc->mDirectOpenCount++;
772 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
773 return mOutputs.keyAt(i);
774 }
775 }
776 }
777 // close direct output if currently open and configured with different parameters
778 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700779 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700780 }
781 outputDesc = new AudioOutputDescriptor(profile);
782 outputDesc->mDevice = device;
783 outputDesc->mSamplingRate = samplingRate;
784 outputDesc->mFormat = format;
785 outputDesc->mChannelMask = channelMask;
786 outputDesc->mLatency = 0;
787 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
788 outputDesc->mRefCount[stream] = 0;
789 outputDesc->mStopTime[stream] = 0;
790 outputDesc->mDirectOpenCount = 1;
791 output = mpClientInterface->openOutput(profile->mModule->mHandle,
792 &outputDesc->mDevice,
793 &outputDesc->mSamplingRate,
794 &outputDesc->mFormat,
795 &outputDesc->mChannelMask,
796 &outputDesc->mLatency,
797 outputDesc->mFlags,
798 offloadInfo);
799
800 // only accept an output with the requested parameters
801 if (output == 0 ||
802 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
803 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
804 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
805 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
806 "format %d %d, channelMask %04x %04x", output, samplingRate,
807 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
808 outputDesc->mChannelMask);
809 if (output != 0) {
810 mpClientInterface->closeOutput(output);
811 }
Eric Laurente552edb2014-03-10 17:42:56 -0700812 return 0;
813 }
814 audio_io_handle_t srcOutput = getOutputForEffect();
815 addOutput(output, outputDesc);
816 audio_io_handle_t dstOutput = getOutputForEffect();
817 if (dstOutput == output) {
818 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
819 }
820 mPreviousOutputs = mOutputs;
821 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700822 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700823 return output;
824 }
825
826 // ignoring channel mask due to downmix capability in mixer
827
828 // open a non direct output
829
830 // for non direct outputs, only PCM is supported
831 if (audio_is_linear_pcm(format)) {
832 // get which output is suitable for the specified stream. The actual
833 // routing change will happen when startOutput() will be called
834 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
835
836 output = selectOutput(outputs, flags);
837 }
838 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
839 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
840
841 ALOGV("getOutput() returns output %d", output);
842
843 return output;
844}
845
Eric Laurente0720872014-03-11 09:30:41 -0700846audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700847 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700848{
849 // select one output among several that provide a path to a particular device or set of
850 // devices (the list was previously build by getOutputsForDevice()).
851 // The priority is as follows:
852 // 1: the output with the highest number of requested policy flags
853 // 2: the primary output
854 // 3: the first output in the list
855
856 if (outputs.size() == 0) {
857 return 0;
858 }
859 if (outputs.size() == 1) {
860 return outputs[0];
861 }
862
863 int maxCommonFlags = 0;
864 audio_io_handle_t outputFlags = 0;
865 audio_io_handle_t outputPrimary = 0;
866
867 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700868 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700869 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700870 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700871 if (commonFlags > maxCommonFlags) {
872 outputFlags = outputs[i];
873 maxCommonFlags = commonFlags;
874 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
875 }
876 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
877 outputPrimary = outputs[i];
878 }
879 }
880 }
881
882 if (outputFlags != 0) {
883 return outputFlags;
884 }
885 if (outputPrimary != 0) {
886 return outputPrimary;
887 }
888
889 return outputs[0];
890}
891
Eric Laurente0720872014-03-11 09:30:41 -0700892status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700893 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700894 int session)
895{
896 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
897 ssize_t index = mOutputs.indexOfKey(output);
898 if (index < 0) {
899 ALOGW("startOutput() unknown output %d", output);
900 return BAD_VALUE;
901 }
902
Eric Laurent1f2f2232014-06-02 12:01:23 -0700903 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700904
905 // increment usage count for this stream on the requested output:
906 // NOTE that the usage count is the same for duplicated output and hardware output which is
907 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
908 outputDesc->changeRefCount(stream, 1);
909
910 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700911 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700912 routing_strategy strategy = getStrategy(stream);
913 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
914 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
915 uint32_t waitMs = 0;
916 bool force = false;
917 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700918 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 if (desc != outputDesc) {
920 // force a device change if any other output is managed by the same hw
921 // module and has a current device selection that differs from selected device.
922 // In this case, the audio HAL must receive the new device selection so that it can
923 // change the device currently selected by the other active output.
924 if (outputDesc->sharesHwModuleWith(desc) &&
925 desc->device() != newDevice) {
926 force = true;
927 }
928 // wait for audio on other active outputs to be presented when starting
929 // a notification so that audio focus effect can propagate.
930 uint32_t latency = desc->latency();
931 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
932 waitMs = latency;
933 }
934 }
935 }
936 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
937
938 // handle special case for sonification while in call
939 if (isInCall()) {
940 handleIncallSonification(stream, true, false);
941 }
942
943 // apply volume rules for current stream and device if necessary
944 checkAndSetVolume(stream,
945 mStreams[stream].getVolumeIndex(newDevice),
946 output,
947 newDevice);
948
949 // update the outputs if starting an output with a stream that can affect notification
950 // routing
951 handleNotificationRoutingForStream(stream);
952 if (waitMs > muteWaitMs) {
953 usleep((waitMs - muteWaitMs) * 2 * 1000);
954 }
955 }
956 return NO_ERROR;
957}
958
959
Eric Laurente0720872014-03-11 09:30:41 -0700960status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700961 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700962 int session)
963{
964 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
965 ssize_t index = mOutputs.indexOfKey(output);
966 if (index < 0) {
967 ALOGW("stopOutput() unknown output %d", output);
968 return BAD_VALUE;
969 }
970
Eric Laurent1f2f2232014-06-02 12:01:23 -0700971 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700972
973 // handle special case for sonification while in call
974 if (isInCall()) {
975 handleIncallSonification(stream, false, false);
976 }
977
978 if (outputDesc->mRefCount[stream] > 0) {
979 // decrement usage count of this stream on the output
980 outputDesc->changeRefCount(stream, -1);
981 // store time at which the stream was stopped - see isStreamActive()
982 if (outputDesc->mRefCount[stream] == 0) {
983 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700984 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700985 // delay the device switch by twice the latency because stopOutput() is executed when
986 // the track stop() command is received and at that time the audio track buffer can
987 // still contain data that needs to be drained. The latency only covers the audio HAL
988 // and kernel buffers. Also the latency does not always include additional delay in the
989 // audio path (audio DSP, CODEC ...)
990 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
991
992 // force restoring the device selection on other active outputs if it differs from the
993 // one being selected for this output
994 for (size_t i = 0; i < mOutputs.size(); i++) {
995 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700996 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700997 if (curOutput != output &&
998 desc->isActive() &&
999 outputDesc->sharesHwModuleWith(desc) &&
1000 (newDevice != desc->device())) {
1001 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001002 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001003 true,
1004 outputDesc->mLatency*2);
1005 }
1006 }
1007 // update the outputs if stopping one with a stream that can affect notification routing
1008 handleNotificationRoutingForStream(stream);
1009 }
1010 return NO_ERROR;
1011 } else {
1012 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1013 return INVALID_OPERATION;
1014 }
1015}
1016
Eric Laurente0720872014-03-11 09:30:41 -07001017void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001018{
1019 ALOGV("releaseOutput() %d", output);
1020 ssize_t index = mOutputs.indexOfKey(output);
1021 if (index < 0) {
1022 ALOGW("releaseOutput() releasing unknown output %d", output);
1023 return;
1024 }
1025
1026#ifdef AUDIO_POLICY_TEST
1027 int testIndex = testOutputIndex(output);
1028 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001029 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001030 if (outputDesc->isActive()) {
1031 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001032 mOutputs.removeItem(output);
1033 mTestOutputs[testIndex] = 0;
1034 }
1035 return;
1036 }
1037#endif //AUDIO_POLICY_TEST
1038
Eric Laurent1f2f2232014-06-02 12:01:23 -07001039 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001040 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001041 if (desc->mDirectOpenCount <= 0) {
1042 ALOGW("releaseOutput() invalid open count %d for output %d",
1043 desc->mDirectOpenCount, output);
1044 return;
1045 }
1046 if (--desc->mDirectOpenCount == 0) {
1047 closeOutput(output);
1048 // If effects where present on the output, audioflinger moved them to the primary
1049 // output by default: move them back to the appropriate output.
1050 audio_io_handle_t dstOutput = getOutputForEffect();
1051 if (dstOutput != mPrimaryOutput) {
1052 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1053 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001054 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001055 }
1056 }
1057}
1058
1059
Eric Laurente0720872014-03-11 09:30:41 -07001060audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001061 uint32_t samplingRate,
1062 audio_format_t format,
1063 audio_channel_mask_t channelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001064 audio_in_acoustics_t acoustics,
1065 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001066{
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001067 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x, "
1068 "flags %#x",
1069 inputSource, samplingRate, format, channelMask, acoustics, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001070
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001071 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
1073 if (device == AUDIO_DEVICE_NONE) {
1074 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1075 return 0;
1076 }
1077
1078 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001079 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001080 case AUDIO_SOURCE_VOICE_UPLINK:
1081 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1082 break;
1083 case AUDIO_SOURCE_VOICE_DOWNLINK:
1084 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1085 break;
1086 case AUDIO_SOURCE_VOICE_CALL:
1087 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1088 break;
1089 default:
1090 break;
1091 }
1092
Eric Laurent1c333e22014-05-20 10:48:17 -07001093 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001094 samplingRate,
1095 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001096 channelMask,
1097 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001098 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001099 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1100 "channelMask 0x%X, flags %#x",
1101 device, samplingRate, format, channelMask, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001102 return 0;
1103 }
1104
1105 if (profile->mModule->mHandle == 0) {
1106 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1107 return 0;
1108 }
1109
Eric Laurent1f2f2232014-06-02 12:01:23 -07001110 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001111
1112 inputDesc->mInputSource = inputSource;
1113 inputDesc->mDevice = device;
1114 inputDesc->mSamplingRate = samplingRate;
1115 inputDesc->mFormat = format;
1116 inputDesc->mChannelMask = channelMask;
1117 inputDesc->mRefCount = 0;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001118 inputDesc->mOpenRefCount = 1;
1119
1120 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurente552edb2014-03-10 17:42:56 -07001121 &inputDesc->mDevice,
1122 &inputDesc->mSamplingRate,
1123 &inputDesc->mFormat,
Glenn Kastenec40d282014-07-15 15:31:26 -07001124 &inputDesc->mChannelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001125 flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001126
1127 // only accept input with the exact requested set of parameters
1128 if (input == 0 ||
1129 (samplingRate != inputDesc->mSamplingRate) ||
1130 (format != inputDesc->mFormat) ||
1131 (channelMask != inputDesc->mChannelMask)) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001132 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurente552edb2014-03-10 17:42:56 -07001133 samplingRate, format, channelMask);
1134 if (input != 0) {
1135 mpClientInterface->closeInput(input);
1136 }
Eric Laurente552edb2014-03-10 17:42:56 -07001137 return 0;
1138 }
Eric Laurentd4692962014-05-05 18:13:44 -07001139 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001140 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001141 return input;
1142}
1143
Eric Laurente0720872014-03-11 09:30:41 -07001144status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001145{
1146 ALOGV("startInput() input %d", input);
1147 ssize_t index = mInputs.indexOfKey(input);
1148 if (index < 0) {
1149 ALOGW("startInput() unknown input %d", input);
1150 return BAD_VALUE;
1151 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001152 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001153
Glenn Kasten74a8e252014-07-24 14:09:55 -07001154 // virtual input devices are compatible with other input devices
1155 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1156
1157 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001158 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001159 if (activeInput != 0 && activeInput != input) {
1160
1161 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1162 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001163 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001164 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001165 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001166 stopInput(activeInput);
1167 releaseInput(activeInput);
1168 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001169 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001170 return INVALID_OPERATION;
1171 }
1172 }
1173 }
1174
Glenn Kasten74a8e252014-07-24 14:09:55 -07001175 if (inputDesc->mRefCount == 0) {
1176 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001177
Glenn Kasten74a8e252014-07-24 14:09:55 -07001178 // Automatically enable the remote submix output when input is started.
1179 // For remote submix (a virtual device), we open only one input per capture request.
1180 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1181 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1182 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1183 }
Eric Laurente552edb2014-03-10 17:42:56 -07001184 }
1185
Eric Laurente552edb2014-03-10 17:42:56 -07001186 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1187
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001188 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001189 return NO_ERROR;
1190}
1191
Eric Laurente0720872014-03-11 09:30:41 -07001192status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001193{
1194 ALOGV("stopInput() input %d", input);
1195 ssize_t index = mInputs.indexOfKey(input);
1196 if (index < 0) {
1197 ALOGW("stopInput() unknown input %d", input);
1198 return BAD_VALUE;
1199 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001200 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001201
1202 if (inputDesc->mRefCount == 0) {
1203 ALOGW("stopInput() input %d already stopped", input);
1204 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001205 }
1206
1207 inputDesc->mRefCount--;
1208 if (inputDesc->mRefCount == 0) {
1209
Eric Laurente552edb2014-03-10 17:42:56 -07001210 // automatically disable the remote submix output when input is stopped
1211 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1212 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001213 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001214 }
1215
Eric Laurent1c333e22014-05-20 10:48:17 -07001216 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001217 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001218 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001219}
1220
Eric Laurente0720872014-03-11 09:30:41 -07001221void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001222{
1223 ALOGV("releaseInput() %d", input);
1224 ssize_t index = mInputs.indexOfKey(input);
1225 if (index < 0) {
1226 ALOGW("releaseInput() releasing unknown input %d", input);
1227 return;
1228 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001229 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1230 ALOG_ASSERT(inputDesc != 0);
1231 if (inputDesc->mOpenRefCount == 0) {
1232 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1233 return;
1234 }
1235 inputDesc->mOpenRefCount--;
1236 if (inputDesc->mOpenRefCount > 0) {
1237 ALOGV("releaseInput() exit > 0");
1238 return;
1239 }
1240
Eric Laurente552edb2014-03-10 17:42:56 -07001241 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001242 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001243 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001244 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001245 ALOGV("releaseInput() exit");
1246}
1247
Eric Laurentd4692962014-05-05 18:13:44 -07001248void AudioPolicyManager::closeAllInputs() {
1249 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1250 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1251 }
1252 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001253 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001254}
1255
Eric Laurente0720872014-03-11 09:30:41 -07001256void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001257 int indexMin,
1258 int indexMax)
1259{
1260 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1261 if (indexMin < 0 || indexMin >= indexMax) {
1262 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1263 return;
1264 }
1265 mStreams[stream].mIndexMin = indexMin;
1266 mStreams[stream].mIndexMax = indexMax;
1267}
1268
Eric Laurente0720872014-03-11 09:30:41 -07001269status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001270 int index,
1271 audio_devices_t device)
1272{
1273
1274 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1275 return BAD_VALUE;
1276 }
1277 if (!audio_is_output_device(device)) {
1278 return BAD_VALUE;
1279 }
1280
1281 // Force max volume if stream cannot be muted
1282 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1283
1284 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1285 stream, device, index);
1286
1287 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1288 // clear all device specific values
1289 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1290 mStreams[stream].mIndexCur.clear();
1291 }
1292 mStreams[stream].mIndexCur.add(device, index);
1293
1294 // compute and apply stream volume on all outputs according to connected device
1295 status_t status = NO_ERROR;
1296 for (size_t i = 0; i < mOutputs.size(); i++) {
1297 audio_devices_t curDevice =
1298 getDeviceForVolume(mOutputs.valueAt(i)->device());
1299 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1300 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1301 if (volStatus != NO_ERROR) {
1302 status = volStatus;
1303 }
1304 }
1305 }
1306 return status;
1307}
1308
Eric Laurente0720872014-03-11 09:30:41 -07001309status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001310 int *index,
1311 audio_devices_t device)
1312{
1313 if (index == NULL) {
1314 return BAD_VALUE;
1315 }
1316 if (!audio_is_output_device(device)) {
1317 return BAD_VALUE;
1318 }
1319 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1320 // the strategy the stream belongs to.
1321 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1322 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1323 }
1324 device = getDeviceForVolume(device);
1325
1326 *index = mStreams[stream].getVolumeIndex(device);
1327 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1328 return NO_ERROR;
1329}
1330
Eric Laurente0720872014-03-11 09:30:41 -07001331audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001332 const SortedVector<audio_io_handle_t>& outputs)
1333{
1334 // select one output among several suitable for global effects.
1335 // The priority is as follows:
1336 // 1: An offloaded output. If the effect ends up not being offloadable,
1337 // AudioFlinger will invalidate the track and the offloaded output
1338 // will be closed causing the effect to be moved to a PCM output.
1339 // 2: A deep buffer output
1340 // 3: the first output in the list
1341
1342 if (outputs.size() == 0) {
1343 return 0;
1344 }
1345
1346 audio_io_handle_t outputOffloaded = 0;
1347 audio_io_handle_t outputDeepBuffer = 0;
1348
1349 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001350 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001351 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001352 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1353 outputOffloaded = outputs[i];
1354 }
1355 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1356 outputDeepBuffer = outputs[i];
1357 }
1358 }
1359
1360 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1361 outputOffloaded, outputDeepBuffer);
1362 if (outputOffloaded != 0) {
1363 return outputOffloaded;
1364 }
1365 if (outputDeepBuffer != 0) {
1366 return outputDeepBuffer;
1367 }
1368
1369 return outputs[0];
1370}
1371
Eric Laurente0720872014-03-11 09:30:41 -07001372audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001373{
1374 // apply simple rule where global effects are attached to the same output as MUSIC streams
1375
Eric Laurent3b73df72014-03-11 09:06:29 -07001376 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001377 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1378 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1379
1380 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1381 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1382 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1383
1384 return output;
1385}
1386
Eric Laurente0720872014-03-11 09:30:41 -07001387status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001388 audio_io_handle_t io,
1389 uint32_t strategy,
1390 int session,
1391 int id)
1392{
1393 ssize_t index = mOutputs.indexOfKey(io);
1394 if (index < 0) {
1395 index = mInputs.indexOfKey(io);
1396 if (index < 0) {
1397 ALOGW("registerEffect() unknown io %d", io);
1398 return INVALID_OPERATION;
1399 }
1400 }
1401
1402 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1403 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1404 desc->name, desc->memoryUsage);
1405 return INVALID_OPERATION;
1406 }
1407 mTotalEffectsMemory += desc->memoryUsage;
1408 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1409 desc->name, io, strategy, session, id);
1410 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1411
Eric Laurent1f2f2232014-06-02 12:01:23 -07001412 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1413 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1414 effectDesc->mIo = io;
1415 effectDesc->mStrategy = (routing_strategy)strategy;
1416 effectDesc->mSession = session;
1417 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001418
Eric Laurent1f2f2232014-06-02 12:01:23 -07001419 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001420
1421 return NO_ERROR;
1422}
1423
Eric Laurente0720872014-03-11 09:30:41 -07001424status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001425{
1426 ssize_t index = mEffects.indexOfKey(id);
1427 if (index < 0) {
1428 ALOGW("unregisterEffect() unknown effect ID %d", id);
1429 return INVALID_OPERATION;
1430 }
1431
Eric Laurent1f2f2232014-06-02 12:01:23 -07001432 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001433
Eric Laurent1f2f2232014-06-02 12:01:23 -07001434 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001435
Eric Laurent1f2f2232014-06-02 12:01:23 -07001436 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001437 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001438 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1439 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001440 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001441 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001442 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001443 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001444
1445 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001446
1447 return NO_ERROR;
1448}
1449
Eric Laurente0720872014-03-11 09:30:41 -07001450status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001451{
1452 ssize_t index = mEffects.indexOfKey(id);
1453 if (index < 0) {
1454 ALOGW("unregisterEffect() unknown effect ID %d", id);
1455 return INVALID_OPERATION;
1456 }
1457
1458 return setEffectEnabled(mEffects.valueAt(index), enabled);
1459}
1460
Eric Laurent1f2f2232014-06-02 12:01:23 -07001461status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001462{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001463 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001464 ALOGV("setEffectEnabled(%s) effect already %s",
1465 enabled?"true":"false", enabled?"enabled":"disabled");
1466 return INVALID_OPERATION;
1467 }
1468
1469 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001470 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001471 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001472 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001473 return INVALID_OPERATION;
1474 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001475 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001476 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1477 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001478 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001479 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001480 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1481 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001482 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001483 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001484 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1485 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001486 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001487 return NO_ERROR;
1488}
1489
Eric Laurente0720872014-03-11 09:30:41 -07001490bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001491{
1492 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1494 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1495 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001496 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001497 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001498 return true;
1499 }
1500 }
1501 return false;
1502}
1503
Eric Laurente0720872014-03-11 09:30:41 -07001504bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001505{
1506 nsecs_t sysTime = systemTime();
1507 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001508 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001509 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001510 return true;
1511 }
1512 }
1513 return false;
1514}
1515
Eric Laurente0720872014-03-11 09:30:41 -07001516bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001517 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001518{
1519 nsecs_t sysTime = systemTime();
1520 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001521 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001522 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001523 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001524 return true;
1525 }
1526 }
1527 return false;
1528}
1529
Eric Laurente0720872014-03-11 09:30:41 -07001530bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001531{
1532 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001533 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001534 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001535 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001536 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1537 && (inputDescriptor->mRefCount > 0)) {
1538 return true;
1539 }
1540 }
1541 return false;
1542}
1543
1544
Eric Laurente0720872014-03-11 09:30:41 -07001545status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001546{
1547 const size_t SIZE = 256;
1548 char buffer[SIZE];
1549 String8 result;
1550
1551 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1552 result.append(buffer);
1553
1554 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1555 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001556 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1557 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001558 snprintf(buffer, SIZE, " Force use for communications %d\n",
1559 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001560 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001561 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001562 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001563 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001564 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001565 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001566 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001567 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001568 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001569 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1570 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1571 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001572
Eric Laurent3a4311c2014-03-17 12:00:47 -07001573 snprintf(buffer, SIZE, " Available output devices:\n");
1574 result.append(buffer);
1575 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001576 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001577 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001578 }
1579 snprintf(buffer, SIZE, "\n Available input devices:\n");
1580 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001581 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001582 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001583 }
Eric Laurente552edb2014-03-10 17:42:56 -07001584
1585 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1586 write(fd, buffer, strlen(buffer));
1587 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001588 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001589 write(fd, buffer, strlen(buffer));
1590 mHwModules[i]->dump(fd);
1591 }
1592
1593 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1594 write(fd, buffer, strlen(buffer));
1595 for (size_t i = 0; i < mOutputs.size(); i++) {
1596 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1597 write(fd, buffer, strlen(buffer));
1598 mOutputs.valueAt(i)->dump(fd);
1599 }
1600
1601 snprintf(buffer, SIZE, "\nInputs dump:\n");
1602 write(fd, buffer, strlen(buffer));
1603 for (size_t i = 0; i < mInputs.size(); i++) {
1604 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1605 write(fd, buffer, strlen(buffer));
1606 mInputs.valueAt(i)->dump(fd);
1607 }
1608
1609 snprintf(buffer, SIZE, "\nStreams dump:\n");
1610 write(fd, buffer, strlen(buffer));
1611 snprintf(buffer, SIZE,
1612 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1613 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001614 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001615 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001616 write(fd, buffer, strlen(buffer));
1617 mStreams[i].dump(fd);
1618 }
1619
1620 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1621 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1622 write(fd, buffer, strlen(buffer));
1623
1624 snprintf(buffer, SIZE, "Registered effects:\n");
1625 write(fd, buffer, strlen(buffer));
1626 for (size_t i = 0; i < mEffects.size(); i++) {
1627 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1628 write(fd, buffer, strlen(buffer));
1629 mEffects.valueAt(i)->dump(fd);
1630 }
1631
1632
1633 return NO_ERROR;
1634}
1635
1636// This function checks for the parameters which can be offloaded.
1637// This can be enhanced depending on the capability of the DSP and policy
1638// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001639bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001640{
1641 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001642 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001643 offloadInfo.sample_rate, offloadInfo.channel_mask,
1644 offloadInfo.format,
1645 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1646 offloadInfo.has_video);
1647
1648 // Check if offload has been disabled
1649 char propValue[PROPERTY_VALUE_MAX];
1650 if (property_get("audio.offload.disable", propValue, "0")) {
1651 if (atoi(propValue) != 0) {
1652 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1653 return false;
1654 }
1655 }
1656
1657 // Check if stream type is music, then only allow offload as of now.
1658 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1659 {
1660 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1661 return false;
1662 }
1663
1664 //TODO: enable audio offloading with video when ready
1665 if (offloadInfo.has_video)
1666 {
1667 ALOGV("isOffloadSupported: has_video == true, returning false");
1668 return false;
1669 }
1670
1671 //If duration is less than minimum value defined in property, return false
1672 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1673 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1674 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1675 return false;
1676 }
1677 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1678 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1679 return false;
1680 }
1681
1682 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1683 // creating an offloaded track and tearing it down immediately after start when audioflinger
1684 // detects there is an active non offloadable effect.
1685 // FIXME: We should check the audio session here but we do not have it in this context.
1686 // This may prevent offloading in rare situations where effects are left active by apps
1687 // in the background.
1688 if (isNonOffloadableEffectEnabled()) {
1689 return false;
1690 }
1691
1692 // See if there is a profile to support this.
1693 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001694 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001695 offloadInfo.sample_rate,
1696 offloadInfo.format,
1697 offloadInfo.channel_mask,
1698 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001699 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1700 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001701}
1702
Eric Laurent6a94d692014-05-20 11:18:06 -07001703status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1704 audio_port_type_t type,
1705 unsigned int *num_ports,
1706 struct audio_port *ports,
1707 unsigned int *generation)
1708{
1709 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1710 generation == NULL) {
1711 return BAD_VALUE;
1712 }
1713 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1714 if (ports == NULL) {
1715 *num_ports = 0;
1716 }
1717
1718 size_t portsWritten = 0;
1719 size_t portsMax = *num_ports;
1720 *num_ports = 0;
1721 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1722 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1723 for (size_t i = 0;
1724 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1725 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1726 }
1727 *num_ports += mAvailableOutputDevices.size();
1728 }
1729 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1730 for (size_t i = 0;
1731 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1732 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1733 }
1734 *num_ports += mAvailableInputDevices.size();
1735 }
1736 }
1737 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1738 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1739 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1740 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1741 }
1742 *num_ports += mInputs.size();
1743 }
1744 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001745 size_t numOutputs = 0;
1746 for (size_t i = 0; i < mOutputs.size(); i++) {
1747 if (!mOutputs[i]->isDuplicated()) {
1748 numOutputs++;
1749 if (portsWritten < portsMax) {
1750 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1751 }
1752 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001753 }
Eric Laurent84c70242014-06-23 08:46:27 -07001754 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001755 }
1756 }
1757 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001758 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001759 return NO_ERROR;
1760}
1761
1762status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1763{
1764 return NO_ERROR;
1765}
1766
Eric Laurent1f2f2232014-06-02 12:01:23 -07001767sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001768 audio_port_handle_t id) const
1769{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001770 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001771 for (size_t i = 0; i < mOutputs.size(); i++) {
1772 outputDesc = mOutputs.valueAt(i);
1773 if (outputDesc->mId == id) {
1774 break;
1775 }
1776 }
1777 return outputDesc;
1778}
1779
Eric Laurent1f2f2232014-06-02 12:01:23 -07001780sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001781 audio_port_handle_t id) const
1782{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001783 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001784 for (size_t i = 0; i < mInputs.size(); i++) {
1785 inputDesc = mInputs.valueAt(i);
1786 if (inputDesc->mId == id) {
1787 break;
1788 }
1789 }
1790 return inputDesc;
1791}
1792
Eric Laurent1f2f2232014-06-02 12:01:23 -07001793sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1794 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001795{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001796 sp <HwModule> module;
1797
Eric Laurent6a94d692014-05-20 11:18:06 -07001798 for (size_t i = 0; i < mHwModules.size(); i++) {
1799 if (mHwModules[i]->mHandle == 0) {
1800 continue;
1801 }
1802 if (audio_is_output_device(device)) {
1803 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1804 {
1805 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1806 return mHwModules[i];
1807 }
1808 }
1809 } else {
1810 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1811 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1812 device & ~AUDIO_DEVICE_BIT_IN) {
1813 return mHwModules[i];
1814 }
1815 }
1816 }
1817 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001818 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001819}
1820
Eric Laurent1f2f2232014-06-02 12:01:23 -07001821sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001822{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001823 sp <HwModule> module;
1824
Eric Laurent1afeecb2014-05-14 08:52:28 -07001825 for (size_t i = 0; i < mHwModules.size(); i++)
1826 {
1827 if (strcmp(mHwModules[i]->mName, name) == 0) {
1828 return mHwModules[i];
1829 }
1830 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001831 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001832}
1833
1834
Eric Laurent6a94d692014-05-20 11:18:06 -07001835status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1836 audio_patch_handle_t *handle,
1837 uid_t uid)
1838{
1839 ALOGV("createAudioPatch()");
1840
1841 if (handle == NULL || patch == NULL) {
1842 return BAD_VALUE;
1843 }
1844 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1845
1846 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1847 return INVALID_OPERATION;
1848 }
1849 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1850 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1851 return INVALID_OPERATION;
1852 }
1853
1854 sp<AudioPatch> patchDesc;
1855 ssize_t index = mAudioPatches.indexOfKey(*handle);
1856
1857 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1858 patch->sinks[0].type);
1859 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1860 patch->sources[0].role,
1861 patch->sources[0].type);
1862
1863 if (index >= 0) {
1864 patchDesc = mAudioPatches.valueAt(index);
1865 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1866 mUidCached, patchDesc->mUid, uid);
1867 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1868 return INVALID_OPERATION;
1869 }
1870 } else {
1871 *handle = 0;
1872 }
1873
1874 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1875 // TODO add support for mix to mix connection
1876 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1877 ALOGV("createAudioPatch() source mix sink not device");
1878 return BAD_VALUE;
1879 }
1880 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001881 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001882 if (outputDesc == NULL) {
1883 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1884 return BAD_VALUE;
1885 }
Eric Laurent84c70242014-06-23 08:46:27 -07001886 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1887 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001888 if (patchDesc != 0) {
1889 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1890 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1891 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1892 return BAD_VALUE;
1893 }
1894 }
1895 sp<DeviceDescriptor> devDesc =
1896 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1897 if (devDesc == 0) {
1898 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1899 return BAD_VALUE;
1900 }
1901
Eric Laurent84c70242014-06-23 08:46:27 -07001902 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001903 patch->sources[0].sample_rate,
1904 patch->sources[0].format,
1905 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001906 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001907 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001908 return INVALID_OPERATION;
1909 }
1910 // TODO: reconfigure output format and channels here
1911 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001912 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001913 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001914 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001915 true,
1916 0,
1917 handle);
1918 index = mAudioPatches.indexOfKey(*handle);
1919 if (index >= 0) {
1920 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1921 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1922 }
1923 patchDesc = mAudioPatches.valueAt(index);
1924 patchDesc->mUid = uid;
1925 ALOGV("createAudioPatch() success");
1926 } else {
1927 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1928 return INVALID_OPERATION;
1929 }
1930 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1931 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1932 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001933 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001934 if (inputDesc == NULL) {
1935 return BAD_VALUE;
1936 }
1937 if (patchDesc != 0) {
1938 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1939 return BAD_VALUE;
1940 }
1941 }
1942 sp<DeviceDescriptor> devDesc =
1943 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1944 if (devDesc == 0) {
1945 return BAD_VALUE;
1946 }
1947
Eric Laurent84c70242014-06-23 08:46:27 -07001948 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001949 patch->sinks[0].sample_rate,
1950 patch->sinks[0].format,
1951 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001952 // FIXME for the parameter type,
1953 // and the NONE
1954 (audio_output_flags_t)
1955 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07001956 return INVALID_OPERATION;
1957 }
1958 // TODO: reconfigure output format and channels here
1959 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001960 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001961 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001962 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001963 true,
1964 handle);
1965 index = mAudioPatches.indexOfKey(*handle);
1966 if (index >= 0) {
1967 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1968 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1969 }
1970 patchDesc = mAudioPatches.valueAt(index);
1971 patchDesc->mUid = uid;
1972 ALOGV("createAudioPatch() success");
1973 } else {
1974 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1975 return INVALID_OPERATION;
1976 }
1977 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1978 // device to device connection
1979 if (patchDesc != 0) {
1980 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1981 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1982 return BAD_VALUE;
1983 }
1984 }
1985
1986 sp<DeviceDescriptor> srcDeviceDesc =
1987 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1988 sp<DeviceDescriptor> sinkDeviceDesc =
1989 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1990 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1991 return BAD_VALUE;
1992 }
1993 //update source and sink with our own data as the data passed in the patch may
1994 // be incomplete.
1995 struct audio_patch newPatch = *patch;
1996 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1997 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1998
Eric Laurent6a94d692014-05-20 11:18:06 -07001999 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002000 SortedVector<audio_io_handle_t> outputs =
2001 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2002 // if the sink device is reachable via an opened output stream, request to go via
2003 // this output stream by adding a second source to the patch description
2004 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2005 if (output != AUDIO_IO_HANDLE_NONE) {
2006 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2007 if (outputDesc->isDuplicated()) {
2008 return INVALID_OPERATION;
2009 }
2010 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2011 newPatch.num_sources = 2;
2012 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002013 }
2014 // TODO: check from routing capabilities in config file and other conflicting patches
2015
2016 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2017 if (index >= 0) {
2018 afPatchHandle = patchDesc->mAfPatchHandle;
2019 }
2020
2021 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2022 &afPatchHandle,
2023 0);
2024 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2025 status, afPatchHandle);
2026 if (status == NO_ERROR) {
2027 if (index < 0) {
2028 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2029 &newPatch, uid);
2030 addAudioPatch(patchDesc->mHandle, patchDesc);
2031 } else {
2032 patchDesc->mPatch = newPatch;
2033 }
2034 patchDesc->mAfPatchHandle = afPatchHandle;
2035 *handle = patchDesc->mHandle;
2036 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002037 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002038 } else {
2039 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2040 status);
2041 return INVALID_OPERATION;
2042 }
2043 } else {
2044 return BAD_VALUE;
2045 }
2046 } else {
2047 return BAD_VALUE;
2048 }
2049 return NO_ERROR;
2050}
2051
2052status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2053 uid_t uid)
2054{
2055 ALOGV("releaseAudioPatch() patch %d", handle);
2056
2057 ssize_t index = mAudioPatches.indexOfKey(handle);
2058
2059 if (index < 0) {
2060 return BAD_VALUE;
2061 }
2062 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2063 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2064 mUidCached, patchDesc->mUid, uid);
2065 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2066 return INVALID_OPERATION;
2067 }
2068
2069 struct audio_patch *patch = &patchDesc->mPatch;
2070 patchDesc->mUid = mUidCached;
2071 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002072 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002073 if (outputDesc == NULL) {
2074 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2075 return BAD_VALUE;
2076 }
2077
2078 setOutputDevice(outputDesc->mIoHandle,
2079 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2080 true,
2081 0,
2082 NULL);
2083 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2084 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002085 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002086 if (inputDesc == NULL) {
2087 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2088 return BAD_VALUE;
2089 }
2090 setInputDevice(inputDesc->mIoHandle,
2091 getNewInputDevice(inputDesc->mIoHandle),
2092 true,
2093 NULL);
2094 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2095 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2096 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2097 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2098 status, patchDesc->mAfPatchHandle);
2099 removeAudioPatch(patchDesc->mHandle);
2100 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002101 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002102 } else {
2103 return BAD_VALUE;
2104 }
2105 } else {
2106 return BAD_VALUE;
2107 }
2108 return NO_ERROR;
2109}
2110
2111status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2112 struct audio_patch *patches,
2113 unsigned int *generation)
2114{
2115 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2116 generation == NULL) {
2117 return BAD_VALUE;
2118 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002119 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002120 *num_patches, patches, mAudioPatches.size());
2121 if (patches == NULL) {
2122 *num_patches = 0;
2123 }
2124
2125 size_t patchesWritten = 0;
2126 size_t patchesMax = *num_patches;
2127 for (size_t i = 0;
2128 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2129 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2130 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002131 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002132 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2133 }
2134 *num_patches = mAudioPatches.size();
2135
2136 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002137 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002138 return NO_ERROR;
2139}
2140
Eric Laurente1715a42014-05-20 11:30:42 -07002141status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002142{
Eric Laurente1715a42014-05-20 11:30:42 -07002143 ALOGV("setAudioPortConfig()");
2144
2145 if (config == NULL) {
2146 return BAD_VALUE;
2147 }
2148 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2149 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002150 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2151 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002152 }
2153
Eric Laurenta121f902014-06-03 13:32:54 -07002154 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002155 if (config->type == AUDIO_PORT_TYPE_MIX) {
2156 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002157 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002158 if (outputDesc == NULL) {
2159 return BAD_VALUE;
2160 }
Eric Laurent84c70242014-06-23 08:46:27 -07002161 ALOG_ASSERT(!outputDesc->isDuplicated(),
2162 "setAudioPortConfig() called on duplicated output %d",
2163 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002164 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002165 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002166 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002167 if (inputDesc == NULL) {
2168 return BAD_VALUE;
2169 }
Eric Laurenta121f902014-06-03 13:32:54 -07002170 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002171 } else {
2172 return BAD_VALUE;
2173 }
2174 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2175 sp<DeviceDescriptor> deviceDesc;
2176 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2177 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2178 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2179 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2180 } else {
2181 return BAD_VALUE;
2182 }
2183 if (deviceDesc == NULL) {
2184 return BAD_VALUE;
2185 }
Eric Laurenta121f902014-06-03 13:32:54 -07002186 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002187 } else {
2188 return BAD_VALUE;
2189 }
2190
Eric Laurenta121f902014-06-03 13:32:54 -07002191 struct audio_port_config backupConfig;
2192 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2193 if (status == NO_ERROR) {
2194 struct audio_port_config newConfig;
2195 audioPortConfig->toAudioPortConfig(&newConfig, config);
2196 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002197 }
Eric Laurenta121f902014-06-03 13:32:54 -07002198 if (status != NO_ERROR) {
2199 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002200 }
Eric Laurente1715a42014-05-20 11:30:42 -07002201
2202 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002203}
2204
2205void AudioPolicyManager::clearAudioPatches(uid_t uid)
2206{
2207 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2208 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2209 if (patchDesc->mUid == uid) {
2210 // releaseAudioPatch() removes the patch from mAudioPatches
2211 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2212 i--;
2213 }
2214 }
2215 }
2216}
2217
2218status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2219 const sp<AudioPatch>& patch)
2220{
2221 ssize_t index = mAudioPatches.indexOfKey(handle);
2222
2223 if (index >= 0) {
2224 ALOGW("addAudioPatch() patch %d already in", handle);
2225 return ALREADY_EXISTS;
2226 }
2227 mAudioPatches.add(handle, patch);
2228 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2229 "sink handle %d",
2230 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2231 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2232 return NO_ERROR;
2233}
2234
2235status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2236{
2237 ssize_t index = mAudioPatches.indexOfKey(handle);
2238
2239 if (index < 0) {
2240 ALOGW("removeAudioPatch() patch %d not in", handle);
2241 return ALREADY_EXISTS;
2242 }
2243 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2244 mAudioPatches.valueAt(index)->mAfPatchHandle);
2245 mAudioPatches.removeItemsAt(index);
2246 return NO_ERROR;
2247}
2248
Eric Laurente552edb2014-03-10 17:42:56 -07002249// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002250// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002251// ----------------------------------------------------------------------------
2252
Eric Laurent3a4311c2014-03-17 12:00:47 -07002253uint32_t AudioPolicyManager::nextUniqueId()
2254{
2255 return android_atomic_inc(&mNextUniqueId);
2256}
2257
Eric Laurent6a94d692014-05-20 11:18:06 -07002258uint32_t AudioPolicyManager::nextAudioPortGeneration()
2259{
2260 return android_atomic_inc(&mAudioPortGeneration);
2261}
2262
Eric Laurente0720872014-03-11 09:30:41 -07002263AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002264 :
2265#ifdef AUDIO_POLICY_TEST
2266 Thread(false),
2267#endif //AUDIO_POLICY_TEST
2268 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002269 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002270 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2271 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002272 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002273 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2274 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002275{
Eric Laurent6a94d692014-05-20 11:18:06 -07002276 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002277 mpClientInterface = clientInterface;
2278
Eric Laurent3b73df72014-03-11 09:06:29 -07002279 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2280 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002281 }
2282
Eric Laurent1afeecb2014-05-14 08:52:28 -07002283 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002284 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2285 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2286 ALOGE("could not load audio policy configuration file, setting defaults");
2287 defaultAudioPolicyConfig();
2288 }
2289 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002290 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002291
2292 // must be done after reading the policy
2293 initializeVolumeCurves();
2294
2295 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002296 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2297 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002298 for (size_t i = 0; i < mHwModules.size(); i++) {
2299 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2300 if (mHwModules[i]->mHandle == 0) {
2301 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2302 continue;
2303 }
2304 // open all output streams needed to access attached devices
2305 // except for direct output streams that are only opened when they are actually
2306 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002307 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002308 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2309 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002310 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002311
Eric Laurent3a4311c2014-03-17 12:00:47 -07002312 if (outProfile->mSupportedDevices.isEmpty()) {
2313 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2314 continue;
2315 }
2316
Eric Laurent83b88082014-06-20 18:31:16 -07002317 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2318 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2319 profileType = mDefaultOutputDevice->mDeviceType;
2320 } else {
2321 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2322 }
2323 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002324 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002325 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002326
Eric Laurent83b88082014-06-20 18:31:16 -07002327 outputDesc->mDevice = profileType;
Eric Laurente552edb2014-03-10 17:42:56 -07002328 audio_io_handle_t output = mpClientInterface->openOutput(
2329 outProfile->mModule->mHandle,
2330 &outputDesc->mDevice,
2331 &outputDesc->mSamplingRate,
2332 &outputDesc->mFormat,
2333 &outputDesc->mChannelMask,
2334 &outputDesc->mLatency,
2335 outputDesc->mFlags);
2336 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002337 ALOGW("Cannot open output stream for device %08x on hw module %s",
2338 outputDesc->mDevice,
2339 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002340 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002341 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002342 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002343 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002344 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002345 // give a valid ID to an attached device once confirmed it is reachable
2346 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2347 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002348 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002349 }
2350 }
Eric Laurente552edb2014-03-10 17:42:56 -07002351 if (mPrimaryOutput == 0 &&
2352 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2353 mPrimaryOutput = output;
2354 }
2355 addOutput(output, outputDesc);
2356 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002357 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002358 true);
2359 }
2360 }
2361 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002362 // open input streams needed to access attached devices to validate
2363 // mAvailableInputDevices list
2364 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2365 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002366 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002367
Eric Laurent3a4311c2014-03-17 12:00:47 -07002368 if (inProfile->mSupportedDevices.isEmpty()) {
2369 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2370 continue;
2371 }
2372
Eric Laurent83b88082014-06-20 18:31:16 -07002373 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2374 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002375 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002376
2377 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002378 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002379 audio_io_handle_t input = mpClientInterface->openInput(
2380 inProfile->mModule->mHandle,
2381 &inputDesc->mDevice,
2382 &inputDesc->mSamplingRate,
2383 &inputDesc->mFormat,
Glenn Kastenec40d282014-07-15 15:31:26 -07002384 &inputDesc->mChannelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002385 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002386
2387 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002388 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002389 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002390 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002391 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002392 // give a valid ID to an attached device once confirmed it is reachable
2393 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2394 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002395 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002396 }
2397 }
2398 mpClientInterface->closeInput(input);
2399 } else {
2400 ALOGW("Cannot open input stream for device %08x on hw module %s",
2401 inputDesc->mDevice,
2402 mHwModules[i]->mName);
2403 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002404 }
2405 }
2406 }
2407 // make sure all attached devices have been allocated a unique ID
2408 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2409 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002410 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002411 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2412 continue;
2413 }
2414 i++;
2415 }
2416 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2417 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002418 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002419 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2420 continue;
2421 }
2422 i++;
2423 }
2424 // make sure default device is reachable
2425 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002426 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002427 }
Eric Laurente552edb2014-03-10 17:42:56 -07002428
2429 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2430
2431 updateDevicesAndOutputs();
2432
2433#ifdef AUDIO_POLICY_TEST
2434 if (mPrimaryOutput != 0) {
2435 AudioParameter outputCmd = AudioParameter();
2436 outputCmd.addInt(String8("set_id"), 0);
2437 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2438
2439 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2440 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002441 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2442 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002443 mTestLatencyMs = 0;
2444 mCurOutput = 0;
2445 mDirectOutput = false;
2446 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2447 mTestOutputs[i] = 0;
2448 }
2449
2450 const size_t SIZE = 256;
2451 char buffer[SIZE];
2452 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2453 run(buffer, ANDROID_PRIORITY_AUDIO);
2454 }
2455#endif //AUDIO_POLICY_TEST
2456}
2457
Eric Laurente0720872014-03-11 09:30:41 -07002458AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002459{
2460#ifdef AUDIO_POLICY_TEST
2461 exit();
2462#endif //AUDIO_POLICY_TEST
2463 for (size_t i = 0; i < mOutputs.size(); i++) {
2464 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002465 }
2466 for (size_t i = 0; i < mInputs.size(); i++) {
2467 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002468 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002469 mAvailableOutputDevices.clear();
2470 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002471 mOutputs.clear();
2472 mInputs.clear();
2473 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002474}
2475
Eric Laurente0720872014-03-11 09:30:41 -07002476status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002477{
2478 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2479}
2480
2481#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002482bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002483{
2484 ALOGV("entering threadLoop()");
2485 while (!exitPending())
2486 {
2487 String8 command;
2488 int valueInt;
2489 String8 value;
2490
2491 Mutex::Autolock _l(mLock);
2492 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2493
2494 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2495 AudioParameter param = AudioParameter(command);
2496
2497 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2498 valueInt != 0) {
2499 ALOGV("Test command %s received", command.string());
2500 String8 target;
2501 if (param.get(String8("target"), target) != NO_ERROR) {
2502 target = "Manager";
2503 }
2504 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2505 param.remove(String8("test_cmd_policy_output"));
2506 mCurOutput = valueInt;
2507 }
2508 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2509 param.remove(String8("test_cmd_policy_direct"));
2510 if (value == "false") {
2511 mDirectOutput = false;
2512 } else if (value == "true") {
2513 mDirectOutput = true;
2514 }
2515 }
2516 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2517 param.remove(String8("test_cmd_policy_input"));
2518 mTestInput = valueInt;
2519 }
2520
2521 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2522 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002523 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002524 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002525 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002526 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002527 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002528 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002529 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002530 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002531 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002532 if (target == "Manager") {
2533 mTestFormat = format;
2534 } else if (mTestOutputs[mCurOutput] != 0) {
2535 AudioParameter outputParam = AudioParameter();
2536 outputParam.addInt(String8("format"), format);
2537 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2538 }
2539 }
2540 }
2541 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2542 param.remove(String8("test_cmd_policy_channels"));
2543 int channels = 0;
2544
2545 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002546 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002547 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002548 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002549 }
2550 if (channels != 0) {
2551 if (target == "Manager") {
2552 mTestChannels = channels;
2553 } else if (mTestOutputs[mCurOutput] != 0) {
2554 AudioParameter outputParam = AudioParameter();
2555 outputParam.addInt(String8("channels"), channels);
2556 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2557 }
2558 }
2559 }
2560 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2561 param.remove(String8("test_cmd_policy_sampleRate"));
2562 if (valueInt >= 0 && valueInt <= 96000) {
2563 int samplingRate = valueInt;
2564 if (target == "Manager") {
2565 mTestSamplingRate = samplingRate;
2566 } else if (mTestOutputs[mCurOutput] != 0) {
2567 AudioParameter outputParam = AudioParameter();
2568 outputParam.addInt(String8("sampling_rate"), samplingRate);
2569 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2570 }
2571 }
2572 }
2573
2574 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2575 param.remove(String8("test_cmd_policy_reopen"));
2576
Eric Laurent1f2f2232014-06-02 12:01:23 -07002577 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002578 mpClientInterface->closeOutput(mPrimaryOutput);
2579
2580 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2581
Eric Laurente552edb2014-03-10 17:42:56 -07002582 mOutputs.removeItem(mPrimaryOutput);
2583
Eric Laurent1f2f2232014-06-02 12:01:23 -07002584 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002585 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2586 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2587 &outputDesc->mDevice,
2588 &outputDesc->mSamplingRate,
2589 &outputDesc->mFormat,
2590 &outputDesc->mChannelMask,
2591 &outputDesc->mLatency,
2592 outputDesc->mFlags);
2593 if (mPrimaryOutput == 0) {
2594 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2595 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2596 } else {
2597 AudioParameter outputCmd = AudioParameter();
2598 outputCmd.addInt(String8("set_id"), 0);
2599 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2600 addOutput(mPrimaryOutput, outputDesc);
2601 }
2602 }
2603
2604
2605 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2606 }
2607 }
2608 return false;
2609}
2610
Eric Laurente0720872014-03-11 09:30:41 -07002611void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002612{
2613 {
2614 AutoMutex _l(mLock);
2615 requestExit();
2616 mWaitWorkCV.signal();
2617 }
2618 requestExitAndWait();
2619}
2620
Eric Laurente0720872014-03-11 09:30:41 -07002621int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002622{
2623 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2624 if (output == mTestOutputs[i]) return i;
2625 }
2626 return 0;
2627}
2628#endif //AUDIO_POLICY_TEST
2629
2630// ---
2631
Eric Laurent1f2f2232014-06-02 12:01:23 -07002632void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002633{
Eric Laurent1c333e22014-05-20 10:48:17 -07002634 outputDesc->mIoHandle = output;
2635 outputDesc->mId = nextUniqueId();
2636 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002637 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002638}
2639
Eric Laurent1f2f2232014-06-02 12:01:23 -07002640void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002641{
Eric Laurent1c333e22014-05-20 10:48:17 -07002642 inputDesc->mIoHandle = input;
2643 inputDesc->mId = nextUniqueId();
2644 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002645 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002646}
Eric Laurente552edb2014-03-10 17:42:56 -07002647
Eric Laurent3a4311c2014-03-17 12:00:47 -07002648String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2649{
2650 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2651 return String8("a2dp_sink_address=")+address;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002652 } else if (device & AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2653 return String8("mix=")+address;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002654 }
2655 return address;
2656}
2657
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002658void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2659 const String8 address /*in*/,
2660 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2661 // look for a match on the given address on the addresses of the outputs:
2662 // find the address by finding the patch that maps to this output
2663 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2664 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2665 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2666 if (patchIdx >= 0) {
2667 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2668 const int numSinks = patchDesc->mPatch.num_sinks;
2669 for (ssize_t j=0; j < numSinks; j++) {
2670 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2671 const char* patchAddr =
2672 patchDesc->mPatch.sinks[j].ext.device.address;
2673 if (strncmp(patchAddr,
2674 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2675 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2676 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2677 outputs.add(desc->mIoHandle);
2678 break;
2679 }
2680 }
2681 }
2682 }
2683}
2684
Eric Laurente0720872014-03-11 09:30:41 -07002685status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002686 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002687 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002689{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002690 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002691
Eric Laurent3b73df72014-03-11 09:06:29 -07002692 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002693 // first list already open outputs that can be routed to this device
2694 for (size_t i = 0; i < mOutputs.size(); i++) {
2695 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002696 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002697 if (!deviceDistinguishesOnAddress(device)) {
2698 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2699 outputs.add(mOutputs.keyAt(i));
2700 } else {
2701 ALOGV(" checking address match due to device 0x%x", device);
2702 findIoHandlesByAddress(desc, address, outputs);
2703 }
Eric Laurente552edb2014-03-10 17:42:56 -07002704 }
2705 }
2706 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002707 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002708 for (size_t i = 0; i < mHwModules.size(); i++)
2709 {
2710 if (mHwModules[i]->mHandle == 0) {
2711 continue;
2712 }
2713 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2714 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002715 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002716 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002717 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2718 }
2719 }
2720 }
2721
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002722 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2723
Eric Laurente552edb2014-03-10 17:42:56 -07002724 if (profiles.isEmpty() && outputs.isEmpty()) {
2725 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2726 return BAD_VALUE;
2727 }
2728
2729 // open outputs for matching profiles if needed. Direct outputs are also opened to
2730 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2731 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002732 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002733
2734 // nothing to do if one output is already opened for this profile
2735 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002736 for (j = 0; j < outputs.size(); j++) {
2737 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002738 if (!desc->isDuplicated() && desc->mProfile == profile) {
2739 break;
2740 }
2741 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002742 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002743 continue;
2744 }
2745
Eric Laurent83b88082014-06-20 18:31:16 -07002746 ALOGV("opening output for device %08x with params %s profile %p",
2747 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002748 desc = new AudioOutputDescriptor(profile);
2749 desc->mDevice = device;
2750 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2751 offloadInfo.sample_rate = desc->mSamplingRate;
2752 offloadInfo.format = desc->mFormat;
2753 offloadInfo.channel_mask = desc->mChannelMask;
2754
2755 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2756 &desc->mDevice,
2757 &desc->mSamplingRate,
2758 &desc->mFormat,
2759 &desc->mChannelMask,
2760 &desc->mLatency,
2761 desc->mFlags,
2762 &offloadInfo);
2763 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002764 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002765 if (!address.isEmpty()) {
2766 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002767 }
2768
Eric Laurentd4692962014-05-05 18:13:44 -07002769 // Here is where we step through and resolve any "dynamic" fields
2770 String8 reply;
2771 char *value;
2772 if (profile->mSamplingRates[0] == 0) {
2773 reply = mpClientInterface->getParameters(output,
2774 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002775 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002776 reply.string());
2777 value = strpbrk((char *)reply.string(), "=");
2778 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002779 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002780 }
Eric Laurentd4692962014-05-05 18:13:44 -07002781 }
2782 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2783 reply = mpClientInterface->getParameters(output,
2784 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002785 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002786 reply.string());
2787 value = strpbrk((char *)reply.string(), "=");
2788 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002789 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002790 }
Eric Laurentd4692962014-05-05 18:13:44 -07002791 }
2792 if (profile->mChannelMasks[0] == 0) {
2793 reply = mpClientInterface->getParameters(output,
2794 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002795 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002796 reply.string());
2797 value = strpbrk((char *)reply.string(), "=");
2798 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002799 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002800 }
Eric Laurentd4692962014-05-05 18:13:44 -07002801 }
2802 if (((profile->mSamplingRates[0] == 0) &&
2803 (profile->mSamplingRates.size() < 2)) ||
2804 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2805 (profile->mFormats.size() < 2)) ||
2806 ((profile->mChannelMasks[0] == 0) &&
2807 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002808 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002809 mpClientInterface->closeOutput(output);
2810 output = 0;
Eric Laurent1e693b52014-07-09 15:03:28 -07002811 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2812 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002813 mpClientInterface->closeOutput(output);
Eric Laurent1e693b52014-07-09 15:03:28 -07002814 desc->mSamplingRate = profile->pickSamplingRate();
2815 desc->mFormat = profile->pickFormat();
2816 desc->mChannelMask = profile->pickChannelMask();
Eric Laurentd4692962014-05-05 18:13:44 -07002817 offloadInfo.sample_rate = desc->mSamplingRate;
Eric Laurent1e693b52014-07-09 15:03:28 -07002818 offloadInfo.format = desc->mFormat;
2819 offloadInfo.channel_mask = desc->mChannelMask;
Eric Laurentd4692962014-05-05 18:13:44 -07002820 output = mpClientInterface->openOutput(
2821 profile->mModule->mHandle,
2822 &desc->mDevice,
2823 &desc->mSamplingRate,
2824 &desc->mFormat,
2825 &desc->mChannelMask,
2826 &desc->mLatency,
2827 desc->mFlags,
2828 &offloadInfo);
2829 }
2830
2831 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002832 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002833 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2834 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002835
Eric Laurentd4692962014-05-05 18:13:44 -07002836 // set initial stream volume for device
2837 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002838
Eric Laurentd4692962014-05-05 18:13:44 -07002839 //TODO: configure audio effect output stage here
2840
2841 // open a duplicating output thread for the new output and the primary output
2842 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2843 mPrimaryOutput);
2844 if (duplicatedOutput != 0) {
2845 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002846 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002847 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2848 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2849 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2850 dupOutputDesc->mFormat = desc->mFormat;
2851 dupOutputDesc->mChannelMask = desc->mChannelMask;
2852 dupOutputDesc->mLatency = desc->mLatency;
2853 addOutput(duplicatedOutput, dupOutputDesc);
2854 applyStreamVolumes(duplicatedOutput, device, 0, true);
2855 } else {
2856 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2857 mPrimaryOutput, output);
2858 mpClientInterface->closeOutput(output);
2859 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002860 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002861 output = 0;
2862 }
Eric Laurente552edb2014-03-10 17:42:56 -07002863 }
2864 }
2865 }
2866 if (output == 0) {
2867 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002868 profiles.removeAt(profile_index);
2869 profile_index--;
2870 } else {
2871 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002872 if (deviceDistinguishesOnAddress(device)) {
2873 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2874 device, address.string());
2875 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2876 NULL/*patch handle*/, address.string());
2877 }
Eric Laurente552edb2014-03-10 17:42:56 -07002878 ALOGV("checkOutputsForDevice(): adding output %d", output);
2879 }
2880 }
2881
2882 if (profiles.isEmpty()) {
2883 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2884 return BAD_VALUE;
2885 }
Eric Laurentd4692962014-05-05 18:13:44 -07002886 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002887 // check if one opened output is not needed any more after disconnecting one device
2888 for (size_t i = 0; i < mOutputs.size(); i++) {
2889 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002890 if (!desc->isDuplicated()) {
2891 if (!(desc->mProfile->mSupportedDevices.types()
2892 & mAvailableOutputDevices.types())) {
2893 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
2894 mOutputs.keyAt(i));
2895 outputs.add(mOutputs.keyAt(i));
2896 } else if (deviceDistinguishesOnAddress(device) &&
2897 // exact match on device
2898 (desc->mProfile->mSupportedDevices.types() == device)) {
2899 findIoHandlesByAddress(desc, address, outputs);
2900 }
Eric Laurente552edb2014-03-10 17:42:56 -07002901 }
2902 }
Eric Laurentd4692962014-05-05 18:13:44 -07002903 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002904 for (size_t i = 0; i < mHwModules.size(); i++)
2905 {
2906 if (mHwModules[i]->mHandle == 0) {
2907 continue;
2908 }
2909 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2910 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002911 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002912 if (profile->mSupportedDevices.types() & device) {
2913 ALOGV("checkOutputsForDevice(): "
2914 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002915 if (profile->mSamplingRates[0] == 0) {
2916 profile->mSamplingRates.clear();
2917 profile->mSamplingRates.add(0);
2918 }
2919 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2920 profile->mFormats.clear();
2921 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2922 }
2923 if (profile->mChannelMasks[0] == 0) {
2924 profile->mChannelMasks.clear();
2925 profile->mChannelMasks.add(0);
2926 }
2927 }
2928 }
2929 }
2930 }
2931 return NO_ERROR;
2932}
2933
Eric Laurentd4692962014-05-05 18:13:44 -07002934status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2935 audio_policy_dev_state_t state,
2936 SortedVector<audio_io_handle_t>& inputs,
2937 const String8 address)
2938{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002939 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002940 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2941 // first list already open inputs that can be routed to this device
2942 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2943 desc = mInputs.valueAt(input_index);
2944 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2945 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2946 inputs.add(mInputs.keyAt(input_index));
2947 }
2948 }
2949
2950 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002951 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002952 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2953 {
2954 if (mHwModules[module_idx]->mHandle == 0) {
2955 continue;
2956 }
2957 for (size_t profile_index = 0;
2958 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2959 profile_index++)
2960 {
2961 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2962 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002963 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07002964 profile_index, module_idx);
2965 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2966 }
2967 }
2968 }
2969
2970 if (profiles.isEmpty() && inputs.isEmpty()) {
2971 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2972 return BAD_VALUE;
2973 }
2974
2975 // open inputs for matching profiles if needed. Direct inputs are also opened to
2976 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2977 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2978
Eric Laurent1c333e22014-05-20 10:48:17 -07002979 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002980 // nothing to do if one input is already opened for this profile
2981 size_t input_index;
2982 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2983 desc = mInputs.valueAt(input_index);
2984 if (desc->mProfile == profile) {
2985 break;
2986 }
2987 }
2988 if (input_index != mInputs.size()) {
2989 continue;
2990 }
2991
2992 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2993 desc = new AudioInputDescriptor(profile);
2994 desc->mDevice = device;
2995
2996 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2997 &desc->mDevice,
2998 &desc->mSamplingRate,
2999 &desc->mFormat,
Glenn Kastenec40d282014-07-15 15:31:26 -07003000 &desc->mChannelMask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003001 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003002
3003 if (input != 0) {
3004 if (!address.isEmpty()) {
3005 mpClientInterface->setParameters(input, addressToParameter(device, address));
3006 }
3007
3008 // Here is where we step through and resolve any "dynamic" fields
3009 String8 reply;
3010 char *value;
3011 if (profile->mSamplingRates[0] == 0) {
3012 reply = mpClientInterface->getParameters(input,
3013 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3014 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3015 reply.string());
3016 value = strpbrk((char *)reply.string(), "=");
3017 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003018 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003019 }
3020 }
3021 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3022 reply = mpClientInterface->getParameters(input,
3023 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3024 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3025 value = strpbrk((char *)reply.string(), "=");
3026 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003027 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003028 }
3029 }
3030 if (profile->mChannelMasks[0] == 0) {
3031 reply = mpClientInterface->getParameters(input,
3032 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3033 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3034 reply.string());
3035 value = strpbrk((char *)reply.string(), "=");
3036 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003037 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003038 }
3039 }
3040 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3041 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3042 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3043 ALOGW("checkInputsForDevice() direct input missing param");
3044 mpClientInterface->closeInput(input);
3045 input = 0;
3046 }
3047
3048 if (input != 0) {
3049 addInput(input, desc);
3050 }
3051 } // endif input != 0
3052
3053 if (input == 0) {
3054 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003055 profiles.removeAt(profile_index);
3056 profile_index--;
3057 } else {
3058 inputs.add(input);
3059 ALOGV("checkInputsForDevice(): adding input %d", input);
3060 }
3061 } // end scan profiles
3062
3063 if (profiles.isEmpty()) {
3064 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3065 return BAD_VALUE;
3066 }
3067 } else {
3068 // Disconnect
3069 // check if one opened input is not needed any more after disconnecting one device
3070 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3071 desc = mInputs.valueAt(input_index);
3072 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3073 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3074 mInputs.keyAt(input_index));
3075 inputs.add(mInputs.keyAt(input_index));
3076 }
3077 }
3078 // Clear any profiles associated with the disconnected device.
3079 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3080 if (mHwModules[module_index]->mHandle == 0) {
3081 continue;
3082 }
3083 for (size_t profile_index = 0;
3084 profile_index < mHwModules[module_index]->mInputProfiles.size();
3085 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003086 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003087 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003088 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003089 profile_index, module_index);
3090 if (profile->mSamplingRates[0] == 0) {
3091 profile->mSamplingRates.clear();
3092 profile->mSamplingRates.add(0);
3093 }
3094 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3095 profile->mFormats.clear();
3096 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3097 }
3098 if (profile->mChannelMasks[0] == 0) {
3099 profile->mChannelMasks.clear();
3100 profile->mChannelMasks.add(0);
3101 }
3102 }
3103 }
3104 }
3105 } // end disconnect
3106
3107 return NO_ERROR;
3108}
3109
3110
Eric Laurente0720872014-03-11 09:30:41 -07003111void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003112{
3113 ALOGV("closeOutput(%d)", output);
3114
Eric Laurent1f2f2232014-06-02 12:01:23 -07003115 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003116 if (outputDesc == NULL) {
3117 ALOGW("closeOutput() unknown output %d", output);
3118 return;
3119 }
3120
3121 // look for duplicated outputs connected to the output being removed.
3122 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003123 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003124 if (dupOutputDesc->isDuplicated() &&
3125 (dupOutputDesc->mOutput1 == outputDesc ||
3126 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003127 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003128 if (dupOutputDesc->mOutput1 == outputDesc) {
3129 outputDesc2 = dupOutputDesc->mOutput2;
3130 } else {
3131 outputDesc2 = dupOutputDesc->mOutput1;
3132 }
3133 // As all active tracks on duplicated output will be deleted,
3134 // and as they were also referenced on the other output, the reference
3135 // count for their stream type must be adjusted accordingly on
3136 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003137 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003138 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003139 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003140 }
3141 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3142 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3143
3144 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003145 mOutputs.removeItem(duplicatedOutput);
3146 }
3147 }
3148
3149 AudioParameter param;
3150 param.add(String8("closing"), String8("true"));
3151 mpClientInterface->setParameters(output, param.toString());
3152
3153 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003154 mOutputs.removeItem(output);
3155 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003156 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003157}
3158
Eric Laurente0720872014-03-11 09:30:41 -07003159SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003160 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003161{
3162 SortedVector<audio_io_handle_t> outputs;
3163
3164 ALOGVV("getOutputsForDevice() device %04x", device);
3165 for (size_t i = 0; i < openOutputs.size(); i++) {
3166 ALOGVV("output %d isDuplicated=%d device=%04x",
3167 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3168 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3169 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3170 outputs.add(openOutputs.keyAt(i));
3171 }
3172 }
3173 return outputs;
3174}
3175
Eric Laurente0720872014-03-11 09:30:41 -07003176bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003177 SortedVector<audio_io_handle_t>& outputs2)
3178{
3179 if (outputs1.size() != outputs2.size()) {
3180 return false;
3181 }
3182 for (size_t i = 0; i < outputs1.size(); i++) {
3183 if (outputs1[i] != outputs2[i]) {
3184 return false;
3185 }
3186 }
3187 return true;
3188}
3189
Eric Laurente0720872014-03-11 09:30:41 -07003190void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003191{
3192 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3193 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3194 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3195 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3196
3197 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3198 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3199 strategy, srcOutputs[0], dstOutputs[0]);
3200 // mute strategy while moving tracks from one output to another
3201 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003202 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003203 if (desc->isStrategyActive(strategy)) {
3204 setStrategyMute(strategy, true, srcOutputs[i]);
3205 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3206 }
3207 }
3208
3209 // Move effects associated to this strategy from previous output to new output
3210 if (strategy == STRATEGY_MEDIA) {
3211 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3212 SortedVector<audio_io_handle_t> moved;
3213 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003214 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3215 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3216 effectDesc->mIo != fxOutput) {
3217 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003218 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3219 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003220 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003221 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003222 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003223 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003224 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003225 }
3226 }
3227 }
3228 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003229 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3230 if (getStrategy((audio_stream_type_t)i) == strategy) {
3231 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003232 }
3233 }
3234 }
3235}
3236
Eric Laurente0720872014-03-11 09:30:41 -07003237void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003238{
3239 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3240 checkOutputForStrategy(STRATEGY_PHONE);
3241 checkOutputForStrategy(STRATEGY_SONIFICATION);
3242 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3243 checkOutputForStrategy(STRATEGY_MEDIA);
3244 checkOutputForStrategy(STRATEGY_DTMF);
3245}
3246
Eric Laurente0720872014-03-11 09:30:41 -07003247audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003248{
Eric Laurente552edb2014-03-10 17:42:56 -07003249 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003250 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003251 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3252 return mOutputs.keyAt(i);
3253 }
3254 }
3255
3256 return 0;
3257}
3258
Eric Laurente0720872014-03-11 09:30:41 -07003259void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003260{
Eric Laurente552edb2014-03-10 17:42:56 -07003261 audio_io_handle_t a2dpOutput = getA2dpOutput();
3262 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003263 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003264 return;
3265 }
3266
Eric Laurent3a4311c2014-03-17 12:00:47 -07003267 bool isScoConnected =
3268 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003269 // suspend A2DP output if:
3270 // (NOT already suspended) &&
3271 // ((SCO device is connected &&
3272 // (forced usage for communication || for record is SCO))) ||
3273 // (phone state is ringing || in call)
3274 //
3275 // restore A2DP output if:
3276 // (Already suspended) &&
3277 // ((SCO device is NOT connected ||
3278 // (forced usage NOT for communication && NOT for record is SCO))) &&
3279 // (phone state is NOT ringing && NOT in call)
3280 //
3281 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003282 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003283 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3284 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3285 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3286 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003287
3288 mpClientInterface->restoreOutput(a2dpOutput);
3289 mA2dpSuspended = false;
3290 }
3291 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003292 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003293 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3294 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3295 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3296 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003297
3298 mpClientInterface->suspendOutput(a2dpOutput);
3299 mA2dpSuspended = true;
3300 }
3301 }
3302}
3303
Eric Laurent1c333e22014-05-20 10:48:17 -07003304audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003305{
3306 audio_devices_t device = AUDIO_DEVICE_NONE;
3307
Eric Laurent1f2f2232014-06-02 12:01:23 -07003308 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003309
3310 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3311 if (index >= 0) {
3312 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3313 if (patchDesc->mUid != mUidCached) {
3314 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3315 outputDesc->device(), outputDesc->mPatchHandle);
3316 return outputDesc->device();
3317 }
3318 }
3319
Eric Laurente552edb2014-03-10 17:42:56 -07003320 // check the following by order of priority to request a routing change if necessary:
3321 // 1: the strategy enforced audible is active on the output:
3322 // use device for strategy enforced audible
3323 // 2: we are in call or the strategy phone is active on the output:
3324 // use device for strategy phone
3325 // 3: the strategy sonification is active on the output:
3326 // use device for strategy sonification
3327 // 4: the strategy "respectful" sonification is active on the output:
3328 // use device for strategy "respectful" sonification
3329 // 5: the strategy media is active on the output:
3330 // use device for strategy media
3331 // 6: the strategy DTMF is active on the output:
3332 // use device for strategy DTMF
3333 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3334 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3335 } else if (isInCall() ||
3336 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3337 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3338 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3339 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3340 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3341 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3342 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3343 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3344 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3345 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3346 }
3347
Eric Laurent1c333e22014-05-20 10:48:17 -07003348 ALOGV("getNewOutputDevice() selected device %x", device);
3349 return device;
3350}
3351
3352audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3353{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003354 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003355
3356 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3357 if (index >= 0) {
3358 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3359 if (patchDesc->mUid != mUidCached) {
3360 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3361 inputDesc->mDevice, inputDesc->mPatchHandle);
3362 return inputDesc->mDevice;
3363 }
3364 }
3365
Eric Laurent1c333e22014-05-20 10:48:17 -07003366 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3367
3368 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003369 return device;
3370}
3371
Eric Laurente0720872014-03-11 09:30:41 -07003372uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003373 return (uint32_t)getStrategy(stream);
3374}
3375
Eric Laurente0720872014-03-11 09:30:41 -07003376audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003377 // By checking the range of stream before calling getStrategy, we avoid
3378 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3379 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003380 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003381 return AUDIO_DEVICE_NONE;
3382 }
3383 audio_devices_t devices;
3384 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3385 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3386 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3387 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003388 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003389 if (outputDesc->isStrategyActive(strategy)) {
3390 devices = outputDesc->device();
3391 break;
3392 }
Eric Laurente552edb2014-03-10 17:42:56 -07003393 }
3394 return devices;
3395}
3396
Eric Laurente0720872014-03-11 09:30:41 -07003397AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003398 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003399 // stream to strategy mapping
3400 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003401 case AUDIO_STREAM_VOICE_CALL:
3402 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003403 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003404 case AUDIO_STREAM_RING:
3405 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003406 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003407 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003408 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003409 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003410 return STRATEGY_DTMF;
3411 default:
3412 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003413 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003414 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3415 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003416 case AUDIO_STREAM_TTS:
3417 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003418 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003419 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003420 return STRATEGY_ENFORCED_AUDIBLE;
3421 }
3422}
3423
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003424uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3425 // flags to strategy mapping
3426 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3427 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3428 }
3429
3430 // usage to strategy mapping
3431 switch (attr->usage) {
3432 case AUDIO_USAGE_MEDIA:
3433 case AUDIO_USAGE_GAME:
3434 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3435 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3436 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3437 return (uint32_t) STRATEGY_MEDIA;
3438
3439 case AUDIO_USAGE_VOICE_COMMUNICATION:
3440 return (uint32_t) STRATEGY_PHONE;
3441
3442 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3443 return (uint32_t) STRATEGY_DTMF;
3444
3445 case AUDIO_USAGE_ALARM:
3446 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3447 return (uint32_t) STRATEGY_SONIFICATION;
3448
3449 case AUDIO_USAGE_NOTIFICATION:
3450 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3451 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3452 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3453 case AUDIO_USAGE_NOTIFICATION_EVENT:
3454 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3455
3456 case AUDIO_USAGE_UNKNOWN:
3457 default:
3458 return (uint32_t) STRATEGY_MEDIA;
3459 }
3460}
3461
Eric Laurente0720872014-03-11 09:30:41 -07003462void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003463 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003464 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003465 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3466 updateDevicesAndOutputs();
3467 break;
3468 default:
3469 break;
3470 }
3471}
3472
Eric Laurente0720872014-03-11 09:30:41 -07003473audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003474 bool fromCache)
3475{
3476 uint32_t device = AUDIO_DEVICE_NONE;
3477
3478 if (fromCache) {
3479 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3480 strategy, mDeviceForStrategy[strategy]);
3481 return mDeviceForStrategy[strategy];
3482 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003483 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003484 switch (strategy) {
3485
3486 case STRATEGY_SONIFICATION_RESPECTFUL:
3487 if (isInCall()) {
3488 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003489 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003490 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3491 // while media is playing on a remote device, use the the sonification behavior.
3492 // Note that we test this usecase before testing if media is playing because
3493 // the isStreamActive() method only informs about the activity of a stream, not
3494 // if it's for local playback. Note also that we use the same delay between both tests
3495 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003496 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003497 // while media is playing (or has recently played), use the same device
3498 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3499 } else {
3500 // when media is not playing anymore, fall back on the sonification behavior
3501 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3502 }
3503
3504 break;
3505
3506 case STRATEGY_DTMF:
3507 if (!isInCall()) {
3508 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3509 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3510 break;
3511 }
3512 // when in call, DTMF and PHONE strategies follow the same rules
3513 // FALL THROUGH
3514
3515 case STRATEGY_PHONE:
3516 // for phone strategy, we first consider the forced use and then the available devices by order
3517 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003518 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3519 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003520 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003521 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003522 if (device) break;
3523 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003524 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003525 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003526 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003527 if (device) break;
3528 // if SCO device is requested but no SCO device is available, fall back to default case
3529 // FALL THROUGH
3530
3531 default: // FORCE_NONE
3532 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003533 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003534 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003535 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003536 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003537 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003538 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003539 if (device) break;
3540 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003541 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003542 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003543 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003544 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003545 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003546 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003547 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003548 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003549 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003550 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003551 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003552 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003553 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003554 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003555 if (device) break;
3556 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003557 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003558 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003559 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003560 if (device == AUDIO_DEVICE_NONE) {
3561 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3562 }
3563 break;
3564
Eric Laurent3b73df72014-03-11 09:06:29 -07003565 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003566 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3567 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003568 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003569 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003570 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003571 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003572 if (device) break;
3573 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003574 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003575 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003576 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003577 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003578 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003579 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003580 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003581 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003582 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003583 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003584 if (device) break;
3585 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003586 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003587 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003588 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003589 if (device == AUDIO_DEVICE_NONE) {
3590 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3591 }
3592 break;
3593 }
3594 break;
3595
3596 case STRATEGY_SONIFICATION:
3597
3598 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3599 // handleIncallSonification().
3600 if (isInCall()) {
3601 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3602 break;
3603 }
3604 // FALL THROUGH
3605
3606 case STRATEGY_ENFORCED_AUDIBLE:
3607 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3608 // except:
3609 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3610 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3611
3612 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003613 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003614 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003615 if (device == AUDIO_DEVICE_NONE) {
3616 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3617 }
3618 }
3619 // The second device used for sonification is the same as the device used by media strategy
3620 // FALL THROUGH
3621
3622 case STRATEGY_MEDIA: {
3623 uint32_t device2 = AUDIO_DEVICE_NONE;
3624 if (strategy != STRATEGY_SONIFICATION) {
3625 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003626 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003627 }
3628 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003629 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003630 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003631 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003632 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003633 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003634 }
3635 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003636 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003637 }
3638 }
3639 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003640 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003641 }
3642 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003643 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003644 }
3645 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003646 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003647 }
3648 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003649 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 }
3651 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003652 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003653 }
3654 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3655 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003656 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003657 }
3658 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003659 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003660 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 }
3662 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003663 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003664 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003665 int device3 = AUDIO_DEVICE_NONE;
3666 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003667 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003668 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3669 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003670 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003671 }
Eric Laurente552edb2014-03-10 17:42:56 -07003672
Jungshik Jang839e4f32014-06-26 17:23:40 +09003673 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003674 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3675 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3676 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003677
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003678 // If hdmi system audio mode is on, remove speaker out of output list.
3679 if ((strategy == STRATEGY_MEDIA) &&
3680 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3681 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3682 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3683 }
3684
Eric Laurente552edb2014-03-10 17:42:56 -07003685 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003686 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003687 if (device == AUDIO_DEVICE_NONE) {
3688 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3689 }
3690 } break;
3691
3692 default:
3693 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3694 break;
3695 }
3696
3697 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3698 return device;
3699}
3700
Eric Laurente0720872014-03-11 09:30:41 -07003701void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003702{
3703 for (int i = 0; i < NUM_STRATEGIES; i++) {
3704 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3705 }
3706 mPreviousOutputs = mOutputs;
3707}
3708
Eric Laurent1f2f2232014-06-02 12:01:23 -07003709uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003710 audio_devices_t prevDevice,
3711 uint32_t delayMs)
3712{
3713 // mute/unmute strategies using an incompatible device combination
3714 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3715 // if unmuting, unmute only after the specified delay
3716 if (outputDesc->isDuplicated()) {
3717 return 0;
3718 }
3719
3720 uint32_t muteWaitMs = 0;
3721 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003722 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003723
3724 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3725 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3726 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3727 bool doMute = false;
3728
3729 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3730 doMute = true;
3731 outputDesc->mStrategyMutedByDevice[i] = true;
3732 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3733 doMute = true;
3734 outputDesc->mStrategyMutedByDevice[i] = false;
3735 }
Eric Laurent99401132014-05-07 19:48:15 -07003736 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003737 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003738 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003739 // skip output if it does not share any device with current output
3740 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3741 == AUDIO_DEVICE_NONE) {
3742 continue;
3743 }
3744 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3745 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3746 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3747 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3748 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003749 if (mute) {
3750 // FIXME: should not need to double latency if volume could be applied
3751 // immediately by the audioflinger mixer. We must account for the delay
3752 // between now and the next time the audioflinger thread for this output
3753 // will process a buffer (which corresponds to one buffer size,
3754 // usually 1/2 or 1/4 of the latency).
3755 if (muteWaitMs < desc->latency() * 2) {
3756 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003757 }
3758 }
3759 }
3760 }
3761 }
3762 }
3763
Eric Laurent99401132014-05-07 19:48:15 -07003764 // temporary mute output if device selection changes to avoid volume bursts due to
3765 // different per device volumes
3766 if (outputDesc->isActive() && (device != prevDevice)) {
3767 if (muteWaitMs < outputDesc->latency() * 2) {
3768 muteWaitMs = outputDesc->latency() * 2;
3769 }
3770 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3771 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003772 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003773 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003774 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003775 muteWaitMs *2, device);
3776 }
3777 }
3778 }
3779
Eric Laurente552edb2014-03-10 17:42:56 -07003780 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3781 if (muteWaitMs > delayMs) {
3782 muteWaitMs -= delayMs;
3783 usleep(muteWaitMs * 1000);
3784 return muteWaitMs;
3785 }
3786 return 0;
3787}
3788
Eric Laurente0720872014-03-11 09:30:41 -07003789uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003790 audio_devices_t device,
3791 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003792 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003793 audio_patch_handle_t *patchHandle,
3794 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003795{
3796 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003797 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003798 AudioParameter param;
3799 uint32_t muteWaitMs;
3800
3801 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003802 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3803 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003804 return muteWaitMs;
3805 }
3806 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3807 // output profile
3808 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003809 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003810 return 0;
3811 }
3812
3813 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003814 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003815
3816 audio_devices_t prevDevice = outputDesc->mDevice;
3817
3818 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3819
3820 if (device != AUDIO_DEVICE_NONE) {
3821 outputDesc->mDevice = device;
3822 }
3823 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3824
3825 // Do not change the routing if:
3826 // - the requested device is AUDIO_DEVICE_NONE
3827 // - the requested device is the same as current device and force is not specified.
3828 // Doing this check here allows the caller to call setOutputDevice() without conditions
3829 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3830 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3831 return muteWaitMs;
3832 }
3833
3834 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003835
Eric Laurente552edb2014-03-10 17:42:56 -07003836 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003837 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003840 DeviceVector deviceList = (address == NULL) ?
3841 mAvailableOutputDevices.getDevicesFromType(device)
3842 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003843 if (!deviceList.isEmpty()) {
3844 struct audio_patch patch;
3845 outputDesc->toAudioPortConfig(&patch.sources[0]);
3846 patch.num_sources = 1;
3847 patch.num_sinks = 0;
3848 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3849 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003850 patch.num_sinks++;
3851 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 ssize_t index;
3853 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3854 index = mAudioPatches.indexOfKey(*patchHandle);
3855 } else {
3856 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3857 }
3858 sp< AudioPatch> patchDesc;
3859 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3860 if (index >= 0) {
3861 patchDesc = mAudioPatches.valueAt(index);
3862 afPatchHandle = patchDesc->mAfPatchHandle;
3863 }
3864
Eric Laurent1c333e22014-05-20 10:48:17 -07003865 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003866 &afPatchHandle,
3867 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003868 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3869 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003871 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003872 if (index < 0) {
3873 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3874 &patch, mUidCached);
3875 addAudioPatch(patchDesc->mHandle, patchDesc);
3876 } else {
3877 patchDesc->mPatch = patch;
3878 }
3879 patchDesc->mAfPatchHandle = afPatchHandle;
3880 patchDesc->mUid = mUidCached;
3881 if (patchHandle) {
3882 *patchHandle = patchDesc->mHandle;
3883 }
3884 outputDesc->mPatchHandle = patchDesc->mHandle;
3885 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003886 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003887 }
3888 }
3889 }
Eric Laurente552edb2014-03-10 17:42:56 -07003890
3891 // update stream volumes according to new device
3892 applyStreamVolumes(output, device, delayMs);
3893
3894 return muteWaitMs;
3895}
3896
Eric Laurent1c333e22014-05-20 10:48:17 -07003897status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003898 int delayMs,
3899 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003900{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003901 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003902 ssize_t index;
3903 if (patchHandle) {
3904 index = mAudioPatches.indexOfKey(*patchHandle);
3905 } else {
3906 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3907 }
3908 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003909 return INVALID_OPERATION;
3910 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003911 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3912 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003913 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3914 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003915 removeAudioPatch(patchDesc->mHandle);
3916 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003917 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003918 return status;
3919}
3920
3921status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3922 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003923 bool force,
3924 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003925{
3926 status_t status = NO_ERROR;
3927
Eric Laurent1f2f2232014-06-02 12:01:23 -07003928 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003929 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3930 inputDesc->mDevice = device;
3931
3932 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3933 if (!deviceList.isEmpty()) {
3934 struct audio_patch patch;
3935 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07003936 // AUDIO_SOURCE_HOTWORD is for internal use only:
3937 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
3938 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD) {
3939 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
3940 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003941 patch.num_sinks = 1;
3942 //only one input device for now
3943 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003944 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003945 ssize_t index;
3946 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3947 index = mAudioPatches.indexOfKey(*patchHandle);
3948 } else {
3949 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3950 }
3951 sp< AudioPatch> patchDesc;
3952 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3953 if (index >= 0) {
3954 patchDesc = mAudioPatches.valueAt(index);
3955 afPatchHandle = patchDesc->mAfPatchHandle;
3956 }
3957
Eric Laurent1c333e22014-05-20 10:48:17 -07003958 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003959 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003960 0);
3961 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003962 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003963 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003964 if (index < 0) {
3965 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3966 &patch, mUidCached);
3967 addAudioPatch(patchDesc->mHandle, patchDesc);
3968 } else {
3969 patchDesc->mPatch = patch;
3970 }
3971 patchDesc->mAfPatchHandle = afPatchHandle;
3972 patchDesc->mUid = mUidCached;
3973 if (patchHandle) {
3974 *patchHandle = patchDesc->mHandle;
3975 }
3976 inputDesc->mPatchHandle = patchDesc->mHandle;
3977 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003978 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003979 }
3980 }
3981 }
3982 return status;
3983}
3984
Eric Laurent6a94d692014-05-20 11:18:06 -07003985status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3986 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003987{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003988 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 ssize_t index;
3990 if (patchHandle) {
3991 index = mAudioPatches.indexOfKey(*patchHandle);
3992 } else {
3993 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3994 }
3995 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003996 return INVALID_OPERATION;
3997 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003998 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3999 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004000 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4001 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004002 removeAudioPatch(patchDesc->mHandle);
4003 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004004 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004005 return status;
4006}
4007
4008sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07004009 uint32_t samplingRate,
4010 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004011 audio_channel_mask_t channelMask,
4012 audio_input_flags_t flags __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07004013{
4014 // Choose an input profile based on the requested capture parameters: select the first available
4015 // profile supporting all requested parameters.
4016
4017 for (size_t i = 0; i < mHwModules.size(); i++)
4018 {
4019 if (mHwModules[i]->mHandle == 0) {
4020 continue;
4021 }
4022 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4023 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004024 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004025 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07004026 if (profile->isCompatibleProfile(device, samplingRate, format,
4027 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
4028 return profile;
4029 }
4030 }
4031 }
4032 return NULL;
4033}
4034
Eric Laurente0720872014-03-11 09:30:41 -07004035audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004036{
4037 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004038 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4039 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004040 switch (inputSource) {
4041 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004042 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004043 device = AUDIO_DEVICE_IN_VOICE_CALL;
4044 break;
4045 }
4046 // FALL THROUGH
4047
4048 case AUDIO_SOURCE_DEFAULT:
4049 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004050 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4051 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4052 break;
4053 }
4054 // FALL THROUGH
4055
Eric Laurente552edb2014-03-10 17:42:56 -07004056 case AUDIO_SOURCE_VOICE_RECOGNITION:
4057 case AUDIO_SOURCE_HOTWORD:
4058 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004059 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004061 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004063 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004064 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4065 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004067 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4068 }
4069 break;
4070 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004071 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004072 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004073 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004074 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4075 }
4076 break;
4077 case AUDIO_SOURCE_VOICE_DOWNLINK:
4078 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004079 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004080 device = AUDIO_DEVICE_IN_VOICE_CALL;
4081 }
4082 break;
4083 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004084 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004085 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4086 }
4087 break;
4088 default:
4089 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4090 break;
4091 }
4092 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4093 return device;
4094}
4095
Eric Laurente0720872014-03-11 09:30:41 -07004096bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004097{
4098 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4099 device &= ~AUDIO_DEVICE_BIT_IN;
4100 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4101 return true;
4102 }
4103 return false;
4104}
4105
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004106bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4107 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4108}
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004111{
4112 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004113 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004114 if ((input_descriptor->mRefCount > 0)
4115 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4116 return mInputs.keyAt(i);
4117 }
4118 }
4119 return 0;
4120}
4121
4122
Eric Laurente0720872014-03-11 09:30:41 -07004123audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004124{
4125 if (device == AUDIO_DEVICE_NONE) {
4126 // this happens when forcing a route update and no track is active on an output.
4127 // In this case the returned category is not important.
4128 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004129 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004130 // Multiple device selection is either:
4131 // - speaker + one other device: give priority to speaker in this case.
4132 // - one A2DP device + another device: happens with duplicated output. In this case
4133 // retain the device on the A2DP output as the other must not correspond to an active
4134 // selection if not the speaker.
4135 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4136 device = AUDIO_DEVICE_OUT_SPEAKER;
4137 } else {
4138 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4139 }
4140 }
4141
Eric Laurent3b73df72014-03-11 09:06:29 -07004142 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004143 "getDeviceForVolume() invalid device combination: %08x",
4144 device);
4145
4146 return device;
4147}
4148
Eric Laurente0720872014-03-11 09:30:41 -07004149AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004150{
4151 switch(getDeviceForVolume(device)) {
4152 case AUDIO_DEVICE_OUT_EARPIECE:
4153 return DEVICE_CATEGORY_EARPIECE;
4154 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4155 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4156 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4157 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4158 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4159 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4160 return DEVICE_CATEGORY_HEADSET;
4161 case AUDIO_DEVICE_OUT_SPEAKER:
4162 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4163 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4164 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4165 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4166 case AUDIO_DEVICE_OUT_USB_DEVICE:
4167 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4168 default:
4169 return DEVICE_CATEGORY_SPEAKER;
4170 }
4171}
4172
Eric Laurente0720872014-03-11 09:30:41 -07004173float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004174 int indexInUi)
4175{
4176 device_category deviceCategory = getDeviceCategory(device);
4177 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4178
4179 // the volume index in the UI is relative to the min and max volume indices for this stream type
4180 int nbSteps = 1 + curve[VOLMAX].mIndex -
4181 curve[VOLMIN].mIndex;
4182 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4183 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4184
4185 // find what part of the curve this index volume belongs to, or if it's out of bounds
4186 int segment = 0;
4187 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4188 return 0.0f;
4189 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4190 segment = 0;
4191 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4192 segment = 1;
4193 } else if (volIdx <= curve[VOLMAX].mIndex) {
4194 segment = 2;
4195 } else { // out of bounds
4196 return 1.0f;
4197 }
4198
4199 // linear interpolation in the attenuation table in dB
4200 float decibels = curve[segment].mDBAttenuation +
4201 ((float)(volIdx - curve[segment].mIndex)) *
4202 ( (curve[segment+1].mDBAttenuation -
4203 curve[segment].mDBAttenuation) /
4204 ((float)(curve[segment+1].mIndex -
4205 curve[segment].mIndex)) );
4206
4207 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4208
4209 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4210 curve[segment].mIndex, volIdx,
4211 curve[segment+1].mIndex,
4212 curve[segment].mDBAttenuation,
4213 decibels,
4214 curve[segment+1].mDBAttenuation,
4215 amplification);
4216
4217 return amplification;
4218}
4219
Eric Laurente0720872014-03-11 09:30:41 -07004220const AudioPolicyManager::VolumeCurvePoint
4221 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004222 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4223};
4224
Eric Laurente0720872014-03-11 09:30:41 -07004225const AudioPolicyManager::VolumeCurvePoint
4226 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004227 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4228};
4229
Eric Laurente0720872014-03-11 09:30:41 -07004230const AudioPolicyManager::VolumeCurvePoint
4231 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004232 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4233};
4234
Eric Laurente0720872014-03-11 09:30:41 -07004235const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004236 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004237 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004238};
4239
4240const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004241 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004242 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4243};
4244
Eric Laurente0720872014-03-11 09:30:41 -07004245const AudioPolicyManager::VolumeCurvePoint
4246 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004247 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4248};
4249
4250// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4251// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4252// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4253// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4254
Eric Laurente0720872014-03-11 09:30:41 -07004255const AudioPolicyManager::VolumeCurvePoint
4256 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004257 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4258};
4259
Eric Laurente0720872014-03-11 09:30:41 -07004260const AudioPolicyManager::VolumeCurvePoint
4261 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004262 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4263};
4264
Eric Laurente0720872014-03-11 09:30:41 -07004265const AudioPolicyManager::VolumeCurvePoint
4266 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004267 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4268};
4269
Eric Laurente0720872014-03-11 09:30:41 -07004270const AudioPolicyManager::VolumeCurvePoint
4271 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004272 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4273};
4274
Eric Laurente0720872014-03-11 09:30:41 -07004275const AudioPolicyManager::VolumeCurvePoint
4276 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004277 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4278};
4279
Eric Laurente0720872014-03-11 09:30:41 -07004280const AudioPolicyManager::VolumeCurvePoint
4281 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4282 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004283 { // AUDIO_STREAM_VOICE_CALL
4284 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4285 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4286 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4287 },
4288 { // AUDIO_STREAM_SYSTEM
4289 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4290 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4291 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4292 },
4293 { // AUDIO_STREAM_RING
4294 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4295 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4296 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4297 },
4298 { // AUDIO_STREAM_MUSIC
4299 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4300 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4301 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4302 },
4303 { // AUDIO_STREAM_ALARM
4304 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4305 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4306 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4307 },
4308 { // AUDIO_STREAM_NOTIFICATION
4309 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4310 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4311 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4312 },
4313 { // AUDIO_STREAM_BLUETOOTH_SCO
4314 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4315 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4316 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4317 },
4318 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4319 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4320 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4321 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4322 },
4323 { // AUDIO_STREAM_DTMF
4324 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4325 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4326 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4327 },
4328 { // AUDIO_STREAM_TTS
4329 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4330 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4331 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4332 },
4333};
4334
Eric Laurente0720872014-03-11 09:30:41 -07004335void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004336{
4337 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4338 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4339 mStreams[i].mVolumeCurve[j] =
4340 sVolumeProfiles[i][j];
4341 }
4342 }
4343
4344 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4345 if (mSpeakerDrcEnabled) {
4346 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4347 sDefaultSystemVolumeCurveDrc;
4348 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4349 sSpeakerSonificationVolumeCurveDrc;
4350 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4351 sSpeakerSonificationVolumeCurveDrc;
4352 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4353 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004354 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4355 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004356 }
4357}
4358
Eric Laurente0720872014-03-11 09:30:41 -07004359float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004360 int index,
4361 audio_io_handle_t output,
4362 audio_devices_t device)
4363{
4364 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004365 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004366 StreamDescriptor &streamDesc = mStreams[stream];
4367
4368 if (device == AUDIO_DEVICE_NONE) {
4369 device = outputDesc->device();
4370 }
4371
Eric Laurente552edb2014-03-10 17:42:56 -07004372 volume = volIndexToAmpl(device, streamDesc, index);
4373
4374 // if a headset is connected, apply the following rules to ring tones and notifications
4375 // to avoid sound level bursts in user's ears:
4376 // - always attenuate ring tones and notifications volume by 6dB
4377 // - if music is playing, always limit the volume to current music volume,
4378 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004379 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004380 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4381 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4382 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4383 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4384 ((stream_strategy == STRATEGY_SONIFICATION)
4385 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004386 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004387 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004388 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004389 streamDesc.mCanBeMuted) {
4390 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4391 // when the phone is ringing we must consider that music could have been paused just before
4392 // by the music application and behave as if music was active if the last music track was
4393 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004394 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004395 mLimitRingtoneVolume) {
4396 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004397 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4398 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004399 output,
4400 musicDevice);
4401 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4402 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4403 if (volume > minVol) {
4404 volume = minVol;
4405 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4406 }
4407 }
4408 }
4409
4410 return volume;
4411}
4412
Eric Laurente0720872014-03-11 09:30:41 -07004413status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004414 int index,
4415 audio_io_handle_t output,
4416 audio_devices_t device,
4417 int delayMs,
4418 bool force)
4419{
4420
4421 // do not change actual stream volume if the stream is muted
4422 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4423 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4424 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4425 return NO_ERROR;
4426 }
4427
4428 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004429 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4430 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4431 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4432 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004433 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004434 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004435 return INVALID_OPERATION;
4436 }
4437
4438 float volume = computeVolume(stream, index, output, device);
4439 // We actually change the volume if:
4440 // - the float value returned by computeVolume() changed
4441 // - the force flag is set
4442 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4443 force) {
4444 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4445 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4446 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4447 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004448 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4449 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004450 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004451 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004452 }
4453
Eric Laurent3b73df72014-03-11 09:06:29 -07004454 if (stream == AUDIO_STREAM_VOICE_CALL ||
4455 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004456 float voiceVolume;
4457 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004458 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004459 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4460 } else {
4461 voiceVolume = 1.0;
4462 }
4463
4464 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4465 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4466 mLastVoiceVolume = voiceVolume;
4467 }
4468 }
4469
4470 return NO_ERROR;
4471}
4472
Eric Laurente0720872014-03-11 09:30:41 -07004473void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004474 audio_devices_t device,
4475 int delayMs,
4476 bool force)
4477{
4478 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4479
Eric Laurent3b73df72014-03-11 09:06:29 -07004480 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4481 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004482 mStreams[stream].getVolumeIndex(device),
4483 output,
4484 device,
4485 delayMs,
4486 force);
4487 }
4488}
4489
Eric Laurente0720872014-03-11 09:30:41 -07004490void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004491 bool on,
4492 audio_io_handle_t output,
4493 int delayMs,
4494 audio_devices_t device)
4495{
4496 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004497 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4498 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4499 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004500 }
4501 }
4502}
4503
Eric Laurente0720872014-03-11 09:30:41 -07004504void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004505 bool on,
4506 audio_io_handle_t output,
4507 int delayMs,
4508 audio_devices_t device)
4509{
4510 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004511 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004512 if (device == AUDIO_DEVICE_NONE) {
4513 device = outputDesc->device();
4514 }
4515
4516 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4517 stream, on, output, outputDesc->mMuteCount[stream], device);
4518
4519 if (on) {
4520 if (outputDesc->mMuteCount[stream] == 0) {
4521 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004522 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4523 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004524 checkAndSetVolume(stream, 0, output, device, delayMs);
4525 }
4526 }
4527 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4528 outputDesc->mMuteCount[stream]++;
4529 } else {
4530 if (outputDesc->mMuteCount[stream] == 0) {
4531 ALOGV("setStreamMute() unmuting non muted stream!");
4532 return;
4533 }
4534 if (--outputDesc->mMuteCount[stream] == 0) {
4535 checkAndSetVolume(stream,
4536 streamDesc.getVolumeIndex(device),
4537 output,
4538 device,
4539 delayMs);
4540 }
4541 }
4542}
4543
Eric Laurente0720872014-03-11 09:30:41 -07004544void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004545 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004546{
4547 // if the stream pertains to sonification strategy and we are in call we must
4548 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4549 // in the device used for phone strategy and play the tone if the selected device does not
4550 // interfere with the device used for phone strategy
4551 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4552 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004553 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004554 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4555 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004556 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004557 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4558 stream, starting, outputDesc->mDevice, stateChange);
4559 if (outputDesc->mRefCount[stream]) {
4560 int muteCount = 1;
4561 if (stateChange) {
4562 muteCount = outputDesc->mRefCount[stream];
4563 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004564 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004565 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4566 for (int i = 0; i < muteCount; i++) {
4567 setStreamMute(stream, starting, mPrimaryOutput);
4568 }
4569 } else {
4570 ALOGV("handleIncallSonification() high visibility");
4571 if (outputDesc->device() &
4572 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4573 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4574 for (int i = 0; i < muteCount; i++) {
4575 setStreamMute(stream, starting, mPrimaryOutput);
4576 }
4577 }
4578 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004579 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4580 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004581 } else {
4582 mpClientInterface->stopTone();
4583 }
4584 }
4585 }
4586 }
4587}
4588
Eric Laurente0720872014-03-11 09:30:41 -07004589bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004590{
4591 return isStateInCall(mPhoneState);
4592}
4593
Eric Laurente0720872014-03-11 09:30:41 -07004594bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004595 return ((state == AUDIO_MODE_IN_CALL) ||
4596 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004597}
4598
Eric Laurente0720872014-03-11 09:30:41 -07004599uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004600{
4601 return MAX_EFFECTS_CPU_LOAD;
4602}
4603
Eric Laurente0720872014-03-11 09:30:41 -07004604uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004605{
4606 return MAX_EFFECTS_MEMORY;
4607}
4608
Eric Laurent6a94d692014-05-20 11:18:06 -07004609
Eric Laurente552edb2014-03-10 17:42:56 -07004610// --- AudioOutputDescriptor class implementation
4611
Eric Laurente0720872014-03-11 09:30:41 -07004612AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004613 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004614 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004615 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004616 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4617{
4618 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004619 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004620 mRefCount[i] = 0;
4621 mCurVolume[i] = -1.0;
4622 mMuteCount[i] = 0;
4623 mStopTime[i] = 0;
4624 }
4625 for (int i = 0; i < NUM_STRATEGIES; i++) {
4626 mStrategyMutedByDevice[i] = false;
4627 }
4628 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004629 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004630 mSamplingRate = profile->pickSamplingRate();
4631 mFormat = profile->pickFormat();
4632 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004633 if (profile->mGains.size() > 0) {
4634 profile->mGains[0]->getDefaultConfig(&mGain);
4635 }
Eric Laurente552edb2014-03-10 17:42:56 -07004636 mFlags = profile->mFlags;
4637 }
4638}
4639
Eric Laurente0720872014-03-11 09:30:41 -07004640audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004641{
4642 if (isDuplicated()) {
4643 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4644 } else {
4645 return mDevice;
4646 }
4647}
4648
Eric Laurente0720872014-03-11 09:30:41 -07004649uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004650{
4651 if (isDuplicated()) {
4652 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4653 } else {
4654 return mLatency;
4655 }
4656}
4657
Eric Laurente0720872014-03-11 09:30:41 -07004658bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004659 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004660{
4661 if (isDuplicated()) {
4662 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4663 } else if (outputDesc->isDuplicated()){
4664 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4665 } else {
4666 return (mProfile->mModule == outputDesc->mProfile->mModule);
4667 }
4668}
4669
Eric Laurente0720872014-03-11 09:30:41 -07004670void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004671 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004672{
4673 // forward usage count change to attached outputs
4674 if (isDuplicated()) {
4675 mOutput1->changeRefCount(stream, delta);
4676 mOutput2->changeRefCount(stream, delta);
4677 }
4678 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004679 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4680 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004681 mRefCount[stream] = 0;
4682 return;
4683 }
4684 mRefCount[stream] += delta;
4685 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4686}
4687
Eric Laurente0720872014-03-11 09:30:41 -07004688audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004689{
4690 if (isDuplicated()) {
4691 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4692 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004693 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
4695}
4696
Eric Laurente0720872014-03-11 09:30:41 -07004697bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004698{
4699 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4700}
4701
Eric Laurente0720872014-03-11 09:30:41 -07004702bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004703 uint32_t inPastMs,
4704 nsecs_t sysTime) const
4705{
4706 if ((sysTime == 0) && (inPastMs != 0)) {
4707 sysTime = systemTime();
4708 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004709 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4710 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004711 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004712 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004713 return true;
4714 }
4715 }
4716 return false;
4717}
4718
Eric Laurente0720872014-03-11 09:30:41 -07004719bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004720 uint32_t inPastMs,
4721 nsecs_t sysTime) const
4722{
4723 if (mRefCount[stream] != 0) {
4724 return true;
4725 }
4726 if (inPastMs == 0) {
4727 return false;
4728 }
4729 if (sysTime == 0) {
4730 sysTime = systemTime();
4731 }
4732 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4733 return true;
4734 }
4735 return false;
4736}
4737
Eric Laurent1c333e22014-05-20 10:48:17 -07004738void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 struct audio_port_config *dstConfig,
4740 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004741{
Eric Laurent84c70242014-06-23 08:46:27 -07004742 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4743
Eric Laurent1f2f2232014-06-02 12:01:23 -07004744 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4745 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4746 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004747 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004748 }
4749 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4750
Eric Laurent6a94d692014-05-20 11:18:06 -07004751 dstConfig->id = mId;
4752 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4753 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4755 dstConfig->ext.mix.handle = mIoHandle;
4756 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004757}
4758
4759void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4760 struct audio_port *port) const
4761{
Eric Laurent84c70242014-06-23 08:46:27 -07004762 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004763 mProfile->toAudioPort(port);
4764 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004765 toAudioPortConfig(&port->active_config);
4766 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004767 port->ext.mix.handle = mIoHandle;
4768 port->ext.mix.latency_class =
4769 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4770}
Eric Laurente552edb2014-03-10 17:42:56 -07004771
Eric Laurente0720872014-03-11 09:30:41 -07004772status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004773{
4774 const size_t SIZE = 256;
4775 char buffer[SIZE];
4776 String8 result;
4777
4778 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4779 result.append(buffer);
4780 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4781 result.append(buffer);
4782 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4783 result.append(buffer);
4784 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4785 result.append(buffer);
4786 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4787 result.append(buffer);
4788 snprintf(buffer, SIZE, " Devices %08x\n", device());
4789 result.append(buffer);
4790 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4791 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004792 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4793 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4794 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004795 result.append(buffer);
4796 }
4797 write(fd, result.string(), result.size());
4798
4799 return NO_ERROR;
4800}
4801
4802// --- AudioInputDescriptor class implementation
4803
Eric Laurent1c333e22014-05-20 10:48:17 -07004804AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004805 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004806 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004807 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004808{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004809 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004810 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004811 mSamplingRate = profile->pickSamplingRate();
4812 mFormat = profile->pickFormat();
4813 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004814 if (profile->mGains.size() > 0) {
4815 profile->mGains[0]->getDefaultConfig(&mGain);
4816 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004817 }
Eric Laurente552edb2014-03-10 17:42:56 -07004818}
4819
Eric Laurent1c333e22014-05-20 10:48:17 -07004820void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004821 struct audio_port_config *dstConfig,
4822 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004823{
Eric Laurent84c70242014-06-23 08:46:27 -07004824 ALOG_ASSERT(mProfile != 0,
4825 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004826 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4827 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4828 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004829 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004830 }
4831
4832 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4833
Eric Laurent6a94d692014-05-20 11:18:06 -07004834 dstConfig->id = mId;
4835 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4836 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004837 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4838 dstConfig->ext.mix.handle = mIoHandle;
4839 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004840}
4841
4842void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4843 struct audio_port *port) const
4844{
Eric Laurent84c70242014-06-23 08:46:27 -07004845 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4846
Eric Laurent1c333e22014-05-20 10:48:17 -07004847 mProfile->toAudioPort(port);
4848 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004849 toAudioPortConfig(&port->active_config);
4850 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004851 port->ext.mix.handle = mIoHandle;
4852 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4853}
4854
Eric Laurente0720872014-03-11 09:30:41 -07004855status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004856{
4857 const size_t SIZE = 256;
4858 char buffer[SIZE];
4859 String8 result;
4860
4861 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4862 result.append(buffer);
4863 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4864 result.append(buffer);
4865 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4866 result.append(buffer);
4867 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4868 result.append(buffer);
4869 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4870 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004871 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
4872 result.append(buffer);
4873
Eric Laurente552edb2014-03-10 17:42:56 -07004874 write(fd, result.string(), result.size());
4875
4876 return NO_ERROR;
4877}
4878
4879// --- StreamDescriptor class implementation
4880
Eric Laurente0720872014-03-11 09:30:41 -07004881AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004882 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4883{
4884 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4885}
4886
Eric Laurente0720872014-03-11 09:30:41 -07004887int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004888{
Eric Laurente0720872014-03-11 09:30:41 -07004889 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004890 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4891 if (mIndexCur.indexOfKey(device) < 0) {
4892 device = AUDIO_DEVICE_OUT_DEFAULT;
4893 }
4894 return mIndexCur.valueFor(device);
4895}
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004898{
4899 const size_t SIZE = 256;
4900 char buffer[SIZE];
4901 String8 result;
4902
4903 snprintf(buffer, SIZE, "%s %02d %02d ",
4904 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4905 result.append(buffer);
4906 for (size_t i = 0; i < mIndexCur.size(); i++) {
4907 snprintf(buffer, SIZE, "%04x : %02d, ",
4908 mIndexCur.keyAt(i),
4909 mIndexCur.valueAt(i));
4910 result.append(buffer);
4911 }
4912 result.append("\n");
4913
4914 write(fd, result.string(), result.size());
4915}
4916
4917// --- EffectDescriptor class implementation
4918
Eric Laurente0720872014-03-11 09:30:41 -07004919status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004920{
4921 const size_t SIZE = 256;
4922 char buffer[SIZE];
4923 String8 result;
4924
4925 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4926 result.append(buffer);
4927 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4928 result.append(buffer);
4929 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4930 result.append(buffer);
4931 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4932 result.append(buffer);
4933 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4934 result.append(buffer);
4935 write(fd, result.string(), result.size());
4936
4937 return NO_ERROR;
4938}
4939
Eric Laurent1c333e22014-05-20 10:48:17 -07004940// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004941
Eric Laurente0720872014-03-11 09:30:41 -07004942AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004943 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4944 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004945{
4946}
4947
Eric Laurente0720872014-03-11 09:30:41 -07004948AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004949{
4950 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004951 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004952 }
4953 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004954 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004955 }
4956 free((void *)mName);
4957}
4958
Eric Laurent1afeecb2014-05-14 08:52:28 -07004959status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4960{
4961 cnode *node = root->first_child;
4962
4963 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4964
4965 while (node) {
4966 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4967 profile->loadSamplingRates((char *)node->value);
4968 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4969 profile->loadFormats((char *)node->value);
4970 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4971 profile->loadInChannels((char *)node->value);
4972 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4973 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4974 mDeclaredDevices);
4975 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4976 profile->loadGains(node);
4977 }
4978 node = node->next;
4979 }
4980 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4981 "loadInput() invalid supported devices");
4982 ALOGW_IF(profile->mChannelMasks.size() == 0,
4983 "loadInput() invalid supported channel masks");
4984 ALOGW_IF(profile->mSamplingRates.size() == 0,
4985 "loadInput() invalid supported sampling rates");
4986 ALOGW_IF(profile->mFormats.size() == 0,
4987 "loadInput() invalid supported formats");
4988 if (!profile->mSupportedDevices.isEmpty() &&
4989 (profile->mChannelMasks.size() != 0) &&
4990 (profile->mSamplingRates.size() != 0) &&
4991 (profile->mFormats.size() != 0)) {
4992
4993 ALOGV("loadInput() adding input Supported Devices %04x",
4994 profile->mSupportedDevices.types());
4995
4996 mInputProfiles.add(profile);
4997 return NO_ERROR;
4998 } else {
4999 return BAD_VALUE;
5000 }
5001}
5002
5003status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5004{
5005 cnode *node = root->first_child;
5006
5007 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5008
5009 while (node) {
5010 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5011 profile->loadSamplingRates((char *)node->value);
5012 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5013 profile->loadFormats((char *)node->value);
5014 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5015 profile->loadOutChannels((char *)node->value);
5016 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5017 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5018 mDeclaredDevices);
5019 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5020 profile->mFlags = parseFlagNames((char *)node->value);
5021 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5022 profile->loadGains(node);
5023 }
5024 node = node->next;
5025 }
5026 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5027 "loadOutput() invalid supported devices");
5028 ALOGW_IF(profile->mChannelMasks.size() == 0,
5029 "loadOutput() invalid supported channel masks");
5030 ALOGW_IF(profile->mSamplingRates.size() == 0,
5031 "loadOutput() invalid supported sampling rates");
5032 ALOGW_IF(profile->mFormats.size() == 0,
5033 "loadOutput() invalid supported formats");
5034 if (!profile->mSupportedDevices.isEmpty() &&
5035 (profile->mChannelMasks.size() != 0) &&
5036 (profile->mSamplingRates.size() != 0) &&
5037 (profile->mFormats.size() != 0)) {
5038
5039 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5040 profile->mSupportedDevices.types(), profile->mFlags);
5041
5042 mOutputProfiles.add(profile);
5043 return NO_ERROR;
5044 } else {
5045 return BAD_VALUE;
5046 }
5047}
5048
5049status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5050{
5051 cnode *node = root->first_child;
5052
5053 audio_devices_t type = AUDIO_DEVICE_NONE;
5054 while (node) {
5055 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5056 type = parseDeviceNames((char *)node->value);
5057 break;
5058 }
5059 node = node->next;
5060 }
5061 if (type == AUDIO_DEVICE_NONE ||
5062 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5063 ALOGW("loadDevice() bad type %08x", type);
5064 return BAD_VALUE;
5065 }
5066 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5067 deviceDesc->mModule = this;
5068
5069 node = root->first_child;
5070 while (node) {
5071 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5072 deviceDesc->mAddress = String8((char *)node->value);
5073 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5074 if (audio_is_input_device(type)) {
5075 deviceDesc->loadInChannels((char *)node->value);
5076 } else {
5077 deviceDesc->loadOutChannels((char *)node->value);
5078 }
5079 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5080 deviceDesc->loadGains(node);
5081 }
5082 node = node->next;
5083 }
5084
5085 ALOGV("loadDevice() adding device name %s type %08x address %s",
5086 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5087
5088 mDeclaredDevices.add(deviceDesc);
5089
5090 return NO_ERROR;
5091}
5092
Eric Laurente0720872014-03-11 09:30:41 -07005093void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005094{
5095 const size_t SIZE = 256;
5096 char buffer[SIZE];
5097 String8 result;
5098
5099 snprintf(buffer, SIZE, " - name: %s\n", mName);
5100 result.append(buffer);
5101 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5102 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005103 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5104 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005105 write(fd, result.string(), result.size());
5106 if (mOutputProfiles.size()) {
5107 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5108 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005109 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005110 write(fd, buffer, strlen(buffer));
5111 mOutputProfiles[i]->dump(fd);
5112 }
5113 }
5114 if (mInputProfiles.size()) {
5115 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5116 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005117 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005118 write(fd, buffer, strlen(buffer));
5119 mInputProfiles[i]->dump(fd);
5120 }
5121 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005122 if (mDeclaredDevices.size()) {
5123 write(fd, " - devices:\n", strlen(" - devices:\n"));
5124 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5125 mDeclaredDevices[i]->dump(fd, 4, i);
5126 }
5127 }
Eric Laurente552edb2014-03-10 17:42:56 -07005128}
5129
Eric Laurent1c333e22014-05-20 10:48:17 -07005130// --- AudioPort class implementation
5131
Eric Laurenta121f902014-06-03 13:32:54 -07005132
5133AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5134 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005135 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005136{
5137 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5138 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5139}
5140
Eric Laurent1c333e22014-05-20 10:48:17 -07005141void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5142{
5143 port->role = mRole;
5144 port->type = mType;
5145 unsigned int i;
5146 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5147 port->sample_rates[i] = mSamplingRates[i];
5148 }
5149 port->num_sample_rates = i;
5150 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5151 port->channel_masks[i] = mChannelMasks[i];
5152 }
5153 port->num_channel_masks = i;
5154 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5155 port->formats[i] = mFormats[i];
5156 }
5157 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005158
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005159 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005160
5161 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5162 port->gains[i] = mGains[i]->mGain;
5163 }
5164 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005165}
5166
5167
5168void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5169{
5170 char *str = strtok(name, "|");
5171
5172 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5173 // rates should be read from the output stream after it is opened for the first time
5174 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5175 mSamplingRates.add(0);
5176 return;
5177 }
5178
5179 while (str != NULL) {
5180 uint32_t rate = atoi(str);
5181 if (rate != 0) {
5182 ALOGV("loadSamplingRates() adding rate %d", rate);
5183 mSamplingRates.add(rate);
5184 }
5185 str = strtok(NULL, "|");
5186 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005187}
5188
5189void AudioPolicyManager::AudioPort::loadFormats(char *name)
5190{
5191 char *str = strtok(name, "|");
5192
5193 // by convention, "0' in the first entry in mFormats indicates the supported formats
5194 // should be read from the output stream after it is opened for the first time
5195 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5196 mFormats.add(AUDIO_FORMAT_DEFAULT);
5197 return;
5198 }
5199
5200 while (str != NULL) {
5201 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5202 ARRAY_SIZE(sFormatNameToEnumTable),
5203 str);
5204 if (format != AUDIO_FORMAT_DEFAULT) {
5205 mFormats.add(format);
5206 }
5207 str = strtok(NULL, "|");
5208 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005209}
5210
5211void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5212{
5213 const char *str = strtok(name, "|");
5214
5215 ALOGV("loadInChannels() %s", name);
5216
5217 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5218 mChannelMasks.add(0);
5219 return;
5220 }
5221
5222 while (str != NULL) {
5223 audio_channel_mask_t channelMask =
5224 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5225 ARRAY_SIZE(sInChannelsNameToEnumTable),
5226 str);
5227 if (channelMask != 0) {
5228 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5229 mChannelMasks.add(channelMask);
5230 }
5231 str = strtok(NULL, "|");
5232 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005233}
5234
5235void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5236{
5237 const char *str = strtok(name, "|");
5238
5239 ALOGV("loadOutChannels() %s", name);
5240
5241 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5242 // masks should be read from the output stream after it is opened for the first time
5243 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5244 mChannelMasks.add(0);
5245 return;
5246 }
5247
5248 while (str != NULL) {
5249 audio_channel_mask_t channelMask =
5250 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5251 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5252 str);
5253 if (channelMask != 0) {
5254 mChannelMasks.add(channelMask);
5255 }
5256 str = strtok(NULL, "|");
5257 }
5258 return;
5259}
5260
Eric Laurent1afeecb2014-05-14 08:52:28 -07005261audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5262{
5263 const char *str = strtok(name, "|");
5264
5265 ALOGV("loadGainMode() %s", name);
5266 audio_gain_mode_t mode = 0;
5267 while (str != NULL) {
5268 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5269 ARRAY_SIZE(sGainModeNameToEnumTable),
5270 str);
5271 str = strtok(NULL, "|");
5272 }
5273 return mode;
5274}
5275
Eric Laurenta121f902014-06-03 13:32:54 -07005276void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005277{
5278 cnode *node = root->first_child;
5279
Eric Laurenta121f902014-06-03 13:32:54 -07005280 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005281
5282 while (node) {
5283 if (strcmp(node->name, GAIN_MODE) == 0) {
5284 gain->mGain.mode = loadGainMode((char *)node->value);
5285 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005286 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005287 gain->mGain.channel_mask =
5288 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5289 ARRAY_SIZE(sInChannelsNameToEnumTable),
5290 (char *)node->value);
5291 } else {
5292 gain->mGain.channel_mask =
5293 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5294 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5295 (char *)node->value);
5296 }
5297 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5298 gain->mGain.min_value = atoi((char *)node->value);
5299 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5300 gain->mGain.max_value = atoi((char *)node->value);
5301 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5302 gain->mGain.default_value = atoi((char *)node->value);
5303 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5304 gain->mGain.step_value = atoi((char *)node->value);
5305 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5306 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5307 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5308 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5309 }
5310 node = node->next;
5311 }
5312
5313 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5314 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5315
5316 if (gain->mGain.mode == 0) {
5317 return;
5318 }
5319 mGains.add(gain);
5320}
5321
5322void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5323{
5324 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005325 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005326 while (node) {
5327 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005328 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005329 node = node->next;
5330 }
5331}
5332
Eric Laurenta121f902014-06-03 13:32:54 -07005333status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5334{
5335 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5336 if (mSamplingRates[i] == samplingRate) {
5337 return NO_ERROR;
5338 }
5339 }
5340 return BAD_VALUE;
5341}
5342
5343status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5344{
5345 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5346 if (mChannelMasks[i] == channelMask) {
5347 return NO_ERROR;
5348 }
5349 }
5350 return BAD_VALUE;
5351}
5352
5353status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5354{
5355 for (size_t i = 0; i < mFormats.size(); i ++) {
5356 if (mFormats[i] == format) {
5357 return NO_ERROR;
5358 }
5359 }
5360 return BAD_VALUE;
5361}
5362
Eric Laurent1e693b52014-07-09 15:03:28 -07005363
5364uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5365{
5366 // special case for uninitialized dynamic profile
5367 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5368 return 0;
5369 }
5370
5371 uint32_t samplingRate = 0;
5372 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5373
5374 // For mixed output and inputs, use max mixer sampling rates. Do not
5375 // limit sampling rate otherwise
5376 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5377 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5378 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5379 maxRate = UINT_MAX;
5380 }
5381 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5382 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5383 samplingRate = mSamplingRates[i];
5384 }
5385 }
5386 return samplingRate;
5387}
5388
5389audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5390{
5391 // special case for uninitialized dynamic profile
5392 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5393 return AUDIO_CHANNEL_NONE;
5394 }
5395
5396 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5397 uint32_t channelCount = 0;
5398 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5399
5400 // For mixed output and inputs, use max mixer channel count. Do not
5401 // limit channel count otherwise
5402 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5403 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5404 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5405 maxCount = UINT_MAX;
5406 }
5407 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5408 uint32_t cnlCount;
5409 if (mUseInChannelMask) {
5410 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5411 } else {
5412 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5413 }
5414 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5415 channelMask = mChannelMasks[i];
5416 }
5417 }
5418 return channelMask;
5419}
5420
5421const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5422 AUDIO_FORMAT_DEFAULT,
5423 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005424 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005425 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005426 AUDIO_FORMAT_PCM_32_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005427};
5428
5429int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5430 audio_format_t format2)
5431{
5432 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5433 // compressed format and better than any PCM format. This is by design of pickFormat()
5434 if (!audio_is_linear_pcm(format1)) {
5435 if (!audio_is_linear_pcm(format2)) {
5436 return 0;
5437 }
5438 return 1;
5439 }
5440 if (!audio_is_linear_pcm(format2)) {
5441 return -1;
5442 }
5443
5444 int index1 = -1, index2 = -1;
5445 for (size_t i = 0;
5446 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5447 i ++) {
5448 if (sPcmFormatCompareTable[i] == format1) {
5449 index1 = i;
5450 }
5451 if (sPcmFormatCompareTable[i] == format2) {
5452 index2 = i;
5453 }
5454 }
5455 // format1 not found => index1 < 0 => format2 > format1
5456 // format2 not found => index2 < 0 => format2 < format1
5457 return index1 - index2;
5458}
5459
5460audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5461{
5462 // special case for uninitialized dynamic profile
5463 if (mFormats.size() == 1 && mFormats[0] == 0) {
5464 return AUDIO_FORMAT_DEFAULT;
5465 }
5466
5467 audio_format_t format = AUDIO_FORMAT_DEFAULT;
5468 audio_format_t bestFormat = BEST_MIXER_FORMAT;
5469 // For mixed output and inputs, use best mixer output format. Do not
5470 // limit format otherwise
5471 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5472 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5473 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) == 0)))) {
5474 bestFormat = AUDIO_FORMAT_INVALID;
5475 }
5476
5477 for (size_t i = 0; i < mFormats.size(); i ++) {
5478 if ((compareFormats(mFormats[i], format) > 0) &&
5479 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5480 format = mFormats[i];
5481 }
5482 }
5483 return format;
5484}
5485
Eric Laurenta121f902014-06-03 13:32:54 -07005486status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5487 int index) const
5488{
5489 if (index < 0 || (size_t)index >= mGains.size()) {
5490 return BAD_VALUE;
5491 }
5492 return mGains[index]->checkConfig(gainConfig);
5493}
5494
Eric Laurent1afeecb2014-05-14 08:52:28 -07005495void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5496{
5497 const size_t SIZE = 256;
5498 char buffer[SIZE];
5499 String8 result;
5500
5501 if (mName.size() != 0) {
5502 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5503 result.append(buffer);
5504 }
5505
5506 if (mSamplingRates.size() != 0) {
5507 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5508 result.append(buffer);
5509 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005510 if (i == 0 && mSamplingRates[i] == 0) {
5511 snprintf(buffer, SIZE, "Dynamic");
5512 } else {
5513 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5514 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005515 result.append(buffer);
5516 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5517 }
5518 result.append("\n");
5519 }
5520
5521 if (mChannelMasks.size() != 0) {
5522 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5523 result.append(buffer);
5524 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005525 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5526
5527 if (i == 0 && mChannelMasks[i] == 0) {
5528 snprintf(buffer, SIZE, "Dynamic");
5529 } else {
5530 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5531 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005532 result.append(buffer);
5533 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5534 }
5535 result.append("\n");
5536 }
5537
5538 if (mFormats.size() != 0) {
5539 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5540 result.append(buffer);
5541 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005542 const char *formatStr = enumToString(sFormatNameToEnumTable,
5543 ARRAY_SIZE(sFormatNameToEnumTable),
5544 mFormats[i]);
5545 if (i == 0 && strcmp(formatStr, "") == 0) {
5546 snprintf(buffer, SIZE, "Dynamic");
5547 } else {
5548 snprintf(buffer, SIZE, "%-48s", formatStr);
5549 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005550 result.append(buffer);
5551 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5552 }
5553 result.append("\n");
5554 }
5555 write(fd, result.string(), result.size());
5556 if (mGains.size() != 0) {
5557 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5558 write(fd, buffer, strlen(buffer) + 1);
5559 result.append(buffer);
5560 for (size_t i = 0; i < mGains.size(); i++) {
5561 mGains[i]->dump(fd, spaces + 2, i);
5562 }
5563 }
5564}
5565
5566// --- AudioGain class implementation
5567
Eric Laurenta121f902014-06-03 13:32:54 -07005568AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005569{
Eric Laurenta121f902014-06-03 13:32:54 -07005570 mIndex = index;
5571 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005572 memset(&mGain, 0, sizeof(struct audio_gain));
5573}
5574
Eric Laurenta121f902014-06-03 13:32:54 -07005575void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5576{
5577 config->index = mIndex;
5578 config->mode = mGain.mode;
5579 config->channel_mask = mGain.channel_mask;
5580 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5581 config->values[0] = mGain.default_value;
5582 } else {
5583 uint32_t numValues;
5584 if (mUseInChannelMask) {
5585 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5586 } else {
5587 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5588 }
5589 for (size_t i = 0; i < numValues; i++) {
5590 config->values[i] = mGain.default_value;
5591 }
5592 }
5593 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5594 config->ramp_duration_ms = mGain.min_ramp_ms;
5595 }
5596}
5597
5598status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5599{
5600 if ((config->mode & ~mGain.mode) != 0) {
5601 return BAD_VALUE;
5602 }
5603 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5604 if ((config->values[0] < mGain.min_value) ||
5605 (config->values[0] > mGain.max_value)) {
5606 return BAD_VALUE;
5607 }
5608 } else {
5609 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5610 return BAD_VALUE;
5611 }
5612 uint32_t numValues;
5613 if (mUseInChannelMask) {
5614 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5615 } else {
5616 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5617 }
5618 for (size_t i = 0; i < numValues; i++) {
5619 if ((config->values[i] < mGain.min_value) ||
5620 (config->values[i] > mGain.max_value)) {
5621 return BAD_VALUE;
5622 }
5623 }
5624 }
5625 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5626 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5627 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5628 return BAD_VALUE;
5629 }
5630 }
5631 return NO_ERROR;
5632}
5633
Eric Laurent1afeecb2014-05-14 08:52:28 -07005634void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5635{
5636 const size_t SIZE = 256;
5637 char buffer[SIZE];
5638 String8 result;
5639
5640 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5641 result.append(buffer);
5642 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5643 result.append(buffer);
5644 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5645 result.append(buffer);
5646 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5647 result.append(buffer);
5648 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5649 result.append(buffer);
5650 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5651 result.append(buffer);
5652 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5653 result.append(buffer);
5654 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5655 result.append(buffer);
5656 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5657 result.append(buffer);
5658
5659 write(fd, result.string(), result.size());
5660}
5661
Eric Laurent1f2f2232014-06-02 12:01:23 -07005662// --- AudioPortConfig class implementation
5663
5664AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5665{
5666 mSamplingRate = 0;
5667 mChannelMask = AUDIO_CHANNEL_NONE;
5668 mFormat = AUDIO_FORMAT_INVALID;
5669 mGain.index = -1;
5670}
5671
Eric Laurenta121f902014-06-03 13:32:54 -07005672status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5673 const struct audio_port_config *config,
5674 struct audio_port_config *backupConfig)
5675{
5676 struct audio_port_config localBackupConfig;
5677 status_t status = NO_ERROR;
5678
5679 localBackupConfig.config_mask = config->config_mask;
5680 toAudioPortConfig(&localBackupConfig);
5681
5682 if (mAudioPort == 0) {
5683 status = NO_INIT;
5684 goto exit;
5685 }
5686 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5687 status = mAudioPort->checkSamplingRate(config->sample_rate);
5688 if (status != NO_ERROR) {
5689 goto exit;
5690 }
5691 mSamplingRate = config->sample_rate;
5692 }
5693 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5694 status = mAudioPort->checkChannelMask(config->channel_mask);
5695 if (status != NO_ERROR) {
5696 goto exit;
5697 }
5698 mChannelMask = config->channel_mask;
5699 }
5700 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5701 status = mAudioPort->checkFormat(config->format);
5702 if (status != NO_ERROR) {
5703 goto exit;
5704 }
5705 mFormat = config->format;
5706 }
5707 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5708 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5709 if (status != NO_ERROR) {
5710 goto exit;
5711 }
5712 mGain = config->gain;
5713 }
5714
5715exit:
5716 if (status != NO_ERROR) {
5717 applyAudioPortConfig(&localBackupConfig);
5718 }
5719 if (backupConfig != NULL) {
5720 *backupConfig = localBackupConfig;
5721 }
5722 return status;
5723}
5724
Eric Laurent1f2f2232014-06-02 12:01:23 -07005725void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5726 struct audio_port_config *dstConfig,
5727 const struct audio_port_config *srcConfig) const
5728{
5729 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5730 dstConfig->sample_rate = mSamplingRate;
5731 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5732 dstConfig->sample_rate = srcConfig->sample_rate;
5733 }
5734 } else {
5735 dstConfig->sample_rate = 0;
5736 }
5737 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5738 dstConfig->channel_mask = mChannelMask;
5739 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5740 dstConfig->channel_mask = srcConfig->channel_mask;
5741 }
5742 } else {
5743 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5744 }
5745 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5746 dstConfig->format = mFormat;
5747 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5748 dstConfig->format = srcConfig->format;
5749 }
5750 } else {
5751 dstConfig->format = AUDIO_FORMAT_INVALID;
5752 }
5753 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5754 dstConfig->gain = mGain;
5755 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5756 dstConfig->gain = srcConfig->gain;
5757 }
5758 } else {
5759 dstConfig->gain.index = -1;
5760 }
5761 if (dstConfig->gain.index != -1) {
5762 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5763 } else {
5764 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5765 }
5766}
5767
Eric Laurent1c333e22014-05-20 10:48:17 -07005768// --- IOProfile class implementation
5769
Eric Laurent1afeecb2014-05-14 08:52:28 -07005770AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005771 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07005772 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07005773{
5774}
5775
Eric Laurente0720872014-03-11 09:30:41 -07005776AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005777{
5778}
5779
5780// checks if the IO profile is compatible with specified parameters.
5781// Sampling rate, format and channel mask must be specified in order to
5782// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005783bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005784 uint32_t samplingRate,
5785 audio_format_t format,
5786 audio_channel_mask_t channelMask,
5787 audio_output_flags_t flags) const
5788{
5789 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5790 return false;
5791 }
5792
Eric Laurent3a4311c2014-03-17 12:00:47 -07005793 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005794 return false;
5795 }
5796 if ((mFlags & flags) != flags) {
5797 return false;
5798 }
Eric Laurenta121f902014-06-03 13:32:54 -07005799 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005800 return false;
5801 }
Eric Laurenta121f902014-06-03 13:32:54 -07005802 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005803 return false;
5804 }
Eric Laurenta121f902014-06-03 13:32:54 -07005805 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005806 return false;
5807 }
5808 return true;
5809}
5810
Eric Laurente0720872014-03-11 09:30:41 -07005811void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005812{
5813 const size_t SIZE = 256;
5814 char buffer[SIZE];
5815 String8 result;
5816
Eric Laurent1afeecb2014-05-14 08:52:28 -07005817 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005818
Eric Laurente552edb2014-03-10 17:42:56 -07005819 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5820 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005821 snprintf(buffer, SIZE, " - devices:\n");
5822 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005823 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005824 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5825 mSupportedDevices[i]->dump(fd, 6, i);
5826 }
Eric Laurente552edb2014-03-10 17:42:56 -07005827}
5828
Eric Laurentd4692962014-05-05 18:13:44 -07005829void AudioPolicyManager::IOProfile::log()
5830{
5831 const size_t SIZE = 256;
5832 char buffer[SIZE];
5833 String8 result;
5834
5835 ALOGV(" - sampling rates: ");
5836 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5837 ALOGV(" %d", mSamplingRates[i]);
5838 }
5839
5840 ALOGV(" - channel masks: ");
5841 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5842 ALOGV(" 0x%04x", mChannelMasks[i]);
5843 }
5844
5845 ALOGV(" - formats: ");
5846 for (size_t i = 0; i < mFormats.size(); i++) {
5847 ALOGV(" 0x%08x", mFormats[i]);
5848 }
5849
5850 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5851 ALOGV(" - flags: 0x%04x\n", mFlags);
5852}
5853
5854
Eric Laurent3a4311c2014-03-17 12:00:47 -07005855// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005856
Eric Laurent1f2f2232014-06-02 12:01:23 -07005857
5858AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5859 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5860 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5861 AUDIO_PORT_ROLE_SOURCE,
5862 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07005863 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005864{
5865 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005866 if (mGains.size() > 0) {
5867 mGains[0]->getDefaultConfig(&mGain);
5868 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005869}
5870
Eric Laurent3a4311c2014-03-17 12:00:47 -07005871bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005872{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005873 // Devices are considered equal if they:
5874 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5875 // - have the same address or one device does not specify the address
5876 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005877 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005878 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005879 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005880 mChannelMask == other->mChannelMask);
5881}
5882
5883void AudioPolicyManager::DeviceVector::refreshTypes()
5884{
Eric Laurent1c333e22014-05-20 10:48:17 -07005885 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005886 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005887 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005888 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005889 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005890}
5891
5892ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5893{
5894 for(size_t i = 0; i < size(); i++) {
5895 if (item->equals(itemAt(i))) {
5896 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005897 }
5898 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005899 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005900}
5901
Eric Laurent3a4311c2014-03-17 12:00:47 -07005902ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005903{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005904 ssize_t ret = indexOf(item);
5905
5906 if (ret < 0) {
5907 ret = SortedVector::add(item);
5908 if (ret >= 0) {
5909 refreshTypes();
5910 }
5911 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005912 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005913 ret = -1;
5914 }
5915 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005916}
5917
Eric Laurent3a4311c2014-03-17 12:00:47 -07005918ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5919{
5920 size_t i;
5921 ssize_t ret = indexOf(item);
5922
5923 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005924 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005925 } else {
5926 ret = SortedVector::removeAt(ret);
5927 if (ret >= 0) {
5928 refreshTypes();
5929 }
5930 }
5931 return ret;
5932}
5933
5934void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5935{
5936 DeviceVector deviceList;
5937
5938 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5939 types &= ~role_bit;
5940
5941 while (types) {
5942 uint32_t i = 31 - __builtin_clz(types);
5943 uint32_t type = 1 << i;
5944 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005945 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005946 }
5947}
5948
Eric Laurent1afeecb2014-05-14 08:52:28 -07005949void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5950 const DeviceVector& declaredDevices)
5951{
5952 char *devName = strtok(name, "|");
5953 while (devName != NULL) {
5954 if (strlen(devName) != 0) {
5955 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5956 ARRAY_SIZE(sDeviceNameToEnumTable),
5957 devName);
5958 if (type != AUDIO_DEVICE_NONE) {
5959 add(new DeviceDescriptor(String8(""), type));
5960 } else {
5961 sp<DeviceDescriptor> deviceDesc =
5962 declaredDevices.getDeviceFromName(String8(devName));
5963 if (deviceDesc != 0) {
5964 add(deviceDesc);
5965 }
5966 }
5967 }
5968 devName = strtok(NULL, "|");
5969 }
5970}
5971
Eric Laurent1c333e22014-05-20 10:48:17 -07005972sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5973 audio_devices_t type, String8 address) const
5974{
5975 sp<DeviceDescriptor> device;
5976 for (size_t i = 0; i < size(); i++) {
5977 if (itemAt(i)->mDeviceType == type) {
5978 device = itemAt(i);
5979 if (itemAt(i)->mAddress = address) {
5980 break;
5981 }
5982 }
5983 }
5984 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5985 type, address.string(), device.get());
5986 return device;
5987}
5988
Eric Laurent6a94d692014-05-20 11:18:06 -07005989sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5990 audio_port_handle_t id) const
5991{
5992 sp<DeviceDescriptor> device;
5993 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005994 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07005995 if (itemAt(i)->mId == id) {
5996 device = itemAt(i);
5997 break;
5998 }
5999 }
6000 return device;
6001}
6002
Eric Laurent1c333e22014-05-20 10:48:17 -07006003AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6004 audio_devices_t type) const
6005{
6006 DeviceVector devices;
6007 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6008 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6009 devices.add(itemAt(i));
6010 type &= ~itemAt(i)->mDeviceType;
6011 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6012 itemAt(i)->mDeviceType, itemAt(i).get());
6013 }
6014 }
6015 return devices;
6016}
6017
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006018AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6019 audio_devices_t type, String8 address) const
6020{
6021 DeviceVector devices;
6022 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6023 for (size_t i = 0; i < size(); i++) {
6024 //ALOGV(" at i=%d: device=%x, addr=%s",
6025 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6026 if (itemAt(i)->mDeviceType == type) {
6027 if (itemAt(i)->mAddress == address) {
6028 //ALOGV(" found matching address %s", address.string());
6029 devices.add(itemAt(i));
6030 }
6031 }
6032 }
6033 return devices;
6034}
6035
Eric Laurent1afeecb2014-05-14 08:52:28 -07006036sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6037 const String8& name) const
6038{
6039 sp<DeviceDescriptor> device;
6040 for (size_t i = 0; i < size(); i++) {
6041 if (itemAt(i)->mName == name) {
6042 device = itemAt(i);
6043 break;
6044 }
6045 }
6046 return device;
6047}
6048
Eric Laurent6a94d692014-05-20 11:18:06 -07006049void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6050 struct audio_port_config *dstConfig,
6051 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006052{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006053 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6054 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006055 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006056 }
6057
6058 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6059
Eric Laurent6a94d692014-05-20 11:18:06 -07006060 dstConfig->id = mId;
6061 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006062 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006063 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006064 dstConfig->ext.device.type = mDeviceType;
6065 dstConfig->ext.device.hw_module = mModule->mHandle;
6066 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006067}
6068
6069void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6070{
Eric Laurent83b88082014-06-20 18:31:16 -07006071 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006072 AudioPort::toAudioPort(port);
6073 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006074 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006075 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006076 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006077 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6078}
6079
Eric Laurent1afeecb2014-05-14 08:52:28 -07006080status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006081{
6082 const size_t SIZE = 256;
6083 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006084 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006085
Eric Laurent1afeecb2014-05-14 08:52:28 -07006086 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6087 result.append(buffer);
6088 if (mId != 0) {
6089 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6090 result.append(buffer);
6091 }
6092 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6093 enumToString(sDeviceNameToEnumTable,
6094 ARRAY_SIZE(sDeviceNameToEnumTable),
6095 mDeviceType));
6096 result.append(buffer);
6097 if (mAddress.size() != 0) {
6098 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6099 result.append(buffer);
6100 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006101 write(fd, result.string(), result.size());
6102 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006103
6104 return NO_ERROR;
6105}
6106
6107
6108// --- audio_policy.conf file parsing
6109
Eric Laurente0720872014-03-11 09:30:41 -07006110audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006111{
6112 uint32_t flag = 0;
6113
6114 // it is OK to cast name to non const here as we are not going to use it after
6115 // strtok() modifies it
6116 char *flagName = strtok(name, "|");
6117 while (flagName != NULL) {
6118 if (strlen(flagName) != 0) {
6119 flag |= stringToEnum(sFlagNameToEnumTable,
6120 ARRAY_SIZE(sFlagNameToEnumTable),
6121 flagName);
6122 }
6123 flagName = strtok(NULL, "|");
6124 }
6125 //force direct flag if offload flag is set: offloading implies a direct output stream
6126 // and all common behaviors are driven by checking only the direct flag
6127 // this should normally be set appropriately in the policy configuration file
6128 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6129 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6130 }
6131
6132 return (audio_output_flags_t)flag;
6133}
6134
Eric Laurente0720872014-03-11 09:30:41 -07006135audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006136{
6137 uint32_t device = 0;
6138
6139 char *devName = strtok(name, "|");
6140 while (devName != NULL) {
6141 if (strlen(devName) != 0) {
6142 device |= stringToEnum(sDeviceNameToEnumTable,
6143 ARRAY_SIZE(sDeviceNameToEnumTable),
6144 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006145 }
Eric Laurente552edb2014-03-10 17:42:56 -07006146 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006147 }
Eric Laurente552edb2014-03-10 17:42:56 -07006148 return device;
6149}
6150
Eric Laurente0720872014-03-11 09:30:41 -07006151void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006152{
Eric Laurente552edb2014-03-10 17:42:56 -07006153 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006154 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006155 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006156
Eric Laurent1afeecb2014-05-14 08:52:28 -07006157 node = config_find(root, DEVICES_TAG);
6158 if (node != NULL) {
6159 node = node->first_child;
6160 while (node) {
6161 ALOGV("loadHwModule() loading device %s", node->name);
6162 status_t tmpStatus = module->loadDevice(node);
6163 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6164 status = tmpStatus;
6165 }
6166 node = node->next;
6167 }
6168 }
6169 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006170 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006171 node = node->first_child;
6172 while (node) {
6173 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006174 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006175 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6176 status = tmpStatus;
6177 }
6178 node = node->next;
6179 }
6180 }
6181 node = config_find(root, INPUTS_TAG);
6182 if (node != NULL) {
6183 node = node->first_child;
6184 while (node) {
6185 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006186 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006187 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6188 status = tmpStatus;
6189 }
6190 node = node->next;
6191 }
6192 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006193 loadGlobalConfig(root, module);
6194
Eric Laurente552edb2014-03-10 17:42:56 -07006195 if (status == NO_ERROR) {
6196 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006197 }
6198}
6199
Eric Laurente0720872014-03-11 09:30:41 -07006200void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006201{
6202 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6203 if (node == NULL) {
6204 return;
6205 }
6206
6207 node = node->first_child;
6208 while (node) {
6209 ALOGV("loadHwModules() loading module %s", node->name);
6210 loadHwModule(node);
6211 node = node->next;
6212 }
6213}
6214
Eric Laurent1f2f2232014-06-02 12:01:23 -07006215void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006216{
6217 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006218
Eric Laurente552edb2014-03-10 17:42:56 -07006219 if (node == NULL) {
6220 return;
6221 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006222 DeviceVector declaredDevices;
6223 if (module != NULL) {
6224 declaredDevices = module->mDeclaredDevices;
6225 }
6226
Eric Laurente552edb2014-03-10 17:42:56 -07006227 node = node->first_child;
6228 while (node) {
6229 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006230 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6231 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006232 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6233 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006234 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006235 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006236 ARRAY_SIZE(sDeviceNameToEnumTable),
6237 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006238 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006239 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006240 } else {
6241 ALOGW("loadGlobalConfig() default device not specified");
6242 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006243 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006244 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006245 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6246 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006247 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006248 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6249 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6250 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006251 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6252 uint32_t major, minor;
6253 sscanf((char *)node->value, "%u.%u", &major, &minor);
6254 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6255 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6256 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006257 }
6258 node = node->next;
6259 }
6260}
6261
Eric Laurente0720872014-03-11 09:30:41 -07006262status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006263{
6264 cnode *root;
6265 char *data;
6266
6267 data = (char *)load_file(path, NULL);
6268 if (data == NULL) {
6269 return -ENODEV;
6270 }
6271 root = config_node("", "");
6272 config_load(root, data);
6273
Eric Laurente552edb2014-03-10 17:42:56 -07006274 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006275 // legacy audio_policy.conf files have one global_configuration section
6276 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006277 config_free(root);
6278 free(root);
6279 free(data);
6280
6281 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6282
6283 return NO_ERROR;
6284}
6285
Eric Laurente0720872014-03-11 09:30:41 -07006286void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006287{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006288 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006289 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006290 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6291 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006292 mAvailableOutputDevices.add(mDefaultOutputDevice);
6293 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006294
6295 module = new HwModule("primary");
6296
Eric Laurent1afeecb2014-05-14 08:52:28 -07006297 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006298 profile->mSamplingRates.add(44100);
6299 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6300 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006301 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006302 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6303 module->mOutputProfiles.add(profile);
6304
Eric Laurent1afeecb2014-05-14 08:52:28 -07006305 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006306 profile->mSamplingRates.add(8000);
6307 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6308 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006309 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006310 module->mInputProfiles.add(profile);
6311
6312 mHwModules.add(module);
6313}
6314
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006315audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6316{
6317 // flags to stream type mapping
6318 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6319 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6320 }
6321 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6322 return AUDIO_STREAM_BLUETOOTH_SCO;
6323 }
6324
6325 // usage to stream type mapping
6326 switch (attr->usage) {
6327 case AUDIO_USAGE_MEDIA:
6328 case AUDIO_USAGE_GAME:
6329 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6330 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6331 return AUDIO_STREAM_MUSIC;
6332 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6333 return AUDIO_STREAM_SYSTEM;
6334 case AUDIO_USAGE_VOICE_COMMUNICATION:
6335 return AUDIO_STREAM_VOICE_CALL;
6336
6337 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6338 return AUDIO_STREAM_DTMF;
6339
6340 case AUDIO_USAGE_ALARM:
6341 return AUDIO_STREAM_ALARM;
6342 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6343 return AUDIO_STREAM_RING;
6344
6345 case AUDIO_USAGE_NOTIFICATION:
6346 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6347 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6348 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6349 case AUDIO_USAGE_NOTIFICATION_EVENT:
6350 return AUDIO_STREAM_NOTIFICATION;
6351
6352 case AUDIO_USAGE_UNKNOWN:
6353 default:
6354 return AUDIO_STREAM_MUSIC;
6355 }
6356}
Eric Laurente552edb2014-03-10 17:42:56 -07006357}; // namespace android