| 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" | 
 | 18 | //#define LOG_NDEBUG 0 | 
 | 19 |  | 
 | 20 | // Log debug messages about velocity tracking. | 
 | 21 | #define DEBUG_VELOCITY 0 | 
 | 22 |  | 
 | 23 | // Log debug messages about the progress of the algorithm itself. | 
 | 24 | #define DEBUG_STRATEGY 0 | 
 | 25 |  | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 26 | #include <inttypes.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 27 | #include <limits.h> | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 28 | #include <math.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 29 |  | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 30 | #include <android-base/stringprintf.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 31 | #include <cutils/properties.h> | 
 | 32 | #include <input/VelocityTracker.h> | 
 | 33 | #include <utils/BitSet.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 34 | #include <utils/Timers.h> | 
 | 35 |  | 
 | 36 | namespace android { | 
 | 37 |  | 
 | 38 | // Nanoseconds per milliseconds. | 
 | 39 | static const nsecs_t NANOS_PER_MS = 1000000; | 
 | 40 |  | 
 | 41 | // Threshold for determining that a pointer has stopped moving. | 
 | 42 | // Some input devices do not send ACTION_MOVE events in the case where a pointer has | 
 | 43 | // stopped.  We need to detect this case so that we can accurately predict the | 
 | 44 | // velocity after the pointer starts moving again. | 
 | 45 | static const nsecs_t ASSUME_POINTER_STOPPED_TIME = 40 * NANOS_PER_MS; | 
 | 46 |  | 
 | 47 |  | 
 | 48 | static float vectorDot(const float* a, const float* b, uint32_t m) { | 
 | 49 |     float r = 0; | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 50 |     for (size_t i = 0; i < m; i++) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 51 |         r += *(a++) * *(b++); | 
 | 52 |     } | 
 | 53 |     return r; | 
 | 54 | } | 
 | 55 |  | 
 | 56 | static float vectorNorm(const float* a, uint32_t m) { | 
 | 57 |     float r = 0; | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 58 |     for (size_t i = 0; i < m; i++) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 59 |         float t = *(a++); | 
 | 60 |         r += t * t; | 
 | 61 |     } | 
 | 62 |     return sqrtf(r); | 
 | 63 | } | 
 | 64 |  | 
 | 65 | #if DEBUG_STRATEGY || DEBUG_VELOCITY | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 66 | static std::string vectorToString(const float* a, uint32_t m) { | 
 | 67 |     std::string str; | 
 | 68 |     str += "["; | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 69 |     for (size_t i = 0; i < m; i++) { | 
 | 70 |         if (i) { | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 71 |             str += ","; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 72 |         } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 73 |         str += android::base::StringPrintf(" %f", *(a++)); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 74 |     } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 75 |     str += " ]"; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 76 |     return str; | 
 | 77 | } | 
 | 78 |  | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 79 | static std::string matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) { | 
 | 80 |     std::string str; | 
 | 81 |     str = "["; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 82 |     for (size_t i = 0; i < m; i++) { | 
 | 83 |         if (i) { | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 84 |             str += ","; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 85 |         } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 86 |         str += " ["; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 87 |         for (size_t j = 0; j < n; j++) { | 
 | 88 |             if (j) { | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 89 |                 str += ","; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 90 |             } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 91 |             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] | 92 |         } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 93 |         str += " ]"; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 94 |     } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 95 |     str += " ]"; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 96 |     return str; | 
 | 97 | } | 
 | 98 | #endif | 
 | 99 |  | 
 | 100 |  | 
 | 101 | // --- VelocityTracker --- | 
 | 102 |  | 
 | 103 | // The default velocity tracker strategy. | 
 | 104 | // Although other strategies are available for testing and comparison purposes, | 
 | 105 | // this is the strategy that applications will actually use.  Be very careful | 
 | 106 | // when adjusting the default strategy because it can dramatically affect | 
 | 107 | // (often in a bad way) the user experience. | 
 | 108 | const char* VelocityTracker::DEFAULT_STRATEGY = "lsq2"; | 
 | 109 |  | 
 | 110 | VelocityTracker::VelocityTracker(const char* strategy) : | 
 | 111 |         mLastEventTime(0), mCurrentPointerIdBits(0), mActivePointerId(-1) { | 
 | 112 |     char value[PROPERTY_VALUE_MAX]; | 
 | 113 |  | 
 | 114 |     // Allow the default strategy to be overridden using a system property for debugging. | 
 | 115 |     if (!strategy) { | 
 | 116 |         int length = property_get("debug.velocitytracker.strategy", value, NULL); | 
 | 117 |         if (length > 0) { | 
 | 118 |             strategy = value; | 
 | 119 |         } else { | 
 | 120 |             strategy = DEFAULT_STRATEGY; | 
 | 121 |         } | 
 | 122 |     } | 
 | 123 |  | 
 | 124 |     // Configure the strategy. | 
 | 125 |     if (!configureStrategy(strategy)) { | 
 | 126 |         ALOGD("Unrecognized velocity tracker strategy name '%s'.", strategy); | 
 | 127 |         if (!configureStrategy(DEFAULT_STRATEGY)) { | 
 | 128 |             LOG_ALWAYS_FATAL("Could not create the default velocity tracker strategy '%s'!", | 
 | 129 |                     strategy); | 
 | 130 |         } | 
 | 131 |     } | 
 | 132 | } | 
 | 133 |  | 
 | 134 | VelocityTracker::~VelocityTracker() { | 
 | 135 |     delete mStrategy; | 
 | 136 | } | 
 | 137 |  | 
 | 138 | bool VelocityTracker::configureStrategy(const char* strategy) { | 
 | 139 |     mStrategy = createStrategy(strategy); | 
 | 140 |     return mStrategy != NULL; | 
 | 141 | } | 
 | 142 |  | 
 | 143 | VelocityTrackerStrategy* VelocityTracker::createStrategy(const char* strategy) { | 
 | 144 |     if (!strcmp("lsq1", strategy)) { | 
 | 145 |         // 1st order least squares.  Quality: POOR. | 
 | 146 |         // Frequently underfits the touch data especially when the finger accelerates | 
 | 147 |         // or changes direction.  Often underestimates velocity.  The direction | 
 | 148 |         // is overly influenced by historical touch points. | 
 | 149 |         return new LeastSquaresVelocityTrackerStrategy(1); | 
 | 150 |     } | 
 | 151 |     if (!strcmp("lsq2", strategy)) { | 
 | 152 |         // 2nd order least squares.  Quality: VERY GOOD. | 
 | 153 |         // Pretty much ideal, but can be confused by certain kinds of touch data, | 
 | 154 |         // particularly if the panel has a tendency to generate delayed, | 
 | 155 |         // duplicate or jittery touch coordinates when the finger is released. | 
 | 156 |         return new LeastSquaresVelocityTrackerStrategy(2); | 
 | 157 |     } | 
 | 158 |     if (!strcmp("lsq3", strategy)) { | 
 | 159 |         // 3rd order least squares.  Quality: UNUSABLE. | 
 | 160 |         // Frequently overfits the touch data yielding wildly divergent estimates | 
 | 161 |         // of the velocity when the finger is released. | 
 | 162 |         return new LeastSquaresVelocityTrackerStrategy(3); | 
 | 163 |     } | 
 | 164 |     if (!strcmp("wlsq2-delta", strategy)) { | 
 | 165 |         // 2nd order weighted least squares, delta weighting.  Quality: EXPERIMENTAL | 
 | 166 |         return new LeastSquaresVelocityTrackerStrategy(2, | 
 | 167 |                 LeastSquaresVelocityTrackerStrategy::WEIGHTING_DELTA); | 
 | 168 |     } | 
 | 169 |     if (!strcmp("wlsq2-central", strategy)) { | 
 | 170 |         // 2nd order weighted least squares, central weighting.  Quality: EXPERIMENTAL | 
 | 171 |         return new LeastSquaresVelocityTrackerStrategy(2, | 
 | 172 |                 LeastSquaresVelocityTrackerStrategy::WEIGHTING_CENTRAL); | 
 | 173 |     } | 
 | 174 |     if (!strcmp("wlsq2-recent", strategy)) { | 
 | 175 |         // 2nd order weighted least squares, recent weighting.  Quality: EXPERIMENTAL | 
 | 176 |         return new LeastSquaresVelocityTrackerStrategy(2, | 
 | 177 |                 LeastSquaresVelocityTrackerStrategy::WEIGHTING_RECENT); | 
 | 178 |     } | 
 | 179 |     if (!strcmp("int1", strategy)) { | 
 | 180 |         // 1st order integrating filter.  Quality: GOOD. | 
 | 181 |         // Not as good as 'lsq2' because it cannot estimate acceleration but it is | 
 | 182 |         // more tolerant of errors.  Like 'lsq1', this strategy tends to underestimate | 
 | 183 |         // the velocity of a fling but this strategy tends to respond to changes in | 
 | 184 |         // direction more quickly and accurately. | 
 | 185 |         return new IntegratingVelocityTrackerStrategy(1); | 
 | 186 |     } | 
 | 187 |     if (!strcmp("int2", strategy)) { | 
 | 188 |         // 2nd order integrating filter.  Quality: EXPERIMENTAL. | 
 | 189 |         // For comparison purposes only.  Unlike 'int1' this strategy can compensate | 
 | 190 |         // for acceleration but it typically overestimates the effect. | 
 | 191 |         return new IntegratingVelocityTrackerStrategy(2); | 
 | 192 |     } | 
 | 193 |     if (!strcmp("legacy", strategy)) { | 
 | 194 |         // Legacy velocity tracker algorithm.  Quality: POOR. | 
 | 195 |         // For comparison purposes only.  This algorithm is strongly influenced by | 
 | 196 |         // old data points, consistently underestimates velocity and takes a very long | 
 | 197 |         // time to adjust to changes in direction. | 
 | 198 |         return new LegacyVelocityTrackerStrategy(); | 
 | 199 |     } | 
 | 200 |     return NULL; | 
 | 201 | } | 
 | 202 |  | 
 | 203 | void VelocityTracker::clear() { | 
 | 204 |     mCurrentPointerIdBits.clear(); | 
 | 205 |     mActivePointerId = -1; | 
 | 206 |  | 
 | 207 |     mStrategy->clear(); | 
 | 208 | } | 
 | 209 |  | 
 | 210 | void VelocityTracker::clearPointers(BitSet32 idBits) { | 
 | 211 |     BitSet32 remainingIdBits(mCurrentPointerIdBits.value & ~idBits.value); | 
 | 212 |     mCurrentPointerIdBits = remainingIdBits; | 
 | 213 |  | 
 | 214 |     if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) { | 
 | 215 |         mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1; | 
 | 216 |     } | 
 | 217 |  | 
 | 218 |     mStrategy->clearPointers(idBits); | 
 | 219 | } | 
 | 220 |  | 
 | 221 | void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) { | 
 | 222 |     while (idBits.count() > MAX_POINTERS) { | 
 | 223 |         idBits.clearLastMarkedBit(); | 
 | 224 |     } | 
 | 225 |  | 
 | 226 |     if ((mCurrentPointerIdBits.value & idBits.value) | 
 | 227 |             && eventTime >= mLastEventTime + ASSUME_POINTER_STOPPED_TIME) { | 
 | 228 | #if DEBUG_VELOCITY | 
 | 229 |         ALOGD("VelocityTracker: stopped for %0.3f ms, clearing state.", | 
 | 230 |                 (eventTime - mLastEventTime) * 0.000001f); | 
 | 231 | #endif | 
 | 232 |         // We have not received any movements for too long.  Assume that all pointers | 
 | 233 |         // have stopped. | 
 | 234 |         mStrategy->clear(); | 
 | 235 |     } | 
 | 236 |     mLastEventTime = eventTime; | 
 | 237 |  | 
 | 238 |     mCurrentPointerIdBits = idBits; | 
 | 239 |     if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) { | 
 | 240 |         mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit(); | 
 | 241 |     } | 
 | 242 |  | 
 | 243 |     mStrategy->addMovement(eventTime, idBits, positions); | 
 | 244 |  | 
 | 245 | #if DEBUG_VELOCITY | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 246 |     ALOGD("VelocityTracker: addMovement eventTime=%" PRId64 ", idBits=0x%08x, activePointerId=%d", | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 247 |             eventTime, idBits.value, mActivePointerId); | 
 | 248 |     for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) { | 
 | 249 |         uint32_t id = iterBits.firstMarkedBit(); | 
 | 250 |         uint32_t index = idBits.getIndexOfBit(id); | 
 | 251 |         iterBits.clearBit(id); | 
 | 252 |         Estimator estimator; | 
 | 253 |         getEstimator(id, &estimator); | 
 | 254 |         ALOGD("  %d: position (%0.3f, %0.3f), " | 
 | 255 |                 "estimator (degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f)", | 
 | 256 |                 id, positions[index].x, positions[index].y, | 
 | 257 |                 int(estimator.degree), | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 258 |                 vectorToString(estimator.xCoeff, estimator.degree + 1).c_str(), | 
 | 259 |                 vectorToString(estimator.yCoeff, estimator.degree + 1).c_str(), | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 260 |                 estimator.confidence); | 
 | 261 |     } | 
 | 262 | #endif | 
 | 263 | } | 
 | 264 |  | 
 | 265 | void VelocityTracker::addMovement(const MotionEvent* event) { | 
 | 266 |     int32_t actionMasked = event->getActionMasked(); | 
 | 267 |  | 
 | 268 |     switch (actionMasked) { | 
 | 269 |     case AMOTION_EVENT_ACTION_DOWN: | 
 | 270 |     case AMOTION_EVENT_ACTION_HOVER_ENTER: | 
 | 271 |         // Clear all pointers on down before adding the new movement. | 
 | 272 |         clear(); | 
 | 273 |         break; | 
 | 274 |     case AMOTION_EVENT_ACTION_POINTER_DOWN: { | 
 | 275 |         // Start a new movement trace for a pointer that just went down. | 
 | 276 |         // We do this on down instead of on up because the client may want to query the | 
 | 277 |         // final velocity for a pointer that just went up. | 
 | 278 |         BitSet32 downIdBits; | 
 | 279 |         downIdBits.markBit(event->getPointerId(event->getActionIndex())); | 
 | 280 |         clearPointers(downIdBits); | 
 | 281 |         break; | 
 | 282 |     } | 
 | 283 |     case AMOTION_EVENT_ACTION_MOVE: | 
 | 284 |     case AMOTION_EVENT_ACTION_HOVER_MOVE: | 
 | 285 |         break; | 
 | 286 |     default: | 
 | 287 |         // Ignore all other actions because they do not convey any new information about | 
 | 288 |         // pointer movement.  We also want to preserve the last known velocity of the pointers. | 
 | 289 |         // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position | 
 | 290 |         // of the pointers that went up.  ACTION_POINTER_UP does include the new position of | 
 | 291 |         // pointers that remained down but we will also receive an ACTION_MOVE with this | 
 | 292 |         // information if any of them actually moved.  Since we don't know how many pointers | 
 | 293 |         // will be going up at once it makes sense to just wait for the following ACTION_MOVE | 
 | 294 |         // before adding the movement. | 
 | 295 |         return; | 
 | 296 |     } | 
 | 297 |  | 
 | 298 |     size_t pointerCount = event->getPointerCount(); | 
 | 299 |     if (pointerCount > MAX_POINTERS) { | 
 | 300 |         pointerCount = MAX_POINTERS; | 
 | 301 |     } | 
 | 302 |  | 
 | 303 |     BitSet32 idBits; | 
 | 304 |     for (size_t i = 0; i < pointerCount; i++) { | 
 | 305 |         idBits.markBit(event->getPointerId(i)); | 
 | 306 |     } | 
 | 307 |  | 
 | 308 |     uint32_t pointerIndex[MAX_POINTERS]; | 
 | 309 |     for (size_t i = 0; i < pointerCount; i++) { | 
 | 310 |         pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i)); | 
 | 311 |     } | 
 | 312 |  | 
 | 313 |     nsecs_t eventTime; | 
 | 314 |     Position positions[pointerCount]; | 
 | 315 |  | 
 | 316 |     size_t historySize = event->getHistorySize(); | 
 | 317 |     for (size_t h = 0; h < historySize; h++) { | 
 | 318 |         eventTime = event->getHistoricalEventTime(h); | 
 | 319 |         for (size_t i = 0; i < pointerCount; i++) { | 
 | 320 |             uint32_t index = pointerIndex[i]; | 
 | 321 |             positions[index].x = event->getHistoricalX(i, h); | 
 | 322 |             positions[index].y = event->getHistoricalY(i, h); | 
 | 323 |         } | 
 | 324 |         addMovement(eventTime, idBits, positions); | 
 | 325 |     } | 
 | 326 |  | 
 | 327 |     eventTime = event->getEventTime(); | 
 | 328 |     for (size_t i = 0; i < pointerCount; i++) { | 
 | 329 |         uint32_t index = pointerIndex[i]; | 
 | 330 |         positions[index].x = event->getX(i); | 
 | 331 |         positions[index].y = event->getY(i); | 
 | 332 |     } | 
 | 333 |     addMovement(eventTime, idBits, positions); | 
 | 334 | } | 
 | 335 |  | 
 | 336 | bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const { | 
 | 337 |     Estimator estimator; | 
 | 338 |     if (getEstimator(id, &estimator) && estimator.degree >= 1) { | 
 | 339 |         *outVx = estimator.xCoeff[1]; | 
 | 340 |         *outVy = estimator.yCoeff[1]; | 
 | 341 |         return true; | 
 | 342 |     } | 
 | 343 |     *outVx = 0; | 
 | 344 |     *outVy = 0; | 
 | 345 |     return false; | 
 | 346 | } | 
 | 347 |  | 
 | 348 | bool VelocityTracker::getEstimator(uint32_t id, Estimator* outEstimator) const { | 
 | 349 |     return mStrategy->getEstimator(id, outEstimator); | 
 | 350 | } | 
 | 351 |  | 
 | 352 |  | 
 | 353 | // --- LeastSquaresVelocityTrackerStrategy --- | 
 | 354 |  | 
 | 355 | const nsecs_t LeastSquaresVelocityTrackerStrategy::HORIZON; | 
 | 356 | const uint32_t LeastSquaresVelocityTrackerStrategy::HISTORY_SIZE; | 
 | 357 |  | 
 | 358 | LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy( | 
 | 359 |         uint32_t degree, Weighting weighting) : | 
 | 360 |         mDegree(degree), mWeighting(weighting) { | 
 | 361 |     clear(); | 
 | 362 | } | 
 | 363 |  | 
 | 364 | LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() { | 
 | 365 | } | 
 | 366 |  | 
 | 367 | void LeastSquaresVelocityTrackerStrategy::clear() { | 
 | 368 |     mIndex = 0; | 
 | 369 |     mMovements[0].idBits.clear(); | 
 | 370 | } | 
 | 371 |  | 
 | 372 | void LeastSquaresVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
 | 373 |     BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); | 
 | 374 |     mMovements[mIndex].idBits = remainingIdBits; | 
 | 375 | } | 
 | 376 |  | 
 | 377 | void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
 | 378 |         const VelocityTracker::Position* positions) { | 
 | 379 |     if (++mIndex == HISTORY_SIZE) { | 
 | 380 |         mIndex = 0; | 
 | 381 |     } | 
 | 382 |  | 
 | 383 |     Movement& movement = mMovements[mIndex]; | 
 | 384 |     movement.eventTime = eventTime; | 
 | 385 |     movement.idBits = idBits; | 
 | 386 |     uint32_t count = idBits.count(); | 
 | 387 |     for (uint32_t i = 0; i < count; i++) { | 
 | 388 |         movement.positions[i] = positions[i]; | 
 | 389 |     } | 
 | 390 | } | 
 | 391 |  | 
 | 392 | /** | 
 | 393 |  * Solves a linear least squares problem to obtain a N degree polynomial that fits | 
 | 394 |  * the specified input data as nearly as possible. | 
 | 395 |  * | 
 | 396 |  * Returns true if a solution is found, false otherwise. | 
 | 397 |  * | 
 | 398 |  * The input consists of two vectors of data points X and Y with indices 0..m-1 | 
 | 399 |  * along with a weight vector W of the same size. | 
 | 400 |  * | 
 | 401 |  * The output is a vector B with indices 0..n that describes a polynomial | 
 | 402 |  * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i] | 
 | 403 |  * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized. | 
 | 404 |  * | 
 | 405 |  * Accordingly, the weight vector W should be initialized by the caller with the | 
 | 406 |  * reciprocal square root of the variance of the error in each input data point. | 
 | 407 |  * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]). | 
 | 408 |  * The weights express the relative importance of each data point.  If the weights are | 
 | 409 |  * all 1, then the data points are considered to be of equal importance when fitting | 
 | 410 |  * the polynomial.  It is a good idea to choose weights that diminish the importance | 
 | 411 |  * of data points that may have higher than usual error margins. | 
 | 412 |  * | 
 | 413 |  * Errors among data points are assumed to be independent.  W is represented here | 
 | 414 |  * as a vector although in the literature it is typically taken to be a diagonal matrix. | 
 | 415 |  * | 
 | 416 |  * That is to say, the function that generated the input data can be approximated | 
 | 417 |  * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n. | 
 | 418 |  * | 
 | 419 |  * The coefficient of determination (R^2) is also returned to describe the goodness | 
 | 420 |  * of fit of the model for the given data.  It is a value between 0 and 1, where 1 | 
 | 421 |  * indicates perfect correspondence. | 
 | 422 |  * | 
 | 423 |  * This function first expands the X vector to a m by n matrix A such that | 
 | 424 |  * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then | 
 | 425 |  * multiplies it by w[i]./ | 
 | 426 |  * | 
 | 427 |  * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q | 
 | 428 |  * and an m by n upper triangular matrix R.  Because R is upper triangular (lower | 
 | 429 |  * part is all zeroes), we can simplify the decomposition into an m by n matrix | 
 | 430 |  * Q1 and a n by n matrix R1 such that A = Q1 R1. | 
 | 431 |  * | 
 | 432 |  * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y) | 
 | 433 |  * to find B. | 
 | 434 |  * | 
 | 435 |  * For efficiency, we lay out A and Q column-wise in memory because we frequently | 
 | 436 |  * operate on the column vectors.  Conversely, we lay out R row-wise. | 
 | 437 |  * | 
 | 438 |  * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares | 
 | 439 |  * http://en.wikipedia.org/wiki/Gram-Schmidt | 
 | 440 |  */ | 
 | 441 | static bool solveLeastSquares(const float* x, const float* y, | 
 | 442 |         const float* w, uint32_t m, uint32_t n, float* outB, float* outDet) { | 
 | 443 | #if DEBUG_STRATEGY | 
 | 444 |     ALOGD("solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n), | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 445 |             vectorToString(x, m).c_str(), vectorToString(y, m).c_str(), | 
 | 446 |             vectorToString(w, m).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 447 | #endif | 
 | 448 |  | 
 | 449 |     // Expand the X vector to a matrix A, pre-multiplied by the weights. | 
 | 450 |     float a[n][m]; // column-major order | 
 | 451 |     for (uint32_t h = 0; h < m; h++) { | 
 | 452 |         a[0][h] = w[h]; | 
 | 453 |         for (uint32_t i = 1; i < n; i++) { | 
 | 454 |             a[i][h] = a[i - 1][h] * x[h]; | 
 | 455 |         } | 
 | 456 |     } | 
 | 457 | #if DEBUG_STRATEGY | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 458 |     ALOGD("  - a=%s", matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 459 | #endif | 
 | 460 |  | 
 | 461 |     // Apply the Gram-Schmidt process to A to obtain its QR decomposition. | 
 | 462 |     float q[n][m]; // orthonormal basis, column-major order | 
 | 463 |     float r[n][n]; // upper triangular matrix, row-major order | 
 | 464 |     for (uint32_t j = 0; j < n; j++) { | 
 | 465 |         for (uint32_t h = 0; h < m; h++) { | 
 | 466 |             q[j][h] = a[j][h]; | 
 | 467 |         } | 
 | 468 |         for (uint32_t i = 0; i < j; i++) { | 
 | 469 |             float dot = vectorDot(&q[j][0], &q[i][0], m); | 
 | 470 |             for (uint32_t h = 0; h < m; h++) { | 
 | 471 |                 q[j][h] -= dot * q[i][h]; | 
 | 472 |             } | 
 | 473 |         } | 
 | 474 |  | 
 | 475 |         float norm = vectorNorm(&q[j][0], m); | 
 | 476 |         if (norm < 0.000001f) { | 
 | 477 |             // vectors are linearly dependent or zero so no solution | 
 | 478 | #if DEBUG_STRATEGY | 
 | 479 |             ALOGD("  - no solution, norm=%f", norm); | 
 | 480 | #endif | 
 | 481 |             return false; | 
 | 482 |         } | 
 | 483 |  | 
 | 484 |         float invNorm = 1.0f / norm; | 
 | 485 |         for (uint32_t h = 0; h < m; h++) { | 
 | 486 |             q[j][h] *= invNorm; | 
 | 487 |         } | 
 | 488 |         for (uint32_t i = 0; i < n; i++) { | 
 | 489 |             r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m); | 
 | 490 |         } | 
 | 491 |     } | 
 | 492 | #if DEBUG_STRATEGY | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 493 |     ALOGD("  - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str()); | 
 | 494 |     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] | 495 |  | 
 | 496 |     // calculate QR, if we factored A correctly then QR should equal A | 
 | 497 |     float qr[n][m]; | 
 | 498 |     for (uint32_t h = 0; h < m; h++) { | 
 | 499 |         for (uint32_t i = 0; i < n; i++) { | 
 | 500 |             qr[i][h] = 0; | 
 | 501 |             for (uint32_t j = 0; j < n; j++) { | 
 | 502 |                 qr[i][h] += q[j][h] * r[j][i]; | 
 | 503 |             } | 
 | 504 |         } | 
 | 505 |     } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 506 |     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] | 507 | #endif | 
 | 508 |  | 
 | 509 |     // Solve R B = Qt W Y to find B.  This is easy because R is upper triangular. | 
 | 510 |     // We just work from bottom-right to top-left calculating B's coefficients. | 
 | 511 |     float wy[m]; | 
 | 512 |     for (uint32_t h = 0; h < m; h++) { | 
 | 513 |         wy[h] = y[h] * w[h]; | 
 | 514 |     } | 
