1 /*
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 
21 namespace android {
22 
JoystickInputMapper(InputDeviceContext & deviceContext)23 JoystickInputMapper::JoystickInputMapper(InputDeviceContext& deviceContext)
24       : InputMapper(deviceContext) {}
25 
~JoystickInputMapper()26 JoystickInputMapper::~JoystickInputMapper() {}
27 
getSources()28 uint32_t JoystickInputMapper::getSources() {
29     return AINPUT_SOURCE_JOYSTICK;
30 }
31 
populateDeviceInfo(InputDeviceInfo * info)32 void 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 
addMotionRange(int32_t axisId,const Axis & axis,InputDeviceInfo * info)45 void 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. */
getCompatAxis(int32_t axis)61 int32_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 
dump(std::string & dump)71 void 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 
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)109 void 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++) {
116             if (!(getAbsAxisUsage(abs, getDeviceContext().getDeviceClasses()) &
117                   INPUT_DEVICE_CLASS_JOYSTICK)) {
118                 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;
126                 bool explicitlyMapped = !getDeviceContext().mapAxis(abs, &axisInfo);
127                 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 
haveAxis(int32_t axisId)201 bool 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 
pruneAxes(bool ignoreExplicitlyMappedAxes)213 void 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 
isCenteredAxis(int32_t axis)225 bool 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 
reset(nsecs_t when)244 void 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 
process(const RawEvent * rawEvent)255 void 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 
sync(nsecs_t when,bool force)304 void JoystickInputMapper::sync(nsecs_t when, bool force) {
305     if (!filterAxes(force)) {
306         return;
307     }
308 
309     int32_t metaState = getContext()->getGlobalMetaState();
310     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 
336     NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_JOYSTICK,
337                           ADISPLAY_ID_NONE, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
338                           buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
339                           &pointerProperties, &pointerCoords, 0, 0,
340                           AMOTION_EVENT_INVALID_CURSOR_POSITION,
341                           AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
342     getListener()->notifyMotion(&args);
343 }
344 
setPointerCoordsAxisValue(PointerCoords * pointerCoords,int32_t axis,float value)345 void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
346                                                     float value) {
347     pointerCoords->setAxisValue(axis, value);
348     /* In order to ease the transition for developers from using the old axes
349      * to the newer, more semantically correct axes, we'll continue to produce
350      * values for the old axes as mirrors of the value of their corresponding
351      * new axes. */
352     int32_t compatAxis = getCompatAxis(axis);
353     if (compatAxis >= 0) {
354         pointerCoords->setAxisValue(compatAxis, value);
355     }
356 }
357 
filterAxes(bool force)358 bool JoystickInputMapper::filterAxes(bool force) {
359     bool atLeastOneSignificantChange = force;
360     size_t numAxes = mAxes.size();
361     for (size_t i = 0; i < numAxes; i++) {
362         Axis& axis = mAxes.editValueAt(i);
363         if (force ||
364             hasValueChangedSignificantly(axis.filter, axis.newValue, axis.currentValue, axis.min,
365                                          axis.max)) {
366             axis.currentValue = axis.newValue;
367             atLeastOneSignificantChange = true;
368         }
369         if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
370             if (force ||
371                 hasValueChangedSignificantly(axis.filter, axis.highNewValue, axis.highCurrentValue,
372                                              axis.min, axis.max)) {
373                 axis.highCurrentValue = axis.highNewValue;
374                 atLeastOneSignificantChange = true;
375             }
376         }
377     }
378     return atLeastOneSignificantChange;
379 }
380 
hasValueChangedSignificantly(float filter,float newValue,float currentValue,float min,float max)381 bool JoystickInputMapper::hasValueChangedSignificantly(float filter, float newValue,
382                                                        float currentValue, float min, float max) {
383     if (newValue != currentValue) {
384         // Filter out small changes in value unless the value is converging on the axis
385         // bounds or center point.  This is intended to reduce the amount of information
386         // sent to applications by particularly noisy joysticks (such as PS3).
387         if (fabs(newValue - currentValue) > filter ||
388             hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) ||
389             hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) ||
390             hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
391             return true;
392         }
393     }
394     return false;
395 }
396 
hasMovedNearerToValueWithinFilteredRange(float filter,float newValue,float currentValue,float thresholdValue)397 bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(float filter, float newValue,
398                                                                    float currentValue,
399                                                                    float thresholdValue) {
400     float newDistance = fabs(newValue - thresholdValue);
401     if (newDistance < filter) {
402         float oldDistance = fabs(currentValue - thresholdValue);
403         if (newDistance < oldDistance) {
404             return true;
405         }
406     }
407     return false;
408 }
409 
410 } // namespace android
411