blob: 6f2fcf4ce47dc39fea87f1c639e02542cb873e4d [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 Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +000072 coeff[i] = 0;
Jeff Brown5912f952013-07-01 19:10:31 -070073 }
74 }
75 };
76
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +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 Wubshit37acf6e2022-08-27 05:48:51 +0000135 // Populates 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 void populateComputedVelocity(ComputedVelocity& computedVelocity, int32_t units,
139 float maxVelocity);
140
141 // Gets an estimator for the recent movements of the specified pointer id for the given axis.
Jeff Brown5912f952013-07-01 19:10:31 -0700142 // Returns false and clears the estimator if there is no information available
143 // about the pointer.
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000144 bool getEstimator(int32_t axis, uint32_t id, Estimator* outEstimator) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700145
146 // Gets the active pointer id, or -1 if none.
147 inline int32_t getActivePointerId() const { return mActivePointerId; }
148
Jeff Brown5912f952013-07-01 19:10:31 -0700149private:
Chris Yef8591482020-04-17 11:49:17 -0700150 // The default velocity tracker strategy.
151 // Although other strategies are available for testing and comparison purposes,
152 // this is the strategy that applications will actually use. Be very careful
153 // when adjusting the default strategy because it can dramatically affect
154 // (often in a bad way) the user experience.
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000155 // TODO(b/32830165): define default strategy per axis.
Chris Yef8591482020-04-17 11:49:17 -0700156 static const Strategy DEFAULT_STRATEGY = Strategy::LSQ2;
Jeff Brown5912f952013-07-01 19:10:31 -0700157
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000158 // Set of all axes supported for velocity tracking.
159 static const std::set<int32_t> SUPPORTED_AXES;
160
161 // Axes specifying location on a 2D plane (i.e. X and Y).
162 static const std::set<int32_t> PLANAR_AXES;
163
Jeff Brown5912f952013-07-01 19:10:31 -0700164 nsecs_t mLastEventTime;
165 BitSet32 mCurrentPointerIdBits;
166 int32_t mActivePointerId;
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000167 std::map<int32_t /*axis*/, std::unique_ptr<VelocityTrackerStrategy>> mStrategies;
Jeff Brown5912f952013-07-01 19:10:31 -0700168
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000169 void configureStrategy(int32_t axis, const Strategy strategy);
Jeff Brown5912f952013-07-01 19:10:31 -0700170
Chris Yef8591482020-04-17 11:49:17 -0700171 static std::unique_ptr<VelocityTrackerStrategy> createStrategy(const Strategy strategy);
Jeff Brown5912f952013-07-01 19:10:31 -0700172};
173
174
175/*
176 * Implements a particular velocity tracker algorithm.
177 */
178class VelocityTrackerStrategy {
179protected:
180 VelocityTrackerStrategy() { }
181
182public:
183 virtual ~VelocityTrackerStrategy() { }
184
185 virtual void clear() = 0;
186 virtual void clearPointers(BitSet32 idBits) = 0;
187 virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000188 const std::vector<float>& positions) = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700189 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0;
190};
191
192
193/*
194 * Velocity tracker algorithm based on least-squares linear regression.
195 */
196class LeastSquaresVelocityTrackerStrategy : public VelocityTrackerStrategy {
197public:
198 enum Weighting {
199 // No weights applied. All data points are equally reliable.
200 WEIGHTING_NONE,
201
202 // Weight by time delta. Data points clustered together are weighted less.
203 WEIGHTING_DELTA,
204
205 // Weight such that points within a certain horizon are weighed more than those
206 // outside of that horizon.
207 WEIGHTING_CENTRAL,
208
209 // Weight such that points older than a certain amount are weighed less.
210 WEIGHTING_RECENT,
211 };
212
213 // Degree must be no greater than Estimator::MAX_DEGREE.
214 LeastSquaresVelocityTrackerStrategy(uint32_t degree, Weighting weighting = WEIGHTING_NONE);
215 virtual ~LeastSquaresVelocityTrackerStrategy();
216
217 virtual void clear();
218 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500219 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000220 const std::vector<float>& positions) override;
Jeff Brown5912f952013-07-01 19:10:31 -0700221 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
222
223private:
224 // Sample horizon.
225 // We don't use too much history by default since we want to react to quick
226 // changes in direction.
227 static const nsecs_t HORIZON = 100 * 1000000; // 100 ms
228
229 // Number of samples to keep.
230 static const uint32_t HISTORY_SIZE = 20;
231
232 struct Movement {
233 nsecs_t eventTime;
234 BitSet32 idBits;
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000235 float positions[MAX_POINTERS];
Jeff Brown5912f952013-07-01 19:10:31 -0700236
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000237 inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
Jeff Brown5912f952013-07-01 19:10:31 -0700238 };
239
240 float chooseWeight(uint32_t index) const;
241
242 const uint32_t mDegree;
243 const Weighting mWeighting;
244 uint32_t mIndex;
245 Movement mMovements[HISTORY_SIZE];
246};
247
248
249/*
250 * Velocity tracker algorithm that uses an IIR filter.
251 */
252class IntegratingVelocityTrackerStrategy : public VelocityTrackerStrategy {
253public:
254 // Degree must be 1 or 2.
255 IntegratingVelocityTrackerStrategy(uint32_t degree);
256 ~IntegratingVelocityTrackerStrategy();
257
258 virtual void clear();
259 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500260 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000261 const std::vector<float>& positions) override;
Jeff Brown5912f952013-07-01 19:10:31 -0700262 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
263
264private:
265 // Current state estimate for a particular pointer.
266 struct State {
267 nsecs_t updateTime;
268 uint32_t degree;
269
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000270 float pos, vel, accel;
Jeff Brown5912f952013-07-01 19:10:31 -0700271 };
272
273 const uint32_t mDegree;
274 BitSet32 mPointerIdBits;
275 State mPointerState[MAX_POINTER_ID + 1];
276
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000277 void initState(State& state, nsecs_t eventTime, float pos) const;
278 void updateState(State& state, nsecs_t eventTime, float pos) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700279 void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const;
280};
281
282
283/*
284 * Velocity tracker strategy used prior to ICS.
285 */
286class LegacyVelocityTrackerStrategy : public VelocityTrackerStrategy {
287public:
288 LegacyVelocityTrackerStrategy();
289 virtual ~LegacyVelocityTrackerStrategy();
290
291 virtual void clear();
292 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500293 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000294 const std::vector<float>& positions) override;
Jeff Brown5912f952013-07-01 19:10:31 -0700295 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
296
297private:
298 // Oldest sample to consider when calculating the velocity.
299 static const nsecs_t HORIZON = 200 * 1000000; // 100 ms
300
301 // Number of samples to keep.
302 static const uint32_t HISTORY_SIZE = 20;
303
304 // The minimum duration between samples when estimating velocity.
305 static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms
306
307 struct Movement {
308 nsecs_t eventTime;
309 BitSet32 idBits;
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000310 float positions[MAX_POINTERS];
Jeff Brown5912f952013-07-01 19:10:31 -0700311
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000312 inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
Jeff Brown5912f952013-07-01 19:10:31 -0700313 };
314
315 uint32_t mIndex;
316 Movement mMovements[HISTORY_SIZE];
317};
318
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100319class ImpulseVelocityTrackerStrategy : public VelocityTrackerStrategy {
320public:
321 ImpulseVelocityTrackerStrategy();
322 virtual ~ImpulseVelocityTrackerStrategy();
323
324 virtual void clear();
325 virtual void clearPointers(BitSet32 idBits);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -0500326 void addMovement(nsecs_t eventTime, BitSet32 idBits,
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000327 const std::vector<float>& positions) override;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100328 virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
329
330private:
331 // Sample horizon.
332 // We don't use too much history by default since we want to react to quick
333 // changes in direction.
334 static constexpr nsecs_t HORIZON = 100 * 1000000; // 100 ms
335
336 // Number of samples to keep.
337 static constexpr size_t HISTORY_SIZE = 20;
338
339 struct Movement {
340 nsecs_t eventTime;
341 BitSet32 idBits;
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000342 float positions[MAX_POINTERS];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100343
Yeabkal Wubshit37acf6e2022-08-27 05:48:51 +0000344 inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100345 };
346
347 size_t mIndex;
348 Movement mMovements[HISTORY_SIZE];
349};
350
Jeff Brown5912f952013-07-01 19:10:31 -0700351} // namespace android
352
353#endif // _LIBINPUT_VELOCITY_TRACKER_H