Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1 | /* |
| 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 Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 18 | |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 19 | #include <array> |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 20 | #include <inttypes.h> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 21 | #include <limits.h> |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 22 | #include <math.h> |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 23 | #include <optional> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 24 | |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 25 | #include <android-base/stringprintf.h> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 26 | #include <input/VelocityTracker.h> |
| 27 | #include <utils/BitSet.h> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 28 | #include <utils/Timers.h> |
| 29 | |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 30 | using std::literals::chrono_literals::operator""ms; |
| 31 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 32 | namespace android { |
| 33 | |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 34 | /** |
| 35 | * Log debug messages about velocity tracking. |
| 36 | * Enable this via "adb shell setprop log.tag.VelocityTrackerVelocity DEBUG" (requires restart) |
| 37 | */ |
| 38 | const bool DEBUG_VELOCITY = |
| 39 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Velocity", ANDROID_LOG_INFO); |
| 40 | |
| 41 | /** |
| 42 | * Log debug messages about the progress of the algorithm itself. |
| 43 | * Enable this via "adb shell setprop log.tag.VelocityTrackerStrategy DEBUG" (requires restart) |
| 44 | */ |
| 45 | const bool DEBUG_STRATEGY = |
| 46 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Strategy", ANDROID_LOG_INFO); |
| 47 | |
| 48 | /** |
| 49 | * Log debug messages about the 'impulse' strategy. |
| 50 | * Enable this via "adb shell setprop log.tag.VelocityTrackerImpulse DEBUG" (requires restart) |
| 51 | */ |
| 52 | const bool DEBUG_IMPULSE = |
| 53 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Impulse", ANDROID_LOG_INFO); |
| 54 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 55 | // Nanoseconds per milliseconds. |
| 56 | static const nsecs_t NANOS_PER_MS = 1000000; |
| 57 | |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 58 | // All axes supported for velocity tracking, mapped to their default strategies. |
| 59 | // Although other strategies are available for testing and comparison purposes, |
| 60 | // the default strategy is the one that applications will actually use. Be very careful |
| 61 | // when adjusting the default strategy because it can dramatically affect |
| 62 | // (often in a bad way) the user experience. |
| 63 | static const std::map<int32_t, VelocityTracker::Strategy> DEFAULT_STRATEGY_BY_AXIS = |
| 64 | {{AMOTION_EVENT_AXIS_X, VelocityTracker::Strategy::LSQ2}, |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 65 | {AMOTION_EVENT_AXIS_Y, VelocityTracker::Strategy::LSQ2}, |
| 66 | {AMOTION_EVENT_AXIS_SCROLL, VelocityTracker::Strategy::IMPULSE}}; |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 67 | |
| 68 | // Axes specifying location on a 2D plane (i.e. X and Y). |
| 69 | static const std::set<int32_t> PLANAR_AXES = {AMOTION_EVENT_AXIS_X, AMOTION_EVENT_AXIS_Y}; |
| 70 | |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 71 | // Axes whose motion values are differential values (i.e. deltas). |
| 72 | static const std::set<int32_t> DIFFERENTIAL_AXES = {AMOTION_EVENT_AXIS_SCROLL}; |
| 73 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 74 | // Threshold for determining that a pointer has stopped moving. |
| 75 | // Some input devices do not send ACTION_MOVE events in the case where a pointer has |
| 76 | // stopped. We need to detect this case so that we can accurately predict the |
| 77 | // velocity after the pointer starts moving again. |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 78 | static const std::chrono::duration ASSUME_POINTER_STOPPED_TIME = 40ms; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 79 | |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 80 | static std::string toString(std::chrono::nanoseconds t) { |
| 81 | std::stringstream stream; |
| 82 | stream.precision(1); |
| 83 | stream << std::fixed << std::chrono::duration<float, std::milli>(t).count() << " ms"; |
| 84 | return stream.str(); |
| 85 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 86 | |
| 87 | static float vectorDot(const float* a, const float* b, uint32_t m) { |
| 88 | float r = 0; |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 89 | for (size_t i = 0; i < m; i++) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 90 | r += *(a++) * *(b++); |
| 91 | } |
| 92 | return r; |
| 93 | } |
| 94 | |
| 95 | static float vectorNorm(const float* a, uint32_t m) { |
| 96 | float r = 0; |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 97 | for (size_t i = 0; i < m; i++) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 98 | float t = *(a++); |
| 99 | r += t * t; |
| 100 | } |
| 101 | return sqrtf(r); |
| 102 | } |
| 103 | |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 104 | static std::string vectorToString(const float* a, uint32_t m) { |
| 105 | std::string str; |
| 106 | str += "["; |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 107 | for (size_t i = 0; i < m; i++) { |
| 108 | if (i) { |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 109 | str += ","; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 110 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 111 | str += android::base::StringPrintf(" %f", *(a++)); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 112 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 113 | str += " ]"; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 114 | return str; |
| 115 | } |
| 116 | |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 117 | static std::string vectorToString(const std::vector<float>& v) { |
| 118 | return vectorToString(v.data(), v.size()); |
| 119 | } |
| 120 | |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 121 | static std::string matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) { |
| 122 | std::string str; |
| 123 | str = "["; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 124 | for (size_t i = 0; i < m; i++) { |
| 125 | if (i) { |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 126 | str += ","; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 127 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 128 | str += " ["; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 129 | for (size_t j = 0; j < n; j++) { |
| 130 | if (j) { |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 131 | str += ","; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 132 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 133 | str += android::base::StringPrintf(" %f", a[rowMajor ? i * n + j : j * m + i]); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 134 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 135 | str += " ]"; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 136 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 137 | str += " ]"; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 138 | return str; |
| 139 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 140 | |
| 141 | |
| 142 | // --- VelocityTracker --- |
| 143 | |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 144 | VelocityTracker::VelocityTracker(const Strategy strategy) |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 145 | : mLastEventTime(0), |
| 146 | mCurrentPointerIdBits(0), |
| 147 | mActivePointerId(-1), |
| 148 | mOverrideStrategy(strategy) {} |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 149 | |
| 150 | VelocityTracker::~VelocityTracker() { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 151 | } |
| 152 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 153 | void VelocityTracker::configureStrategy(int32_t axis) { |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 154 | const bool isDifferentialAxis = DIFFERENTIAL_AXES.find(axis) != DIFFERENTIAL_AXES.end(); |
| 155 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 156 | std::unique_ptr<VelocityTrackerStrategy> createdStrategy; |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 157 | if (mOverrideStrategy != VelocityTracker::Strategy::DEFAULT) { |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 158 | createdStrategy = createStrategy(mOverrideStrategy, isDifferentialAxis /* deltaValues */); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 159 | } else { |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 160 | createdStrategy = createStrategy(DEFAULT_STRATEGY_BY_AXIS.at(axis), |
| 161 | isDifferentialAxis /* deltaValues */); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 162 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 163 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 164 | LOG_ALWAYS_FATAL_IF(createdStrategy == nullptr, |
| 165 | "Could not create velocity tracker strategy for axis '%" PRId32 "'!", axis); |
| 166 | mConfiguredStrategies[axis] = std::move(createdStrategy); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 167 | } |
| 168 | |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 169 | std::unique_ptr<VelocityTrackerStrategy> VelocityTracker::createStrategy( |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 170 | VelocityTracker::Strategy strategy, bool deltaValues) { |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 171 | switch (strategy) { |
| 172 | case VelocityTracker::Strategy::IMPULSE: |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 173 | ALOGI_IF(DEBUG_STRATEGY, "Initializing impulse strategy"); |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 174 | return std::make_unique<ImpulseVelocityTrackerStrategy>(deltaValues); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 175 | |
| 176 | case VelocityTracker::Strategy::LSQ1: |
| 177 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(1); |
| 178 | |
| 179 | case VelocityTracker::Strategy::LSQ2: |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 180 | ALOGI_IF(DEBUG_STRATEGY && !DEBUG_IMPULSE, "Initializing lsq2 strategy"); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 181 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(2); |
| 182 | |
| 183 | case VelocityTracker::Strategy::LSQ3: |
| 184 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(3); |
| 185 | |
| 186 | case VelocityTracker::Strategy::WLSQ2_DELTA: |
| 187 | return std::make_unique< |
| 188 | LeastSquaresVelocityTrackerStrategy>(2, |
| 189 | LeastSquaresVelocityTrackerStrategy:: |
| 190 | WEIGHTING_DELTA); |
| 191 | case VelocityTracker::Strategy::WLSQ2_CENTRAL: |
| 192 | return std::make_unique< |
| 193 | LeastSquaresVelocityTrackerStrategy>(2, |
| 194 | LeastSquaresVelocityTrackerStrategy:: |
| 195 | WEIGHTING_CENTRAL); |
| 196 | case VelocityTracker::Strategy::WLSQ2_RECENT: |
| 197 | return std::make_unique< |
| 198 | LeastSquaresVelocityTrackerStrategy>(2, |
| 199 | LeastSquaresVelocityTrackerStrategy:: |
| 200 | WEIGHTING_RECENT); |
| 201 | |
| 202 | case VelocityTracker::Strategy::INT1: |
| 203 | return std::make_unique<IntegratingVelocityTrackerStrategy>(1); |
| 204 | |
| 205 | case VelocityTracker::Strategy::INT2: |
| 206 | return std::make_unique<IntegratingVelocityTrackerStrategy>(2); |
| 207 | |
| 208 | case VelocityTracker::Strategy::LEGACY: |
| 209 | return std::make_unique<LegacyVelocityTrackerStrategy>(); |
| 210 | |
| 211 | default: |
| 212 | break; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 213 | } |
Yi Kong | 5bed83b | 2018-07-17 12:53:47 -0700 | [diff] [blame] | 214 | return nullptr; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 215 | } |
| 216 | |
| 217 | void VelocityTracker::clear() { |
| 218 | mCurrentPointerIdBits.clear(); |
| 219 | mActivePointerId = -1; |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 220 | mConfiguredStrategies.clear(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 221 | } |
| 222 | |
| 223 | void VelocityTracker::clearPointers(BitSet32 idBits) { |
| 224 | BitSet32 remainingIdBits(mCurrentPointerIdBits.value & ~idBits.value); |
| 225 | mCurrentPointerIdBits = remainingIdBits; |
| 226 | |
| 227 | if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) { |
| 228 | mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1; |
| 229 | } |
| 230 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 231 | for (const auto& [_, strategy] : mConfiguredStrategies) { |
| 232 | strategy->clearPointers(idBits); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 233 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 234 | } |
| 235 | |
Siarhei Vishniakou | ae0f990 | 2020-09-14 19:23:31 -0500 | [diff] [blame] | 236 | void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 237 | const std::map<int32_t /*axis*/, std::vector<float>>& positions) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 238 | while (idBits.count() > MAX_POINTERS) { |
| 239 | idBits.clearLastMarkedBit(); |
| 240 | } |
| 241 | |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 242 | if ((mCurrentPointerIdBits.value & idBits.value) && |
| 243 | std::chrono::nanoseconds(eventTime - mLastEventTime) > ASSUME_POINTER_STOPPED_TIME) { |
| 244 | ALOGD_IF(DEBUG_VELOCITY, "VelocityTracker: stopped for %s, clearing state.", |
| 245 | toString(std::chrono::nanoseconds(eventTime - mLastEventTime)).c_str()); |
| 246 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 247 | // We have not received any movements for too long. Assume that all pointers |
| 248 | // have stopped. |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 249 | mConfiguredStrategies.clear(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 250 | } |
| 251 | mLastEventTime = eventTime; |
| 252 | |
| 253 | mCurrentPointerIdBits = idBits; |
| 254 | if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) { |
| 255 | mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit(); |
| 256 | } |
| 257 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 258 | for (const auto& [axis, positionValues] : positions) { |
| 259 | LOG_ALWAYS_FATAL_IF(idBits.count() != positionValues.size(), |
| 260 | "Mismatching number of pointers, idBits=%" PRIu32 ", positions=%zu", |
| 261 | idBits.count(), positionValues.size()); |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 262 | if (mConfiguredStrategies.find(axis) == mConfiguredStrategies.end()) { |
| 263 | configureStrategy(axis); |
| 264 | } |
| 265 | mConfiguredStrategies[axis]->addMovement(eventTime, idBits, positionValues); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 266 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 267 | |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 268 | if (DEBUG_VELOCITY) { |
| 269 | ALOGD("VelocityTracker: addMovement eventTime=%" PRId64 |
| 270 | ", idBits=0x%08x, activePointerId=%d", |
| 271 | eventTime, idBits.value, mActivePointerId); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 272 | for (const auto& positionsEntry : positions) { |
| 273 | for (BitSet32 iterBits(idBits); !iterBits.isEmpty();) { |
| 274 | uint32_t id = iterBits.firstMarkedBit(); |
| 275 | uint32_t index = idBits.getIndexOfBit(id); |
| 276 | iterBits.clearBit(id); |
| 277 | Estimator estimator; |
| 278 | getEstimator(positionsEntry.first, id, &estimator); |
| 279 | ALOGD(" %d: axis=%d, position=%0.3f, " |
| 280 | "estimator (degree=%d, coeff=%s, confidence=%f)", |
| 281 | id, positionsEntry.first, positionsEntry.second[index], int(estimator.degree), |
| 282 | vectorToString(estimator.coeff, estimator.degree + 1).c_str(), |
| 283 | estimator.confidence); |
| 284 | } |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 285 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 286 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 287 | } |
| 288 | |
| 289 | void VelocityTracker::addMovement(const MotionEvent* event) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 290 | // Stores data about which axes to process based on the incoming motion event. |
| 291 | std::set<int32_t> axesToProcess; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 292 | int32_t actionMasked = event->getActionMasked(); |
| 293 | |
| 294 | switch (actionMasked) { |
| 295 | case AMOTION_EVENT_ACTION_DOWN: |
| 296 | case AMOTION_EVENT_ACTION_HOVER_ENTER: |
| 297 | // Clear all pointers on down before adding the new movement. |
| 298 | clear(); |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 299 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 300 | break; |
| 301 | case AMOTION_EVENT_ACTION_POINTER_DOWN: { |
| 302 | // Start a new movement trace for a pointer that just went down. |
| 303 | // We do this on down instead of on up because the client may want to query the |
| 304 | // final velocity for a pointer that just went up. |
| 305 | BitSet32 downIdBits; |
| 306 | downIdBits.markBit(event->getPointerId(event->getActionIndex())); |
| 307 | clearPointers(downIdBits); |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 308 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 309 | break; |
| 310 | } |
| 311 | case AMOTION_EVENT_ACTION_MOVE: |
| 312 | case AMOTION_EVENT_ACTION_HOVER_MOVE: |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 313 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 314 | break; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 315 | case AMOTION_EVENT_ACTION_POINTER_UP: |
| 316 | case AMOTION_EVENT_ACTION_UP: { |
| 317 | std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime); |
| 318 | if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) { |
| 319 | ALOGD_IF(DEBUG_VELOCITY, |
| 320 | "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.", |
| 321 | toString(delaySinceLastEvent).c_str()); |
| 322 | // We have not received any movements for too long. Assume that all pointers |
| 323 | // have stopped. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 324 | for (int32_t axis : PLANAR_AXES) { |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 325 | mConfiguredStrategies.erase(axis); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 326 | } |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 327 | } |
| 328 | // These actions because they do not convey any new information about |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 329 | // pointer movement. We also want to preserve the last known velocity of the pointers. |
| 330 | // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position |
| 331 | // of the pointers that went up. ACTION_POINTER_UP does include the new position of |
| 332 | // pointers that remained down but we will also receive an ACTION_MOVE with this |
| 333 | // information if any of them actually moved. Since we don't know how many pointers |
| 334 | // will be going up at once it makes sense to just wait for the following ACTION_MOVE |
| 335 | // before adding the movement. |
| 336 | return; |
| 337 | } |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 338 | case AMOTION_EVENT_ACTION_SCROLL: |
| 339 | axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL); |
| 340 | break; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 341 | default: |
| 342 | // Ignore all other actions. |
| 343 | return; |
| 344 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 345 | |
| 346 | size_t pointerCount = event->getPointerCount(); |
| 347 | if (pointerCount > MAX_POINTERS) { |
| 348 | pointerCount = MAX_POINTERS; |
| 349 | } |
| 350 | |
| 351 | BitSet32 idBits; |
| 352 | for (size_t i = 0; i < pointerCount; i++) { |
| 353 | idBits.markBit(event->getPointerId(i)); |
| 354 | } |
| 355 | |
| 356 | uint32_t pointerIndex[MAX_POINTERS]; |
| 357 | for (size_t i = 0; i < pointerCount; i++) { |
| 358 | pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i)); |
| 359 | } |
| 360 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 361 | std::map<int32_t, std::vector<float>> positions; |
| 362 | for (int32_t axis : axesToProcess) { |
| 363 | positions[axis].resize(pointerCount); |
| 364 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 365 | |
| 366 | size_t historySize = event->getHistorySize(); |
Siarhei Vishniakou | 69e4d0f | 2020-09-14 19:53:29 -0500 | [diff] [blame] | 367 | for (size_t h = 0; h <= historySize; h++) { |
| 368 | nsecs_t eventTime = event->getHistoricalEventTime(h); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 369 | for (int32_t axis : axesToProcess) { |
| 370 | for (size_t i = 0; i < pointerCount; i++) { |
| 371 | positions[axis][pointerIndex[i]] = event->getHistoricalAxisValue(axis, i, h); |
| 372 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 373 | } |
| 374 | addMovement(eventTime, idBits, positions); |
| 375 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 376 | } |
| 377 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 378 | std::optional<float> VelocityTracker::getVelocity(int32_t axis, uint32_t id) const { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 379 | Estimator estimator; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 380 | bool validVelocity = getEstimator(axis, id, &estimator) && estimator.degree >= 1; |
| 381 | if (validVelocity) { |
| 382 | return estimator.coeff[1]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 383 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 384 | return {}; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 385 | } |
| 386 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 387 | VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units, |
| 388 | float maxVelocity) { |
| 389 | ComputedVelocity computedVelocity; |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 390 | for (const auto& [axis, _] : mConfiguredStrategies) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 391 | BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits); |
| 392 | while (!copyIdBits.isEmpty()) { |
| 393 | uint32_t id = copyIdBits.clearFirstMarkedBit(); |
| 394 | std::optional<float> velocity = getVelocity(axis, id); |
| 395 | if (velocity) { |
| 396 | float adjustedVelocity = |
| 397 | std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity); |
| 398 | computedVelocity.addVelocity(axis, id, adjustedVelocity); |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | return computedVelocity; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 403 | } |
| 404 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 405 | bool VelocityTracker::getEstimator(int32_t axis, uint32_t id, Estimator* outEstimator) const { |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 406 | const auto& it = mConfiguredStrategies.find(axis); |
| 407 | if (it == mConfiguredStrategies.end()) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 408 | return false; |
| 409 | } |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 410 | return it->second->getEstimator(id, outEstimator); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 411 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 412 | |
| 413 | // --- LeastSquaresVelocityTrackerStrategy --- |
| 414 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 415 | LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree, |
| 416 | Weighting weighting) |
| 417 | : mDegree(degree), mWeighting(weighting), mIndex(0) {} |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 418 | |
| 419 | LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() { |
| 420 | } |
| 421 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 422 | void LeastSquaresVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { |
| 423 | BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); |
| 424 | mMovements[mIndex].idBits = remainingIdBits; |
| 425 | } |
| 426 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 427 | void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, |
| 428 | const std::vector<float>& positions) { |
Siarhei Vishniakou | 346ac6a | 2019-04-10 09:58:05 -0700 | [diff] [blame] | 429 | if (mMovements[mIndex].eventTime != eventTime) { |
| 430 | // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates |
| 431 | // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include |
| 432 | // the new pointer. If the eventtimes for both events are identical, just update the data |
| 433 | // for this time. |
| 434 | // We only compare against the last value, as it is likely that addMovement is called |
| 435 | // in chronological order as events occur. |
| 436 | mIndex++; |
| 437 | } |
| 438 | if (mIndex == HISTORY_SIZE) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 439 | mIndex = 0; |
| 440 | } |
| 441 | |
| 442 | Movement& movement = mMovements[mIndex]; |
| 443 | movement.eventTime = eventTime; |
| 444 | movement.idBits = idBits; |
| 445 | uint32_t count = idBits.count(); |
| 446 | for (uint32_t i = 0; i < count; i++) { |
| 447 | movement.positions[i] = positions[i]; |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | /** |
| 452 | * Solves a linear least squares problem to obtain a N degree polynomial that fits |
| 453 | * the specified input data as nearly as possible. |
| 454 | * |
| 455 | * Returns true if a solution is found, false otherwise. |
| 456 | * |
| 457 | * The input consists of two vectors of data points X and Y with indices 0..m-1 |
| 458 | * along with a weight vector W of the same size. |
| 459 | * |
| 460 | * The output is a vector B with indices 0..n that describes a polynomial |
| 461 | * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i] |
| 462 | * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized. |
| 463 | * |
| 464 | * Accordingly, the weight vector W should be initialized by the caller with the |
| 465 | * reciprocal square root of the variance of the error in each input data point. |
| 466 | * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]). |
| 467 | * The weights express the relative importance of each data point. If the weights are |
| 468 | * all 1, then the data points are considered to be of equal importance when fitting |
| 469 | * the polynomial. It is a good idea to choose weights that diminish the importance |
| 470 | * of data points that may have higher than usual error margins. |
| 471 | * |
| 472 | * Errors among data points are assumed to be independent. W is represented here |
| 473 | * as a vector although in the literature it is typically taken to be a diagonal matrix. |
| 474 | * |
| 475 | * That is to say, the function that generated the input data can be approximated |
| 476 | * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n. |
| 477 | * |
| 478 | * The coefficient of determination (R^2) is also returned to describe the goodness |
| 479 | * of fit of the model for the given data. It is a value between 0 and 1, where 1 |
| 480 | * indicates perfect correspondence. |
| 481 | * |
| 482 | * This function first expands the X vector to a m by n matrix A such that |
| 483 | * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then |
| 484 | * multiplies it by w[i]./ |
| 485 | * |
| 486 | * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q |
| 487 | * and an m by n upper triangular matrix R. Because R is upper triangular (lower |
| 488 | * part is all zeroes), we can simplify the decomposition into an m by n matrix |
| 489 | * Q1 and a n by n matrix R1 such that A = Q1 R1. |
| 490 | * |
| 491 | * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y) |
| 492 | * to find B. |
| 493 | * |
| 494 | * For efficiency, we lay out A and Q column-wise in memory because we frequently |
| 495 | * operate on the column vectors. Conversely, we lay out R row-wise. |
| 496 | * |
| 497 | * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares |
| 498 | * http://en.wikipedia.org/wiki/Gram-Schmidt |
| 499 | */ |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 500 | static bool solveLeastSquares(const std::vector<float>& x, const std::vector<float>& y, |
| 501 | const std::vector<float>& w, uint32_t n, float* outB, float* outDet) { |
| 502 | const size_t m = x.size(); |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 503 | |
| 504 | ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n), |
| 505 | vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str()); |
| 506 | |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 507 | LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes"); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 508 | |
| 509 | // Expand the X vector to a matrix A, pre-multiplied by the weights. |
| 510 | float a[n][m]; // column-major order |
| 511 | for (uint32_t h = 0; h < m; h++) { |
| 512 | a[0][h] = w[h]; |
| 513 | for (uint32_t i = 1; i < n; i++) { |
| 514 | a[i][h] = a[i - 1][h] * x[h]; |
| 515 | } |
| 516 | } |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 517 | |
| 518 | ALOGD_IF(DEBUG_STRATEGY, " - a=%s", |
| 519 | matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 520 | |
| 521 | // Apply the Gram-Schmidt process to A to obtain its QR decomposition. |
| 522 | float q[n][m]; // orthonormal basis, column-major order |
| 523 | float r[n][n]; // upper triangular matrix, row-major order |
| 524 | for (uint32_t j = 0; j < n; j++) { |
| 525 | for (uint32_t h = 0; h < m; h++) { |
| 526 | q[j][h] = a[j][h]; |
| 527 | } |
| 528 | for (uint32_t i = 0; i < j; i++) { |
| 529 | float dot = vectorDot(&q[j][0], &q[i][0], m); |
| 530 | for (uint32_t h = 0; h < m; h++) { |
| 531 | q[j][h] -= dot * q[i][h]; |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | float norm = vectorNorm(&q[j][0], m); |
| 536 | if (norm < 0.000001f) { |
| 537 | // vectors are linearly dependent or zero so no solution |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 538 | ALOGD_IF(DEBUG_STRATEGY, " - no solution, norm=%f", norm); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 539 | return false; |
| 540 | } |
| 541 | |
| 542 | float invNorm = 1.0f / norm; |
| 543 | for (uint32_t h = 0; h < m; h++) { |
| 544 | q[j][h] *= invNorm; |
| 545 | } |
| 546 | for (uint32_t i = 0; i < n; i++) { |
| 547 | r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m); |
| 548 | } |
| 549 | } |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 550 | if (DEBUG_STRATEGY) { |
| 551 | ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str()); |
| 552 | ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 553 | |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 554 | // calculate QR, if we factored A correctly then QR should equal A |
| 555 | float qr[n][m]; |
| 556 | for (uint32_t h = 0; h < m; h++) { |
| 557 | for (uint32_t i = 0; i < n; i++) { |
| 558 | qr[i][h] = 0; |
| 559 | for (uint32_t j = 0; j < n; j++) { |
| 560 | qr[i][h] += q[j][h] * r[j][i]; |
| 561 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 562 | } |
| 563 | } |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 564 | ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 565 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 566 | |
| 567 | // Solve R B = Qt W Y to find B. This is easy because R is upper triangular. |
| 568 | // We just work from bottom-right to top-left calculating B's coefficients. |
| 569 | float wy[m]; |
| 570 | for (uint32_t h = 0; h < m; h++) { |
| 571 | wy[h] = y[h] * w[h]; |
| 572 | } |
Dan Austin | 389ddba | 2015-09-22 14:32:03 -0700 | [diff] [blame] | 573 | for (uint32_t i = n; i != 0; ) { |
| 574 | i--; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 575 | outB[i] = vectorDot(&q[i][0], wy, m); |
| 576 | for (uint32_t j = n - 1; j > i; j--) { |
| 577 | outB[i] -= r[i][j] * outB[j]; |
| 578 | } |
| 579 | outB[i] /= r[i][i]; |
| 580 | } |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 581 | |
| 582 | ALOGD_IF(DEBUG_STRATEGY, " - b=%s", vectorToString(outB, n).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 583 | |
| 584 | // Calculate the coefficient of determination as 1 - (SSerr / SStot) where |
| 585 | // SSerr is the residual sum of squares (variance of the error), |
| 586 | // and SStot is the total sum of squares (variance of the data) where each |
| 587 | // has been weighted. |
| 588 | float ymean = 0; |
| 589 | for (uint32_t h = 0; h < m; h++) { |
| 590 | ymean += y[h]; |
| 591 | } |
| 592 | ymean /= m; |
| 593 | |
| 594 | float sserr = 0; |
| 595 | float sstot = 0; |
| 596 | for (uint32_t h = 0; h < m; h++) { |
| 597 | float err = y[h] - outB[0]; |
| 598 | float term = 1; |
| 599 | for (uint32_t i = 1; i < n; i++) { |
| 600 | term *= x[h]; |
| 601 | err -= term * outB[i]; |
| 602 | } |
| 603 | sserr += w[h] * w[h] * err * err; |
| 604 | float var = y[h] - ymean; |
| 605 | sstot += w[h] * w[h] * var * var; |
| 606 | } |
| 607 | *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 608 | |
| 609 | ALOGD_IF(DEBUG_STRATEGY, " - sserr=%f", sserr); |
| 610 | ALOGD_IF(DEBUG_STRATEGY, " - sstot=%f", sstot); |
| 611 | ALOGD_IF(DEBUG_STRATEGY, " - det=%f", *outDet); |
| 612 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 613 | return true; |
| 614 | } |
| 615 | |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 616 | /* |
| 617 | * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to |
| 618 | * the default implementation |
| 619 | */ |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 620 | static std::optional<std::array<float, 3>> solveUnweightedLeastSquaresDeg2( |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 621 | const std::vector<float>& x, const std::vector<float>& y) { |
| 622 | const size_t count = x.size(); |
| 623 | LOG_ALWAYS_FATAL_IF(count != y.size(), "Mismatching array sizes"); |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 624 | // Solving y = a*x^2 + b*x + c |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 625 | float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0; |
| 626 | |
| 627 | for (size_t i = 0; i < count; i++) { |
| 628 | float xi = x[i]; |
| 629 | float yi = y[i]; |
| 630 | float xi2 = xi*xi; |
| 631 | float xi3 = xi2*xi; |
| 632 | float xi4 = xi3*xi; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 633 | float xiyi = xi*yi; |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 634 | float xi2yi = xi2*yi; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 635 | |
| 636 | sxi += xi; |
| 637 | sxi2 += xi2; |
| 638 | sxiyi += xiyi; |
| 639 | sxi2yi += xi2yi; |
| 640 | syi += yi; |
| 641 | sxi3 += xi3; |
| 642 | sxi4 += xi4; |
| 643 | } |
| 644 | |
| 645 | float Sxx = sxi2 - sxi*sxi / count; |
| 646 | float Sxy = sxiyi - sxi*syi / count; |
| 647 | float Sxx2 = sxi3 - sxi*sxi2 / count; |
| 648 | float Sx2y = sxi2yi - sxi2*syi / count; |
| 649 | float Sx2x2 = sxi4 - sxi2*sxi2 / count; |
| 650 | |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 651 | float denominator = Sxx*Sx2x2 - Sxx2*Sxx2; |
| 652 | if (denominator == 0) { |
| 653 | ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2); |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 654 | return std::nullopt; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 655 | } |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 656 | // Compute a |
| 657 | float numerator = Sx2y*Sxx - Sxy*Sxx2; |
| 658 | float a = numerator / denominator; |
| 659 | |
| 660 | // Compute b |
| 661 | numerator = Sxy*Sx2x2 - Sx2y*Sxx2; |
| 662 | float b = numerator / denominator; |
| 663 | |
| 664 | // Compute c |
| 665 | float c = syi/count - b * sxi/count - a * sxi2/count; |
| 666 | |
| 667 | return std::make_optional(std::array<float, 3>({c, b, a})); |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 668 | } |
| 669 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 670 | bool LeastSquaresVelocityTrackerStrategy::getEstimator(uint32_t id, |
| 671 | VelocityTracker::Estimator* outEstimator) const { |
| 672 | outEstimator->clear(); |
| 673 | |
| 674 | // Iterate over movement samples in reverse time order and collect samples. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 675 | std::vector<float> positions; |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 676 | std::vector<float> w; |
| 677 | std::vector<float> time; |
| 678 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 679 | uint32_t index = mIndex; |
| 680 | const Movement& newestMovement = mMovements[mIndex]; |
| 681 | do { |
| 682 | const Movement& movement = mMovements[index]; |
| 683 | if (!movement.idBits.hasBit(id)) { |
| 684 | break; |
| 685 | } |
| 686 | |
| 687 | nsecs_t age = newestMovement.eventTime - movement.eventTime; |
| 688 | if (age > HORIZON) { |
| 689 | break; |
| 690 | } |
| 691 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 692 | positions.push_back(movement.getPosition(id)); |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 693 | w.push_back(chooseWeight(index)); |
| 694 | time.push_back(-age * 0.000000001f); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 695 | index = (index == 0 ? HISTORY_SIZE : index) - 1; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 696 | } while (positions.size() < HISTORY_SIZE); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 697 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 698 | const size_t m = positions.size(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 699 | if (m == 0) { |
| 700 | return false; // no data |
| 701 | } |
| 702 | |
| 703 | // Calculate a least squares polynomial fit. |
| 704 | uint32_t degree = mDegree; |
| 705 | if (degree > m - 1) { |
| 706 | degree = m - 1; |
| 707 | } |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 708 | |
| 709 | if (degree == 2 && mWeighting == WEIGHTING_NONE) { |
| 710 | // Optimize unweighted, quadratic polynomial fit |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 711 | std::optional<std::array<float, 3>> coeff = |
| 712 | solveUnweightedLeastSquaresDeg2(time, positions); |
| 713 | if (coeff) { |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 714 | outEstimator->time = newestMovement.eventTime; |
| 715 | outEstimator->degree = 2; |
| 716 | outEstimator->confidence = 1; |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 717 | for (size_t i = 0; i <= outEstimator->degree; i++) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 718 | outEstimator->coeff[i] = (*coeff)[i]; |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 719 | } |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 720 | return true; |
| 721 | } |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 722 | } else if (degree >= 1) { |
| 723 | // General case for an Nth degree polynomial fit |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 724 | float det; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 725 | uint32_t n = degree + 1; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 726 | if (solveLeastSquares(time, positions, w, n, outEstimator->coeff, &det)) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 727 | outEstimator->time = newestMovement.eventTime; |
| 728 | outEstimator->degree = degree; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 729 | outEstimator->confidence = det; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 730 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 731 | ALOGD_IF(DEBUG_STRATEGY, "estimate: degree=%d, coeff=%s, confidence=%f", |
| 732 | int(outEstimator->degree), vectorToString(outEstimator->coeff, n).c_str(), |
| 733 | outEstimator->confidence); |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 734 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 735 | return true; |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | // No velocity data available for this pointer, but we do have its current position. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 740 | outEstimator->coeff[0] = positions[0]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 741 | outEstimator->time = newestMovement.eventTime; |
| 742 | outEstimator->degree = 0; |
| 743 | outEstimator->confidence = 1; |
| 744 | return true; |
| 745 | } |
| 746 | |
| 747 | float LeastSquaresVelocityTrackerStrategy::chooseWeight(uint32_t index) const { |
| 748 | switch (mWeighting) { |
| 749 | case WEIGHTING_DELTA: { |
| 750 | // Weight points based on how much time elapsed between them and the next |
| 751 | // point so that points that "cover" a shorter time span are weighed less. |
| 752 | // delta 0ms: 0.5 |
| 753 | // delta 10ms: 1.0 |
| 754 | if (index == mIndex) { |
| 755 | return 1.0f; |
| 756 | } |
| 757 | uint32_t nextIndex = (index + 1) % HISTORY_SIZE; |
| 758 | float deltaMillis = (mMovements[nextIndex].eventTime- mMovements[index].eventTime) |
| 759 | * 0.000001f; |
| 760 | if (deltaMillis < 0) { |
| 761 | return 0.5f; |
| 762 | } |
| 763 | if (deltaMillis < 10) { |
| 764 | return 0.5f + deltaMillis * 0.05; |
| 765 | } |
| 766 | return 1.0f; |
| 767 | } |
| 768 | |
| 769 | case WEIGHTING_CENTRAL: { |
| 770 | // Weight points based on their age, weighing very recent and very old points less. |
| 771 | // age 0ms: 0.5 |
| 772 | // age 10ms: 1.0 |
| 773 | // age 50ms: 1.0 |
| 774 | // age 60ms: 0.5 |
| 775 | float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime) |
| 776 | * 0.000001f; |
| 777 | if (ageMillis < 0) { |
| 778 | return 0.5f; |
| 779 | } |
| 780 | if (ageMillis < 10) { |
| 781 | return 0.5f + ageMillis * 0.05; |
| 782 | } |
| 783 | if (ageMillis < 50) { |
| 784 | return 1.0f; |
| 785 | } |
| 786 | if (ageMillis < 60) { |
| 787 | return 0.5f + (60 - ageMillis) * 0.05; |
| 788 | } |
| 789 | return 0.5f; |
| 790 | } |
| 791 | |
| 792 | case WEIGHTING_RECENT: { |
| 793 | // Weight points based on their age, weighing older points less. |
| 794 | // age 0ms: 1.0 |
| 795 | // age 50ms: 1.0 |
| 796 | // age 100ms: 0.5 |
| 797 | float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime) |
| 798 | * 0.000001f; |
| 799 | if (ageMillis < 50) { |
| 800 | return 1.0f; |
| 801 | } |
| 802 | if (ageMillis < 100) { |
| 803 | return 0.5f + (100 - ageMillis) * 0.01f; |
| 804 | } |
| 805 | return 0.5f; |
| 806 | } |
| 807 | |
| 808 | case WEIGHTING_NONE: |
| 809 | default: |
| 810 | return 1.0f; |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | |
| 815 | // --- IntegratingVelocityTrackerStrategy --- |
| 816 | |
| 817 | IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) : |
| 818 | mDegree(degree) { |
| 819 | } |
| 820 | |
| 821 | IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() { |
| 822 | } |
| 823 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 824 | void IntegratingVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { |
| 825 | mPointerIdBits.value &= ~idBits.value; |
| 826 | } |
| 827 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 828 | void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, |
| 829 | const std::vector<float>& positions) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 830 | uint32_t index = 0; |
| 831 | for (BitSet32 iterIdBits(idBits); !iterIdBits.isEmpty();) { |
| 832 | uint32_t id = iterIdBits.clearFirstMarkedBit(); |
| 833 | State& state = mPointerState[id]; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 834 | const float position = positions[index++]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 835 | if (mPointerIdBits.hasBit(id)) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 836 | updateState(state, eventTime, position); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 837 | } else { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 838 | initState(state, eventTime, position); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 839 | } |
| 840 | } |
| 841 | |
| 842 | mPointerIdBits = idBits; |
| 843 | } |
| 844 | |
| 845 | bool IntegratingVelocityTrackerStrategy::getEstimator(uint32_t id, |
| 846 | VelocityTracker::Estimator* outEstimator) const { |
| 847 | outEstimator->clear(); |
| 848 | |
| 849 | if (mPointerIdBits.hasBit(id)) { |
| 850 | const State& state = mPointerState[id]; |
| 851 | populateEstimator(state, outEstimator); |
| 852 | return true; |
| 853 | } |
| 854 | |
| 855 | return false; |
| 856 | } |
| 857 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 858 | void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime, |
| 859 | float pos) const { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 860 | state.updateTime = eventTime; |
| 861 | state.degree = 0; |
| 862 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 863 | state.pos = pos; |
| 864 | state.accel = 0; |
| 865 | state.vel = 0; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 866 | } |
| 867 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 868 | void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime, |
| 869 | float pos) const { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 870 | const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS; |
| 871 | const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds |
| 872 | |
| 873 | if (eventTime <= state.updateTime + MIN_TIME_DELTA) { |
| 874 | return; |
| 875 | } |
| 876 | |
| 877 | float dt = (eventTime - state.updateTime) * 0.000000001f; |
| 878 | state.updateTime = eventTime; |
| 879 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 880 | float vel = (pos - state.pos) / dt; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 881 | if (state.degree == 0) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 882 | state.vel = vel; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 883 | state.degree = 1; |
| 884 | } else { |
| 885 | float alpha = dt / (FILTER_TIME_CONSTANT + dt); |
| 886 | if (mDegree == 1) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 887 | state.vel += (vel - state.vel) * alpha; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 888 | } else { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 889 | float accel = (vel - state.vel) / dt; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 890 | if (state.degree == 1) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 891 | state.accel = accel; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 892 | state.degree = 2; |
| 893 | } else { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 894 | state.accel += (accel - state.accel) * alpha; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 895 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 896 | state.vel += (state.accel * dt) * alpha; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 897 | } |
| 898 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 899 | state.pos = pos; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 900 | } |
| 901 | |
| 902 | void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state, |
| 903 | VelocityTracker::Estimator* outEstimator) const { |
| 904 | outEstimator->time = state.updateTime; |
| 905 | outEstimator->confidence = 1.0f; |
| 906 | outEstimator->degree = state.degree; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 907 | outEstimator->coeff[0] = state.pos; |
| 908 | outEstimator->coeff[1] = state.vel; |
| 909 | outEstimator->coeff[2] = state.accel / 2; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 910 | } |
| 911 | |
| 912 | |
| 913 | // --- LegacyVelocityTrackerStrategy --- |
| 914 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 915 | LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() : mIndex(0) {} |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 916 | |
| 917 | LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() { |
| 918 | } |
| 919 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 920 | void LegacyVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { |
| 921 | BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); |
| 922 | mMovements[mIndex].idBits = remainingIdBits; |
| 923 | } |
| 924 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 925 | void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, |
| 926 | const std::vector<float>& positions) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 927 | if (++mIndex == HISTORY_SIZE) { |
| 928 | mIndex = 0; |
| 929 | } |
| 930 | |
| 931 | Movement& movement = mMovements[mIndex]; |
| 932 | movement.eventTime = eventTime; |
| 933 | movement.idBits = idBits; |
| 934 | uint32_t count = idBits.count(); |
| 935 | for (uint32_t i = 0; i < count; i++) { |
| 936 | movement.positions[i] = positions[i]; |
| 937 | } |
| 938 | } |
| 939 | |
| 940 | bool LegacyVelocityTrackerStrategy::getEstimator(uint32_t id, |
| 941 | VelocityTracker::Estimator* outEstimator) const { |
| 942 | outEstimator->clear(); |
| 943 | |
| 944 | const Movement& newestMovement = mMovements[mIndex]; |
| 945 | if (!newestMovement.idBits.hasBit(id)) { |
| 946 | return false; // no data |
| 947 | } |
| 948 | |
| 949 | // Find the oldest sample that contains the pointer and that is not older than HORIZON. |
| 950 | nsecs_t minTime = newestMovement.eventTime - HORIZON; |
| 951 | uint32_t oldestIndex = mIndex; |
| 952 | uint32_t numTouches = 1; |
| 953 | do { |
| 954 | uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1; |
| 955 | const Movement& nextOldestMovement = mMovements[nextOldestIndex]; |
| 956 | if (!nextOldestMovement.idBits.hasBit(id) |
| 957 | || nextOldestMovement.eventTime < minTime) { |
| 958 | break; |
| 959 | } |
| 960 | oldestIndex = nextOldestIndex; |
| 961 | } while (++numTouches < HISTORY_SIZE); |
| 962 | |
| 963 | // Calculate an exponentially weighted moving average of the velocity estimate |
| 964 | // at different points in time measured relative to the oldest sample. |
| 965 | // This is essentially an IIR filter. Newer samples are weighted more heavily |
| 966 | // than older samples. Samples at equal time points are weighted more or less |
| 967 | // equally. |
| 968 | // |
| 969 | // One tricky problem is that the sample data may be poorly conditioned. |
| 970 | // Sometimes samples arrive very close together in time which can cause us to |
| 971 | // overestimate the velocity at that time point. Most samples might be measured |
| 972 | // 16ms apart but some consecutive samples could be only 0.5sm apart because |
| 973 | // the hardware or driver reports them irregularly or in bursts. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 974 | float accumV = 0; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 975 | uint32_t index = oldestIndex; |
| 976 | uint32_t samplesUsed = 0; |
| 977 | const Movement& oldestMovement = mMovements[oldestIndex]; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 978 | float oldestPosition = oldestMovement.getPosition(id); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 979 | nsecs_t lastDuration = 0; |
| 980 | |
| 981 | while (numTouches-- > 1) { |
| 982 | if (++index == HISTORY_SIZE) { |
| 983 | index = 0; |
| 984 | } |
| 985 | const Movement& movement = mMovements[index]; |
| 986 | nsecs_t duration = movement.eventTime - oldestMovement.eventTime; |
| 987 | |
| 988 | // If the duration between samples is small, we may significantly overestimate |
| 989 | // the velocity. Consequently, we impose a minimum duration constraint on the |
| 990 | // samples that we include in the calculation. |
| 991 | if (duration >= MIN_DURATION) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 992 | float position = movement.getPosition(id); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 993 | float scale = 1000000000.0f / duration; // one over time delta in seconds |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 994 | float v = (position - oldestPosition) * scale; |
| 995 | accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 996 | lastDuration = duration; |
| 997 | samplesUsed += 1; |
| 998 | } |
| 999 | } |
| 1000 | |
| 1001 | // Report velocity. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1002 | float newestPosition = newestMovement.getPosition(id); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1003 | outEstimator->time = newestMovement.eventTime; |
| 1004 | outEstimator->confidence = 1; |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1005 | outEstimator->coeff[0] = newestPosition; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1006 | if (samplesUsed) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1007 | outEstimator->coeff[1] = accumV; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1008 | outEstimator->degree = 1; |
| 1009 | } else { |
| 1010 | outEstimator->degree = 0; |
| 1011 | } |
| 1012 | return true; |
| 1013 | } |
| 1014 | |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1015 | // --- ImpulseVelocityTrackerStrategy --- |
| 1016 | |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1017 | ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues) |
| 1018 | : mDeltaValues(deltaValues), mIndex(0) {} |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1019 | |
| 1020 | ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() { |
| 1021 | } |
| 1022 | |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1023 | void ImpulseVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { |
| 1024 | BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); |
| 1025 | mMovements[mIndex].idBits = remainingIdBits; |
| 1026 | } |
| 1027 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1028 | void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, |
| 1029 | const std::vector<float>& positions) { |
Siarhei Vishniakou | 346ac6a | 2019-04-10 09:58:05 -0700 | [diff] [blame] | 1030 | if (mMovements[mIndex].eventTime != eventTime) { |
| 1031 | // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates |
| 1032 | // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include |
| 1033 | // the new pointer. If the eventtimes for both events are identical, just update the data |
| 1034 | // for this time. |
| 1035 | // We only compare against the last value, as it is likely that addMovement is called |
| 1036 | // in chronological order as events occur. |
| 1037 | mIndex++; |
| 1038 | } |
| 1039 | if (mIndex == HISTORY_SIZE) { |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1040 | mIndex = 0; |
| 1041 | } |
| 1042 | |
| 1043 | Movement& movement = mMovements[mIndex]; |
| 1044 | movement.eventTime = eventTime; |
| 1045 | movement.idBits = idBits; |
| 1046 | uint32_t count = idBits.count(); |
| 1047 | for (uint32_t i = 0; i < count; i++) { |
| 1048 | movement.positions[i] = positions[i]; |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | /** |
| 1053 | * Calculate the total impulse provided to the screen and the resulting velocity. |
| 1054 | * |
| 1055 | * The touchscreen is modeled as a physical object. |
| 1056 | * Initial condition is discussed below, but for now suppose that v(t=0) = 0 |
| 1057 | * |
| 1058 | * The kinetic energy of the object at the release is E=0.5*m*v^2 |
| 1059 | * Then vfinal = sqrt(2E/m). The goal is to calculate E. |
| 1060 | * |
| 1061 | * The kinetic energy at the release is equal to the total work done on the object by the finger. |
| 1062 | * The total work W is the sum of all dW along the path. |
| 1063 | * |
| 1064 | * dW = F*dx, where dx is the piece of path traveled. |
| 1065 | * Force is change of momentum over time, F = dp/dt = m dv/dt. |
| 1066 | * Then substituting: |
| 1067 | * dW = m (dv/dt) * dx = m * v * dv |
| 1068 | * |
| 1069 | * Summing along the path, we get: |
| 1070 | * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv) |
| 1071 | * Since the mass stays constant, the equation for final velocity is: |
| 1072 | * vfinal = sqrt(2*sum(v * dv)) |
| 1073 | * |
| 1074 | * Here, |
| 1075 | * dv : change of velocity = (v[i+1]-v[i]) |
| 1076 | * dx : change of distance = (x[i+1]-x[i]) |
| 1077 | * dt : change of time = (t[i+1]-t[i]) |
| 1078 | * v : instantaneous velocity = dx/dt |
| 1079 | * |
| 1080 | * The final formula is: |
| 1081 | * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i |
| 1082 | * The absolute value is needed to properly account for the sign. If the velocity over a |
| 1083 | * particular segment descreases, then this indicates braking, which means that negative |
| 1084 | * work was done. So for two positive, but decreasing, velocities, this contribution would be |
| 1085 | * negative and will cause a smaller final velocity. |
| 1086 | * |
| 1087 | * Initial condition |
| 1088 | * There are two ways to deal with initial condition: |
| 1089 | * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest. |
| 1090 | * This is not entirely accurate. We are only taking the past X ms of touch data, where X is |
| 1091 | * currently equal to 100. However, a touch event that created a fling probably lasted for longer |
| 1092 | * than that, which would mean that the user has already been interacting with the touchscreen |
| 1093 | * and it has probably already been moving. |
| 1094 | * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this |
| 1095 | * initial velocity and the equivalent energy, and start with this initial energy. |
| 1096 | * Consider an example where we have the following data, consisting of 3 points: |
| 1097 | * time: t0, t1, t2 |
| 1098 | * x : x0, x1, x2 |
| 1099 | * v : 0 , v1, v2 |
| 1100 | * Here is what will happen in each of these scenarios: |
| 1101 | * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get |
| 1102 | * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0 |
| 1103 | * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1))) |
| 1104 | * since velocity is a real number |
| 1105 | * 2) If we treat the screen as already moving, then it must already have an energy (per mass) |
| 1106 | * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment |
| 1107 | * will contribute to the total kinetic energy (since we can effectively consider that v0=v1). |
| 1108 | * This will give the following expression for the final velocity: |
| 1109 | * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1))) |
| 1110 | * This analysis can be generalized to an arbitrary number of samples. |
| 1111 | * |
| 1112 | * |
| 1113 | * Comparing the two equations above, we see that the only mathematical difference |
| 1114 | * is the factor of 1/2 in front of the first velocity term. |
| 1115 | * This boundary condition would allow for the "proper" calculation of the case when all of the |
| 1116 | * samples are equally spaced in time and distance, which should suggest a constant velocity. |
| 1117 | * |
| 1118 | * Note that approach 2) is sensitive to the proper ordering of the data in time, since |
| 1119 | * the boundary condition must be applied to the oldest sample to be accurate. |
| 1120 | */ |
Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 1121 | static float kineticEnergyToVelocity(float work) { |
| 1122 | static constexpr float sqrt2 = 1.41421356237; |
| 1123 | return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2; |
| 1124 | } |
| 1125 | |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1126 | static float calculateImpulseVelocity(const nsecs_t* t, const float* x, size_t count, |
| 1127 | bool deltaValues) { |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1128 | // The input should be in reversed time order (most recent sample at index i=0) |
| 1129 | // t[i] is in nanoseconds, but due to FP arithmetic, convert to seconds inside this function |
Siarhei Vishniakou | 6de8f5e | 2018-03-02 18:48:15 -0800 | [diff] [blame] | 1130 | static constexpr float SECONDS_PER_NANO = 1E-9; |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1131 | |
| 1132 | if (count < 2) { |
| 1133 | return 0; // if 0 or 1 points, velocity is zero |
| 1134 | } |
| 1135 | if (t[1] > t[0]) { // Algorithm will still work, but not perfectly |
| 1136 | ALOGE("Samples provided to calculateImpulseVelocity in the wrong order"); |
| 1137 | } |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1138 | |
| 1139 | // If the data values are delta values, we do not have to calculate deltas here. |
| 1140 | // We can use the delta values directly, along with the calculated time deltas. |
| 1141 | // Since the data value input is in reversed time order: |
| 1142 | // [a] for non-delta inputs, instantenous velocity = (x[i] - x[i-1])/(t[i] - t[i-1]) |
| 1143 | // [b] for delta inputs, instantenous velocity = -x[i-1]/(t[i] - t[i - 1]) |
| 1144 | // e.g., let the non-delta values are: V = [2, 3, 7], the equivalent deltas are D = [2, 1, 4]. |
| 1145 | // Since the input is in reversed time order, the input values for this function would be |
| 1146 | // V'=[7, 3, 2] and D'=[4, 1, 2] for the non-delta and delta values, respectively. |
| 1147 | // |
| 1148 | // The equivalent of {(V'[2] - V'[1]) = 2 - 3 = -1} would be {-D'[1] = -1} |
| 1149 | // Similarly, the equivalent of {(V'[1] - V'[0]) = 3 - 7 = -4} would be {-D'[0] = -4} |
| 1150 | |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1151 | if (count == 2) { // if 2 points, basic linear calculation |
| 1152 | if (t[1] == t[0]) { |
| 1153 | ALOGE("Events have identical time stamps t=%" PRId64 ", setting velocity = 0", t[0]); |
| 1154 | return 0; |
| 1155 | } |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1156 | const float deltaX = deltaValues ? -x[0] : x[1] - x[0]; |
| 1157 | return deltaX / (SECONDS_PER_NANO * (t[1] - t[0])); |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1158 | } |
| 1159 | // Guaranteed to have at least 3 points here |
| 1160 | float work = 0; |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1161 | for (size_t i = count - 1; i > 0 ; i--) { // start with the oldest sample and go forward in time |
| 1162 | if (t[i] == t[i-1]) { |
| 1163 | ALOGE("Events have identical time stamps t=%" PRId64 ", skipping sample", t[i]); |
| 1164 | continue; |
| 1165 | } |
Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 1166 | float vprev = kineticEnergyToVelocity(work); // v[i-1] |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1167 | const float deltaX = deltaValues ? -x[i-1] : x[i] - x[i-1]; |
| 1168 | float vcurr = deltaX / (SECONDS_PER_NANO * (t[i] - t[i-1])); // v[i] |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1169 | work += (vcurr - vprev) * fabsf(vcurr); |
| 1170 | if (i == count - 1) { |
| 1171 | work *= 0.5; // initial condition, case 2) above |
| 1172 | } |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1173 | } |
Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 1174 | return kineticEnergyToVelocity(work); |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1175 | } |
| 1176 | |
| 1177 | bool ImpulseVelocityTrackerStrategy::getEstimator(uint32_t id, |
| 1178 | VelocityTracker::Estimator* outEstimator) const { |
| 1179 | outEstimator->clear(); |
| 1180 | |
| 1181 | // Iterate over movement samples in reverse time order and collect samples. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1182 | float positions[HISTORY_SIZE]; |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1183 | nsecs_t time[HISTORY_SIZE]; |
| 1184 | size_t m = 0; // number of points that will be used for fitting |
| 1185 | size_t index = mIndex; |
| 1186 | const Movement& newestMovement = mMovements[mIndex]; |
| 1187 | do { |
| 1188 | const Movement& movement = mMovements[index]; |
| 1189 | if (!movement.idBits.hasBit(id)) { |
| 1190 | break; |
| 1191 | } |
| 1192 | |
| 1193 | nsecs_t age = newestMovement.eventTime - movement.eventTime; |
| 1194 | if (age > HORIZON) { |
| 1195 | break; |
| 1196 | } |
| 1197 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1198 | positions[m] = movement.getPosition(id); |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1199 | time[m] = movement.eventTime; |
| 1200 | index = (index == 0 ? HISTORY_SIZE : index) - 1; |
| 1201 | } while (++m < HISTORY_SIZE); |
| 1202 | |
| 1203 | if (m == 0) { |
| 1204 | return false; // no data |
| 1205 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1206 | outEstimator->coeff[0] = 0; |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1207 | outEstimator->coeff[1] = calculateImpulseVelocity(time, positions, m, mDeltaValues); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1208 | outEstimator->coeff[2] = 0; |
| 1209 | |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1210 | outEstimator->time = newestMovement.eventTime; |
| 1211 | outEstimator->degree = 2; // similar results to 2nd degree fit |
| 1212 | outEstimator->confidence = 1; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 1213 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1214 | ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", outEstimator->coeff[1]); |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 1215 | |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1216 | if (DEBUG_IMPULSE) { |
| 1217 | // TODO(b/134179997): delete this block once the switch to 'impulse' is complete. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1218 | // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons. |
| 1219 | // X axis chosen arbitrarily for velocity comparisons. |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1220 | VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2); |
| 1221 | BitSet32 idBits; |
| 1222 | const uint32_t pointerId = 0; |
| 1223 | idBits.markBit(pointerId); |
| 1224 | for (ssize_t i = m - 1; i >= 0; i--) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1225 | lsq2.addMovement(time[i], idBits, {{AMOTION_EVENT_AXIS_X, {positions[i]}}}); |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1226 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1227 | std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId); |
| 1228 | if (v) { |
| 1229 | ALOGD("lsq2 velocity: %.1f", *v); |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1230 | } else { |
| 1231 | ALOGD("lsq2 velocity: could not compute velocity"); |
| 1232 | } |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 1233 | } |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1234 | return true; |
| 1235 | } |
| 1236 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1237 | } // namespace android |