blob: 57c85b62801e90b77ba080a12787e3afc5edb9c5 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 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
17#include "Macros.h"
18
19#include "JoystickInputMapper.h"
20
21namespace android {
22
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -080023JoystickInputMapper::JoystickInputMapper(InputDeviceContext& deviceContext)
24 : InputMapper(deviceContext) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070025
26JoystickInputMapper::~JoystickInputMapper() {}
27
28uint32_t JoystickInputMapper::getSources() {
29 return AINPUT_SOURCE_JOYSTICK;
30}
31
32void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
33 InputMapper::populateDeviceInfo(info);
34
35 for (size_t i = 0; i < mAxes.size(); i++) {
36 const Axis& axis = mAxes.valueAt(i);
37 addMotionRange(axis.axisInfo.axis, axis, info);
38
39 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
40 addMotionRange(axis.axisInfo.highAxis, axis, info);
41 }
42 }
43}
44
45void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info) {
46 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz,
47 axis.resolution);
48 /* In order to ease the transition for developers from using the old axes
49 * to the newer, more semantically correct axes, we'll continue to register
50 * the old axes as duplicates of their corresponding new ones. */
51 int32_t compatAxis = getCompatAxis(axisId);
52 if (compatAxis >= 0) {
53 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat,
54 axis.fuzz, axis.resolution);
55 }
56}
57
58/* A mapping from axes the joystick actually has to the axes that should be
59 * artificially created for compatibility purposes.
60 * Returns -1 if no compatibility axis is needed. */
61int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
62 switch (axis) {
63 case AMOTION_EVENT_AXIS_LTRIGGER:
64 return AMOTION_EVENT_AXIS_BRAKE;
65 case AMOTION_EVENT_AXIS_RTRIGGER:
66 return AMOTION_EVENT_AXIS_GAS;
67 }
68 return -1;
69}
70
71void JoystickInputMapper::dump(std::string& dump) {
72 dump += INDENT2 "Joystick Input Mapper:\n";
73
74 dump += INDENT3 "Axes:\n";
75 size_t numAxes = mAxes.size();
76 for (size_t i = 0; i < numAxes; i++) {
77 const Axis& axis = mAxes.valueAt(i);
78 const char* label = getAxisLabel(axis.axisInfo.axis);
79 if (label) {
80 dump += StringPrintf(INDENT4 "%s", label);
81 } else {
82 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
83 }
84 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
85 label = getAxisLabel(axis.axisInfo.highAxis);
86 if (label) {
87 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
88 } else {
89 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
90 axis.axisInfo.splitValue);
91 }
92 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
93 dump += " (invert)";
94 }
95
96 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
97 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
98 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
99 "highScale=%0.5f, highOffset=%0.5f\n",
100 axis.scale, axis.offset, axis.highScale, axis.highOffset);
101 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
102 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
103 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
104 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz,
105 axis.rawAxisInfo.resolution);
106 }
107}
108
109void JoystickInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
110 uint32_t changes) {
111 InputMapper::configure(when, config, changes);
112
113 if (!changes) { // first time only
114 // Collect all axes.
115 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800116 if (!(getAbsAxisUsage(abs, getDeviceContext().getDeviceClasses()) &
117 INPUT_DEVICE_CLASS_JOYSTICK)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700118 continue; // axis must be claimed by a different device
119 }
120
121 RawAbsoluteAxisInfo rawAxisInfo;
122 getAbsoluteAxisInfo(abs, &rawAxisInfo);
123 if (rawAxisInfo.valid) {
124 // Map axis.
125 AxisInfo axisInfo;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800126 bool explicitlyMapped = !getDeviceContext().mapAxis(abs, &axisInfo);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700127 if (!explicitlyMapped) {
128 // Axis is not explicitly mapped, will choose a generic axis later.
129 axisInfo.mode = AxisInfo::MODE_NORMAL;
130 axisInfo.axis = -1;
131 }
132
133 // Apply flat override.
134 int32_t rawFlat =
135 axisInfo.flatOverride < 0 ? rawAxisInfo.flat : axisInfo.flatOverride;
136
137 // Calculate scaling factors and limits.
138 Axis axis;
139 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
140 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
141 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
142 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, highScale,
143 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
144 rawAxisInfo.resolution * scale);
145 } else if (isCenteredAxis(axisInfo.axis)) {
146 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
147 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
148 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, offset, scale,
149 offset, -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
150 rawAxisInfo.resolution * scale);
151 } else {
152 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
153 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, scale,
154 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
155 rawAxisInfo.resolution * scale);
156 }
157
158 // To eliminate noise while the joystick is at rest, filter out small variations
159 // in axis values up front.
160 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
161
162 mAxes.add(abs, axis);
163 }
164 }
165
166 // If there are too many axes, start dropping them.
167 // Prefer to keep explicitly mapped axes.
168 if (mAxes.size() > PointerCoords::MAX_AXES) {
169 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
170 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
171 pruneAxes(true);
172 pruneAxes(false);
173 }
174
175 // Assign generic axis ids to remaining axes.
176 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
177 size_t numAxes = mAxes.size();
178 for (size_t i = 0; i < numAxes; i++) {
179 Axis& axis = mAxes.editValueAt(i);
180 if (axis.axisInfo.axis < 0) {
181 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 &&
182 haveAxis(nextGenericAxisId)) {
183 nextGenericAxisId += 1;
184 }
185
186 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
187 axis.axisInfo.axis = nextGenericAxisId;
188 nextGenericAxisId += 1;
189 } else {
190 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
191 "have already been assigned to other axes.",
192 getDeviceName().c_str(), mAxes.keyAt(i));
193 mAxes.removeItemsAt(i--);
194 numAxes -= 1;
195 }
196 }
197 }
198 }
199}
200
201bool JoystickInputMapper::haveAxis(int32_t axisId) {
202 size_t numAxes = mAxes.size();
203 for (size_t i = 0; i < numAxes; i++) {
204 const Axis& axis = mAxes.valueAt(i);
205 if (axis.axisInfo.axis == axisId ||
206 (axis.axisInfo.mode == AxisInfo::MODE_SPLIT && axis.axisInfo.highAxis == axisId)) {
207 return true;
208 }
209 }
210 return false;
211}
212
213void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
214 size_t i = mAxes.size();
215 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
216 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
217 continue;
218 }
219 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
220 getDeviceName().c_str(), mAxes.keyAt(i));
221 mAxes.removeItemsAt(i);
222 }
223}
224
225bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
226 switch (axis) {
227 case AMOTION_EVENT_AXIS_X:
228 case AMOTION_EVENT_AXIS_Y:
229 case AMOTION_EVENT_AXIS_Z:
230 case AMOTION_EVENT_AXIS_RX:
231 case AMOTION_EVENT_AXIS_RY:
232 case AMOTION_EVENT_AXIS_RZ:
233 case AMOTION_EVENT_AXIS_HAT_X:
234 case AMOTION_EVENT_AXIS_HAT_Y:
235 case AMOTION_EVENT_AXIS_ORIENTATION:
236 case AMOTION_EVENT_AXIS_RUDDER:
237 case AMOTION_EVENT_AXIS_WHEEL:
238 return true;
239 default:
240 return false;
241 }
242}
243
244void JoystickInputMapper::reset(nsecs_t when) {
245 // Recenter all axes.
246 size_t numAxes = mAxes.size();
247 for (size_t i = 0; i < numAxes; i++) {
248 Axis& axis = mAxes.editValueAt(i);
249 axis.resetValue();
250 }
251
252 InputMapper::reset(when);
253}
254
255void JoystickInputMapper::process(const RawEvent* rawEvent) {
256 switch (rawEvent->type) {
257 case EV_ABS: {
258 ssize_t index = mAxes.indexOfKey(rawEvent->code);
259 if (index >= 0) {
260 Axis& axis = mAxes.editValueAt(index);
261 float newValue, highNewValue;
262 switch (axis.axisInfo.mode) {
263 case AxisInfo::MODE_INVERT:
264 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) * axis.scale +
265 axis.offset;
266 highNewValue = 0.0f;
267 break;
268 case AxisInfo::MODE_SPLIT:
269 if (rawEvent->value < axis.axisInfo.splitValue) {
270 newValue = (axis.axisInfo.splitValue - rawEvent->value) * axis.scale +
271 axis.offset;
272 highNewValue = 0.0f;
273 } else if (rawEvent->value > axis.axisInfo.splitValue) {
274 newValue = 0.0f;
275 highNewValue =
276 (rawEvent->value - axis.axisInfo.splitValue) * axis.highScale +
277 axis.highOffset;
278 } else {
279 newValue = 0.0f;
280 highNewValue = 0.0f;
281 }
282 break;
283 default:
284 newValue = rawEvent->value * axis.scale + axis.offset;
285 highNewValue = 0.0f;
286 break;
287 }
288 axis.newValue = newValue;
289 axis.highNewValue = highNewValue;
290 }
291 break;
292 }
293
294 case EV_SYN:
295 switch (rawEvent->code) {
296 case SYN_REPORT:
297 sync(rawEvent->when, false /*force*/);
298 break;
299 }
300 break;
301 }
302}
303
304void JoystickInputMapper::sync(nsecs_t when, bool force) {
305 if (!filterAxes(force)) {
306 return;
307 }
308
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800309 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700310 int32_t buttonState = 0;
311
312 PointerProperties pointerProperties;
313 pointerProperties.clear();
314 pointerProperties.id = 0;
315 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
316
317 PointerCoords pointerCoords;
318 pointerCoords.clear();
319
320 size_t numAxes = mAxes.size();
321 for (size_t i = 0; i < numAxes; i++) {
322 const Axis& axis = mAxes.valueAt(i);
323 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
324 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
325 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
326 axis.highCurrentValue);
327 }
328 }
329
330 // Moving a joystick axis should not wake the device because joysticks can
331 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
332 // button will likely wake the device.
333 // TODO: Use the input device configuration to control this behavior more finely.
334 uint32_t policyFlags = 0;
335
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800336 NotifyMotionArgs args(getContext()->getNextSequenceNum(), when, getDeviceId(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
338 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
339 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
340 &pointerProperties, &pointerCoords, 0, 0,
341 AMOTION_EVENT_INVALID_CURSOR_POSITION,
342 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
343 getListener()->notifyMotion(&args);
344}
345
346void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
347 float value) {
348 pointerCoords->setAxisValue(axis, value);
349 /* In order to ease the transition for developers from using the old axes
350 * to the newer, more semantically correct axes, we'll continue to produce
351 * values for the old axes as mirrors of the value of their corresponding
352 * new axes. */
353 int32_t compatAxis = getCompatAxis(axis);
354 if (compatAxis >= 0) {
355 pointerCoords->setAxisValue(compatAxis, value);
356 }
357}
358
359bool JoystickInputMapper::filterAxes(bool force) {
360 bool atLeastOneSignificantChange = force;
361 size_t numAxes = mAxes.size();
362 for (size_t i = 0; i < numAxes; i++) {
363 Axis& axis = mAxes.editValueAt(i);
364 if (force ||
365 hasValueChangedSignificantly(axis.filter, axis.newValue, axis.currentValue, axis.min,
366 axis.max)) {
367 axis.currentValue = axis.newValue;
368 atLeastOneSignificantChange = true;
369 }
370 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
371 if (force ||
372 hasValueChangedSignificantly(axis.filter, axis.highNewValue, axis.highCurrentValue,
373 axis.min, axis.max)) {
374 axis.highCurrentValue = axis.highNewValue;
375 atLeastOneSignificantChange = true;
376 }
377 }
378 }
379 return atLeastOneSignificantChange;
380}
381
382bool JoystickInputMapper::hasValueChangedSignificantly(float filter, float newValue,
383 float currentValue, float min, float max) {
384 if (newValue != currentValue) {
385 // Filter out small changes in value unless the value is converging on the axis
386 // bounds or center point. This is intended to reduce the amount of information
387 // sent to applications by particularly noisy joysticks (such as PS3).
388 if (fabs(newValue - currentValue) > filter ||
389 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) ||
390 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) ||
391 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
392 return true;
393 }
394 }
395 return false;
396}
397
398bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(float filter, float newValue,
399 float currentValue,
400 float thresholdValue) {
401 float newDistance = fabs(newValue - thresholdValue);
402 if (newDistance < filter) {
403 float oldDistance = fabs(currentValue - thresholdValue);
404 if (newDistance < oldDistance) {
405 return true;
406 }
407 }
408 return false;
409}
410
411} // namespace android