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