| Dan Austin | 389ddba | 2015-09-22 14:32:03 -0700 | [diff] [blame] | 515 |     for (uint32_t i = n; i != 0; ) { | 
 | 516 |         i--; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 517 |         outB[i] = vectorDot(&q[i][0], wy, m); | 
 | 518 |         for (uint32_t j = n - 1; j > i; j--) { | 
 | 519 |             outB[i] -= r[i][j] * outB[j]; | 
 | 520 |         } | 
 | 521 |         outB[i] /= r[i][i]; | 
 | 522 |     } | 
 | 523 | #if DEBUG_STRATEGY | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 524 |     ALOGD("  - b=%s", vectorToString(outB, n).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 525 | #endif | 
 | 526 |  | 
 | 527 |     // Calculate the coefficient of determination as 1 - (SSerr / SStot) where | 
 | 528 |     // SSerr is the residual sum of squares (variance of the error), | 
 | 529 |     // and SStot is the total sum of squares (variance of the data) where each | 
 | 530 |     // has been weighted. | 
 | 531 |     float ymean = 0; | 
 | 532 |     for (uint32_t h = 0; h < m; h++) { | 
 | 533 |         ymean += y[h]; | 
 | 534 |     } | 
 | 535 |     ymean /= m; | 
 | 536 |  | 
 | 537 |     float sserr = 0; | 
 | 538 |     float sstot = 0; | 
 | 539 |     for (uint32_t h = 0; h < m; h++) { | 
 | 540 |         float err = y[h] - outB[0]; | 
 | 541 |         float term = 1; | 
 | 542 |         for (uint32_t i = 1; i < n; i++) { | 
 | 543 |             term *= x[h]; | 
 | 544 |             err -= term * outB[i]; | 
 | 545 |         } | 
 | 546 |         sserr += w[h] * w[h] * err * err; | 
 | 547 |         float var = y[h] - ymean; | 
 | 548 |         sstot += w[h] * w[h] * var * var; | 
 | 549 |     } | 
 | 550 |     *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1; | 
 | 551 | #if DEBUG_STRATEGY | 
 | 552 |     ALOGD("  - sserr=%f", sserr); | 
 | 553 |     ALOGD("  - sstot=%f", sstot); | 
 | 554 |     ALOGD("  - det=%f", *outDet); | 
 | 555 | #endif | 
 | 556 |     return true; | 
 | 557 | } | 
 | 558 |  | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 559 | /* | 
 | 560 |  * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to | 
 | 561 |  * the default implementation | 
 | 562 |  */ | 
 | 563 | static float solveUnweightedLeastSquaresDeg2(const float* x, const float* y, size_t count) { | 
 | 564 |     float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0; | 
 | 565 |  | 
 | 566 |     for (size_t i = 0; i < count; i++) { | 
 | 567 |         float xi = x[i]; | 
 | 568 |         float yi = y[i]; | 
 | 569 |         float xi2 = xi*xi; | 
 | 570 |         float xi3 = xi2*xi; | 
 | 571 |         float xi4 = xi3*xi; | 
 | 572 |         float xi2yi = xi2*yi; | 
 | 573 |         float xiyi = xi*yi; | 
 | 574 |  | 
 | 575 |         sxi += xi; | 
 | 576 |         sxi2 += xi2; | 
 | 577 |         sxiyi += xiyi; | 
 | 578 |         sxi2yi += xi2yi; | 
 | 579 |         syi += yi; | 
 | 580 |         sxi3 += xi3; | 
 | 581 |         sxi4 += xi4; | 
 | 582 |     } | 
 | 583 |  | 
 | 584 |     float Sxx = sxi2 - sxi*sxi / count; | 
 | 585 |     float Sxy = sxiyi - sxi*syi / count; | 
 | 586 |     float Sxx2 = sxi3 - sxi*sxi2 / count; | 
 | 587 |     float Sx2y = sxi2yi - sxi2*syi / count; | 
 | 588 |     float Sx2x2 = sxi4 - sxi2*sxi2 / count; | 
 | 589 |  | 
 | 590 |     float numerator = Sxy*Sx2x2 - Sx2y*Sxx2; | 
 | 591 |     float denominator = Sxx*Sx2x2 - Sxx2*Sxx2; | 
 | 592 |     if (denominator == 0) { | 
 | 593 |         ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2); | 
 | 594 |         return 0; | 
 | 595 |     } | 
 | 596 |     return numerator/denominator; | 
 | 597 | } | 
 | 598 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 599 | bool LeastSquaresVelocityTrackerStrategy::getEstimator(uint32_t id, | 
 | 600 |         VelocityTracker::Estimator* outEstimator) const { | 
 | 601 |     outEstimator->clear(); | 
 | 602 |  | 
 | 603 |     // Iterate over movement samples in reverse time order and collect samples. | 
 | 604 |     float x[HISTORY_SIZE]; | 
 | 605 |     float y[HISTORY_SIZE]; | 
 | 606 |     float w[HISTORY_SIZE]; | 
 | 607 |     float time[HISTORY_SIZE]; | 
 | 608 |     uint32_t m = 0; | 
 | 609 |     uint32_t index = mIndex; | 
 | 610 |     const Movement& newestMovement = mMovements[mIndex]; | 
 | 611 |     do { | 
 | 612 |         const Movement& movement = mMovements[index]; | 
 | 613 |         if (!movement.idBits.hasBit(id)) { | 
 | 614 |             break; | 
 | 615 |         } | 
 | 616 |  | 
 | 617 |         nsecs_t age = newestMovement.eventTime - movement.eventTime; | 
 | 618 |         if (age > HORIZON) { | 
 | 619 |             break; | 
 | 620 |         } | 
 | 621 |  | 
 | 622 |         const VelocityTracker::Position& position = movement.getPosition(id); | 
 | 623 |         x[m] = position.x; | 
 | 624 |         y[m] = position.y; | 
 | 625 |         w[m] = chooseWeight(index); | 
 | 626 |         time[m] = -age * 0.000000001f; | 
 | 627 |         index = (index == 0 ? HISTORY_SIZE : index) - 1; | 
 | 628 |     } while (++m < HISTORY_SIZE); | 
 | 629 |  | 
 | 630 |     if (m == 0) { | 
 | 631 |         return false; // no data | 
 | 632 |     } | 
 | 633 |  | 
 | 634 |     // Calculate a least squares polynomial fit. | 
 | 635 |     uint32_t degree = mDegree; | 
 | 636 |     if (degree > m - 1) { | 
 | 637 |         degree = m - 1; | 
 | 638 |     } | 
 | 639 |     if (degree >= 1) { | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 640 |         if (degree == 2 && mWeighting == WEIGHTING_NONE) { // optimize unweighted, degree=2 fit | 
 | 641 |             outEstimator->time = newestMovement.eventTime; | 
 | 642 |             outEstimator->degree = 2; | 
 | 643 |             outEstimator->confidence = 1; | 
 | 644 |             outEstimator->xCoeff[0] = 0; // only slope is calculated, set rest of coefficients = 0 | 
 | 645 |             outEstimator->yCoeff[0] = 0; | 
 | 646 |             outEstimator->xCoeff[1] = solveUnweightedLeastSquaresDeg2(time, x, m); | 
 | 647 |             outEstimator->yCoeff[1] = solveUnweightedLeastSquaresDeg2(time, y, m); | 
 | 648 |             outEstimator->xCoeff[2] = 0; | 
 | 649 |             outEstimator->yCoeff[2] = 0; | 
 | 650 |             return true; | 
 | 651 |         } | 
 | 652 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 653 |         float xdet, ydet; | 
 | 654 |         uint32_t n = degree + 1; | 
 | 655 |         if (solveLeastSquares(time, x, w, m, n, outEstimator->xCoeff, &xdet) | 
 | 656 |                 && solveLeastSquares(time, y, w, m, n, outEstimator->yCoeff, &ydet)) { | 
 | 657 |             outEstimator->time = newestMovement.eventTime; | 
 | 658 |             outEstimator->degree = degree; | 
 | 659 |             outEstimator->confidence = xdet * ydet; | 
 | 660 | #if DEBUG_STRATEGY | 
 | 661 |             ALOGD("estimate: degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f", | 
 | 662 |                     int(outEstimator->degree), | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 663 |                     vectorToString(outEstimator->xCoeff, n).c_str(), | 
 | 664 |                     vectorToString(outEstimator->yCoeff, n).c_str(), | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 665 |                     outEstimator->confidence); | 
 | 666 | #endif | 
 | 667 |             return true; | 
 | 668 |         } | 
 | 669 |     } | 
 | 670 |  | 
 | 671 |     // No velocity data available for this pointer, but we do have its current position. | 
 | 672 |     outEstimator->xCoeff[0] = x[0]; | 
 | 673 |     outEstimator->yCoeff[0] = y[0]; | 
 | 674 |     outEstimator->time = newestMovement.eventTime; | 
 | 675 |     outEstimator->degree = 0; | 
 | 676 |     outEstimator->confidence = 1; | 
 | 677 |     return true; | 
 | 678 | } | 
 | 679 |  | 
 | 680 | float LeastSquaresVelocityTrackerStrategy::chooseWeight(uint32_t index) const { | 
 | 681 |     switch (mWeighting) { | 
 | 682 |     case WEIGHTING_DELTA: { | 
 | 683 |         // Weight points based on how much time elapsed between them and the next | 
 | 684 |         // point so that points that "cover" a shorter time span are weighed less. | 
 | 685 |         //   delta  0ms: 0.5 | 
 | 686 |         //   delta 10ms: 1.0 | 
 | 687 |         if (index == mIndex) { | 
 | 688 |             return 1.0f; | 
 | 689 |         } | 
 | 690 |         uint32_t nextIndex = (index + 1) % HISTORY_SIZE; | 
 | 691 |         float deltaMillis = (mMovements[nextIndex].eventTime- mMovements[index].eventTime) | 
 | 692 |                 * 0.000001f; | 
 | 693 |         if (deltaMillis < 0) { | 
 | 694 |             return 0.5f; | 
 | 695 |         } | 
 | 696 |         if (deltaMillis < 10) { | 
 | 697 |             return 0.5f + deltaMillis * 0.05; | 
 | 698 |         } | 
 | 699 |         return 1.0f; | 
 | 700 |     } | 
 | 701 |  | 
 | 702 |     case WEIGHTING_CENTRAL: { | 
 | 703 |         // Weight points based on their age, weighing very recent and very old points less. | 
 | 704 |         //   age  0ms: 0.5 | 
 | 705 |         //   age 10ms: 1.0 | 
 | 706 |         //   age 50ms: 1.0 | 
 | 707 |         //   age 60ms: 0.5 | 
 | 708 |         float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime) | 
 | 709 |                 * 0.000001f; | 
 | 710 |         if (ageMillis < 0) { | 
 | 711 |             return 0.5f; | 
 | 712 |         } | 
 | 713 |         if (ageMillis < 10) { | 
 | 714 |             return 0.5f + ageMillis * 0.05; | 
 | 715 |         } | 
 | 716 |         if (ageMillis < 50) { | 
 | 717 |             return 1.0f; | 
 | 718 |         } | 
 | 719 |         if (ageMillis < 60) { | 
 | 720 |             return 0.5f + (60 - ageMillis) * 0.05; | 
 | 721 |         } | 
 | 722 |         return 0.5f; | 
 | 723 |     } | 
 | 724 |  | 
 | 725 |     case WEIGHTING_RECENT: { | 
 | 726 |         // Weight points based on their age, weighing older points less. | 
 | 727 |         //   age   0ms: 1.0 | 
 | 728 |         //   age  50ms: 1.0 | 
 | 729 |         //   age 100ms: 0.5 | 
 | 730 |         float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime) | 
 | 731 |                 * 0.000001f; | 
 | 732 |         if (ageMillis < 50) { | 
 | 733 |             return 1.0f; | 
 | 734 |         } | 
 | 735 |         if (ageMillis < 100) { | 
 | 736 |             return 0.5f + (100 - ageMillis) * 0.01f; | 
 | 737 |         } | 
 | 738 |         return 0.5f; | 
 | 739 |     } | 
 | 740 |  | 
 | 741 |     case WEIGHTING_NONE: | 
 | 742 |     default: | 
 | 743 |         return 1.0f; | 
 | 744 |     } | 
 | 745 | } | 
 | 746 |  | 
 | 747 |  | 
 | 748 | // --- IntegratingVelocityTrackerStrategy --- | 
 | 749 |  | 
 | 750 | IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) : | 
 | 751 |         mDegree(degree) { | 
 | 752 | } | 
 | 753 |  | 
 | 754 | IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() { | 
 | 755 | } | 
 | 756 |  | 
 | 757 | void IntegratingVelocityTrackerStrategy::clear() { | 
 | 758 |     mPointerIdBits.clear(); | 
 | 759 | } | 
 | 760 |  | 
 | 761 | void IntegratingVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
 | 762 |     mPointerIdBits.value &= ~idBits.value; | 
 | 763 | } | 
 | 764 |  | 
 | 765 | void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
 | 766 |         const VelocityTracker::Position* positions) { | 
 | 767 |     uint32_t index = 0; | 
 | 768 |     for (BitSet32 iterIdBits(idBits); !iterIdBits.isEmpty();) { | 
 | 769 |         uint32_t id = iterIdBits.clearFirstMarkedBit(); | 
 | 770 |         State& state = mPointerState[id]; | 
 | 771 |         const VelocityTracker::Position& position = positions[index++]; | 
 | 772 |         if (mPointerIdBits.hasBit(id)) { | 
 | 773 |             updateState(state, eventTime, position.x, position.y); | 
 | 774 |         } else { | 
 | 775 |             initState(state, eventTime, position.x, position.y); | 
 | 776 |         } | 
 | 777 |     } | 
 | 778 |  | 
 | 779 |     mPointerIdBits = idBits; | 
 | 780 | } | 
 | 781 |  | 
 | 782 | bool IntegratingVelocityTrackerStrategy::getEstimator(uint32_t id, | 
 | 783 |         VelocityTracker::Estimator* outEstimator) const { | 
 | 784 |     outEstimator->clear(); | 
 | 785 |  | 
 | 786 |     if (mPointerIdBits.hasBit(id)) { | 
 | 787 |         const State& state = mPointerState[id]; | 
 | 788 |         populateEstimator(state, outEstimator); | 
 | 789 |         return true; | 
 | 790 |     } | 
 | 791 |  | 
 | 792 |     return false; | 
 | 793 | } | 
 | 794 |  | 
 | 795 | void IntegratingVelocityTrackerStrategy::initState(State& state, | 
 | 796 |         nsecs_t eventTime, float xpos, float ypos) const { | 
 | 797 |     state.updateTime = eventTime; | 
 | 798 |     state.degree = 0; | 
 | 799 |  | 
 | 800 |     state.xpos = xpos; | 
 | 801 |     state.xvel = 0; | 
 | 802 |     state.xaccel = 0; | 
 | 803 |     state.ypos = ypos; | 
 | 804 |     state.yvel = 0; | 
 | 805 |     state.yaccel = 0; | 
 | 806 | } | 
 | 807 |  | 
 | 808 | void IntegratingVelocityTrackerStrategy::updateState(State& state, | 
 | 809 |         nsecs_t eventTime, float xpos, float ypos) const { | 
 | 810 |     const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS; | 
 | 811 |     const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds | 
 | 812 |  | 
 | 813 |     if (eventTime <= state.updateTime + MIN_TIME_DELTA) { | 
 | 814 |         return; | 
 | 815 |     } | 
 | 816 |  | 
 | 817 |     float dt = (eventTime - state.updateTime) * 0.000000001f; | 
 | 818 |     state.updateTime = eventTime; | 
 | 819 |  | 
 | 820 |     float xvel = (xpos - state.xpos) / dt; | 
 | 821 |     float yvel = (ypos - state.ypos) / dt; | 
 | 822 |     if (state.degree == 0) { | 
 | 823 |         state.xvel = xvel; | 
 | 824 |         state.yvel = yvel; | 
 | 825 |         state.degree = 1; | 
 | 826 |     } else { | 
 | 827 |         float alpha = dt / (FILTER_TIME_CONSTANT + dt); | 
 | 828 |         if (mDegree == 1) { | 
 | 829 |             state.xvel += (xvel - state.xvel) * alpha; | 
 | 830 |             state.yvel += (yvel - state.yvel) * alpha; | 
 | 831 |         } else { | 
 | 832 |             float xaccel = (xvel - state.xvel) / dt; | 
 | 833 |             float yaccel = (yvel - state.yvel) / dt; | 
 | 834 |             if (state.degree == 1) { | 
 | 835 |                 state.xaccel = xaccel; | 
 | 836 |                 state.yaccel = yaccel; | 
 | 837 |                 state.degree = 2; | 
 | 838 |             } else { | 
 | 839 |                 state.xaccel += (xaccel - state.xaccel) * alpha; | 
 | 840 |                 state.yaccel += (yaccel - state.yaccel) * alpha; | 
 | 841 |             } | 
 | 842 |             state.xvel += (state.xaccel * dt) * alpha; | 
 | 843 |             state.yvel += (state.yaccel * dt) * alpha; | 
 | 844 |         } | 
 | 845 |     } | 
 | 846 |     state.xpos = xpos; | 
 | 847 |     state.ypos = ypos; | 
 | 848 | } | 
 | 849 |  | 
 | 850 | void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state, | 
 | 851 |         VelocityTracker::Estimator* outEstimator) const { | 
 | 852 |     outEstimator->time = state.updateTime; | 
 | 853 |     outEstimator->confidence = 1.0f; | 
 | 854 |     outEstimator->degree = state.degree; | 
 | 855 |     outEstimator->xCoeff[0] = state.xpos; | 
 | 856 |     outEstimator->xCoeff[1] = state.xvel; | 
 | 857 |     outEstimator->xCoeff[2] = state.xaccel / 2; | 
 | 858 |     outEstimator->yCoeff[0] = state.ypos; | 
 | 859 |     outEstimator->yCoeff[1] = state.yvel; | 
 | 860 |     outEstimator->yCoeff[2] = state.yaccel / 2; | 
 | 861 | } | 
 | 862 |  | 
 | 863 |  | 
 | 864 | // --- LegacyVelocityTrackerStrategy --- | 
 | 865 |  | 
 | 866 | const nsecs_t LegacyVelocityTrackerStrategy::HORIZON; | 
 | 867 | const uint32_t LegacyVelocityTrackerStrategy::HISTORY_SIZE; | 
 | 868 | const nsecs_t LegacyVelocityTrackerStrategy::MIN_DURATION; | 
 | 869 |  | 
 | 870 | LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() { | 
 | 871 |     clear(); | 
 | 872 | } | 
 | 873 |  | 
 | 874 | LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() { | 
 | 875 | } | 
 | 876 |  | 
 | 877 | void LegacyVelocityTrackerStrategy::clear() { | 
 | 878 |     mIndex = 0; | 
 | 879 |     mMovements[0].idBits.clear(); | 
 | 880 | } | 
 | 881 |  | 
 | 882 | void LegacyVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
 | 883 |     BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); | 
 | 884 |     mMovements[mIndex].idBits = remainingIdBits; | 
 | 885 | } | 
 | 886 |  | 
 | 887 | void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
 | 888 |         const VelocityTracker::Position* positions) { | 
 | 889 |     if (++mIndex == HISTORY_SIZE) { | 
 | 890 |         mIndex = 0; | 
 | 891 |     } | 
 | 892 |  | 
 | 893 |     Movement& movement = mMovements[mIndex]; | 
 | 894 |     movement.eventTime = eventTime; | 
 | 895 |     movement.idBits = idBits; | 
 | 896 |     uint32_t count = idBits.count(); | 
 | 897 |     for (uint32_t i = 0; i < count; i++) { | 
 | 898 |         movement.positions[i] = positions[i]; | 
 | 899 |     } | 
 | 900 | } | 
 | 901 |  | 
 | 902 | bool LegacyVelocityTrackerStrategy::getEstimator(uint32_t id, | 
 | 903 |         VelocityTracker::Estimator* outEstimator) const { | 
 | 904 |     outEstimator->clear(); | 
 | 905 |  | 
 | 906 |     const Movement& newestMovement = mMovements[mIndex]; | 
 | 907 |     if (!newestMovement.idBits.hasBit(id)) { | 
 | 908 |         return false; // no data | 
 | 909 |     } | 
 | 910 |  | 
 | 911 |     // Find the oldest sample that contains the pointer and that is not older than HORIZON. | 
 | 912 |     nsecs_t minTime = newestMovement.eventTime - HORIZON; | 
 | 913 |     uint32_t oldestIndex = mIndex; | 
 | 914 |     uint32_t numTouches = 1; | 
 | 915 |     do { | 
 | 916 |         uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1; | 
 | 917 |         const Movement& nextOldestMovement = mMovements[nextOldestIndex]; | 
 | 918 |         if (!nextOldestMovement.idBits.hasBit(id) | 
 | 919 |                 || nextOldestMovement.eventTime < minTime) { | 
 | 920 |             break; | 
 | 921 |         } | 
 | 922 |         oldestIndex = nextOldestIndex; | 
 | 923 |     } while (++numTouches < HISTORY_SIZE); | 
 | 924 |  | 
 | 925 |     // Calculate an exponentially weighted moving average of the velocity estimate | 
 | 926 |     // at different points in time measured relative to the oldest sample. | 
 | 927 |     // This is essentially an IIR filter.  Newer samples are weighted more heavily | 
 | 928 |     // than older samples.  Samples at equal time points are weighted more or less | 
 | 929 |     // equally. | 
 | 930 |     // | 
 | 931 |     // One tricky problem is that the sample data may be poorly conditioned. | 
 | 932 |     // Sometimes samples arrive very close together in time which can cause us to | 
 | 933 |     // overestimate the velocity at that time point.  Most samples might be measured | 
 | 934 |     // 16ms apart but some consecutive samples could be only 0.5sm apart because | 
 | 935 |     // the hardware or driver reports them irregularly or in bursts. | 
 | 936 |     float accumVx = 0; | 
 | 937 |     float accumVy = 0; | 
 | 938 |     uint32_t index = oldestIndex; | 
 | 939 |     uint32_t samplesUsed = 0; | 
 | 940 |     const Movement& oldestMovement = mMovements[oldestIndex]; | 
 | 941 |     const VelocityTracker::Position& oldestPosition = oldestMovement.getPosition(id); | 
 | 942 |     nsecs_t lastDuration = 0; | 
 | 943 |  | 
 | 944 |     while (numTouches-- > 1) { | 
 | 945 |         if (++index == HISTORY_SIZE) { | 
 | 946 |             index = 0; | 
 | 947 |         } | 
 | 948 |         const Movement& movement = mMovements[index]; | 
 | 949 |         nsecs_t duration = movement.eventTime - oldestMovement.eventTime; | 
 | 950 |  | 
 | 951 |         // If the duration between samples is small, we may significantly overestimate | 
 | 952 |         // the velocity.  Consequently, we impose a minimum duration constraint on the | 
 | 953 |         // samples that we include in the calculation. | 
 | 954 |         if (duration >= MIN_DURATION) { | 
 | 955 |             const VelocityTracker::Position& position = movement.getPosition(id); | 
 | 956 |             float scale = 1000000000.0f / duration; // one over time delta in seconds | 
 | 957 |             float vx = (position.x - oldestPosition.x) * scale; | 
 | 958 |             float vy = (position.y - oldestPosition.y) * scale; | 
 | 959 |             accumVx = (accumVx * lastDuration + vx * duration) / (duration + lastDuration); | 
 | 960 |             accumVy = (accumVy * lastDuration + vy * duration) / (duration + lastDuration); | 
 | 961 |             lastDuration = duration; | 
 | 962 |             samplesUsed += 1; | 
 | 963 |         } | 
 | 964 |     } | 
 | 965 |  | 
 | 966 |     // Report velocity. | 
 | 967 |     const VelocityTracker::Position& newestPosition = newestMovement.getPosition(id); | 
 | 968 |     outEstimator->time = newestMovement.eventTime; | 
 | 969 |     outEstimator->confidence = 1; | 
 | 970 |     outEstimator->xCoeff[0] = newestPosition.x; | 
 | 971 |     outEstimator->yCoeff[0] = newestPosition.y; | 
 | 972 |     if (samplesUsed) { | 
 | 973 |         outEstimator->xCoeff[1] = accumVx; | 
 | 974 |         outEstimator->yCoeff[1] = accumVy; | 
 | 975 |         outEstimator->degree = 1; | 
 | 976 |     } else { | 
 | 977 |         outEstimator->degree = 0; | 
 | 978 |     } | 
 | 979 |     return true; | 
 | 980 | } | 
 | 981 |  | 
 | 982 | } // namespace android |