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