blob: 1cd782d7a7bf8a414580e25f116695dbea146a45 [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#define LOG_TAG "VelocityTracker"
Jeff Brown5912f952013-07-01 19:10:31 -070018
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -070019#include <array>
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070020#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070021#include <limits.h>
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070022#include <math.h>
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -070023#include <optional>
Jeff Brown5912f952013-07-01 19:10:31 -070024
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -070025#include <android-base/stringprintf.h>
Siarhei Vishniakou657a1732023-01-12 11:58:52 -080026#include <input/PrintTools.h>
Jeff Brown5912f952013-07-01 19:10:31 -070027#include <input/VelocityTracker.h>
28#include <utils/BitSet.h>
Jeff Brown5912f952013-07-01 19:10:31 -070029#include <utils/Timers.h>
30
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +000031using std::literals::chrono_literals::operator""ms;
32
Jeff Brown5912f952013-07-01 19:10:31 -070033namespace android {
34
Siarhei Vishniakou276467b2022-03-17 09:43:28 -070035/**
36 * Log debug messages about velocity tracking.
37 * Enable this via "adb shell setprop log.tag.VelocityTrackerVelocity DEBUG" (requires restart)
38 */
39const bool DEBUG_VELOCITY =
40 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Velocity", ANDROID_LOG_INFO);
41
42/**
43 * Log debug messages about the progress of the algorithm itself.
44 * Enable this via "adb shell setprop log.tag.VelocityTrackerStrategy DEBUG" (requires restart)
45 */
46const bool DEBUG_STRATEGY =
47 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Strategy", ANDROID_LOG_INFO);
48
49/**
50 * Log debug messages about the 'impulse' strategy.
51 * Enable this via "adb shell setprop log.tag.VelocityTrackerImpulse DEBUG" (requires restart)
52 */
53const bool DEBUG_IMPULSE =
54 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Impulse", ANDROID_LOG_INFO);
55
Jeff Brown5912f952013-07-01 19:10:31 -070056// Nanoseconds per milliseconds.
57static const nsecs_t NANOS_PER_MS = 1000000;
58
Yeabkal Wubshit67b3ab02022-09-16 00:18:17 -070059// All axes supported for velocity tracking, mapped to their default strategies.
60// Although other strategies are available for testing and comparison purposes,
61// the default strategy is the one that applications will actually use. Be very careful
62// when adjusting the default strategy because it can dramatically affect
63// (often in a bad way) the user experience.
64static const std::map<int32_t, VelocityTracker::Strategy> DEFAULT_STRATEGY_BY_AXIS =
65 {{AMOTION_EVENT_AXIS_X, VelocityTracker::Strategy::LSQ2},
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -070066 {AMOTION_EVENT_AXIS_Y, VelocityTracker::Strategy::LSQ2},
67 {AMOTION_EVENT_AXIS_SCROLL, VelocityTracker::Strategy::IMPULSE}};
Yeabkal Wubshit67b3ab02022-09-16 00:18:17 -070068
69// Axes specifying location on a 2D plane (i.e. X and Y).
70static const std::set<int32_t> PLANAR_AXES = {AMOTION_EVENT_AXIS_X, AMOTION_EVENT_AXIS_Y};
71
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -070072// Axes whose motion values are differential values (i.e. deltas).
73static const std::set<int32_t> DIFFERENTIAL_AXES = {AMOTION_EVENT_AXIS_SCROLL};
74
Jeff Brown5912f952013-07-01 19:10:31 -070075// Threshold for determining that a pointer has stopped moving.
76// Some input devices do not send ACTION_MOVE events in the case where a pointer has
77// stopped. We need to detect this case so that we can accurately predict the
78// velocity after the pointer starts moving again.
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +000079static const std::chrono::duration ASSUME_POINTER_STOPPED_TIME = 40ms;
Jeff Brown5912f952013-07-01 19:10:31 -070080
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +000081static std::string toString(std::chrono::nanoseconds t) {
82 std::stringstream stream;
83 stream.precision(1);
84 stream << std::fixed << std::chrono::duration<float, std::milli>(t).count() << " ms";
85 return stream.str();
86}
Jeff Brown5912f952013-07-01 19:10:31 -070087
88static float vectorDot(const float* a, const float* b, uint32_t m) {
89 float r = 0;
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070090 for (size_t i = 0; i < m; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -070091 r += *(a++) * *(b++);
92 }
93 return r;
94}
95
96static float vectorNorm(const float* a, uint32_t m) {
97 float r = 0;
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070098 for (size_t i = 0; i < m; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -070099 float t = *(a++);
100 r += t * t;
101 }
102 return sqrtf(r);
103}
104
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700105static std::string vectorToString(const float* a, uint32_t m) {
106 std::string str;
107 str += "[";
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -0700108 for (size_t i = 0; i < m; i++) {
109 if (i) {
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700110 str += ",";
Jeff Brown5912f952013-07-01 19:10:31 -0700111 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700112 str += android::base::StringPrintf(" %f", *(a++));
Jeff Brown5912f952013-07-01 19:10:31 -0700113 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700114 str += " ]";
Jeff Brown5912f952013-07-01 19:10:31 -0700115 return str;
116}
117
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700118static std::string vectorToString(const std::vector<float>& v) {
119 return vectorToString(v.data(), v.size());
120}
121
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700122static std::string matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) {
123 std::string str;
124 str = "[";
Jeff Brown5912f952013-07-01 19:10:31 -0700125 for (size_t i = 0; i < m; i++) {
126 if (i) {
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700127 str += ",";
Jeff Brown5912f952013-07-01 19:10:31 -0700128 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700129 str += " [";
Jeff Brown5912f952013-07-01 19:10:31 -0700130 for (size_t j = 0; j < n; j++) {
131 if (j) {
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700132 str += ",";
Jeff Brown5912f952013-07-01 19:10:31 -0700133 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700134 str += android::base::StringPrintf(" %f", a[rowMajor ? i * n + j : j * m + i]);
Jeff Brown5912f952013-07-01 19:10:31 -0700135 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700136 str += " ]";
Jeff Brown5912f952013-07-01 19:10:31 -0700137 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700138 str += " ]";
Jeff Brown5912f952013-07-01 19:10:31 -0700139 return str;
140}
Jeff Brown5912f952013-07-01 19:10:31 -0700141
142
143// --- VelocityTracker ---
144
Chris Yef8591482020-04-17 11:49:17 -0700145VelocityTracker::VelocityTracker(const Strategy strategy)
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800146 : mLastEventTime(0), mCurrentPointerIdBits(0), mOverrideStrategy(strategy) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700147
148VelocityTracker::~VelocityTracker() {
Jeff Brown5912f952013-07-01 19:10:31 -0700149}
150
Yeabkal Wubshiteca273c2022-10-05 19:06:40 -0700151bool VelocityTracker::isAxisSupported(int32_t axis) {
152 return DEFAULT_STRATEGY_BY_AXIS.find(axis) != DEFAULT_STRATEGY_BY_AXIS.end();
153}
154
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700155void VelocityTracker::configureStrategy(int32_t axis) {
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700156 const bool isDifferentialAxis = DIFFERENTIAL_AXES.find(axis) != DIFFERENTIAL_AXES.end();
157
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000158 std::unique_ptr<VelocityTrackerStrategy> createdStrategy;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700159 if (mOverrideStrategy != VelocityTracker::Strategy::DEFAULT) {
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700160 createdStrategy = createStrategy(mOverrideStrategy, isDifferentialAxis /* deltaValues */);
Chris Yef8591482020-04-17 11:49:17 -0700161 } else {
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700162 createdStrategy = createStrategy(DEFAULT_STRATEGY_BY_AXIS.at(axis),
163 isDifferentialAxis /* deltaValues */);
Chris Yef8591482020-04-17 11:49:17 -0700164 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000165
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700166 LOG_ALWAYS_FATAL_IF(createdStrategy == nullptr,
167 "Could not create velocity tracker strategy for axis '%" PRId32 "'!", axis);
168 mConfiguredStrategies[axis] = std::move(createdStrategy);
Jeff Brown5912f952013-07-01 19:10:31 -0700169}
170
Chris Yef8591482020-04-17 11:49:17 -0700171std::unique_ptr<VelocityTrackerStrategy> VelocityTracker::createStrategy(
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700172 VelocityTracker::Strategy strategy, bool deltaValues) {
Chris Yef8591482020-04-17 11:49:17 -0700173 switch (strategy) {
174 case VelocityTracker::Strategy::IMPULSE:
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000175 ALOGI_IF(DEBUG_STRATEGY, "Initializing impulse strategy");
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700176 return std::make_unique<ImpulseVelocityTrackerStrategy>(deltaValues);
Chris Yef8591482020-04-17 11:49:17 -0700177
178 case VelocityTracker::Strategy::LSQ1:
179 return std::make_unique<LeastSquaresVelocityTrackerStrategy>(1);
180
181 case VelocityTracker::Strategy::LSQ2:
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000182 ALOGI_IF(DEBUG_STRATEGY && !DEBUG_IMPULSE, "Initializing lsq2 strategy");
Chris Yef8591482020-04-17 11:49:17 -0700183 return std::make_unique<LeastSquaresVelocityTrackerStrategy>(2);
184
185 case VelocityTracker::Strategy::LSQ3:
186 return std::make_unique<LeastSquaresVelocityTrackerStrategy>(3);
187
188 case VelocityTracker::Strategy::WLSQ2_DELTA:
189 return std::make_unique<
190 LeastSquaresVelocityTrackerStrategy>(2,
191 LeastSquaresVelocityTrackerStrategy::
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800192 Weighting::DELTA);
Chris Yef8591482020-04-17 11:49:17 -0700193 case VelocityTracker::Strategy::WLSQ2_CENTRAL:
194 return std::make_unique<
195 LeastSquaresVelocityTrackerStrategy>(2,
196 LeastSquaresVelocityTrackerStrategy::
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800197 Weighting::CENTRAL);
Chris Yef8591482020-04-17 11:49:17 -0700198 case VelocityTracker::Strategy::WLSQ2_RECENT:
199 return std::make_unique<
200 LeastSquaresVelocityTrackerStrategy>(2,
201 LeastSquaresVelocityTrackerStrategy::
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800202 Weighting::RECENT);
Chris Yef8591482020-04-17 11:49:17 -0700203
204 case VelocityTracker::Strategy::INT1:
205 return std::make_unique<IntegratingVelocityTrackerStrategy>(1);
206
207 case VelocityTracker::Strategy::INT2:
208 return std::make_unique<IntegratingVelocityTrackerStrategy>(2);
209
210 case VelocityTracker::Strategy::LEGACY:
211 return std::make_unique<LegacyVelocityTrackerStrategy>();
212
213 default:
214 break;
Jeff Brown5912f952013-07-01 19:10:31 -0700215 }
Yi Kong5bed83b2018-07-17 12:53:47 -0700216 return nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700217}
218
219void VelocityTracker::clear() {
220 mCurrentPointerIdBits.clear();
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800221 mActivePointerId = std::nullopt;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700222 mConfiguredStrategies.clear();
Jeff Brown5912f952013-07-01 19:10:31 -0700223}
224
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800225void VelocityTracker::clearPointer(int32_t pointerId) {
226 mCurrentPointerIdBits.clearBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700227
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800228 if (mActivePointerId && *mActivePointerId == pointerId) {
229 // The active pointer id is being removed. Mark it invalid and try to find a new one
230 // from the remaining pointers.
231 mActivePointerId = std::nullopt;
232 if (!mCurrentPointerIdBits.isEmpty()) {
233 mActivePointerId = mCurrentPointerIdBits.firstMarkedBit();
234 }
Jeff Brown5912f952013-07-01 19:10:31 -0700235 }
236
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700237 for (const auto& [_, strategy] : mConfiguredStrategies) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800238 strategy->clearPointer(pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000239 }
Jeff Brown5912f952013-07-01 19:10:31 -0700240}
241
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800242void VelocityTracker::addMovement(nsecs_t eventTime, int32_t pointerId, int32_t axis,
243 float position) {
244 if (mCurrentPointerIdBits.hasBit(pointerId) &&
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000245 std::chrono::nanoseconds(eventTime - mLastEventTime) > ASSUME_POINTER_STOPPED_TIME) {
246 ALOGD_IF(DEBUG_VELOCITY, "VelocityTracker: stopped for %s, clearing state.",
247 toString(std::chrono::nanoseconds(eventTime - mLastEventTime)).c_str());
248
Jeff Brown5912f952013-07-01 19:10:31 -0700249 // We have not received any movements for too long. Assume that all pointers
250 // have stopped.
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700251 mConfiguredStrategies.clear();
Jeff Brown5912f952013-07-01 19:10:31 -0700252 }
253 mLastEventTime = eventTime;
254
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800255 mCurrentPointerIdBits.markBit(pointerId);
256 if (!mActivePointerId) {
257 // Let this be the new active pointer if no active pointer is currently set
258 mActivePointerId = pointerId;
Jeff Brown5912f952013-07-01 19:10:31 -0700259 }
260
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800261 if (mConfiguredStrategies.find(axis) == mConfiguredStrategies.end()) {
262 configureStrategy(axis);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000263 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800264 mConfiguredStrategies[axis]->addMovement(eventTime, pointerId, position);
Jeff Brown5912f952013-07-01 19:10:31 -0700265
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700266 if (DEBUG_VELOCITY) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800267 ALOGD("VelocityTracker: addMovement eventTime=%" PRId64 ", pointerId=%" PRId32
268 ", activePointerId=%s",
269 eventTime, pointerId, toString(mActivePointerId).c_str());
270
271 std::optional<Estimator> estimator = getEstimator(axis, pointerId);
272 ALOGD(" %d: axis=%d, position=%0.3f, "
273 "estimator (degree=%d, coeff=%s, confidence=%f)",
274 pointerId, axis, position, int((*estimator).degree),
275 vectorToString((*estimator).coeff.data(), (*estimator).degree + 1).c_str(),
276 (*estimator).confidence);
Jeff Brown5912f952013-07-01 19:10:31 -0700277 }
Jeff Brown5912f952013-07-01 19:10:31 -0700278}
279
280void VelocityTracker::addMovement(const MotionEvent* event) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000281 // Stores data about which axes to process based on the incoming motion event.
282 std::set<int32_t> axesToProcess;
Jeff Brown5912f952013-07-01 19:10:31 -0700283 int32_t actionMasked = event->getActionMasked();
284
285 switch (actionMasked) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800286 case AMOTION_EVENT_ACTION_DOWN:
287 case AMOTION_EVENT_ACTION_HOVER_ENTER:
288 // Clear all pointers on down before adding the new movement.
289 clear();
290 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
291 break;
292 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
293 // Start a new movement trace for a pointer that just went down.
294 // We do this on down instead of on up because the client may want to query the
295 // final velocity for a pointer that just went up.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800296 clearPointer(event->getPointerId(event->getActionIndex()));
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800297 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
298 break;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000299 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800300 case AMOTION_EVENT_ACTION_MOVE:
301 case AMOTION_EVENT_ACTION_HOVER_MOVE:
302 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
303 break;
304 case AMOTION_EVENT_ACTION_POINTER_UP:
305 case AMOTION_EVENT_ACTION_UP: {
306 std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime);
307 if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) {
308 ALOGD_IF(DEBUG_VELOCITY,
309 "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.",
310 toString(delaySinceLastEvent).c_str());
311 // We have not received any movements for too long. Assume that all pointers
312 // have stopped.
313 for (int32_t axis : PLANAR_AXES) {
314 mConfiguredStrategies.erase(axis);
315 }
316 }
317 // These actions because they do not convey any new information about
318 // pointer movement. We also want to preserve the last known velocity of the pointers.
319 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
320 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
321 // pointers that remained down but we will also receive an ACTION_MOVE with this
322 // information if any of them actually moved. Since we don't know how many pointers
323 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
324 // before adding the movement.
325 return;
326 }
327 case AMOTION_EVENT_ACTION_SCROLL:
328 axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL);
329 break;
330 default:
331 // Ignore all other actions.
332 return;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000333 }
Jeff Brown5912f952013-07-01 19:10:31 -0700334
Jeff Brown5912f952013-07-01 19:10:31 -0700335 size_t historySize = event->getHistorySize();
Siarhei Vishniakou69e4d0f2020-09-14 19:53:29 -0500336 for (size_t h = 0; h <= historySize; h++) {
337 nsecs_t eventTime = event->getHistoricalEventTime(h);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800338 for (size_t i = 0; i < event->getPointerCount(); i++) {
339 // TODO(b/167946721): skip resampled samples
340 const int32_t pointerId = event->getPointerId(i);
341 for (int32_t axis : axesToProcess) {
342 const float position = event->getHistoricalAxisValue(axis, i, h);
343 addMovement(eventTime, pointerId, axis, position);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000344 }
Jeff Brown5912f952013-07-01 19:10:31 -0700345 }
Jeff Brown5912f952013-07-01 19:10:31 -0700346 }
Jeff Brown5912f952013-07-01 19:10:31 -0700347}
348
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800349std::optional<float> VelocityTracker::getVelocity(int32_t axis, int32_t pointerId) const {
350 std::optional<Estimator> estimator = getEstimator(axis, pointerId);
351 if (estimator && (*estimator).degree >= 1) {
352 return (*estimator).coeff[1];
Jeff Brown5912f952013-07-01 19:10:31 -0700353 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000354 return {};
Jeff Brown5912f952013-07-01 19:10:31 -0700355}
356
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000357VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units,
358 float maxVelocity) {
359 ComputedVelocity computedVelocity;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700360 for (const auto& [axis, _] : mConfiguredStrategies) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000361 BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits);
362 while (!copyIdBits.isEmpty()) {
363 uint32_t id = copyIdBits.clearFirstMarkedBit();
364 std::optional<float> velocity = getVelocity(axis, id);
365 if (velocity) {
366 float adjustedVelocity =
367 std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity);
368 computedVelocity.addVelocity(axis, id, adjustedVelocity);
369 }
370 }
371 }
372 return computedVelocity;
Jeff Brown5912f952013-07-01 19:10:31 -0700373}
374
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800375std::optional<VelocityTracker::Estimator> VelocityTracker::getEstimator(int32_t axis,
376 int32_t pointerId) const {
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700377 const auto& it = mConfiguredStrategies.find(axis);
378 if (it == mConfiguredStrategies.end()) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800379 return std::nullopt;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000380 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800381 return it->second->getEstimator(pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000382}
Jeff Brown5912f952013-07-01 19:10:31 -0700383
384// --- LeastSquaresVelocityTrackerStrategy ---
385
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700386LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree,
387 Weighting weighting)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800388 : mDegree(degree), mWeighting(weighting) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700389
390LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {
391}
392
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800393void LeastSquaresVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
394 mIndex.erase(pointerId);
395 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700396}
397
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800398void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
399 float position) {
400 // If data for this pointer already exists, we have a valid entry at the position of
401 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
402 // to the next position in the circular buffer and write the new Movement there. Otherwise,
403 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
404 // for this pointer and write to the first position.
405 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
406 auto [indexIt, _] = mIndex.insert({pointerId, 0});
407 size_t& index = indexIt->second;
408 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700409 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
410 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
411 // the new pointer. If the eventtimes for both events are identical, just update the data
412 // for this time.
413 // We only compare against the last value, as it is likely that addMovement is called
414 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800415 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700416 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800417 if (index == HISTORY_SIZE) {
418 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700419 }
420
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800421 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700422 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800423 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700424}
425
426/**
427 * Solves a linear least squares problem to obtain a N degree polynomial that fits
428 * the specified input data as nearly as possible.
429 *
430 * Returns true if a solution is found, false otherwise.
431 *
432 * The input consists of two vectors of data points X and Y with indices 0..m-1
433 * along with a weight vector W of the same size.
434 *
435 * The output is a vector B with indices 0..n that describes a polynomial
436 * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i]
437 * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized.
438 *
439 * Accordingly, the weight vector W should be initialized by the caller with the
440 * reciprocal square root of the variance of the error in each input data point.
441 * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]).
442 * The weights express the relative importance of each data point. If the weights are
443 * all 1, then the data points are considered to be of equal importance when fitting
444 * the polynomial. It is a good idea to choose weights that diminish the importance
445 * of data points that may have higher than usual error margins.
446 *
447 * Errors among data points are assumed to be independent. W is represented here
448 * as a vector although in the literature it is typically taken to be a diagonal matrix.
449 *
450 * That is to say, the function that generated the input data can be approximated
451 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
452 *
453 * The coefficient of determination (R^2) is also returned to describe the goodness
454 * of fit of the model for the given data. It is a value between 0 and 1, where 1
455 * indicates perfect correspondence.
456 *
457 * This function first expands the X vector to a m by n matrix A such that
458 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then
459 * multiplies it by w[i]./
460 *
461 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
462 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
463 * part is all zeroes), we can simplify the decomposition into an m by n matrix
464 * Q1 and a n by n matrix R1 such that A = Q1 R1.
465 *
466 * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y)
467 * to find B.
468 *
469 * For efficiency, we lay out A and Q column-wise in memory because we frequently
470 * operate on the column vectors. Conversely, we lay out R row-wise.
471 *
472 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
473 * http://en.wikipedia.org/wiki/Gram-Schmidt
474 */
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500475static bool solveLeastSquares(const std::vector<float>& x, const std::vector<float>& y,
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800476 const std::vector<float>& w, uint32_t n,
477 std::array<float, VelocityTracker::Estimator::MAX_DEGREE + 1>& outB,
478 float* outDet) {
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500479 const size_t m = x.size();
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000480
481 ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n),
482 vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str());
483
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500484 LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes");
Jeff Brown5912f952013-07-01 19:10:31 -0700485
486 // Expand the X vector to a matrix A, pre-multiplied by the weights.
487 float a[n][m]; // column-major order
488 for (uint32_t h = 0; h < m; h++) {
489 a[0][h] = w[h];
490 for (uint32_t i = 1; i < n; i++) {
491 a[i][h] = a[i - 1][h] * x[h];
492 }
493 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000494
495 ALOGD_IF(DEBUG_STRATEGY, " - a=%s",
496 matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700497
498 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
499 float q[n][m]; // orthonormal basis, column-major order
500 float r[n][n]; // upper triangular matrix, row-major order
501 for (uint32_t j = 0; j < n; j++) {
502 for (uint32_t h = 0; h < m; h++) {
503 q[j][h] = a[j][h];
504 }
505 for (uint32_t i = 0; i < j; i++) {
506 float dot = vectorDot(&q[j][0], &q[i][0], m);
507 for (uint32_t h = 0; h < m; h++) {
508 q[j][h] -= dot * q[i][h];
509 }
510 }
511
512 float norm = vectorNorm(&q[j][0], m);
513 if (norm < 0.000001f) {
514 // vectors are linearly dependent or zero so no solution
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000515 ALOGD_IF(DEBUG_STRATEGY, " - no solution, norm=%f", norm);
Jeff Brown5912f952013-07-01 19:10:31 -0700516 return false;
517 }
518
519 float invNorm = 1.0f / norm;
520 for (uint32_t h = 0; h < m; h++) {
521 q[j][h] *= invNorm;
522 }
523 for (uint32_t i = 0; i < n; i++) {
524 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
525 }
526 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700527 if (DEBUG_STRATEGY) {
528 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str());
529 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700530
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700531 // calculate QR, if we factored A correctly then QR should equal A
532 float qr[n][m];
533 for (uint32_t h = 0; h < m; h++) {
534 for (uint32_t i = 0; i < n; i++) {
535 qr[i][h] = 0;
536 for (uint32_t j = 0; j < n; j++) {
537 qr[i][h] += q[j][h] * r[j][i];
538 }
Jeff Brown5912f952013-07-01 19:10:31 -0700539 }
540 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700541 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700542 }
Jeff Brown5912f952013-07-01 19:10:31 -0700543
544 // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
545 // We just work from bottom-right to top-left calculating B's coefficients.
546 float wy[m];
547 for (uint32_t h = 0; h < m; h++) {
548 wy[h] = y[h] * w[h];
549 }
Dan Austin389ddba2015-09-22 14:32:03 -0700550 for (uint32_t i = n; i != 0; ) {
551 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700552 outB[i] = vectorDot(&q[i][0], wy, m);
553 for (uint32_t j = n - 1; j > i; j--) {
554 outB[i] -= r[i][j] * outB[j];
555 }
556 outB[i] /= r[i][i];
557 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000558
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800559 ALOGD_IF(DEBUG_STRATEGY, " - b=%s", vectorToString(outB.data(), n).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700560
561 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
562 // SSerr is the residual sum of squares (variance of the error),
563 // and SStot is the total sum of squares (variance of the data) where each
564 // has been weighted.
565 float ymean = 0;
566 for (uint32_t h = 0; h < m; h++) {
567 ymean += y[h];
568 }
569 ymean /= m;
570
571 float sserr = 0;
572 float sstot = 0;
573 for (uint32_t h = 0; h < m; h++) {
574 float err = y[h] - outB[0];
575 float term = 1;
576 for (uint32_t i = 1; i < n; i++) {
577 term *= x[h];
578 err -= term * outB[i];
579 }
580 sserr += w[h] * w[h] * err * err;
581 float var = y[h] - ymean;
582 sstot += w[h] * w[h] * var * var;
583 }
584 *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000585
586 ALOGD_IF(DEBUG_STRATEGY, " - sserr=%f", sserr);
587 ALOGD_IF(DEBUG_STRATEGY, " - sstot=%f", sstot);
588 ALOGD_IF(DEBUG_STRATEGY, " - det=%f", *outDet);
589
Jeff Brown5912f952013-07-01 19:10:31 -0700590 return true;
591}
592
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100593/*
594 * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to
595 * the default implementation
596 */
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700597static std::optional<std::array<float, 3>> solveUnweightedLeastSquaresDeg2(
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500598 const std::vector<float>& x, const std::vector<float>& y) {
599 const size_t count = x.size();
600 LOG_ALWAYS_FATAL_IF(count != y.size(), "Mismatching array sizes");
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700601 // Solving y = a*x^2 + b*x + c
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100602 float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0;
603
604 for (size_t i = 0; i < count; i++) {
605 float xi = x[i];
606 float yi = y[i];
607 float xi2 = xi*xi;
608 float xi3 = xi2*xi;
609 float xi4 = xi3*xi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100610 float xiyi = xi*yi;
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700611 float xi2yi = xi2*yi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100612
613 sxi += xi;
614 sxi2 += xi2;
615 sxiyi += xiyi;
616 sxi2yi += xi2yi;
617 syi += yi;
618 sxi3 += xi3;
619 sxi4 += xi4;
620 }
621
622 float Sxx = sxi2 - sxi*sxi / count;
623 float Sxy = sxiyi - sxi*syi / count;
624 float Sxx2 = sxi3 - sxi*sxi2 / count;
625 float Sx2y = sxi2yi - sxi2*syi / count;
626 float Sx2x2 = sxi4 - sxi2*sxi2 / count;
627
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100628 float denominator = Sxx*Sx2x2 - Sxx2*Sxx2;
629 if (denominator == 0) {
630 ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2);
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700631 return std::nullopt;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100632 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700633 // Compute a
634 float numerator = Sx2y*Sxx - Sxy*Sxx2;
635 float a = numerator / denominator;
636
637 // Compute b
638 numerator = Sxy*Sx2x2 - Sx2y*Sxx2;
639 float b = numerator / denominator;
640
641 // Compute c
642 float c = syi/count - b * sxi/count - a * sxi2/count;
643
644 return std::make_optional(std::array<float, 3>({c, b, a}));
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100645}
646
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800647std::optional<VelocityTracker::Estimator> LeastSquaresVelocityTrackerStrategy::getEstimator(
648 int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800649 const auto movementIt = mMovements.find(pointerId);
650 if (movementIt == mMovements.end()) {
651 return std::nullopt; // no data
652 }
Jeff Brown5912f952013-07-01 19:10:31 -0700653 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000654 std::vector<float> positions;
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500655 std::vector<float> w;
656 std::vector<float> time;
657
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800658 uint32_t index = mIndex.at(pointerId);
659 const Movement& newestMovement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700660 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800661 const Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700662
663 nsecs_t age = newestMovement.eventTime - movement.eventTime;
664 if (age > HORIZON) {
665 break;
666 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800667 if (movement.eventTime == 0 && index != 0) {
668 // All eventTime's are initialized to 0. In this fixed-width circular buffer, it's
669 // possible that not all entries are valid. We use a time=0 as a signal for those
670 // uninitialized values. If we encounter a time of 0 in a position
671 // that's > 0, it means that we hit the block where the data wasn't initialized.
672 // We still don't know whether the value at index=0, with eventTime=0 is valid.
673 // However, that's only possible when the value is by itself. So there's no hard in
674 // processing it anyways, since the velocity for a single point is zero, and this
675 // situation will only be encountered in artificial circumstances (in tests).
676 // In practice, time will never be 0.
677 break;
678 }
679 positions.push_back(movement.position);
680 w.push_back(chooseWeight(pointerId, index));
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500681 time.push_back(-age * 0.000000001f);
Jeff Brown5912f952013-07-01 19:10:31 -0700682 index = (index == 0 ? HISTORY_SIZE : index) - 1;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000683 } while (positions.size() < HISTORY_SIZE);
Jeff Brown5912f952013-07-01 19:10:31 -0700684
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000685 const size_t m = positions.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700686 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800687 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700688 }
689
690 // Calculate a least squares polynomial fit.
691 uint32_t degree = mDegree;
692 if (degree > m - 1) {
693 degree = m - 1;
694 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700695
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800696 if (degree == 2 && mWeighting == Weighting::NONE) {
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700697 // Optimize unweighted, quadratic polynomial fit
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000698 std::optional<std::array<float, 3>> coeff =
699 solveUnweightedLeastSquaresDeg2(time, positions);
700 if (coeff) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800701 VelocityTracker::Estimator estimator;
702 estimator.time = newestMovement.eventTime;
703 estimator.degree = 2;
704 estimator.confidence = 1;
705 for (size_t i = 0; i <= estimator.degree; i++) {
706 estimator.coeff[i] = (*coeff)[i];
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700707 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800708 return estimator;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100709 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700710 } else if (degree >= 1) {
711 // General case for an Nth degree polynomial fit
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000712 float det;
Jeff Brown5912f952013-07-01 19:10:31 -0700713 uint32_t n = degree + 1;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800714 VelocityTracker::Estimator estimator;
715 if (solveLeastSquares(time, positions, w, n, estimator.coeff, &det)) {
716 estimator.time = newestMovement.eventTime;
717 estimator.degree = degree;
718 estimator.confidence = det;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000719
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000720 ALOGD_IF(DEBUG_STRATEGY, "estimate: degree=%d, coeff=%s, confidence=%f",
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800721 int(estimator.degree), vectorToString(estimator.coeff.data(), n).c_str(),
722 estimator.confidence);
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000723
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800724 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -0700725 }
726 }
727
728 // No velocity data available for this pointer, but we do have its current position.
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800729 VelocityTracker::Estimator estimator;
730 estimator.coeff[0] = positions[0];
731 estimator.time = newestMovement.eventTime;
732 estimator.degree = 0;
733 estimator.confidence = 1;
734 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -0700735}
736
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800737float LeastSquaresVelocityTrackerStrategy::chooseWeight(int32_t pointerId, uint32_t index) const {
738 const std::array<Movement, HISTORY_SIZE>& movements = mMovements.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700739 switch (mWeighting) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800740 case Weighting::DELTA: {
741 // Weight points based on how much time elapsed between them and the next
742 // point so that points that "cover" a shorter time span are weighed less.
743 // delta 0ms: 0.5
744 // delta 10ms: 1.0
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800745 if (index == mIndex.at(pointerId)) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800746 return 1.0f;
747 }
748 uint32_t nextIndex = (index + 1) % HISTORY_SIZE;
749 float deltaMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800750 (movements[nextIndex].eventTime - movements[index].eventTime) * 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800751 if (deltaMillis < 0) {
752 return 0.5f;
753 }
754 if (deltaMillis < 10) {
755 return 0.5f + deltaMillis * 0.05;
756 }
Jeff Brown5912f952013-07-01 19:10:31 -0700757 return 1.0f;
758 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800759
760 case Weighting::CENTRAL: {
761 // Weight points based on their age, weighing very recent and very old points less.
762 // age 0ms: 0.5
763 // age 10ms: 1.0
764 // age 50ms: 1.0
765 // age 60ms: 0.5
766 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800767 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
768 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800769 if (ageMillis < 0) {
770 return 0.5f;
771 }
772 if (ageMillis < 10) {
773 return 0.5f + ageMillis * 0.05;
774 }
775 if (ageMillis < 50) {
776 return 1.0f;
777 }
778 if (ageMillis < 60) {
779 return 0.5f + (60 - ageMillis) * 0.05;
780 }
Jeff Brown5912f952013-07-01 19:10:31 -0700781 return 0.5f;
782 }
Jeff Brown5912f952013-07-01 19:10:31 -0700783
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800784 case Weighting::RECENT: {
785 // Weight points based on their age, weighing older points less.
786 // age 0ms: 1.0
787 // age 50ms: 1.0
788 // age 100ms: 0.5
789 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800790 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
791 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800792 if (ageMillis < 50) {
793 return 1.0f;
794 }
795 if (ageMillis < 100) {
796 return 0.5f + (100 - ageMillis) * 0.01f;
797 }
Jeff Brown5912f952013-07-01 19:10:31 -0700798 return 0.5f;
799 }
Jeff Brown5912f952013-07-01 19:10:31 -0700800
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800801 case Weighting::NONE:
Jeff Brown5912f952013-07-01 19:10:31 -0700802 return 1.0f;
Jeff Brown5912f952013-07-01 19:10:31 -0700803 }
804}
805
Jeff Brown5912f952013-07-01 19:10:31 -0700806// --- IntegratingVelocityTrackerStrategy ---
807
808IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) :
809 mDegree(degree) {
810}
811
812IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() {
813}
814
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800815void IntegratingVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
816 mPointerIdBits.clearBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700817}
818
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800819void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
820 float position) {
821 State& state = mPointerState[pointerId];
822 if (mPointerIdBits.hasBit(pointerId)) {
823 updateState(state, eventTime, position);
824 } else {
825 initState(state, eventTime, position);
Jeff Brown5912f952013-07-01 19:10:31 -0700826 }
827
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800828 mPointerIdBits.markBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700829}
830
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800831std::optional<VelocityTracker::Estimator> IntegratingVelocityTrackerStrategy::getEstimator(
832 int32_t pointerId) const {
833 if (mPointerIdBits.hasBit(pointerId)) {
834 const State& state = mPointerState[pointerId];
835 VelocityTracker::Estimator estimator;
836 populateEstimator(state, &estimator);
837 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -0700838 }
839
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800840 return std::nullopt;
Jeff Brown5912f952013-07-01 19:10:31 -0700841}
842
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000843void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime,
844 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700845 state.updateTime = eventTime;
846 state.degree = 0;
847
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000848 state.pos = pos;
849 state.accel = 0;
850 state.vel = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700851}
852
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000853void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime,
854 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700855 const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
856 const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
857
858 if (eventTime <= state.updateTime + MIN_TIME_DELTA) {
859 return;
860 }
861
862 float dt = (eventTime - state.updateTime) * 0.000000001f;
863 state.updateTime = eventTime;
864
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000865 float vel = (pos - state.pos) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700866 if (state.degree == 0) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000867 state.vel = vel;
Jeff Brown5912f952013-07-01 19:10:31 -0700868 state.degree = 1;
869 } else {
870 float alpha = dt / (FILTER_TIME_CONSTANT + dt);
871 if (mDegree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000872 state.vel += (vel - state.vel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700873 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000874 float accel = (vel - state.vel) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700875 if (state.degree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000876 state.accel = accel;
Jeff Brown5912f952013-07-01 19:10:31 -0700877 state.degree = 2;
878 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000879 state.accel += (accel - state.accel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700880 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000881 state.vel += (state.accel * dt) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700882 }
883 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000884 state.pos = pos;
Jeff Brown5912f952013-07-01 19:10:31 -0700885}
886
887void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state,
888 VelocityTracker::Estimator* outEstimator) const {
889 outEstimator->time = state.updateTime;
890 outEstimator->confidence = 1.0f;
891 outEstimator->degree = state.degree;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000892 outEstimator->coeff[0] = state.pos;
893 outEstimator->coeff[1] = state.vel;
894 outEstimator->coeff[2] = state.accel / 2;
Jeff Brown5912f952013-07-01 19:10:31 -0700895}
896
897
898// --- LegacyVelocityTrackerStrategy ---
899
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800900LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() {}
Jeff Brown5912f952013-07-01 19:10:31 -0700901
902LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() {
903}
904
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800905void LegacyVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
906 mIndex.erase(pointerId);
907 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700908}
909
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800910void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
911 float position) {
912 // If data for this pointer already exists, we have a valid entry at the position of
913 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
914 // to the next position in the circular buffer and write the new Movement there. Otherwise,
915 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
916 // for this pointer and write to the first position.
917 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
918 auto [indexIt, _] = mIndex.insert({pointerId, 0});
919 size_t& index = indexIt->second;
920 if (!inserted && movementIt->second[index].eventTime != eventTime) {
921 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
922 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
923 // the new pointer. If the eventtimes for both events are identical, just update the data
924 // for this time.
925 // We only compare against the last value, as it is likely that addMovement is called
926 // in chronological order as events occur.
927 index++;
928 }
929 if (index == HISTORY_SIZE) {
930 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700931 }
932
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800933 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700934 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800935 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700936}
937
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800938std::optional<VelocityTracker::Estimator> LegacyVelocityTrackerStrategy::getEstimator(
939 int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800940 const auto movementIt = mMovements.find(pointerId);
941 if (movementIt == mMovements.end()) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800942 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700943 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800944 const Movement& newestMovement = movementIt->second[mIndex.at(pointerId)];
Jeff Brown5912f952013-07-01 19:10:31 -0700945
946 // Find the oldest sample that contains the pointer and that is not older than HORIZON.
947 nsecs_t minTime = newestMovement.eventTime - HORIZON;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800948 uint32_t oldestIndex = mIndex.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700949 uint32_t numTouches = 1;
950 do {
951 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800952 const Movement& nextOldestMovement = mMovements.at(pointerId)[nextOldestIndex];
953 if (nextOldestMovement.eventTime < minTime) {
Jeff Brown5912f952013-07-01 19:10:31 -0700954 break;
955 }
956 oldestIndex = nextOldestIndex;
957 } while (++numTouches < HISTORY_SIZE);
958
959 // Calculate an exponentially weighted moving average of the velocity estimate
960 // at different points in time measured relative to the oldest sample.
961 // This is essentially an IIR filter. Newer samples are weighted more heavily
962 // than older samples. Samples at equal time points are weighted more or less
963 // equally.
964 //
965 // One tricky problem is that the sample data may be poorly conditioned.
966 // Sometimes samples arrive very close together in time which can cause us to
967 // overestimate the velocity at that time point. Most samples might be measured
968 // 16ms apart but some consecutive samples could be only 0.5sm apart because
969 // the hardware or driver reports them irregularly or in bursts.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000970 float accumV = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700971 uint32_t index = oldestIndex;
972 uint32_t samplesUsed = 0;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800973 const Movement& oldestMovement = mMovements.at(pointerId)[oldestIndex];
974 float oldestPosition = oldestMovement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700975 nsecs_t lastDuration = 0;
976
977 while (numTouches-- > 1) {
978 if (++index == HISTORY_SIZE) {
979 index = 0;
980 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800981 const Movement& movement = mMovements.at(pointerId)[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700982 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
983
984 // If the duration between samples is small, we may significantly overestimate
985 // the velocity. Consequently, we impose a minimum duration constraint on the
986 // samples that we include in the calculation.
987 if (duration >= MIN_DURATION) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800988 float position = movement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700989 float scale = 1000000000.0f / duration; // one over time delta in seconds
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000990 float v = (position - oldestPosition) * scale;
991 accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration);
Jeff Brown5912f952013-07-01 19:10:31 -0700992 lastDuration = duration;
993 samplesUsed += 1;
994 }
995 }
996
997 // Report velocity.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800998 float newestPosition = newestMovement.position;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800999 VelocityTracker::Estimator estimator;
1000 estimator.time = newestMovement.eventTime;
1001 estimator.confidence = 1;
1002 estimator.coeff[0] = newestPosition;
Jeff Brown5912f952013-07-01 19:10:31 -07001003 if (samplesUsed) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001004 estimator.coeff[1] = accumV;
1005 estimator.degree = 1;
Jeff Brown5912f952013-07-01 19:10:31 -07001006 } else {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001007 estimator.degree = 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001008 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001009 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -07001010}
1011
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001012// --- ImpulseVelocityTrackerStrategy ---
1013
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001014ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001015 : mDeltaValues(deltaValues) {}
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001016
1017ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() {
1018}
1019
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001020void ImpulseVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
1021 mIndex.erase(pointerId);
1022 mMovements.erase(pointerId);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001023}
1024
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001025void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
1026 float position) {
1027 // If data for this pointer already exists, we have a valid entry at the position of
1028 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
1029 // to the next position in the circular buffer and write the new Movement there. Otherwise,
1030 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
1031 // for this pointer and write to the first position.
1032 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
1033 auto [indexIt, _] = mIndex.insert({pointerId, 0});
1034 size_t& index = indexIt->second;
1035 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -07001036 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
1037 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
1038 // the new pointer. If the eventtimes for both events are identical, just update the data
1039 // for this time.
1040 // We only compare against the last value, as it is likely that addMovement is called
1041 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001042 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -07001043 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001044 if (index == HISTORY_SIZE) {
1045 index = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001046 }
1047
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001048 Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001049 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001050 movement.position = position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001051}
1052
1053/**
1054 * Calculate the total impulse provided to the screen and the resulting velocity.
1055 *
1056 * The touchscreen is modeled as a physical object.
1057 * Initial condition is discussed below, but for now suppose that v(t=0) = 0
1058 *
1059 * The kinetic energy of the object at the release is E=0.5*m*v^2
1060 * Then vfinal = sqrt(2E/m). The goal is to calculate E.
1061 *
1062 * The kinetic energy at the release is equal to the total work done on the object by the finger.
1063 * The total work W is the sum of all dW along the path.
1064 *
1065 * dW = F*dx, where dx is the piece of path traveled.
1066 * Force is change of momentum over time, F = dp/dt = m dv/dt.
1067 * Then substituting:
1068 * dW = m (dv/dt) * dx = m * v * dv
1069 *
1070 * Summing along the path, we get:
1071 * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv)
1072 * Since the mass stays constant, the equation for final velocity is:
1073 * vfinal = sqrt(2*sum(v * dv))
1074 *
1075 * Here,
1076 * dv : change of velocity = (v[i+1]-v[i])
1077 * dx : change of distance = (x[i+1]-x[i])
1078 * dt : change of time = (t[i+1]-t[i])
1079 * v : instantaneous velocity = dx/dt
1080 *
1081 * The final formula is:
1082 * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i
1083 * The absolute value is needed to properly account for the sign. If the velocity over a
1084 * particular segment descreases, then this indicates braking, which means that negative
1085 * work was done. So for two positive, but decreasing, velocities, this contribution would be
1086 * negative and will cause a smaller final velocity.
1087 *
1088 * Initial condition
1089 * There are two ways to deal with initial condition:
1090 * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest.
1091 * This is not entirely accurate. We are only taking the past X ms of touch data, where X is
1092 * currently equal to 100. However, a touch event that created a fling probably lasted for longer
1093 * than that, which would mean that the user has already been interacting with the touchscreen
1094 * and it has probably already been moving.
1095 * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this
1096 * initial velocity and the equivalent energy, and start with this initial energy.
1097 * Consider an example where we have the following data, consisting of 3 points:
1098 * time: t0, t1, t2
1099 * x : x0, x1, x2
1100 * v : 0 , v1, v2
1101 * Here is what will happen in each of these scenarios:
1102 * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get
1103 * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0
1104 * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1)))
1105 * since velocity is a real number
1106 * 2) If we treat the screen as already moving, then it must already have an energy (per mass)
1107 * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment
1108 * will contribute to the total kinetic energy (since we can effectively consider that v0=v1).
1109 * This will give the following expression for the final velocity:
1110 * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1)))
1111 * This analysis can be generalized to an arbitrary number of samples.
1112 *
1113 *
1114 * Comparing the two equations above, we see that the only mathematical difference
1115 * is the factor of 1/2 in front of the first velocity term.
1116 * This boundary condition would allow for the "proper" calculation of the case when all of the
1117 * samples are equally spaced in time and distance, which should suggest a constant velocity.
1118 *
1119 * Note that approach 2) is sensitive to the proper ordering of the data in time, since
1120 * the boundary condition must be applied to the oldest sample to be accurate.
1121 */
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001122static float kineticEnergyToVelocity(float work) {
1123 static constexpr float sqrt2 = 1.41421356237;
1124 return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2;
1125}
1126
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001127static float calculateImpulseVelocity(const nsecs_t* t, const float* x, size_t count,
1128 bool deltaValues) {
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001129 // The input should be in reversed time order (most recent sample at index i=0)
1130 // t[i] is in nanoseconds, but due to FP arithmetic, convert to seconds inside this function
Siarhei Vishniakou6de8f5e2018-03-02 18:48:15 -08001131 static constexpr float SECONDS_PER_NANO = 1E-9;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001132
1133 if (count < 2) {
1134 return 0; // if 0 or 1 points, velocity is zero
1135 }
1136 if (t[1] > t[0]) { // Algorithm will still work, but not perfectly
1137 ALOGE("Samples provided to calculateImpulseVelocity in the wrong order");
1138 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001139
1140 // If the data values are delta values, we do not have to calculate deltas here.
1141 // We can use the delta values directly, along with the calculated time deltas.
1142 // Since the data value input is in reversed time order:
1143 // [a] for non-delta inputs, instantenous velocity = (x[i] - x[i-1])/(t[i] - t[i-1])
1144 // [b] for delta inputs, instantenous velocity = -x[i-1]/(t[i] - t[i - 1])
1145 // e.g., let the non-delta values are: V = [2, 3, 7], the equivalent deltas are D = [2, 1, 4].
1146 // Since the input is in reversed time order, the input values for this function would be
1147 // V'=[7, 3, 2] and D'=[4, 1, 2] for the non-delta and delta values, respectively.
1148 //
1149 // The equivalent of {(V'[2] - V'[1]) = 2 - 3 = -1} would be {-D'[1] = -1}
1150 // Similarly, the equivalent of {(V'[1] - V'[0]) = 3 - 7 = -4} would be {-D'[0] = -4}
1151
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001152 if (count == 2) { // if 2 points, basic linear calculation
1153 if (t[1] == t[0]) {
1154 ALOGE("Events have identical time stamps t=%" PRId64 ", setting velocity = 0", t[0]);
1155 return 0;
1156 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001157 const float deltaX = deltaValues ? -x[0] : x[1] - x[0];
1158 return deltaX / (SECONDS_PER_NANO * (t[1] - t[0]));
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001159 }
1160 // Guaranteed to have at least 3 points here
1161 float work = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001162 for (size_t i = count - 1; i > 0 ; i--) { // start with the oldest sample and go forward in time
1163 if (t[i] == t[i-1]) {
1164 ALOGE("Events have identical time stamps t=%" PRId64 ", skipping sample", t[i]);
1165 continue;
1166 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001167 float vprev = kineticEnergyToVelocity(work); // v[i-1]
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001168 const float deltaX = deltaValues ? -x[i-1] : x[i] - x[i-1];
1169 float vcurr = deltaX / (SECONDS_PER_NANO * (t[i] - t[i-1])); // v[i]
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001170 work += (vcurr - vprev) * fabsf(vcurr);
1171 if (i == count - 1) {
1172 work *= 0.5; // initial condition, case 2) above
1173 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001174 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001175 return kineticEnergyToVelocity(work);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001176}
1177
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001178std::optional<VelocityTracker::Estimator> ImpulseVelocityTrackerStrategy::getEstimator(
1179 int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001180 const auto movementIt = mMovements.find(pointerId);
1181 if (movementIt == mMovements.end()) {
1182 return std::nullopt; // no data
1183 }
1184
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001185 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001186 float positions[HISTORY_SIZE];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001187 nsecs_t time[HISTORY_SIZE];
1188 size_t m = 0; // number of points that will be used for fitting
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001189 size_t index = mIndex.at(pointerId);
1190 const Movement& newestMovement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001191 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001192 const Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001193
1194 nsecs_t age = newestMovement.eventTime - movement.eventTime;
1195 if (age > HORIZON) {
1196 break;
1197 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001198 if (movement.eventTime == 0 && index != 0) {
1199 // All eventTime's are initialized to 0. If we encounter a time of 0 in a position
1200 // that's >0, it means that we hit the block where the data wasn't initialized.
1201 // It's also possible that the sample at 0 would be invalid, but there's no harm in
1202 // processing it, since it would be just a single point, and will only be encountered
1203 // in artificial circumstances (in tests).
1204 break;
1205 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001206
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001207 positions[m] = movement.position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001208 time[m] = movement.eventTime;
1209 index = (index == 0 ? HISTORY_SIZE : index) - 1;
1210 } while (++m < HISTORY_SIZE);
1211
1212 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001213 return std::nullopt; // no data
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001214 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001215 VelocityTracker::Estimator estimator;
1216 estimator.coeff[0] = 0;
1217 estimator.coeff[1] = calculateImpulseVelocity(time, positions, m, mDeltaValues);
1218 estimator.coeff[2] = 0;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001219
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001220 estimator.time = newestMovement.eventTime;
1221 estimator.degree = 2; // similar results to 2nd degree fit
1222 estimator.confidence = 1;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +00001223
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001224 ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", estimator.coeff[1]);
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +00001225
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001226 if (DEBUG_IMPULSE) {
1227 // TODO(b/134179997): delete this block once the switch to 'impulse' is complete.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001228 // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons.
1229 // X axis chosen arbitrarily for velocity comparisons.
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001230 VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001231 for (ssize_t i = m - 1; i >= 0; i--) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001232 lsq2.addMovement(time[i], pointerId, AMOTION_EVENT_AXIS_X, positions[i]);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001233 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001234 std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001235 if (v) {
1236 ALOGD("lsq2 velocity: %.1f", *v);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001237 } else {
1238 ALOGD("lsq2 velocity: could not compute velocity");
1239 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -07001240 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001241 return estimator;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001242}
1243
Jeff Brown5912f952013-07-01 19:10:31 -07001244} // namespace android