blob: 53603c54cc0c1976046ccd7592efadc60b430060 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001/*
2 * Copyright (C) 2012 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#ifndef _LIBINPUT_VELOCITY_TRACKER_H
18#define _LIBINPUT_VELOCITY_TRACKER_H
19
20#include <input/Input.h>
Jeff Brown5912f952013-07-01 19:10:31 -070021#include <utils/BitSet.h>
Chris Yef8591482020-04-17 11:49:17 -070022#include <utils/Timers.h>
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +000023#include <map>
24#include <set>
Jeff Brown5912f952013-07-01 19:10:31 -070025
26namespace android {
27
28class VelocityTrackerStrategy;
29
30/*
31 * Calculates the velocity of pointer movements over time.
32 */
33class VelocityTracker {
34public:
Chris Yef8591482020-04-17 11:49:17 -070035 enum class Strategy : int32_t {
36 DEFAULT = -1,
37 MIN = 0,
38 IMPULSE = 0,
39 LSQ1 = 1,
40 LSQ2 = 2,
41 LSQ3 = 3,
42 WLSQ2_DELTA = 4,
43 WLSQ2_CENTRAL = 5,
44 WLSQ2_RECENT = 6,
45 INT1 = 7,
46 INT2 = 8,
47 LEGACY = 9,
48 MAX = LEGACY,
49 };
50
Jeff Brown5912f952013-07-01 19:10:31 -070051 struct Estimator {
52 static const size_t MAX_DEGREE = 4;
53
54 // Estimator time base.
55 nsecs_t time;
56
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +000057 // Polynomial coefficients describing motion.
58 float coeff[MAX_DEGREE + 1];
Jeff Brown5912f952013-07-01 19:10:31 -070059
60 // Polynomial degree (number of coefficients), or zero if no information is
61 // available.
62 uint32_t degree;
63
64 // Confidence (coefficient of determination), between 0 (no fit) and 1 (perfect fit).
65 float confidence;
66
67 inline void clear() {
68 time = 0;
69 degree = 0;
70 confidence = 0;
71 for (size_t i = 0; i <= MAX_DEGREE; i++) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +000072 coeff[i] = 0;
Jeff Brown5912f952013-07-01 19:10:31 -070073 }
74 }
75 };
76
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +000077 /*
78 * Contains all available velocity data from a VelocityTracker.
79 */
80 struct ComputedVelocity {
81 inline std::optional<float> getVelocity(int32_t axis, uint32_t id) const {
82 const auto& axisVelocities = mVelocities.find(axis);
83 if (axisVelocities == mVelocities.end()) {
84 return {};
85 }
86
87 const auto& axisIdVelocity = axisVelocities->second.find(id);
88 if (axisIdVelocity == axisVelocities->second.end()) {
89 return {};
90 }
91
92 return axisIdVelocity->second;
93 }
94
95 inline void addVelocity(int32_t axis, uint32_t id, float velocity) {
96 mVelocities[axis][id] = velocity;
97 }
98
99 private:
100 std::map<int32_t /*axis*/, std::map<int32_t /*pointerId*/, float /*velocity*/>> mVelocities;
101 };
102
103 // Creates a velocity tracker using the specified strategy for each supported axis.
Chris Yef8591482020-04-17 11:49:17 -0700104 // If strategy is not provided, uses the default strategy for the platform.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000105 // TODO(b/32830165): support axis-specific strategies.
Chris Yef8591482020-04-17 11:49:17 -0700106 VelocityTracker(const Strategy strategy = Strategy::DEFAULT);
Jeff Brown5912f952013-07-01 19:10:31 -0700107
108 ~VelocityTracker();
109
110 // Resets the velocity tracker state.
111 void clear();
112
113 // Resets the velocity tracker state for specific pointers.
114 // Call this method when some pointers have changed and may be reusing
115 // an id that was assigned to a different pointer earlier.
116 void clearPointers(BitSet32 idBits);
117
118 // Adds movement information for a set of pointers.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000119 // The idBits bitfield specifies the pointer ids of the pointers whose data points
Jeff Brown5912f952013-07-01 19:10:31 -0700120 // are included in the movement.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000121 // The positions map contains a mapping of an axis to positions array.
122 // The positions arrays contain information for each pointer in order by increasing id.
123 // Each array's size should be equal to the number of one bits in idBits.
124 void addMovement(nsecs_t eventTime, BitSet32 idBits,
125 const std::map<int32_t, std::vector<float>>& positions);
Jeff Brown5912f952013-07-01 19:10:31 -0700126
127 // Adds movement information for all pointers in a MotionEvent, including historical samples.
128 void addMovement(const MotionEvent* event);
129
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000130 // Returns the velocity of the specified pointer id and axis in position units per second.
131 // Returns empty optional if there is insufficient movement information for the pointer, or if
132 // the given axis is not supported for velocity tracking.
133 std::optional<float> getVelocity(int32_t axis, uint32_t id) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700134
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000135 // Returns a ComputedVelocity instance with all available velocity data, using the given units
136 // (reference: units == 1 means "per millisecond"), and clamping each velocity between
137 // [-maxVelocity, maxVelocity], inclusive.
138 ComputedVelocity getComputedVelocity(int32_t units, float maxVelocity);
139
140 // Gets an estimator for the recent movements of the specified pointer id for the given axis.
Jeff Brown5912f952013-07-01 19:10:31 -0700141 // Returns false and clears the estimator if there is no information available
142 // about the pointer.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000143 bool getEstimator(int32_t axis, uint32_t id, Estimator* outEstimator) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700144
145 // Gets the active pointer id, or -1 if none.
146 inline int32_t getActivePointerId() const { return mActivePointerId; }
147
Jeff Brown5912f952013-07-01 19:10:31 -0700148private:
Chris Yef8591482020-04-17 11:49:17 -0700149 // The default velocity tracker strategy.
150 // Although other strategies are available for testing and comparison purposes,
151 // this is the strategy that applications will actually use. Be very careful
152 // when adjusting the default strategy because it can dramatically affect
153 // (often in a bad way) the user experience.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000154 // TODO(b/32830165): define default strategy per axis.
Chris Yef8591482020-04-17 11:49:17 -0700155 static const Strategy DEFAULT_STRATEGY = Strategy::LSQ2;
Jeff Brown5912f952013-07-01 19:10:31 -0700156
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000157 // Set of all axes supported for velocity tracking.
158 static const std::set<int32_t> SUPPORTED_AXES;
159
160 // Axes specifying location on a 2D plane (i.e. X and Y).
161 static const std::set<int32_t> PLANAR_AXES;
162
Jeff Brown5912f952013-07-01 19:10:31 -0700163 nsecs_t mLastEventTime;
164 BitSet32 mCurrentPointerIdBits;
165 int32_t mActivePointerId;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000166 std::map<int32_t /*axis*/, std::unique_ptr<VelocityTrackerStrategy>> mStrategies;
Jeff Brown5912f952013-07-01 19:10:31 -0700167
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000168 void configureStrategy(int32_t axis, const Strategy strategy);
Jeff Brown5912f952013-07-01 19:10:31 -0700169
Chris Yef8591482020-04-17 11:49:17 -0700170 static std::unique_ptr<VelocityTrackerStrategy> createStrategy(const Strategy strategy);
Jeff Brown5912f952013-07-01 19:10:31 -0700171};
172
173
174/*
175 * Implements a particular velocity tracker algorithm.
176 */
177class VelocityTrackerStrategy {
178protected:
179 VelocityTrackerStrategy() { }
180
181public:
182 virtual ~VelocityTrackerStrategy() { }
183
184 virtual void clear() = 0;
185 virtual void clearPointers(BitSet32 idBits) = 0;
186 virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000187 const std::vector<float>& positions) = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700188 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0;
189};
190
191
192/*
193 * Velocity tracker algorithm based on least-squares linear regression.
194 */
195class LeastSquaresVelocityTrackerStrategy : public VelocityTrackerStrategy {
196public:
197 enum Weighting {
198 // No weights applied. All data points are equally reliable.
199 WEIGHTING_NONE,
200
201 // Weight by time delta. Data points clustered together are weighted less.
202 WEIGHTING_DELTA,
203
204 // Weight such that points within a certain horizon are weighed more than those
205 // outside of that horizon.
206 WEIGHTING_CENTRAL,
207
208 // Weight such that points older than a certain amount are weighed less.
209 WEIGHTING_RECENT,
210 };
211
212 // Degree must be no greater than Estimator::MAX_DEGREE.
213 LeastSquaresVelocityTrackerStrategy(uint32_t degree, Weighting weighting = WEIGHTING_NONE);
214 virtual ~LeastSquaresVelocityTrackerStrategy();
215
216 virtual void clear();
217 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500218 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000219 const std::vector<float>& positions) override;
Jeff Brown5912f952013-07-01 19:10:31 -0700220 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
221
222private:
223 // Sample horizon.
224 // We don't use too much history by default since we want to react to quick
225 // changes in direction.
226 static const nsecs_t HORIZON = 100 * 1000000; // 100 ms
227
228 // Number of samples to keep.
229 static const uint32_t HISTORY_SIZE = 20;
230
231 struct Movement {
232 nsecs_t eventTime;
233 BitSet32 idBits;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000234 float positions[MAX_POINTERS];
Jeff Brown5912f952013-07-01 19:10:31 -0700235
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000236 inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
Jeff Brown5912f952013-07-01 19:10:31 -0700237 };
238
239 float chooseWeight(uint32_t index) const;
240
241 const uint32_t mDegree;
242 const Weighting mWeighting;
243 uint32_t mIndex;
244 Movement mMovements[HISTORY_SIZE];
245};
246
247
248/*
249 * Velocity tracker algorithm that uses an IIR filter.
250 */
251class IntegratingVelocityTrackerStrategy : public VelocityTrackerStrategy {
252public:
253 // Degree must be 1 or 2.
254 IntegratingVelocityTrackerStrategy(uint32_t degree);
255 ~IntegratingVelocityTrackerStrategy();
256
257 virtual void clear();
258 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500259 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000260 const std::vector<float>& positions) override;
Jeff Brown5912f952013-07-01 19:10:31 -0700261 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
262
263private:
264 // Current state estimate for a particular pointer.
265 struct State {
266 nsecs_t updateTime;
267 uint32_t degree;
268
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000269 float pos, vel, accel;
Jeff Brown5912f952013-07-01 19:10:31 -0700270 };
271
272 const uint32_t mDegree;
273 BitSet32 mPointerIdBits;
274 State mPointerState[MAX_POINTER_ID + 1];
275
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000276 void initState(State& state, nsecs_t eventTime, float pos) const;
277 void updateState(State& state, nsecs_t eventTime, float pos) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700278 void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const;
279};
280
281
282/*
283 * Velocity tracker strategy used prior to ICS.
284 */
285class LegacyVelocityTrackerStrategy : public VelocityTrackerStrategy {
286public:
287 LegacyVelocityTrackerStrategy();
288 virtual ~LegacyVelocityTrackerStrategy();
289
290 virtual void clear();
291 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500292 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000293 const std::vector<float>& positions) override;
Jeff Brown5912f952013-07-01 19:10:31 -0700294 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
295
296private:
297 // Oldest sample to consider when calculating the velocity.
298 static const nsecs_t HORIZON = 200 * 1000000; // 100 ms
299
300 // Number of samples to keep.
301 static const uint32_t HISTORY_SIZE = 20;
302
303 // The minimum duration between samples when estimating velocity.
304 static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms
305
306 struct Movement {
307 nsecs_t eventTime;
308 BitSet32 idBits;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000309 float positions[MAX_POINTERS];
Jeff Brown5912f952013-07-01 19:10:31 -0700310
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000311 inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
Jeff Brown5912f952013-07-01 19:10:31 -0700312 };
313
314 uint32_t mIndex;
315 Movement mMovements[HISTORY_SIZE];
316};
317
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100318class ImpulseVelocityTrackerStrategy : public VelocityTrackerStrategy {
319public:
320 ImpulseVelocityTrackerStrategy();
321 virtual ~ImpulseVelocityTrackerStrategy();
322
323 virtual void clear();
324 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500325 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000326 const std::vector<float>& positions) override;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100327 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
328
329private:
330 // Sample horizon.
331 // We don't use too much history by default since we want to react to quick
332 // changes in direction.
333 static constexpr nsecs_t HORIZON = 100 * 1000000; // 100 ms
334
335 // Number of samples to keep.
336 static constexpr size_t HISTORY_SIZE = 20;
337
338 struct Movement {
339 nsecs_t eventTime;
340 BitSet32 idBits;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000341 float positions[MAX_POINTERS];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100342
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000343 inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100344 };
345
346 size_t mIndex;
347 Movement mMovements[HISTORY_SIZE];
348};
349
Jeff Brown5912f952013-07-01 19:10:31 -0700350} // namespace android
351
352#endif // _LIBINPUT_VELOCITY_TRACKER_H