blob: ac042c57909b4bfb19c9702470d81059c7adf4fc [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
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800271 ALOGD(" %d: axis=%d, position=%0.3f, velocity=%s", pointerId, axis, position,
272 toString(getVelocity(axis, pointerId)).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700273 }
Jeff Brown5912f952013-07-01 19:10:31 -0700274}
275
276void VelocityTracker::addMovement(const MotionEvent* event) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000277 // Stores data about which axes to process based on the incoming motion event.
278 std::set<int32_t> axesToProcess;
Jeff Brown5912f952013-07-01 19:10:31 -0700279 int32_t actionMasked = event->getActionMasked();
280
281 switch (actionMasked) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800282 case AMOTION_EVENT_ACTION_DOWN:
283 case AMOTION_EVENT_ACTION_HOVER_ENTER:
284 // Clear all pointers on down before adding the new movement.
285 clear();
286 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
287 break;
288 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
289 // Start a new movement trace for a pointer that just went down.
290 // We do this on down instead of on up because the client may want to query the
291 // final velocity for a pointer that just went up.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800292 clearPointer(event->getPointerId(event->getActionIndex()));
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800293 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
294 break;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000295 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800296 case AMOTION_EVENT_ACTION_MOVE:
297 case AMOTION_EVENT_ACTION_HOVER_MOVE:
298 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
299 break;
300 case AMOTION_EVENT_ACTION_POINTER_UP:
301 case AMOTION_EVENT_ACTION_UP: {
302 std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime);
303 if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) {
304 ALOGD_IF(DEBUG_VELOCITY,
305 "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.",
306 toString(delaySinceLastEvent).c_str());
307 // We have not received any movements for too long. Assume that all pointers
308 // have stopped.
309 for (int32_t axis : PLANAR_AXES) {
310 mConfiguredStrategies.erase(axis);
311 }
312 }
313 // These actions because they do not convey any new information about
314 // pointer movement. We also want to preserve the last known velocity of the pointers.
315 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
316 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
317 // pointers that remained down but we will also receive an ACTION_MOVE with this
318 // information if any of them actually moved. Since we don't know how many pointers
319 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
320 // before adding the movement.
321 return;
322 }
323 case AMOTION_EVENT_ACTION_SCROLL:
324 axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL);
325 break;
326 default:
327 // Ignore all other actions.
328 return;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000329 }
Jeff Brown5912f952013-07-01 19:10:31 -0700330
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800331 const size_t historySize = event->getHistorySize();
Siarhei Vishniakou69e4d0f2020-09-14 19:53:29 -0500332 for (size_t h = 0; h <= historySize; h++) {
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800333 const nsecs_t eventTime = event->getHistoricalEventTime(h);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800334 for (size_t i = 0; i < event->getPointerCount(); i++) {
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800335 if (event->isResampled(i, h)) {
336 continue; // skip resampled samples
337 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800338 const int32_t pointerId = event->getPointerId(i);
339 for (int32_t axis : axesToProcess) {
340 const float position = event->getHistoricalAxisValue(axis, i, h);
341 addMovement(eventTime, pointerId, axis, position);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000342 }
Jeff Brown5912f952013-07-01 19:10:31 -0700343 }
Jeff Brown5912f952013-07-01 19:10:31 -0700344 }
Jeff Brown5912f952013-07-01 19:10:31 -0700345}
346
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800347std::optional<float> VelocityTracker::getVelocity(int32_t axis, int32_t pointerId) const {
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800348 const auto& it = mConfiguredStrategies.find(axis);
349 if (it != mConfiguredStrategies.end()) {
350 return it->second->getVelocity(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700351 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000352 return {};
Jeff Brown5912f952013-07-01 19:10:31 -0700353}
354
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000355VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units,
356 float maxVelocity) {
357 ComputedVelocity computedVelocity;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700358 for (const auto& [axis, _] : mConfiguredStrategies) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000359 BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits);
360 while (!copyIdBits.isEmpty()) {
361 uint32_t id = copyIdBits.clearFirstMarkedBit();
362 std::optional<float> velocity = getVelocity(axis, id);
363 if (velocity) {
364 float adjustedVelocity =
365 std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity);
366 computedVelocity.addVelocity(axis, id, adjustedVelocity);
367 }
368 }
369 }
370 return computedVelocity;
Jeff Brown5912f952013-07-01 19:10:31 -0700371}
372
Yeabkal Wubshita0e573c2023-03-02 21:08:14 -0800373void AccumulatingVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800374 mIndex.erase(pointerId);
375 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700376}
377
Yeabkal Wubshita0e573c2023-03-02 21:08:14 -0800378void AccumulatingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800379 float position) {
380 // If data for this pointer already exists, we have a valid entry at the position of
381 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
382 // to the next position in the circular buffer and write the new Movement there. Otherwise,
383 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
384 // for this pointer and write to the first position.
385 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
386 auto [indexIt, _] = mIndex.insert({pointerId, 0});
387 size_t& index = indexIt->second;
388 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700389 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
390 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
391 // the new pointer. If the eventtimes for both events are identical, just update the data
392 // for this time.
393 // We only compare against the last value, as it is likely that addMovement is called
394 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800395 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700396 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800397 if (index == HISTORY_SIZE) {
398 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700399 }
400
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800401 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700402 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800403 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700404}
405
Yeabkal Wubshita0e573c2023-03-02 21:08:14 -0800406// --- LeastSquaresVelocityTrackerStrategy ---
407
408LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree,
409 Weighting weighting)
410 : mDegree(degree), mWeighting(weighting) {}
411
412LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {}
413
Jeff Brown5912f952013-07-01 19:10:31 -0700414/**
415 * Solves a linear least squares problem to obtain a N degree polynomial that fits
416 * the specified input data as nearly as possible.
417 *
418 * Returns true if a solution is found, false otherwise.
419 *
420 * The input consists of two vectors of data points X and Y with indices 0..m-1
421 * along with a weight vector W of the same size.
422 *
423 * The output is a vector B with indices 0..n that describes a polynomial
424 * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i]
425 * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized.
426 *
427 * Accordingly, the weight vector W should be initialized by the caller with the
428 * reciprocal square root of the variance of the error in each input data point.
429 * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]).
430 * The weights express the relative importance of each data point. If the weights are
431 * all 1, then the data points are considered to be of equal importance when fitting
432 * the polynomial. It is a good idea to choose weights that diminish the importance
433 * of data points that may have higher than usual error margins.
434 *
435 * Errors among data points are assumed to be independent. W is represented here
436 * as a vector although in the literature it is typically taken to be a diagonal matrix.
437 *
438 * That is to say, the function that generated the input data can be approximated
439 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
440 *
441 * The coefficient of determination (R^2) is also returned to describe the goodness
442 * of fit of the model for the given data. It is a value between 0 and 1, where 1
443 * indicates perfect correspondence.
444 *
445 * This function first expands the X vector to a m by n matrix A such that
446 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then
447 * multiplies it by w[i]./
448 *
449 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
450 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
451 * part is all zeroes), we can simplify the decomposition into an m by n matrix
452 * Q1 and a n by n matrix R1 such that A = Q1 R1.
453 *
454 * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y)
455 * to find B.
456 *
457 * For efficiency, we lay out A and Q column-wise in memory because we frequently
458 * operate on the column vectors. Conversely, we lay out R row-wise.
459 *
460 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
461 * http://en.wikipedia.org/wiki/Gram-Schmidt
462 */
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800463static std::optional<float> solveLeastSquares(const std::vector<float>& x,
464 const std::vector<float>& y,
465 const std::vector<float>& w, uint32_t n) {
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500466 const size_t m = x.size();
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000467
468 ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n),
469 vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str());
470
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500471 LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes");
Jeff Brown5912f952013-07-01 19:10:31 -0700472
473 // Expand the X vector to a matrix A, pre-multiplied by the weights.
474 float a[n][m]; // column-major order
475 for (uint32_t h = 0; h < m; h++) {
476 a[0][h] = w[h];
477 for (uint32_t i = 1; i < n; i++) {
478 a[i][h] = a[i - 1][h] * x[h];
479 }
480 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000481
482 ALOGD_IF(DEBUG_STRATEGY, " - a=%s",
483 matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700484
485 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
486 float q[n][m]; // orthonormal basis, column-major order
487 float r[n][n]; // upper triangular matrix, row-major order
488 for (uint32_t j = 0; j < n; j++) {
489 for (uint32_t h = 0; h < m; h++) {
490 q[j][h] = a[j][h];
491 }
492 for (uint32_t i = 0; i < j; i++) {
493 float dot = vectorDot(&q[j][0], &q[i][0], m);
494 for (uint32_t h = 0; h < m; h++) {
495 q[j][h] -= dot * q[i][h];
496 }
497 }
498
499 float norm = vectorNorm(&q[j][0], m);
500 if (norm < 0.000001f) {
501 // vectors are linearly dependent or zero so no solution
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000502 ALOGD_IF(DEBUG_STRATEGY, " - no solution, norm=%f", norm);
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800503 return {};
Jeff Brown5912f952013-07-01 19:10:31 -0700504 }
505
506 float invNorm = 1.0f / norm;
507 for (uint32_t h = 0; h < m; h++) {
508 q[j][h] *= invNorm;
509 }
510 for (uint32_t i = 0; i < n; i++) {
511 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
512 }
513 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700514 if (DEBUG_STRATEGY) {
515 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str());
516 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700517
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700518 // calculate QR, if we factored A correctly then QR should equal A
519 float qr[n][m];
520 for (uint32_t h = 0; h < m; h++) {
521 for (uint32_t i = 0; i < n; i++) {
522 qr[i][h] = 0;
523 for (uint32_t j = 0; j < n; j++) {
524 qr[i][h] += q[j][h] * r[j][i];
525 }
Jeff Brown5912f952013-07-01 19:10:31 -0700526 }
527 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700528 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700529 }
Jeff Brown5912f952013-07-01 19:10:31 -0700530
531 // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
532 // We just work from bottom-right to top-left calculating B's coefficients.
533 float wy[m];
534 for (uint32_t h = 0; h < m; h++) {
535 wy[h] = y[h] * w[h];
536 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800537 std::array<float, VelocityTracker::MAX_DEGREE + 1> outB;
Dan Austin389ddba2015-09-22 14:32:03 -0700538 for (uint32_t i = n; i != 0; ) {
539 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700540 outB[i] = vectorDot(&q[i][0], wy, m);
541 for (uint32_t j = n - 1; j > i; j--) {
542 outB[i] -= r[i][j] * outB[j];
543 }
544 outB[i] /= r[i][i];
545 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000546
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800547 ALOGD_IF(DEBUG_STRATEGY, " - b=%s", vectorToString(outB.data(), n).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700548
549 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
550 // SSerr is the residual sum of squares (variance of the error),
551 // and SStot is the total sum of squares (variance of the data) where each
552 // has been weighted.
553 float ymean = 0;
554 for (uint32_t h = 0; h < m; h++) {
555 ymean += y[h];
556 }
557 ymean /= m;
558
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800559 if (DEBUG_STRATEGY) {
560 float sserr = 0;
561 float sstot = 0;
562 for (uint32_t h = 0; h < m; h++) {
563 float err = y[h] - outB[0];
564 float term = 1;
565 for (uint32_t i = 1; i < n; i++) {
566 term *= x[h];
567 err -= term * outB[i];
568 }
569 sserr += w[h] * w[h] * err * err;
570 float var = y[h] - ymean;
571 sstot += w[h] * w[h] * var * var;
Jeff Brown5912f952013-07-01 19:10:31 -0700572 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800573 ALOGD(" - sserr=%f", sserr);
574 ALOGD(" - sstot=%f", sstot);
Jeff Brown5912f952013-07-01 19:10:31 -0700575 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000576
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800577 return outB[1];
Jeff Brown5912f952013-07-01 19:10:31 -0700578}
579
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100580/*
581 * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to
582 * the default implementation
583 */
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800584static std::optional<float> solveUnweightedLeastSquaresDeg2(const std::vector<float>& x,
585 const std::vector<float>& y) {
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500586 const size_t count = x.size();
587 LOG_ALWAYS_FATAL_IF(count != y.size(), "Mismatching array sizes");
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700588 // Solving y = a*x^2 + b*x + c
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100589 float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0;
590
591 for (size_t i = 0; i < count; i++) {
592 float xi = x[i];
593 float yi = y[i];
594 float xi2 = xi*xi;
595 float xi3 = xi2*xi;
596 float xi4 = xi3*xi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100597 float xiyi = xi*yi;
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700598 float xi2yi = xi2*yi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100599
600 sxi += xi;
601 sxi2 += xi2;
602 sxiyi += xiyi;
603 sxi2yi += xi2yi;
604 syi += yi;
605 sxi3 += xi3;
606 sxi4 += xi4;
607 }
608
609 float Sxx = sxi2 - sxi*sxi / count;
610 float Sxy = sxiyi - sxi*syi / count;
611 float Sxx2 = sxi3 - sxi*sxi2 / count;
612 float Sx2y = sxi2yi - sxi2*syi / count;
613 float Sx2x2 = sxi4 - sxi2*sxi2 / count;
614
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100615 float denominator = Sxx*Sx2x2 - Sxx2*Sxx2;
616 if (denominator == 0) {
617 ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2);
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700618 return std::nullopt;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100619 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700620
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800621 return (Sxy * Sx2x2 - Sx2y * Sxx2) / denominator;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100622}
623
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800624std::optional<float> LeastSquaresVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800625 const auto movementIt = mMovements.find(pointerId);
626 if (movementIt == mMovements.end()) {
627 return std::nullopt; // no data
628 }
Jeff Brown5912f952013-07-01 19:10:31 -0700629 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000630 std::vector<float> positions;
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500631 std::vector<float> w;
632 std::vector<float> time;
633
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800634 uint32_t index = mIndex.at(pointerId);
635 const Movement& newestMovement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700636 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800637 const Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700638
639 nsecs_t age = newestMovement.eventTime - movement.eventTime;
640 if (age > HORIZON) {
641 break;
642 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800643 if (movement.eventTime == 0 && index != 0) {
644 // All eventTime's are initialized to 0. In this fixed-width circular buffer, it's
645 // possible that not all entries are valid. We use a time=0 as a signal for those
646 // uninitialized values. If we encounter a time of 0 in a position
647 // that's > 0, it means that we hit the block where the data wasn't initialized.
648 // We still don't know whether the value at index=0, with eventTime=0 is valid.
649 // However, that's only possible when the value is by itself. So there's no hard in
650 // processing it anyways, since the velocity for a single point is zero, and this
651 // situation will only be encountered in artificial circumstances (in tests).
652 // In practice, time will never be 0.
653 break;
654 }
655 positions.push_back(movement.position);
656 w.push_back(chooseWeight(pointerId, index));
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500657 time.push_back(-age * 0.000000001f);
Jeff Brown5912f952013-07-01 19:10:31 -0700658 index = (index == 0 ? HISTORY_SIZE : index) - 1;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000659 } while (positions.size() < HISTORY_SIZE);
Jeff Brown5912f952013-07-01 19:10:31 -0700660
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000661 const size_t m = positions.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700662 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800663 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700664 }
665
666 // Calculate a least squares polynomial fit.
667 uint32_t degree = mDegree;
668 if (degree > m - 1) {
669 degree = m - 1;
670 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700671
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800672 if (degree <= 0) {
673 return std::nullopt;
674 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800675 if (degree == 2 && mWeighting == Weighting::NONE) {
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700676 // Optimize unweighted, quadratic polynomial fit
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800677 return solveUnweightedLeastSquaresDeg2(time, positions);
Jeff Brown5912f952013-07-01 19:10:31 -0700678 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800679 // General case for an Nth degree polynomial fit
680 return solveLeastSquares(time, positions, w, degree + 1);
Jeff Brown5912f952013-07-01 19:10:31 -0700681}
682
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800683float LeastSquaresVelocityTrackerStrategy::chooseWeight(int32_t pointerId, uint32_t index) const {
684 const std::array<Movement, HISTORY_SIZE>& movements = mMovements.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700685 switch (mWeighting) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800686 case Weighting::DELTA: {
687 // Weight points based on how much time elapsed between them and the next
688 // point so that points that "cover" a shorter time span are weighed less.
689 // delta 0ms: 0.5
690 // delta 10ms: 1.0
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800691 if (index == mIndex.at(pointerId)) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800692 return 1.0f;
693 }
694 uint32_t nextIndex = (index + 1) % HISTORY_SIZE;
695 float deltaMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800696 (movements[nextIndex].eventTime - movements[index].eventTime) * 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800697 if (deltaMillis < 0) {
698 return 0.5f;
699 }
700 if (deltaMillis < 10) {
701 return 0.5f + deltaMillis * 0.05;
702 }
Jeff Brown5912f952013-07-01 19:10:31 -0700703 return 1.0f;
704 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800705
706 case Weighting::CENTRAL: {
707 // Weight points based on their age, weighing very recent and very old points less.
708 // age 0ms: 0.5
709 // age 10ms: 1.0
710 // age 50ms: 1.0
711 // age 60ms: 0.5
712 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800713 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
714 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800715 if (ageMillis < 0) {
716 return 0.5f;
717 }
718 if (ageMillis < 10) {
719 return 0.5f + ageMillis * 0.05;
720 }
721 if (ageMillis < 50) {
722 return 1.0f;
723 }
724 if (ageMillis < 60) {
725 return 0.5f + (60 - ageMillis) * 0.05;
726 }
Jeff Brown5912f952013-07-01 19:10:31 -0700727 return 0.5f;
728 }
Jeff Brown5912f952013-07-01 19:10:31 -0700729
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800730 case Weighting::RECENT: {
731 // Weight points based on their age, weighing older points less.
732 // age 0ms: 1.0
733 // age 50ms: 1.0
734 // age 100ms: 0.5
735 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800736 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
737 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800738 if (ageMillis < 50) {
739 return 1.0f;
740 }
741 if (ageMillis < 100) {
742 return 0.5f + (100 - ageMillis) * 0.01f;
743 }
Jeff Brown5912f952013-07-01 19:10:31 -0700744 return 0.5f;
745 }
Jeff Brown5912f952013-07-01 19:10:31 -0700746
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800747 case Weighting::NONE:
Jeff Brown5912f952013-07-01 19:10:31 -0700748 return 1.0f;
Jeff Brown5912f952013-07-01 19:10:31 -0700749 }
750}
751
Jeff Brown5912f952013-07-01 19:10:31 -0700752// --- IntegratingVelocityTrackerStrategy ---
753
754IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) :
755 mDegree(degree) {
756}
757
758IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() {
759}
760
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800761void IntegratingVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
762 mPointerIdBits.clearBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700763}
764
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800765void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
766 float position) {
767 State& state = mPointerState[pointerId];
768 if (mPointerIdBits.hasBit(pointerId)) {
769 updateState(state, eventTime, position);
770 } else {
771 initState(state, eventTime, position);
Jeff Brown5912f952013-07-01 19:10:31 -0700772 }
773
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800774 mPointerIdBits.markBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700775}
776
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800777std::optional<float> IntegratingVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800778 if (mPointerIdBits.hasBit(pointerId)) {
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800779 return mPointerState[pointerId].vel;
Jeff Brown5912f952013-07-01 19:10:31 -0700780 }
781
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800782 return std::nullopt;
Jeff Brown5912f952013-07-01 19:10:31 -0700783}
784
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000785void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime,
786 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700787 state.updateTime = eventTime;
788 state.degree = 0;
789
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000790 state.pos = pos;
791 state.accel = 0;
792 state.vel = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700793}
794
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000795void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime,
796 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700797 const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
798 const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
799
800 if (eventTime <= state.updateTime + MIN_TIME_DELTA) {
801 return;
802 }
803
804 float dt = (eventTime - state.updateTime) * 0.000000001f;
805 state.updateTime = eventTime;
806
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000807 float vel = (pos - state.pos) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700808 if (state.degree == 0) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000809 state.vel = vel;
Jeff Brown5912f952013-07-01 19:10:31 -0700810 state.degree = 1;
811 } else {
812 float alpha = dt / (FILTER_TIME_CONSTANT + dt);
813 if (mDegree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000814 state.vel += (vel - state.vel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700815 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000816 float accel = (vel - state.vel) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700817 if (state.degree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000818 state.accel = accel;
Jeff Brown5912f952013-07-01 19:10:31 -0700819 state.degree = 2;
820 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000821 state.accel += (accel - state.accel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700822 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000823 state.vel += (state.accel * dt) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700824 }
825 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000826 state.pos = pos;
Jeff Brown5912f952013-07-01 19:10:31 -0700827}
828
Jeff Brown5912f952013-07-01 19:10:31 -0700829// --- LegacyVelocityTrackerStrategy ---
830
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800831LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() {}
Jeff Brown5912f952013-07-01 19:10:31 -0700832
833LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() {
834}
835
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800836std::optional<float> LegacyVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800837 const auto movementIt = mMovements.find(pointerId);
838 if (movementIt == mMovements.end()) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800839 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700840 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800841 const Movement& newestMovement = movementIt->second[mIndex.at(pointerId)];
Jeff Brown5912f952013-07-01 19:10:31 -0700842
843 // Find the oldest sample that contains the pointer and that is not older than HORIZON.
844 nsecs_t minTime = newestMovement.eventTime - HORIZON;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800845 uint32_t oldestIndex = mIndex.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700846 uint32_t numTouches = 1;
847 do {
848 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800849 const Movement& nextOldestMovement = mMovements.at(pointerId)[nextOldestIndex];
850 if (nextOldestMovement.eventTime < minTime) {
Jeff Brown5912f952013-07-01 19:10:31 -0700851 break;
852 }
853 oldestIndex = nextOldestIndex;
854 } while (++numTouches < HISTORY_SIZE);
855
856 // Calculate an exponentially weighted moving average of the velocity estimate
857 // at different points in time measured relative to the oldest sample.
858 // This is essentially an IIR filter. Newer samples are weighted more heavily
859 // than older samples. Samples at equal time points are weighted more or less
860 // equally.
861 //
862 // One tricky problem is that the sample data may be poorly conditioned.
863 // Sometimes samples arrive very close together in time which can cause us to
864 // overestimate the velocity at that time point. Most samples might be measured
865 // 16ms apart but some consecutive samples could be only 0.5sm apart because
866 // the hardware or driver reports them irregularly or in bursts.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000867 float accumV = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700868 uint32_t index = oldestIndex;
869 uint32_t samplesUsed = 0;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800870 const Movement& oldestMovement = mMovements.at(pointerId)[oldestIndex];
871 float oldestPosition = oldestMovement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700872 nsecs_t lastDuration = 0;
873
874 while (numTouches-- > 1) {
875 if (++index == HISTORY_SIZE) {
876 index = 0;
877 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800878 const Movement& movement = mMovements.at(pointerId)[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700879 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
880
881 // If the duration between samples is small, we may significantly overestimate
882 // the velocity. Consequently, we impose a minimum duration constraint on the
883 // samples that we include in the calculation.
884 if (duration >= MIN_DURATION) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800885 float position = movement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700886 float scale = 1000000000.0f / duration; // one over time delta in seconds
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000887 float v = (position - oldestPosition) * scale;
888 accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration);
Jeff Brown5912f952013-07-01 19:10:31 -0700889 lastDuration = duration;
890 samplesUsed += 1;
891 }
892 }
893
Jeff Brown5912f952013-07-01 19:10:31 -0700894 if (samplesUsed) {
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800895 return accumV;
Jeff Brown5912f952013-07-01 19:10:31 -0700896 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800897 return std::nullopt;
Jeff Brown5912f952013-07-01 19:10:31 -0700898}
899
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100900// --- ImpulseVelocityTrackerStrategy ---
901
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700902ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800903 : mDeltaValues(deltaValues) {}
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100904
905ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() {
906}
907
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100908/**
909 * Calculate the total impulse provided to the screen and the resulting velocity.
910 *
911 * The touchscreen is modeled as a physical object.
912 * Initial condition is discussed below, but for now suppose that v(t=0) = 0
913 *
914 * The kinetic energy of the object at the release is E=0.5*m*v^2
915 * Then vfinal = sqrt(2E/m). The goal is to calculate E.
916 *
917 * The kinetic energy at the release is equal to the total work done on the object by the finger.
918 * The total work W is the sum of all dW along the path.
919 *
920 * dW = F*dx, where dx is the piece of path traveled.
921 * Force is change of momentum over time, F = dp/dt = m dv/dt.
922 * Then substituting:
923 * dW = m (dv/dt) * dx = m * v * dv
924 *
925 * Summing along the path, we get:
926 * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv)
927 * Since the mass stays constant, the equation for final velocity is:
928 * vfinal = sqrt(2*sum(v * dv))
929 *
930 * Here,
931 * dv : change of velocity = (v[i+1]-v[i])
932 * dx : change of distance = (x[i+1]-x[i])
933 * dt : change of time = (t[i+1]-t[i])
934 * v : instantaneous velocity = dx/dt
935 *
936 * The final formula is:
937 * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i
938 * The absolute value is needed to properly account for the sign. If the velocity over a
939 * particular segment descreases, then this indicates braking, which means that negative
940 * work was done. So for two positive, but decreasing, velocities, this contribution would be
941 * negative and will cause a smaller final velocity.
942 *
943 * Initial condition
944 * There are two ways to deal with initial condition:
945 * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest.
946 * This is not entirely accurate. We are only taking the past X ms of touch data, where X is
947 * currently equal to 100. However, a touch event that created a fling probably lasted for longer
948 * than that, which would mean that the user has already been interacting with the touchscreen
949 * and it has probably already been moving.
950 * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this
951 * initial velocity and the equivalent energy, and start with this initial energy.
952 * Consider an example where we have the following data, consisting of 3 points:
953 * time: t0, t1, t2
954 * x : x0, x1, x2
955 * v : 0 , v1, v2
956 * Here is what will happen in each of these scenarios:
957 * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get
958 * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0
959 * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1)))
960 * since velocity is a real number
961 * 2) If we treat the screen as already moving, then it must already have an energy (per mass)
962 * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment
963 * will contribute to the total kinetic energy (since we can effectively consider that v0=v1).
964 * This will give the following expression for the final velocity:
965 * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1)))
966 * This analysis can be generalized to an arbitrary number of samples.
967 *
968 *
969 * Comparing the two equations above, we see that the only mathematical difference
970 * is the factor of 1/2 in front of the first velocity term.
971 * This boundary condition would allow for the "proper" calculation of the case when all of the
972 * samples are equally spaced in time and distance, which should suggest a constant velocity.
973 *
974 * Note that approach 2) is sensitive to the proper ordering of the data in time, since
975 * the boundary condition must be applied to the oldest sample to be accurate.
976 */
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -0700977static float kineticEnergyToVelocity(float work) {
978 static constexpr float sqrt2 = 1.41421356237;
979 return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2;
980}
981
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700982static float calculateImpulseVelocity(const nsecs_t* t, const float* x, size_t count,
983 bool deltaValues) {
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100984 // The input should be in reversed time order (most recent sample at index i=0)
985 // t[i] is in nanoseconds, but due to FP arithmetic, convert to seconds inside this function
Siarhei Vishniakou6de8f5e2018-03-02 18:48:15 -0800986 static constexpr float SECONDS_PER_NANO = 1E-9;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100987
988 if (count < 2) {
989 return 0; // if 0 or 1 points, velocity is zero
990 }
991 if (t[1] > t[0]) { // Algorithm will still work, but not perfectly
992 ALOGE("Samples provided to calculateImpulseVelocity in the wrong order");
993 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700994
995 // If the data values are delta values, we do not have to calculate deltas here.
996 // We can use the delta values directly, along with the calculated time deltas.
997 // Since the data value input is in reversed time order:
998 // [a] for non-delta inputs, instantenous velocity = (x[i] - x[i-1])/(t[i] - t[i-1])
999 // [b] for delta inputs, instantenous velocity = -x[i-1]/(t[i] - t[i - 1])
1000 // e.g., let the non-delta values are: V = [2, 3, 7], the equivalent deltas are D = [2, 1, 4].
1001 // Since the input is in reversed time order, the input values for this function would be
1002 // V'=[7, 3, 2] and D'=[4, 1, 2] for the non-delta and delta values, respectively.
1003 //
1004 // The equivalent of {(V'[2] - V'[1]) = 2 - 3 = -1} would be {-D'[1] = -1}
1005 // Similarly, the equivalent of {(V'[1] - V'[0]) = 3 - 7 = -4} would be {-D'[0] = -4}
1006
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001007 if (count == 2) { // if 2 points, basic linear calculation
1008 if (t[1] == t[0]) {
1009 ALOGE("Events have identical time stamps t=%" PRId64 ", setting velocity = 0", t[0]);
1010 return 0;
1011 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001012 const float deltaX = deltaValues ? -x[0] : x[1] - x[0];
1013 return deltaX / (SECONDS_PER_NANO * (t[1] - t[0]));
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001014 }
1015 // Guaranteed to have at least 3 points here
1016 float work = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001017 for (size_t i = count - 1; i > 0 ; i--) { // start with the oldest sample and go forward in time
1018 if (t[i] == t[i-1]) {
1019 ALOGE("Events have identical time stamps t=%" PRId64 ", skipping sample", t[i]);
1020 continue;
1021 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001022 float vprev = kineticEnergyToVelocity(work); // v[i-1]
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001023 const float deltaX = deltaValues ? -x[i-1] : x[i] - x[i-1];
1024 float vcurr = deltaX / (SECONDS_PER_NANO * (t[i] - t[i-1])); // v[i]
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001025 work += (vcurr - vprev) * fabsf(vcurr);
1026 if (i == count - 1) {
1027 work *= 0.5; // initial condition, case 2) above
1028 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001029 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001030 return kineticEnergyToVelocity(work);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001031}
1032
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -08001033std::optional<float> ImpulseVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001034 const auto movementIt = mMovements.find(pointerId);
1035 if (movementIt == mMovements.end()) {
1036 return std::nullopt; // no data
1037 }
1038
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001039 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001040 float positions[HISTORY_SIZE];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001041 nsecs_t time[HISTORY_SIZE];
1042 size_t m = 0; // number of points that will be used for fitting
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001043 size_t index = mIndex.at(pointerId);
1044 const Movement& newestMovement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001045 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001046 const Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001047
1048 nsecs_t age = newestMovement.eventTime - movement.eventTime;
1049 if (age > HORIZON) {
1050 break;
1051 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001052 if (movement.eventTime == 0 && index != 0) {
1053 // All eventTime's are initialized to 0. If we encounter a time of 0 in a position
1054 // that's >0, it means that we hit the block where the data wasn't initialized.
1055 // It's also possible that the sample at 0 would be invalid, but there's no harm in
1056 // processing it, since it would be just a single point, and will only be encountered
1057 // in artificial circumstances (in tests).
1058 break;
1059 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001060
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001061 positions[m] = movement.position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001062 time[m] = movement.eventTime;
1063 index = (index == 0 ? HISTORY_SIZE : index) - 1;
1064 } while (++m < HISTORY_SIZE);
1065
1066 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001067 return std::nullopt; // no data
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001068 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001069
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -08001070 const float velocity = calculateImpulseVelocity(time, positions, m, mDeltaValues);
1071 ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", velocity);
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +00001072
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001073 if (DEBUG_IMPULSE) {
1074 // TODO(b/134179997): delete this block once the switch to 'impulse' is complete.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001075 // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons.
1076 // X axis chosen arbitrarily for velocity comparisons.
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001077 VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001078 for (ssize_t i = m - 1; i >= 0; i--) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001079 lsq2.addMovement(time[i], pointerId, AMOTION_EVENT_AXIS_X, positions[i]);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001080 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001081 std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001082 if (v) {
1083 ALOGD("lsq2 velocity: %.1f", *v);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001084 } else {
1085 ALOGD("lsq2 velocity: could not compute velocity");
1086 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -07001087 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -08001088 return velocity;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001089}
1090
Jeff Brown5912f952013-07-01 19:10:31 -07001091} // namespace android