blob: 3632914b93530474b3dfc542480f33b299d2399e [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
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800335 const size_t historySize = event->getHistorySize();
Siarhei Vishniakou69e4d0f2020-09-14 19:53:29 -0500336 for (size_t h = 0; h <= historySize; h++) {
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800337 const nsecs_t eventTime = event->getHistoricalEventTime(h);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800338 for (size_t i = 0; i < event->getPointerCount(); i++) {
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800339 if (event->isResampled(i, h)) {
340 continue; // skip resampled samples
341 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800342 const int32_t pointerId = event->getPointerId(i);
343 for (int32_t axis : axesToProcess) {
344 const float position = event->getHistoricalAxisValue(axis, i, h);
345 addMovement(eventTime, pointerId, axis, position);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000346 }
Jeff Brown5912f952013-07-01 19:10:31 -0700347 }
Jeff Brown5912f952013-07-01 19:10:31 -0700348 }
Jeff Brown5912f952013-07-01 19:10:31 -0700349}
350
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800351std::optional<float> VelocityTracker::getVelocity(int32_t axis, int32_t pointerId) const {
352 std::optional<Estimator> estimator = getEstimator(axis, pointerId);
353 if (estimator && (*estimator).degree >= 1) {
354 return (*estimator).coeff[1];
Jeff Brown5912f952013-07-01 19:10:31 -0700355 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000356 return {};
Jeff Brown5912f952013-07-01 19:10:31 -0700357}
358
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000359VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units,
360 float maxVelocity) {
361 ComputedVelocity computedVelocity;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700362 for (const auto& [axis, _] : mConfiguredStrategies) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000363 BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits);
364 while (!copyIdBits.isEmpty()) {
365 uint32_t id = copyIdBits.clearFirstMarkedBit();
366 std::optional<float> velocity = getVelocity(axis, id);
367 if (velocity) {
368 float adjustedVelocity =
369 std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity);
370 computedVelocity.addVelocity(axis, id, adjustedVelocity);
371 }
372 }
373 }
374 return computedVelocity;
Jeff Brown5912f952013-07-01 19:10:31 -0700375}
376
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800377std::optional<VelocityTracker::Estimator> VelocityTracker::getEstimator(int32_t axis,
378 int32_t pointerId) const {
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700379 const auto& it = mConfiguredStrategies.find(axis);
380 if (it == mConfiguredStrategies.end()) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800381 return std::nullopt;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000382 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800383 return it->second->getEstimator(pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000384}
Jeff Brown5912f952013-07-01 19:10:31 -0700385
386// --- LeastSquaresVelocityTrackerStrategy ---
387
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700388LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree,
389 Weighting weighting)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800390 : mDegree(degree), mWeighting(weighting) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700391
392LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {
393}
394
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800395void LeastSquaresVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
396 mIndex.erase(pointerId);
397 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700398}
399
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800400void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
401 float position) {
402 // If data for this pointer already exists, we have a valid entry at the position of
403 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
404 // to the next position in the circular buffer and write the new Movement there. Otherwise,
405 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
406 // for this pointer and write to the first position.
407 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
408 auto [indexIt, _] = mIndex.insert({pointerId, 0});
409 size_t& index = indexIt->second;
410 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700411 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
412 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
413 // the new pointer. If the eventtimes for both events are identical, just update the data
414 // for this time.
415 // We only compare against the last value, as it is likely that addMovement is called
416 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800417 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700418 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800419 if (index == HISTORY_SIZE) {
420 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700421 }
422
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800423 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700424 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800425 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700426}
427
428/**
429 * Solves a linear least squares problem to obtain a N degree polynomial that fits
430 * the specified input data as nearly as possible.
431 *
432 * Returns true if a solution is found, false otherwise.
433 *
434 * The input consists of two vectors of data points X and Y with indices 0..m-1
435 * along with a weight vector W of the same size.
436 *
437 * The output is a vector B with indices 0..n that describes a polynomial
438 * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i]
439 * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized.
440 *
441 * Accordingly, the weight vector W should be initialized by the caller with the
442 * reciprocal square root of the variance of the error in each input data point.
443 * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]).
444 * The weights express the relative importance of each data point. If the weights are
445 * all 1, then the data points are considered to be of equal importance when fitting
446 * the polynomial. It is a good idea to choose weights that diminish the importance
447 * of data points that may have higher than usual error margins.
448 *
449 * Errors among data points are assumed to be independent. W is represented here
450 * as a vector although in the literature it is typically taken to be a diagonal matrix.
451 *
452 * That is to say, the function that generated the input data can be approximated
453 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
454 *
455 * The coefficient of determination (R^2) is also returned to describe the goodness
456 * of fit of the model for the given data. It is a value between 0 and 1, where 1
457 * indicates perfect correspondence.
458 *
459 * This function first expands the X vector to a m by n matrix A such that
460 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then
461 * multiplies it by w[i]./
462 *
463 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
464 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
465 * part is all zeroes), we can simplify the decomposition into an m by n matrix
466 * Q1 and a n by n matrix R1 such that A = Q1 R1.
467 *
468 * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y)
469 * to find B.
470 *
471 * For efficiency, we lay out A and Q column-wise in memory because we frequently
472 * operate on the column vectors. Conversely, we lay out R row-wise.
473 *
474 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
475 * http://en.wikipedia.org/wiki/Gram-Schmidt
476 */
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500477static bool solveLeastSquares(const std::vector<float>& x, const std::vector<float>& y,
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800478 const std::vector<float>& w, uint32_t n,
479 std::array<float, VelocityTracker::Estimator::MAX_DEGREE + 1>& outB,
480 float* outDet) {
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500481 const size_t m = x.size();
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000482
483 ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n),
484 vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str());
485
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500486 LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes");
Jeff Brown5912f952013-07-01 19:10:31 -0700487
488 // Expand the X vector to a matrix A, pre-multiplied by the weights.
489 float a[n][m]; // column-major order
490 for (uint32_t h = 0; h < m; h++) {
491 a[0][h] = w[h];
492 for (uint32_t i = 1; i < n; i++) {
493 a[i][h] = a[i - 1][h] * x[h];
494 }
495 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000496
497 ALOGD_IF(DEBUG_STRATEGY, " - a=%s",
498 matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700499
500 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
501 float q[n][m]; // orthonormal basis, column-major order
502 float r[n][n]; // upper triangular matrix, row-major order
503 for (uint32_t j = 0; j < n; j++) {
504 for (uint32_t h = 0; h < m; h++) {
505 q[j][h] = a[j][h];
506 }
507 for (uint32_t i = 0; i < j; i++) {
508 float dot = vectorDot(&q[j][0], &q[i][0], m);
509 for (uint32_t h = 0; h < m; h++) {
510 q[j][h] -= dot * q[i][h];
511 }
512 }
513
514 float norm = vectorNorm(&q[j][0], m);
515 if (norm < 0.000001f) {
516 // vectors are linearly dependent or zero so no solution
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000517 ALOGD_IF(DEBUG_STRATEGY, " - no solution, norm=%f", norm);
Jeff Brown5912f952013-07-01 19:10:31 -0700518 return false;
519 }
520
521 float invNorm = 1.0f / norm;
522 for (uint32_t h = 0; h < m; h++) {
523 q[j][h] *= invNorm;
524 }
525 for (uint32_t i = 0; i < n; i++) {
526 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
527 }
528 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700529 if (DEBUG_STRATEGY) {
530 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str());
531 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700532
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700533 // calculate QR, if we factored A correctly then QR should equal A
534 float qr[n][m];
535 for (uint32_t h = 0; h < m; h++) {
536 for (uint32_t i = 0; i < n; i++) {
537 qr[i][h] = 0;
538 for (uint32_t j = 0; j < n; j++) {
539 qr[i][h] += q[j][h] * r[j][i];
540 }
Jeff Brown5912f952013-07-01 19:10:31 -0700541 }
542 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700543 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700544 }
Jeff Brown5912f952013-07-01 19:10:31 -0700545
546 // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
547 // We just work from bottom-right to top-left calculating B's coefficients.
548 float wy[m];
549 for (uint32_t h = 0; h < m; h++) {
550 wy[h] = y[h] * w[h];
551 }
Dan Austin389ddba2015-09-22 14:32:03 -0700552 for (uint32_t i = n; i != 0; ) {
553 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700554 outB[i] = vectorDot(&q[i][0], wy, m);
555 for (uint32_t j = n - 1; j > i; j--) {
556 outB[i] -= r[i][j] * outB[j];
557 }
558 outB[i] /= r[i][i];
559 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000560
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800561 ALOGD_IF(DEBUG_STRATEGY, " - b=%s", vectorToString(outB.data(), n).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700562
563 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
564 // SSerr is the residual sum of squares (variance of the error),
565 // and SStot is the total sum of squares (variance of the data) where each
566 // has been weighted.
567 float ymean = 0;
568 for (uint32_t h = 0; h < m; h++) {
569 ymean += y[h];
570 }
571 ymean /= m;
572
573 float sserr = 0;
574 float sstot = 0;
575 for (uint32_t h = 0; h < m; h++) {
576 float err = y[h] - outB[0];
577 float term = 1;
578 for (uint32_t i = 1; i < n; i++) {
579 term *= x[h];
580 err -= term * outB[i];
581 }
582 sserr += w[h] * w[h] * err * err;
583 float var = y[h] - ymean;
584 sstot += w[h] * w[h] * var * var;
585 }
586 *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000587
588 ALOGD_IF(DEBUG_STRATEGY, " - sserr=%f", sserr);
589 ALOGD_IF(DEBUG_STRATEGY, " - sstot=%f", sstot);
590 ALOGD_IF(DEBUG_STRATEGY, " - det=%f", *outDet);
591
Jeff Brown5912f952013-07-01 19:10:31 -0700592 return true;
593}
594
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100595/*
596 * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to
597 * the default implementation
598 */
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700599static std::optional<std::array<float, 3>> solveUnweightedLeastSquaresDeg2(
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500600 const std::vector<float>& x, const std::vector<float>& y) {
601 const size_t count = x.size();
602 LOG_ALWAYS_FATAL_IF(count != y.size(), "Mismatching array sizes");
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700603 // Solving y = a*x^2 + b*x + c
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100604 float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0;
605
606 for (size_t i = 0; i < count; i++) {
607 float xi = x[i];
608 float yi = y[i];
609 float xi2 = xi*xi;
610 float xi3 = xi2*xi;
611 float xi4 = xi3*xi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100612 float xiyi = xi*yi;
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700613 float xi2yi = xi2*yi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100614
615 sxi += xi;
616 sxi2 += xi2;
617 sxiyi += xiyi;
618 sxi2yi += xi2yi;
619 syi += yi;
620 sxi3 += xi3;
621 sxi4 += xi4;
622 }
623
624 float Sxx = sxi2 - sxi*sxi / count;
625 float Sxy = sxiyi - sxi*syi / count;
626 float Sxx2 = sxi3 - sxi*sxi2 / count;
627 float Sx2y = sxi2yi - sxi2*syi / count;
628 float Sx2x2 = sxi4 - sxi2*sxi2 / count;
629
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100630 float denominator = Sxx*Sx2x2 - Sxx2*Sxx2;
631 if (denominator == 0) {
632 ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2);
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700633 return std::nullopt;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100634 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700635 // Compute a
636 float numerator = Sx2y*Sxx - Sxy*Sxx2;
637 float a = numerator / denominator;
638
639 // Compute b
640 numerator = Sxy*Sx2x2 - Sx2y*Sxx2;
641 float b = numerator / denominator;
642
643 // Compute c
644 float c = syi/count - b * sxi/count - a * sxi2/count;
645
646 return std::make_optional(std::array<float, 3>({c, b, a}));
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100647}
648
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800649std::optional<VelocityTracker::Estimator> LeastSquaresVelocityTrackerStrategy::getEstimator(
650 int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800651 const auto movementIt = mMovements.find(pointerId);
652 if (movementIt == mMovements.end()) {
653 return std::nullopt; // no data
654 }
Jeff Brown5912f952013-07-01 19:10:31 -0700655 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000656 std::vector<float> positions;
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500657 std::vector<float> w;
658 std::vector<float> time;
659
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800660 uint32_t index = mIndex.at(pointerId);
661 const Movement& newestMovement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700662 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800663 const Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700664
665 nsecs_t age = newestMovement.eventTime - movement.eventTime;
666 if (age > HORIZON) {
667 break;
668 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800669 if (movement.eventTime == 0 && index != 0) {
670 // All eventTime's are initialized to 0. In this fixed-width circular buffer, it's
671 // possible that not all entries are valid. We use a time=0 as a signal for those
672 // uninitialized values. If we encounter a time of 0 in a position
673 // that's > 0, it means that we hit the block where the data wasn't initialized.
674 // We still don't know whether the value at index=0, with eventTime=0 is valid.
675 // However, that's only possible when the value is by itself. So there's no hard in
676 // processing it anyways, since the velocity for a single point is zero, and this
677 // situation will only be encountered in artificial circumstances (in tests).
678 // In practice, time will never be 0.
679 break;
680 }
681 positions.push_back(movement.position);
682 w.push_back(chooseWeight(pointerId, index));
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500683 time.push_back(-age * 0.000000001f);
Jeff Brown5912f952013-07-01 19:10:31 -0700684 index = (index == 0 ? HISTORY_SIZE : index) - 1;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000685 } while (positions.size() < HISTORY_SIZE);
Jeff Brown5912f952013-07-01 19:10:31 -0700686
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000687 const size_t m = positions.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700688 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800689 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700690 }
691
692 // Calculate a least squares polynomial fit.
693 uint32_t degree = mDegree;
694 if (degree > m - 1) {
695 degree = m - 1;
696 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700697
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800698 if (degree == 2 && mWeighting == Weighting::NONE) {
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700699 // Optimize unweighted, quadratic polynomial fit
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000700 std::optional<std::array<float, 3>> coeff =
701 solveUnweightedLeastSquaresDeg2(time, positions);
702 if (coeff) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800703 VelocityTracker::Estimator estimator;
704 estimator.time = newestMovement.eventTime;
705 estimator.degree = 2;
706 estimator.confidence = 1;
707 for (size_t i = 0; i <= estimator.degree; i++) {
708 estimator.coeff[i] = (*coeff)[i];
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700709 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800710 return estimator;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100711 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700712 } else if (degree >= 1) {
713 // General case for an Nth degree polynomial fit
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000714 float det;
Jeff Brown5912f952013-07-01 19:10:31 -0700715 uint32_t n = degree + 1;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800716 VelocityTracker::Estimator estimator;
717 if (solveLeastSquares(time, positions, w, n, estimator.coeff, &det)) {
718 estimator.time = newestMovement.eventTime;
719 estimator.degree = degree;
720 estimator.confidence = det;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000721
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000722 ALOGD_IF(DEBUG_STRATEGY, "estimate: degree=%d, coeff=%s, confidence=%f",
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800723 int(estimator.degree), vectorToString(estimator.coeff.data(), n).c_str(),
724 estimator.confidence);
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000725
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800726 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -0700727 }
728 }
729
730 // No velocity data available for this pointer, but we do have its current position.
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800731 VelocityTracker::Estimator estimator;
732 estimator.coeff[0] = positions[0];
733 estimator.time = newestMovement.eventTime;
734 estimator.degree = 0;
735 estimator.confidence = 1;
736 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -0700737}
738
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800739float LeastSquaresVelocityTrackerStrategy::chooseWeight(int32_t pointerId, uint32_t index) const {
740 const std::array<Movement, HISTORY_SIZE>& movements = mMovements.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700741 switch (mWeighting) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800742 case Weighting::DELTA: {
743 // Weight points based on how much time elapsed between them and the next
744 // point so that points that "cover" a shorter time span are weighed less.
745 // delta 0ms: 0.5
746 // delta 10ms: 1.0
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800747 if (index == mIndex.at(pointerId)) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800748 return 1.0f;
749 }
750 uint32_t nextIndex = (index + 1) % HISTORY_SIZE;
751 float deltaMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800752 (movements[nextIndex].eventTime - movements[index].eventTime) * 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800753 if (deltaMillis < 0) {
754 return 0.5f;
755 }
756 if (deltaMillis < 10) {
757 return 0.5f + deltaMillis * 0.05;
758 }
Jeff Brown5912f952013-07-01 19:10:31 -0700759 return 1.0f;
760 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800761
762 case Weighting::CENTRAL: {
763 // Weight points based on their age, weighing very recent and very old points less.
764 // age 0ms: 0.5
765 // age 10ms: 1.0
766 // age 50ms: 1.0
767 // age 60ms: 0.5
768 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800769 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
770 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800771 if (ageMillis < 0) {
772 return 0.5f;
773 }
774 if (ageMillis < 10) {
775 return 0.5f + ageMillis * 0.05;
776 }
777 if (ageMillis < 50) {
778 return 1.0f;
779 }
780 if (ageMillis < 60) {
781 return 0.5f + (60 - ageMillis) * 0.05;
782 }
Jeff Brown5912f952013-07-01 19:10:31 -0700783 return 0.5f;
784 }
Jeff Brown5912f952013-07-01 19:10:31 -0700785
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800786 case Weighting::RECENT: {
787 // Weight points based on their age, weighing older points less.
788 // age 0ms: 1.0
789 // age 50ms: 1.0
790 // age 100ms: 0.5
791 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800792 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
793 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800794 if (ageMillis < 50) {
795 return 1.0f;
796 }
797 if (ageMillis < 100) {
798 return 0.5f + (100 - ageMillis) * 0.01f;
799 }
Jeff Brown5912f952013-07-01 19:10:31 -0700800 return 0.5f;
801 }
Jeff Brown5912f952013-07-01 19:10:31 -0700802
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800803 case Weighting::NONE:
Jeff Brown5912f952013-07-01 19:10:31 -0700804 return 1.0f;
Jeff Brown5912f952013-07-01 19:10:31 -0700805 }
806}
807
Jeff Brown5912f952013-07-01 19:10:31 -0700808// --- IntegratingVelocityTrackerStrategy ---
809
810IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) :
811 mDegree(degree) {
812}
813
814IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() {
815}
816
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800817void IntegratingVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
818 mPointerIdBits.clearBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700819}
820
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800821void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
822 float position) {
823 State& state = mPointerState[pointerId];
824 if (mPointerIdBits.hasBit(pointerId)) {
825 updateState(state, eventTime, position);
826 } else {
827 initState(state, eventTime, position);
Jeff Brown5912f952013-07-01 19:10:31 -0700828 }
829
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800830 mPointerIdBits.markBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700831}
832
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800833std::optional<VelocityTracker::Estimator> IntegratingVelocityTrackerStrategy::getEstimator(
834 int32_t pointerId) const {
835 if (mPointerIdBits.hasBit(pointerId)) {
836 const State& state = mPointerState[pointerId];
837 VelocityTracker::Estimator estimator;
838 populateEstimator(state, &estimator);
839 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -0700840 }
841
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800842 return std::nullopt;
Jeff Brown5912f952013-07-01 19:10:31 -0700843}
844
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000845void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime,
846 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700847 state.updateTime = eventTime;
848 state.degree = 0;
849
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000850 state.pos = pos;
851 state.accel = 0;
852 state.vel = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700853}
854
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000855void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime,
856 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700857 const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
858 const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
859
860 if (eventTime <= state.updateTime + MIN_TIME_DELTA) {
861 return;
862 }
863
864 float dt = (eventTime - state.updateTime) * 0.000000001f;
865 state.updateTime = eventTime;
866
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000867 float vel = (pos - state.pos) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700868 if (state.degree == 0) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000869 state.vel = vel;
Jeff Brown5912f952013-07-01 19:10:31 -0700870 state.degree = 1;
871 } else {
872 float alpha = dt / (FILTER_TIME_CONSTANT + dt);
873 if (mDegree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000874 state.vel += (vel - state.vel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700875 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000876 float accel = (vel - state.vel) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700877 if (state.degree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000878 state.accel = accel;
Jeff Brown5912f952013-07-01 19:10:31 -0700879 state.degree = 2;
880 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000881 state.accel += (accel - state.accel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700882 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000883 state.vel += (state.accel * dt) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700884 }
885 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000886 state.pos = pos;
Jeff Brown5912f952013-07-01 19:10:31 -0700887}
888
889void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state,
890 VelocityTracker::Estimator* outEstimator) const {
891 outEstimator->time = state.updateTime;
892 outEstimator->confidence = 1.0f;
893 outEstimator->degree = state.degree;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000894 outEstimator->coeff[0] = state.pos;
895 outEstimator->coeff[1] = state.vel;
896 outEstimator->coeff[2] = state.accel / 2;
Jeff Brown5912f952013-07-01 19:10:31 -0700897}
898
899
900// --- LegacyVelocityTrackerStrategy ---
901
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800902LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() {}
Jeff Brown5912f952013-07-01 19:10:31 -0700903
904LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() {
905}
906
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800907void LegacyVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
908 mIndex.erase(pointerId);
909 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700910}
911
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800912void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
913 float position) {
914 // If data for this pointer already exists, we have a valid entry at the position of
915 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
916 // to the next position in the circular buffer and write the new Movement there. Otherwise,
917 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
918 // for this pointer and write to the first position.
919 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
920 auto [indexIt, _] = mIndex.insert({pointerId, 0});
921 size_t& index = indexIt->second;
922 if (!inserted && movementIt->second[index].eventTime != eventTime) {
923 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
924 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
925 // the new pointer. If the eventtimes for both events are identical, just update the data
926 // for this time.
927 // We only compare against the last value, as it is likely that addMovement is called
928 // in chronological order as events occur.
929 index++;
930 }
931 if (index == HISTORY_SIZE) {
932 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700933 }
934
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800935 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700936 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800937 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700938}
939
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800940std::optional<VelocityTracker::Estimator> LegacyVelocityTrackerStrategy::getEstimator(
941 int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800942 const auto movementIt = mMovements.find(pointerId);
943 if (movementIt == mMovements.end()) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800944 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700945 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800946 const Movement& newestMovement = movementIt->second[mIndex.at(pointerId)];
Jeff Brown5912f952013-07-01 19:10:31 -0700947
948 // Find the oldest sample that contains the pointer and that is not older than HORIZON.
949 nsecs_t minTime = newestMovement.eventTime - HORIZON;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800950 uint32_t oldestIndex = mIndex.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700951 uint32_t numTouches = 1;
952 do {
953 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800954 const Movement& nextOldestMovement = mMovements.at(pointerId)[nextOldestIndex];
955 if (nextOldestMovement.eventTime < minTime) {
Jeff Brown5912f952013-07-01 19:10:31 -0700956 break;
957 }
958 oldestIndex = nextOldestIndex;
959 } while (++numTouches < HISTORY_SIZE);
960
961 // Calculate an exponentially weighted moving average of the velocity estimate
962 // at different points in time measured relative to the oldest sample.
963 // This is essentially an IIR filter. Newer samples are weighted more heavily
964 // than older samples. Samples at equal time points are weighted more or less
965 // equally.
966 //
967 // One tricky problem is that the sample data may be poorly conditioned.
968 // Sometimes samples arrive very close together in time which can cause us to
969 // overestimate the velocity at that time point. Most samples might be measured
970 // 16ms apart but some consecutive samples could be only 0.5sm apart because
971 // the hardware or driver reports them irregularly or in bursts.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000972 float accumV = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700973 uint32_t index = oldestIndex;
974 uint32_t samplesUsed = 0;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800975 const Movement& oldestMovement = mMovements.at(pointerId)[oldestIndex];
976 float oldestPosition = oldestMovement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700977 nsecs_t lastDuration = 0;
978
979 while (numTouches-- > 1) {
980 if (++index == HISTORY_SIZE) {
981 index = 0;
982 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800983 const Movement& movement = mMovements.at(pointerId)[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700984 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
985
986 // If the duration between samples is small, we may significantly overestimate
987 // the velocity. Consequently, we impose a minimum duration constraint on the
988 // samples that we include in the calculation.
989 if (duration >= MIN_DURATION) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800990 float position = movement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700991 float scale = 1000000000.0f / duration; // one over time delta in seconds
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000992 float v = (position - oldestPosition) * scale;
993 accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration);
Jeff Brown5912f952013-07-01 19:10:31 -0700994 lastDuration = duration;
995 samplesUsed += 1;
996 }
997 }
998
999 // Report velocity.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001000 float newestPosition = newestMovement.position;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001001 VelocityTracker::Estimator estimator;
1002 estimator.time = newestMovement.eventTime;
1003 estimator.confidence = 1;
1004 estimator.coeff[0] = newestPosition;
Jeff Brown5912f952013-07-01 19:10:31 -07001005 if (samplesUsed) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001006 estimator.coeff[1] = accumV;
1007 estimator.degree = 1;
Jeff Brown5912f952013-07-01 19:10:31 -07001008 } else {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001009 estimator.degree = 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001010 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001011 return estimator;
Jeff Brown5912f952013-07-01 19:10:31 -07001012}
1013
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001014// --- ImpulseVelocityTrackerStrategy ---
1015
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001016ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001017 : mDeltaValues(deltaValues) {}
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001018
1019ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() {
1020}
1021
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001022void ImpulseVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
1023 mIndex.erase(pointerId);
1024 mMovements.erase(pointerId);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001025}
1026
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001027void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
1028 float position) {
1029 // If data for this pointer already exists, we have a valid entry at the position of
1030 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
1031 // to the next position in the circular buffer and write the new Movement there. Otherwise,
1032 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
1033 // for this pointer and write to the first position.
1034 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
1035 auto [indexIt, _] = mIndex.insert({pointerId, 0});
1036 size_t& index = indexIt->second;
1037 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -07001038 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
1039 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
1040 // the new pointer. If the eventtimes for both events are identical, just update the data
1041 // for this time.
1042 // We only compare against the last value, as it is likely that addMovement is called
1043 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001044 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -07001045 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001046 if (index == HISTORY_SIZE) {
1047 index = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001048 }
1049
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001050 Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001051 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001052 movement.position = position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001053}
1054
1055/**
1056 * Calculate the total impulse provided to the screen and the resulting velocity.
1057 *
1058 * The touchscreen is modeled as a physical object.
1059 * Initial condition is discussed below, but for now suppose that v(t=0) = 0
1060 *
1061 * The kinetic energy of the object at the release is E=0.5*m*v^2
1062 * Then vfinal = sqrt(2E/m). The goal is to calculate E.
1063 *
1064 * The kinetic energy at the release is equal to the total work done on the object by the finger.
1065 * The total work W is the sum of all dW along the path.
1066 *
1067 * dW = F*dx, where dx is the piece of path traveled.
1068 * Force is change of momentum over time, F = dp/dt = m dv/dt.
1069 * Then substituting:
1070 * dW = m (dv/dt) * dx = m * v * dv
1071 *
1072 * Summing along the path, we get:
1073 * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv)
1074 * Since the mass stays constant, the equation for final velocity is:
1075 * vfinal = sqrt(2*sum(v * dv))
1076 *
1077 * Here,
1078 * dv : change of velocity = (v[i+1]-v[i])
1079 * dx : change of distance = (x[i+1]-x[i])
1080 * dt : change of time = (t[i+1]-t[i])
1081 * v : instantaneous velocity = dx/dt
1082 *
1083 * The final formula is:
1084 * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i
1085 * The absolute value is needed to properly account for the sign. If the velocity over a
1086 * particular segment descreases, then this indicates braking, which means that negative
1087 * work was done. So for two positive, but decreasing, velocities, this contribution would be
1088 * negative and will cause a smaller final velocity.
1089 *
1090 * Initial condition
1091 * There are two ways to deal with initial condition:
1092 * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest.
1093 * This is not entirely accurate. We are only taking the past X ms of touch data, where X is
1094 * currently equal to 100. However, a touch event that created a fling probably lasted for longer
1095 * than that, which would mean that the user has already been interacting with the touchscreen
1096 * and it has probably already been moving.
1097 * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this
1098 * initial velocity and the equivalent energy, and start with this initial energy.
1099 * Consider an example where we have the following data, consisting of 3 points:
1100 * time: t0, t1, t2
1101 * x : x0, x1, x2
1102 * v : 0 , v1, v2
1103 * Here is what will happen in each of these scenarios:
1104 * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get
1105 * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0
1106 * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1)))
1107 * since velocity is a real number
1108 * 2) If we treat the screen as already moving, then it must already have an energy (per mass)
1109 * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment
1110 * will contribute to the total kinetic energy (since we can effectively consider that v0=v1).
1111 * This will give the following expression for the final velocity:
1112 * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1)))
1113 * This analysis can be generalized to an arbitrary number of samples.
1114 *
1115 *
1116 * Comparing the two equations above, we see that the only mathematical difference
1117 * is the factor of 1/2 in front of the first velocity term.
1118 * This boundary condition would allow for the "proper" calculation of the case when all of the
1119 * samples are equally spaced in time and distance, which should suggest a constant velocity.
1120 *
1121 * Note that approach 2) is sensitive to the proper ordering of the data in time, since
1122 * the boundary condition must be applied to the oldest sample to be accurate.
1123 */
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001124static float kineticEnergyToVelocity(float work) {
1125 static constexpr float sqrt2 = 1.41421356237;
1126 return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2;
1127}
1128
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001129static float calculateImpulseVelocity(const nsecs_t* t, const float* x, size_t count,
1130 bool deltaValues) {
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001131 // The input should be in reversed time order (most recent sample at index i=0)
1132 // t[i] is in nanoseconds, but due to FP arithmetic, convert to seconds inside this function
Siarhei Vishniakou6de8f5e2018-03-02 18:48:15 -08001133 static constexpr float SECONDS_PER_NANO = 1E-9;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001134
1135 if (count < 2) {
1136 return 0; // if 0 or 1 points, velocity is zero
1137 }
1138 if (t[1] > t[0]) { // Algorithm will still work, but not perfectly
1139 ALOGE("Samples provided to calculateImpulseVelocity in the wrong order");
1140 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001141
1142 // If the data values are delta values, we do not have to calculate deltas here.
1143 // We can use the delta values directly, along with the calculated time deltas.
1144 // Since the data value input is in reversed time order:
1145 // [a] for non-delta inputs, instantenous velocity = (x[i] - x[i-1])/(t[i] - t[i-1])
1146 // [b] for delta inputs, instantenous velocity = -x[i-1]/(t[i] - t[i - 1])
1147 // e.g., let the non-delta values are: V = [2, 3, 7], the equivalent deltas are D = [2, 1, 4].
1148 // Since the input is in reversed time order, the input values for this function would be
1149 // V'=[7, 3, 2] and D'=[4, 1, 2] for the non-delta and delta values, respectively.
1150 //
1151 // The equivalent of {(V'[2] - V'[1]) = 2 - 3 = -1} would be {-D'[1] = -1}
1152 // Similarly, the equivalent of {(V'[1] - V'[0]) = 3 - 7 = -4} would be {-D'[0] = -4}
1153
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001154 if (count == 2) { // if 2 points, basic linear calculation
1155 if (t[1] == t[0]) {
1156 ALOGE("Events have identical time stamps t=%" PRId64 ", setting velocity = 0", t[0]);
1157 return 0;
1158 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001159 const float deltaX = deltaValues ? -x[0] : x[1] - x[0];
1160 return deltaX / (SECONDS_PER_NANO * (t[1] - t[0]));
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001161 }
1162 // Guaranteed to have at least 3 points here
1163 float work = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001164 for (size_t i = count - 1; i > 0 ; i--) { // start with the oldest sample and go forward in time
1165 if (t[i] == t[i-1]) {
1166 ALOGE("Events have identical time stamps t=%" PRId64 ", skipping sample", t[i]);
1167 continue;
1168 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001169 float vprev = kineticEnergyToVelocity(work); // v[i-1]
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001170 const float deltaX = deltaValues ? -x[i-1] : x[i] - x[i-1];
1171 float vcurr = deltaX / (SECONDS_PER_NANO * (t[i] - t[i-1])); // v[i]
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001172 work += (vcurr - vprev) * fabsf(vcurr);
1173 if (i == count - 1) {
1174 work *= 0.5; // initial condition, case 2) above
1175 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001176 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001177 return kineticEnergyToVelocity(work);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001178}
1179
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001180std::optional<VelocityTracker::Estimator> ImpulseVelocityTrackerStrategy::getEstimator(
1181 int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001182 const auto movementIt = mMovements.find(pointerId);
1183 if (movementIt == mMovements.end()) {
1184 return std::nullopt; // no data
1185 }
1186
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001187 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001188 float positions[HISTORY_SIZE];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001189 nsecs_t time[HISTORY_SIZE];
1190 size_t m = 0; // number of points that will be used for fitting
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001191 size_t index = mIndex.at(pointerId);
1192 const Movement& newestMovement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001193 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001194 const Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001195
1196 nsecs_t age = newestMovement.eventTime - movement.eventTime;
1197 if (age > HORIZON) {
1198 break;
1199 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001200 if (movement.eventTime == 0 && index != 0) {
1201 // All eventTime's are initialized to 0. If we encounter a time of 0 in a position
1202 // that's >0, it means that we hit the block where the data wasn't initialized.
1203 // It's also possible that the sample at 0 would be invalid, but there's no harm in
1204 // processing it, since it would be just a single point, and will only be encountered
1205 // in artificial circumstances (in tests).
1206 break;
1207 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001208
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001209 positions[m] = movement.position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001210 time[m] = movement.eventTime;
1211 index = (index == 0 ? HISTORY_SIZE : index) - 1;
1212 } while (++m < HISTORY_SIZE);
1213
1214 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001215 return std::nullopt; // no data
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001216 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001217 VelocityTracker::Estimator estimator;
1218 estimator.coeff[0] = 0;
1219 estimator.coeff[1] = calculateImpulseVelocity(time, positions, m, mDeltaValues);
1220 estimator.coeff[2] = 0;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001221
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001222 estimator.time = newestMovement.eventTime;
1223 estimator.degree = 2; // similar results to 2nd degree fit
1224 estimator.confidence = 1;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +00001225
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001226 ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", estimator.coeff[1]);
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +00001227
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001228 if (DEBUG_IMPULSE) {
1229 // TODO(b/134179997): delete this block once the switch to 'impulse' is complete.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001230 // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons.
1231 // X axis chosen arbitrarily for velocity comparisons.
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001232 VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001233 for (ssize_t i = m - 1; i >= 0; i--) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001234 lsq2.addMovement(time[i], pointerId, AMOTION_EVENT_AXIS_X, positions[i]);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001235 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001236 std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001237 if (v) {
1238 ALOGD("lsq2 velocity: %.1f", *v);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001239 } else {
1240 ALOGD("lsq2 velocity: could not compute velocity");
1241 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -07001242 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001243 return estimator;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001244}
1245
Jeff Brown5912f952013-07-01 19:10:31 -07001246} // namespace android