xref: /aosp_15_r20/frameworks/native/libs/input/MotionPredictor.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1*38e8c45fSAndroid Build Coastguard Worker /*
2*38e8c45fSAndroid Build Coastguard Worker  * Copyright (C) 2022 The Android Open Source Project
3*38e8c45fSAndroid Build Coastguard Worker  *
4*38e8c45fSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*38e8c45fSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*38e8c45fSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*38e8c45fSAndroid Build Coastguard Worker  *
8*38e8c45fSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*38e8c45fSAndroid Build Coastguard Worker  *
10*38e8c45fSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*38e8c45fSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*38e8c45fSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*38e8c45fSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*38e8c45fSAndroid Build Coastguard Worker  * limitations under the License.
15*38e8c45fSAndroid Build Coastguard Worker  */
16*38e8c45fSAndroid Build Coastguard Worker 
17*38e8c45fSAndroid Build Coastguard Worker #define LOG_TAG "MotionPredictor"
18*38e8c45fSAndroid Build Coastguard Worker 
19*38e8c45fSAndroid Build Coastguard Worker #include <input/MotionPredictor.h>
20*38e8c45fSAndroid Build Coastguard Worker 
21*38e8c45fSAndroid Build Coastguard Worker #include <algorithm>
22*38e8c45fSAndroid Build Coastguard Worker #include <array>
23*38e8c45fSAndroid Build Coastguard Worker #include <cinttypes>
24*38e8c45fSAndroid Build Coastguard Worker #include <cmath>
25*38e8c45fSAndroid Build Coastguard Worker #include <cstddef>
26*38e8c45fSAndroid Build Coastguard Worker #include <cstdint>
27*38e8c45fSAndroid Build Coastguard Worker #include <limits>
28*38e8c45fSAndroid Build Coastguard Worker #include <optional>
29*38e8c45fSAndroid Build Coastguard Worker #include <string>
30*38e8c45fSAndroid Build Coastguard Worker #include <utility>
31*38e8c45fSAndroid Build Coastguard Worker #include <vector>
32*38e8c45fSAndroid Build Coastguard Worker 
33*38e8c45fSAndroid Build Coastguard Worker #include <android-base/logging.h>
34*38e8c45fSAndroid Build Coastguard Worker #include <android-base/strings.h>
35*38e8c45fSAndroid Build Coastguard Worker #include <android/input.h>
36*38e8c45fSAndroid Build Coastguard Worker #include <com_android_input_flags.h>
37*38e8c45fSAndroid Build Coastguard Worker 
38*38e8c45fSAndroid Build Coastguard Worker #include <attestation/HmacKeyManager.h>
39*38e8c45fSAndroid Build Coastguard Worker #include <ftl/enum.h>
40*38e8c45fSAndroid Build Coastguard Worker #include <input/TfLiteMotionPredictor.h>
41*38e8c45fSAndroid Build Coastguard Worker 
42*38e8c45fSAndroid Build Coastguard Worker namespace input_flags = com::android::input::flags;
43*38e8c45fSAndroid Build Coastguard Worker 
44*38e8c45fSAndroid Build Coastguard Worker namespace android {
45*38e8c45fSAndroid Build Coastguard Worker namespace {
46*38e8c45fSAndroid Build Coastguard Worker 
47*38e8c45fSAndroid Build Coastguard Worker /**
48*38e8c45fSAndroid Build Coastguard Worker  * Log debug messages about predictions.
49*38e8c45fSAndroid Build Coastguard Worker  * Enable this via "adb shell setprop log.tag.MotionPredictor DEBUG"
50*38e8c45fSAndroid Build Coastguard Worker  */
isDebug()51*38e8c45fSAndroid Build Coastguard Worker bool isDebug() {
52*38e8c45fSAndroid Build Coastguard Worker     return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
53*38e8c45fSAndroid Build Coastguard Worker }
54*38e8c45fSAndroid Build Coastguard Worker 
55*38e8c45fSAndroid Build Coastguard Worker // Converts a prediction of some polar (r, phi) to Cartesian (x, y) when applied to an axis.
convertPrediction(const TfLiteMotionPredictorSample::Point & axisFrom,const TfLiteMotionPredictorSample::Point & axisTo,float r,float phi)56*38e8c45fSAndroid Build Coastguard Worker TfLiteMotionPredictorSample::Point convertPrediction(
57*38e8c45fSAndroid Build Coastguard Worker         const TfLiteMotionPredictorSample::Point& axisFrom,
58*38e8c45fSAndroid Build Coastguard Worker         const TfLiteMotionPredictorSample::Point& axisTo, float r, float phi) {
59*38e8c45fSAndroid Build Coastguard Worker     const TfLiteMotionPredictorSample::Point axis = axisTo - axisFrom;
60*38e8c45fSAndroid Build Coastguard Worker     const float axis_phi = std::atan2(axis.y, axis.x);
61*38e8c45fSAndroid Build Coastguard Worker     const float x_delta = r * std::cos(axis_phi + phi);
62*38e8c45fSAndroid Build Coastguard Worker     const float y_delta = r * std::sin(axis_phi + phi);
63*38e8c45fSAndroid Build Coastguard Worker     return {.x = axisTo.x + x_delta, .y = axisTo.y + y_delta};
64*38e8c45fSAndroid Build Coastguard Worker }
65*38e8c45fSAndroid Build Coastguard Worker 
normalizeRange(float x,float min,float max)66*38e8c45fSAndroid Build Coastguard Worker float normalizeRange(float x, float min, float max) {
67*38e8c45fSAndroid Build Coastguard Worker     const float normalized = (x - min) / (max - min);
68*38e8c45fSAndroid Build Coastguard Worker     return std::min(1.0f, std::max(0.0f, normalized));
69*38e8c45fSAndroid Build Coastguard Worker }
70*38e8c45fSAndroid Build Coastguard Worker 
71*38e8c45fSAndroid Build Coastguard Worker } // namespace
72*38e8c45fSAndroid Build Coastguard Worker 
73*38e8c45fSAndroid Build Coastguard Worker // --- JerkTracker ---
74*38e8c45fSAndroid Build Coastguard Worker 
JerkTracker(bool normalizedDt,float alpha)75*38e8c45fSAndroid Build Coastguard Worker JerkTracker::JerkTracker(bool normalizedDt, float alpha)
76*38e8c45fSAndroid Build Coastguard Worker       : mNormalizedDt(normalizedDt), mAlpha(alpha) {}
77*38e8c45fSAndroid Build Coastguard Worker 
pushSample(int64_t timestamp,float xPos,float yPos)78*38e8c45fSAndroid Build Coastguard Worker void JerkTracker::pushSample(int64_t timestamp, float xPos, float yPos) {
79*38e8c45fSAndroid Build Coastguard Worker     // If we previously had full samples, we have a previous jerk calculation
80*38e8c45fSAndroid Build Coastguard Worker     // to do weighted smoothing.
81*38e8c45fSAndroid Build Coastguard Worker     const bool applySmoothing = mTimestamps.size() == mTimestamps.capacity();
82*38e8c45fSAndroid Build Coastguard Worker     mTimestamps.pushBack(timestamp);
83*38e8c45fSAndroid Build Coastguard Worker     const int numSamples = mTimestamps.size();
84*38e8c45fSAndroid Build Coastguard Worker 
85*38e8c45fSAndroid Build Coastguard Worker     std::array<float, 4> newXDerivatives;
86*38e8c45fSAndroid Build Coastguard Worker     std::array<float, 4> newYDerivatives;
87*38e8c45fSAndroid Build Coastguard Worker 
88*38e8c45fSAndroid Build Coastguard Worker     /**
89*38e8c45fSAndroid Build Coastguard Worker      * Diagram showing the calculation of higher order derivatives of sample x3
90*38e8c45fSAndroid Build Coastguard Worker      * collected at time=t3.
91*38e8c45fSAndroid Build Coastguard Worker      * Terms in parentheses are not stored (and not needed for calculations)
92*38e8c45fSAndroid Build Coastguard Worker      *  t0 ----- t1  ----- t2 ----- t3
93*38e8c45fSAndroid Build Coastguard Worker      * (x0)-----(x1) ----- x2 ----- x3
94*38e8c45fSAndroid Build Coastguard Worker      * (x'0) --- x'1 ---  x'2
95*38e8c45fSAndroid Build Coastguard Worker      *  x''0  -  x''1
96*38e8c45fSAndroid Build Coastguard Worker      *  x'''0
97*38e8c45fSAndroid Build Coastguard Worker      *
98*38e8c45fSAndroid Build Coastguard Worker      * In this example:
99*38e8c45fSAndroid Build Coastguard Worker      * x'2 = (x3 - x2) / (t3 - t2)
100*38e8c45fSAndroid Build Coastguard Worker      * x''1 = (x'2 - x'1) / (t2 - t1)
101*38e8c45fSAndroid Build Coastguard Worker      * x'''0 = (x''1 - x''0) / (t1 - t0)
102*38e8c45fSAndroid Build Coastguard Worker      * Therefore, timestamp history is needed to calculate higher order derivatives,
103*38e8c45fSAndroid Build Coastguard Worker      * compared to just the last calculated derivative sample.
104*38e8c45fSAndroid Build Coastguard Worker      *
105*38e8c45fSAndroid Build Coastguard Worker      * If mNormalizedDt = true, then dt = 1 and the division is moot.
106*38e8c45fSAndroid Build Coastguard Worker      */
107*38e8c45fSAndroid Build Coastguard Worker     for (int i = 0; i < numSamples; ++i) {
108*38e8c45fSAndroid Build Coastguard Worker         if (i == 0) {
109*38e8c45fSAndroid Build Coastguard Worker             newXDerivatives[i] = xPos;
110*38e8c45fSAndroid Build Coastguard Worker             newYDerivatives[i] = yPos;
111*38e8c45fSAndroid Build Coastguard Worker         } else {
112*38e8c45fSAndroid Build Coastguard Worker             newXDerivatives[i] = newXDerivatives[i - 1] - mXDerivatives[i - 1];
113*38e8c45fSAndroid Build Coastguard Worker             newYDerivatives[i] = newYDerivatives[i - 1] - mYDerivatives[i - 1];
114*38e8c45fSAndroid Build Coastguard Worker             if (!mNormalizedDt) {
115*38e8c45fSAndroid Build Coastguard Worker                 const float dt = mTimestamps[numSamples - i] - mTimestamps[numSamples - i - 1];
116*38e8c45fSAndroid Build Coastguard Worker                 newXDerivatives[i] = newXDerivatives[i] / dt;
117*38e8c45fSAndroid Build Coastguard Worker                 newYDerivatives[i] = newYDerivatives[i] / dt;
118*38e8c45fSAndroid Build Coastguard Worker             }
119*38e8c45fSAndroid Build Coastguard Worker         }
120*38e8c45fSAndroid Build Coastguard Worker     }
121*38e8c45fSAndroid Build Coastguard Worker 
122*38e8c45fSAndroid Build Coastguard Worker     if (numSamples == static_cast<int>(mTimestamps.capacity())) {
123*38e8c45fSAndroid Build Coastguard Worker         float newJerkMagnitude = std::hypot(newXDerivatives[3], newYDerivatives[3]);
124*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "raw jerk: %f", newJerkMagnitude);
125*38e8c45fSAndroid Build Coastguard Worker         if (applySmoothing) {
126*38e8c45fSAndroid Build Coastguard Worker             mJerkMagnitude = mJerkMagnitude + (mAlpha * (newJerkMagnitude - mJerkMagnitude));
127*38e8c45fSAndroid Build Coastguard Worker         } else {
128*38e8c45fSAndroid Build Coastguard Worker             mJerkMagnitude = newJerkMagnitude;
129*38e8c45fSAndroid Build Coastguard Worker         }
130*38e8c45fSAndroid Build Coastguard Worker     }
131*38e8c45fSAndroid Build Coastguard Worker 
132*38e8c45fSAndroid Build Coastguard Worker     std::swap(newXDerivatives, mXDerivatives);
133*38e8c45fSAndroid Build Coastguard Worker     std::swap(newYDerivatives, mYDerivatives);
134*38e8c45fSAndroid Build Coastguard Worker }
135*38e8c45fSAndroid Build Coastguard Worker 
reset()136*38e8c45fSAndroid Build Coastguard Worker void JerkTracker::reset() {
137*38e8c45fSAndroid Build Coastguard Worker     mTimestamps.clear();
138*38e8c45fSAndroid Build Coastguard Worker }
139*38e8c45fSAndroid Build Coastguard Worker 
jerkMagnitude() const140*38e8c45fSAndroid Build Coastguard Worker std::optional<float> JerkTracker::jerkMagnitude() const {
141*38e8c45fSAndroid Build Coastguard Worker     if (mTimestamps.size() == mTimestamps.capacity()) {
142*38e8c45fSAndroid Build Coastguard Worker         return mJerkMagnitude;
143*38e8c45fSAndroid Build Coastguard Worker     }
144*38e8c45fSAndroid Build Coastguard Worker     return std::nullopt;
145*38e8c45fSAndroid Build Coastguard Worker }
146*38e8c45fSAndroid Build Coastguard Worker 
147*38e8c45fSAndroid Build Coastguard Worker // --- MotionPredictor ---
148*38e8c45fSAndroid Build Coastguard Worker 
MotionPredictor(nsecs_t predictionTimestampOffsetNanos,std::function<bool ()> checkMotionPredictionEnabled,ReportAtomFunction reportAtomFunction)149*38e8c45fSAndroid Build Coastguard Worker MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
150*38e8c45fSAndroid Build Coastguard Worker                                  std::function<bool()> checkMotionPredictionEnabled,
151*38e8c45fSAndroid Build Coastguard Worker                                  ReportAtomFunction reportAtomFunction)
152*38e8c45fSAndroid Build Coastguard Worker       : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
153*38e8c45fSAndroid Build Coastguard Worker         mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)),
154*38e8c45fSAndroid Build Coastguard Worker         mReportAtomFunction(reportAtomFunction) {}
155*38e8c45fSAndroid Build Coastguard Worker 
initializeObjects()156*38e8c45fSAndroid Build Coastguard Worker void MotionPredictor::initializeObjects() {
157*38e8c45fSAndroid Build Coastguard Worker     mModel = TfLiteMotionPredictorModel::create();
158*38e8c45fSAndroid Build Coastguard Worker     LOG_ALWAYS_FATAL_IF(!mModel);
159*38e8c45fSAndroid Build Coastguard Worker 
160*38e8c45fSAndroid Build Coastguard Worker     // mJerkTracker assumes normalized dt = 1 between recorded samples because
161*38e8c45fSAndroid Build Coastguard Worker     // the underlying mModel input also assumes fixed-interval samples.
162*38e8c45fSAndroid Build Coastguard Worker     // Normalized dt as 1 is also used to correspond with the similar Jank
163*38e8c45fSAndroid Build Coastguard Worker     // implementation from the JetPack MotionPredictor implementation.
164*38e8c45fSAndroid Build Coastguard Worker     mJerkTracker = std::make_unique<JerkTracker>(/*normalizedDt=*/true, mModel->config().jerkAlpha);
165*38e8c45fSAndroid Build Coastguard Worker 
166*38e8c45fSAndroid Build Coastguard Worker     mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
167*38e8c45fSAndroid Build Coastguard Worker 
168*38e8c45fSAndroid Build Coastguard Worker     mMetricsManager =
169*38e8c45fSAndroid Build Coastguard Worker             std::make_unique<MotionPredictorMetricsManager>(mModel->config().predictionInterval,
170*38e8c45fSAndroid Build Coastguard Worker                                                             mModel->outputLength(),
171*38e8c45fSAndroid Build Coastguard Worker                                                             mReportAtomFunction);
172*38e8c45fSAndroid Build Coastguard Worker }
173*38e8c45fSAndroid Build Coastguard Worker 
record(const MotionEvent & event)174*38e8c45fSAndroid Build Coastguard Worker android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
175*38e8c45fSAndroid Build Coastguard Worker     if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
176*38e8c45fSAndroid Build Coastguard Worker         // We still have an active gesture for another device. The provided MotionEvent is not
177*38e8c45fSAndroid Build Coastguard Worker         // consistent with the previous gesture.
178*38e8c45fSAndroid Build Coastguard Worker         LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
179*38e8c45fSAndroid Build Coastguard Worker                    << __func__ << " is called with " << event;
180*38e8c45fSAndroid Build Coastguard Worker         return android::base::Error()
181*38e8c45fSAndroid Build Coastguard Worker                 << "Inconsistent event stream: still have an active gesture from device "
182*38e8c45fSAndroid Build Coastguard Worker                 << mLastEvent->getDeviceId() << ", but received " << event;
183*38e8c45fSAndroid Build Coastguard Worker     }
184*38e8c45fSAndroid Build Coastguard Worker     if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
185*38e8c45fSAndroid Build Coastguard Worker         ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
186*38e8c45fSAndroid Build Coastguard Worker               inputEventSourceToString(event.getSource()).c_str());
187*38e8c45fSAndroid Build Coastguard Worker         return {};
188*38e8c45fSAndroid Build Coastguard Worker     }
189*38e8c45fSAndroid Build Coastguard Worker 
190*38e8c45fSAndroid Build Coastguard Worker     if (!mModel) {
191*38e8c45fSAndroid Build Coastguard Worker         initializeObjects();
192*38e8c45fSAndroid Build Coastguard Worker     }
193*38e8c45fSAndroid Build Coastguard Worker 
194*38e8c45fSAndroid Build Coastguard Worker     // Pass input event to the MetricsManager.
195*38e8c45fSAndroid Build Coastguard Worker     mMetricsManager->onRecord(event);
196*38e8c45fSAndroid Build Coastguard Worker 
197*38e8c45fSAndroid Build Coastguard Worker     const int32_t action = event.getActionMasked();
198*38e8c45fSAndroid Build Coastguard Worker     if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
199*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "End of event stream");
200*38e8c45fSAndroid Build Coastguard Worker         mBuffers->reset();
201*38e8c45fSAndroid Build Coastguard Worker         mJerkTracker->reset();
202*38e8c45fSAndroid Build Coastguard Worker         mLastEvent.reset();
203*38e8c45fSAndroid Build Coastguard Worker         return {};
204*38e8c45fSAndroid Build Coastguard Worker     } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
205*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "Skipping unsupported %s action",
206*38e8c45fSAndroid Build Coastguard Worker                  MotionEvent::actionToString(action).c_str());
207*38e8c45fSAndroid Build Coastguard Worker         return {};
208*38e8c45fSAndroid Build Coastguard Worker     }
209*38e8c45fSAndroid Build Coastguard Worker 
210*38e8c45fSAndroid Build Coastguard Worker     if (event.getPointerCount() != 1) {
211*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
212*38e8c45fSAndroid Build Coastguard Worker         return {};
213*38e8c45fSAndroid Build Coastguard Worker     }
214*38e8c45fSAndroid Build Coastguard Worker 
215*38e8c45fSAndroid Build Coastguard Worker     const ToolType toolType = event.getPointerProperties(0)->toolType;
216*38e8c45fSAndroid Build Coastguard Worker     if (toolType != ToolType::STYLUS) {
217*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
218*38e8c45fSAndroid Build Coastguard Worker                  ftl::enum_string(toolType).c_str());
219*38e8c45fSAndroid Build Coastguard Worker         return {};
220*38e8c45fSAndroid Build Coastguard Worker     }
221*38e8c45fSAndroid Build Coastguard Worker 
222*38e8c45fSAndroid Build Coastguard Worker     for (size_t i = 0; i <= event.getHistorySize(); ++i) {
223*38e8c45fSAndroid Build Coastguard Worker         if (event.isResampled(0, i)) {
224*38e8c45fSAndroid Build Coastguard Worker             continue;
225*38e8c45fSAndroid Build Coastguard Worker         }
226*38e8c45fSAndroid Build Coastguard Worker         const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
227*38e8c45fSAndroid Build Coastguard Worker         mBuffers->pushSample(event.getHistoricalEventTime(i),
228*38e8c45fSAndroid Build Coastguard Worker                              {
229*38e8c45fSAndroid Build Coastguard Worker                                      .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
230*38e8c45fSAndroid Build Coastguard Worker                                      .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
231*38e8c45fSAndroid Build Coastguard Worker                                      .pressure = event.getHistoricalPressure(0, i),
232*38e8c45fSAndroid Build Coastguard Worker                                      .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
233*38e8c45fSAndroid Build Coastguard Worker                                                                           0, i),
234*38e8c45fSAndroid Build Coastguard Worker                                      .orientation = event.getHistoricalOrientation(0, i),
235*38e8c45fSAndroid Build Coastguard Worker                              });
236*38e8c45fSAndroid Build Coastguard Worker         mJerkTracker->pushSample(event.getHistoricalEventTime(i),
237*38e8c45fSAndroid Build Coastguard Worker                                  coords->getAxisValue(AMOTION_EVENT_AXIS_X),
238*38e8c45fSAndroid Build Coastguard Worker                                  coords->getAxisValue(AMOTION_EVENT_AXIS_Y));
239*38e8c45fSAndroid Build Coastguard Worker     }
240*38e8c45fSAndroid Build Coastguard Worker 
241*38e8c45fSAndroid Build Coastguard Worker     if (!mLastEvent) {
242*38e8c45fSAndroid Build Coastguard Worker         mLastEvent = MotionEvent();
243*38e8c45fSAndroid Build Coastguard Worker     }
244*38e8c45fSAndroid Build Coastguard Worker     mLastEvent->copyFrom(&event, /*keepHistory=*/false);
245*38e8c45fSAndroid Build Coastguard Worker 
246*38e8c45fSAndroid Build Coastguard Worker     return {};
247*38e8c45fSAndroid Build Coastguard Worker }
248*38e8c45fSAndroid Build Coastguard Worker 
predict(nsecs_t timestamp)249*38e8c45fSAndroid Build Coastguard Worker std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
250*38e8c45fSAndroid Build Coastguard Worker     if (mBuffers == nullptr || !mBuffers->isReady()) {
251*38e8c45fSAndroid Build Coastguard Worker         return nullptr;
252*38e8c45fSAndroid Build Coastguard Worker     }
253*38e8c45fSAndroid Build Coastguard Worker 
254*38e8c45fSAndroid Build Coastguard Worker     LOG_ALWAYS_FATAL_IF(!mModel);
255*38e8c45fSAndroid Build Coastguard Worker     mBuffers->copyTo(*mModel);
256*38e8c45fSAndroid Build Coastguard Worker     LOG_ALWAYS_FATAL_IF(!mModel->invoke());
257*38e8c45fSAndroid Build Coastguard Worker 
258*38e8c45fSAndroid Build Coastguard Worker     // Read out the predictions.
259*38e8c45fSAndroid Build Coastguard Worker     const std::span<const float> predictedR = mModel->outputR();
260*38e8c45fSAndroid Build Coastguard Worker     const std::span<const float> predictedPhi = mModel->outputPhi();
261*38e8c45fSAndroid Build Coastguard Worker     const std::span<const float> predictedPressure = mModel->outputPressure();
262*38e8c45fSAndroid Build Coastguard Worker 
263*38e8c45fSAndroid Build Coastguard Worker     TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
264*38e8c45fSAndroid Build Coastguard Worker     TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
265*38e8c45fSAndroid Build Coastguard Worker 
266*38e8c45fSAndroid Build Coastguard Worker     if (isDebug()) {
267*38e8c45fSAndroid Build Coastguard Worker         ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
268*38e8c45fSAndroid Build Coastguard Worker         ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
269*38e8c45fSAndroid Build Coastguard Worker         ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
270*38e8c45fSAndroid Build Coastguard Worker         ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
271*38e8c45fSAndroid Build Coastguard Worker         ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
272*38e8c45fSAndroid Build Coastguard Worker         ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
273*38e8c45fSAndroid Build Coastguard Worker         ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
274*38e8c45fSAndroid Build Coastguard Worker         ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
275*38e8c45fSAndroid Build Coastguard Worker         ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
276*38e8c45fSAndroid Build Coastguard Worker         ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
277*38e8c45fSAndroid Build Coastguard Worker     }
278*38e8c45fSAndroid Build Coastguard Worker 
279*38e8c45fSAndroid Build Coastguard Worker     LOG_ALWAYS_FATAL_IF(!mLastEvent);
280*38e8c45fSAndroid Build Coastguard Worker     const MotionEvent& event = *mLastEvent;
281*38e8c45fSAndroid Build Coastguard Worker     bool hasPredictions = false;
282*38e8c45fSAndroid Build Coastguard Worker     std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
283*38e8c45fSAndroid Build Coastguard Worker     int64_t predictionTime = mBuffers->lastTimestamp();
284*38e8c45fSAndroid Build Coastguard Worker     const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
285*38e8c45fSAndroid Build Coastguard Worker 
286*38e8c45fSAndroid Build Coastguard Worker     const float jerkMagnitude = mJerkTracker->jerkMagnitude().value_or(0);
287*38e8c45fSAndroid Build Coastguard Worker     const float fractionKept =
288*38e8c45fSAndroid Build Coastguard Worker             1 - normalizeRange(jerkMagnitude, mModel->config().lowJerk, mModel->config().highJerk);
289*38e8c45fSAndroid Build Coastguard Worker     // float to ensure proper division below.
290*38e8c45fSAndroid Build Coastguard Worker     const float predictionTimeWindow = futureTime - predictionTime;
291*38e8c45fSAndroid Build Coastguard Worker     const int maxNumPredictions = static_cast<int>(
292*38e8c45fSAndroid Build Coastguard Worker             std::ceil(predictionTimeWindow / mModel->config().predictionInterval * fractionKept));
293*38e8c45fSAndroid Build Coastguard Worker     ALOGD_IF(isDebug(),
294*38e8c45fSAndroid Build Coastguard Worker              "jerk (d^3p/normalizedDt^3): %f, fraction of prediction window pruned: %f, max number "
295*38e8c45fSAndroid Build Coastguard Worker              "of predictions: %d",
296*38e8c45fSAndroid Build Coastguard Worker              jerkMagnitude, 1 - fractionKept, maxNumPredictions);
297*38e8c45fSAndroid Build Coastguard Worker     for (size_t i = 0; i < static_cast<size_t>(predictedR.size()) && predictionTime <= futureTime;
298*38e8c45fSAndroid Build Coastguard Worker          ++i) {
299*38e8c45fSAndroid Build Coastguard Worker         if (predictedR[i] < mModel->config().distanceNoiseFloor) {
300*38e8c45fSAndroid Build Coastguard Worker             // Stop predicting when the predicted output is below the model's noise floor.
301*38e8c45fSAndroid Build Coastguard Worker             //
302*38e8c45fSAndroid Build Coastguard Worker             // We assume that all subsequent predictions in the batch are unreliable because later
303*38e8c45fSAndroid Build Coastguard Worker             // predictions are conditional on earlier predictions, and a state of noise is not a
304*38e8c45fSAndroid Build Coastguard Worker             // good basis for prediction.
305*38e8c45fSAndroid Build Coastguard Worker             //
306*38e8c45fSAndroid Build Coastguard Worker             // The UX trade-off is that this potentially sacrifices some predictions when the input
307*38e8c45fSAndroid Build Coastguard Worker             // device starts to speed up, but avoids producing noisy predictions as it slows down.
308*38e8c45fSAndroid Build Coastguard Worker             break;
309*38e8c45fSAndroid Build Coastguard Worker         }
310*38e8c45fSAndroid Build Coastguard Worker         if (input_flags::enable_prediction_pruning_via_jerk_thresholding()) {
311*38e8c45fSAndroid Build Coastguard Worker             if (i >= static_cast<size_t>(maxNumPredictions)) {
312*38e8c45fSAndroid Build Coastguard Worker                 break;
313*38e8c45fSAndroid Build Coastguard Worker             }
314*38e8c45fSAndroid Build Coastguard Worker         }
315*38e8c45fSAndroid Build Coastguard Worker         // TODO(b/266747654): Stop predictions if confidence is < some
316*38e8c45fSAndroid Build Coastguard Worker         // threshold. Currently predictions are pruned via jerk thresholding.
317*38e8c45fSAndroid Build Coastguard Worker 
318*38e8c45fSAndroid Build Coastguard Worker         const TfLiteMotionPredictorSample::Point predictedPoint =
319*38e8c45fSAndroid Build Coastguard Worker                 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
320*38e8c45fSAndroid Build Coastguard Worker 
321*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "prediction %zu: %f, %f", i, predictedPoint.x, predictedPoint.y);
322*38e8c45fSAndroid Build Coastguard Worker         PointerCoords coords;
323*38e8c45fSAndroid Build Coastguard Worker         coords.clear();
324*38e8c45fSAndroid Build Coastguard Worker         coords.setAxisValue(AMOTION_EVENT_AXIS_X, predictedPoint.x);
325*38e8c45fSAndroid Build Coastguard Worker         coords.setAxisValue(AMOTION_EVENT_AXIS_Y, predictedPoint.y);
326*38e8c45fSAndroid Build Coastguard Worker         coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
327*38e8c45fSAndroid Build Coastguard Worker         // Copy forward tilt and orientation from the last event until they are predicted
328*38e8c45fSAndroid Build Coastguard Worker         // (b/291789258).
329*38e8c45fSAndroid Build Coastguard Worker         coords.setAxisValue(AMOTION_EVENT_AXIS_TILT,
330*38e8c45fSAndroid Build Coastguard Worker                             event.getAxisValue(AMOTION_EVENT_AXIS_TILT, 0));
331*38e8c45fSAndroid Build Coastguard Worker         coords.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION,
332*38e8c45fSAndroid Build Coastguard Worker                             event.getRawPointerCoords(0)->getAxisValue(
333*38e8c45fSAndroid Build Coastguard Worker                                     AMOTION_EVENT_AXIS_ORIENTATION));
334*38e8c45fSAndroid Build Coastguard Worker 
335*38e8c45fSAndroid Build Coastguard Worker         predictionTime += mModel->config().predictionInterval;
336*38e8c45fSAndroid Build Coastguard Worker         if (i == 0) {
337*38e8c45fSAndroid Build Coastguard Worker             hasPredictions = true;
338*38e8c45fSAndroid Build Coastguard Worker             prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
339*38e8c45fSAndroid Build Coastguard Worker                                    event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
340*38e8c45fSAndroid Build Coastguard Worker                                    event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
341*38e8c45fSAndroid Build Coastguard Worker                                    event.getMetaState(), event.getButtonState(),
342*38e8c45fSAndroid Build Coastguard Worker                                    event.getClassification(), event.getTransform(),
343*38e8c45fSAndroid Build Coastguard Worker                                    event.getXPrecision(), event.getYPrecision(),
344*38e8c45fSAndroid Build Coastguard Worker                                    event.getRawXCursorPosition(), event.getRawYCursorPosition(),
345*38e8c45fSAndroid Build Coastguard Worker                                    event.getRawTransform(), event.getDownTime(), predictionTime,
346*38e8c45fSAndroid Build Coastguard Worker                                    event.getPointerCount(), event.getPointerProperties(), &coords);
347*38e8c45fSAndroid Build Coastguard Worker         } else {
348*38e8c45fSAndroid Build Coastguard Worker             prediction->addSample(predictionTime, &coords, prediction->getId());
349*38e8c45fSAndroid Build Coastguard Worker         }
350*38e8c45fSAndroid Build Coastguard Worker 
351*38e8c45fSAndroid Build Coastguard Worker         axisFrom = axisTo;
352*38e8c45fSAndroid Build Coastguard Worker         axisTo = predictedPoint;
353*38e8c45fSAndroid Build Coastguard Worker     }
354*38e8c45fSAndroid Build Coastguard Worker 
355*38e8c45fSAndroid Build Coastguard Worker     if (!hasPredictions) {
356*38e8c45fSAndroid Build Coastguard Worker         return nullptr;
357*38e8c45fSAndroid Build Coastguard Worker     }
358*38e8c45fSAndroid Build Coastguard Worker 
359*38e8c45fSAndroid Build Coastguard Worker     // Pass predictions to the MetricsManager.
360*38e8c45fSAndroid Build Coastguard Worker     LOG_ALWAYS_FATAL_IF(!mMetricsManager);
361*38e8c45fSAndroid Build Coastguard Worker     mMetricsManager->onPredict(*prediction);
362*38e8c45fSAndroid Build Coastguard Worker 
363*38e8c45fSAndroid Build Coastguard Worker     return prediction;
364*38e8c45fSAndroid Build Coastguard Worker }
365*38e8c45fSAndroid Build Coastguard Worker 
isPredictionAvailable(int32_t,int32_t source)366*38e8c45fSAndroid Build Coastguard Worker bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
367*38e8c45fSAndroid Build Coastguard Worker     // Global flag override
368*38e8c45fSAndroid Build Coastguard Worker     if (!mCheckMotionPredictionEnabled()) {
369*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "Prediction not available due to flag override");
370*38e8c45fSAndroid Build Coastguard Worker         return false;
371*38e8c45fSAndroid Build Coastguard Worker     }
372*38e8c45fSAndroid Build Coastguard Worker 
373*38e8c45fSAndroid Build Coastguard Worker     // Prediction is only supported for stylus sources.
374*38e8c45fSAndroid Build Coastguard Worker     if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
375*38e8c45fSAndroid Build Coastguard Worker         ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
376*38e8c45fSAndroid Build Coastguard Worker                  inputEventSourceToString(source).c_str());
377*38e8c45fSAndroid Build Coastguard Worker         return false;
378*38e8c45fSAndroid Build Coastguard Worker     }
379*38e8c45fSAndroid Build Coastguard Worker     return true;
380*38e8c45fSAndroid Build Coastguard Worker }
381*38e8c45fSAndroid Build Coastguard Worker 
382*38e8c45fSAndroid Build Coastguard Worker } // namespace android
383