blob: 5b61d3953f5c490f11dcc79c119893cfb32ad152 [file] [log] [blame]
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -08001/*
2 * Copyright (C) 2022 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 "MotionPredictor"
18
19#include <input/MotionPredictor.h>
20
Derek Wuaaa47312024-03-26 15:53:44 -070021#include <algorithm>
Derek Wu705068d2024-03-20 10:41:37 -070022#include <array>
Philip Quinn8f953ab2022-12-06 15:37:07 -080023#include <cinttypes>
24#include <cmath>
25#include <cstddef>
26#include <cstdint>
Derek Wuea36ee72024-03-25 13:17:51 -070027#include <limits>
Derek Wu705068d2024-03-20 10:41:37 -070028#include <optional>
Philip Quinn8f953ab2022-12-06 15:37:07 -080029#include <string>
Derek Wu705068d2024-03-20 10:41:37 -070030#include <utility>
Philip Quinn8f953ab2022-12-06 15:37:07 -080031#include <vector>
32
Yeabkal Wubshit64f090f2023-03-03 17:35:11 -080033#include <android-base/logging.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080034#include <android-base/strings.h>
35#include <android/input.h>
Derek Wuea36ee72024-03-25 13:17:51 -070036#include <com_android_input_flags.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080037
38#include <attestation/HmacKeyManager.h>
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -070039#include <ftl/enum.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080040#include <input/TfLiteMotionPredictor.h>
41
Derek Wuea36ee72024-03-25 13:17:51 -070042namespace input_flags = com::android::input::flags;
43
Philip Quinn8f953ab2022-12-06 15:37:07 -080044namespace android {
45namespace {
46
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080047/**
48 * Log debug messages about predictions.
49 * Enable this via "adb shell setprop log.tag.MotionPredictor DEBUG"
50 */
Philip Quinn8f953ab2022-12-06 15:37:07 -080051bool isDebug() {
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080052 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
53}
54
Philip Quinn8f953ab2022-12-06 15:37:07 -080055// Converts a prediction of some polar (r, phi) to Cartesian (x, y) when applied to an axis.
56TfLiteMotionPredictorSample::Point convertPrediction(
57 const TfLiteMotionPredictorSample::Point& axisFrom,
58 const TfLiteMotionPredictorSample::Point& axisTo, float r, float phi) {
59 const TfLiteMotionPredictorSample::Point axis = axisTo - axisFrom;
60 const float axis_phi = std::atan2(axis.y, axis.x);
61 const float x_delta = r * std::cos(axis_phi + phi);
62 const float y_delta = r * std::sin(axis_phi + phi);
63 return {.x = axisTo.x + x_delta, .y = axisTo.y + y_delta};
64}
65
Derek Wuaaa47312024-03-26 15:53:44 -070066float normalizeRange(float x, float min, float max) {
67 const float normalized = (x - min) / (max - min);
68 return std::min(1.0f, std::max(0.0f, normalized));
69}
70
Philip Quinn8f953ab2022-12-06 15:37:07 -080071} // namespace
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080072
Derek Wu705068d2024-03-20 10:41:37 -070073// --- JerkTracker ---
74
75JerkTracker::JerkTracker(bool normalizedDt) : mNormalizedDt(normalizedDt) {}
76
77void JerkTracker::pushSample(int64_t timestamp, float xPos, float yPos) {
78 mTimestamps.pushBack(timestamp);
79 const int numSamples = mTimestamps.size();
80
81 std::array<float, 4> newXDerivatives;
82 std::array<float, 4> newYDerivatives;
83
84 /**
85 * Diagram showing the calculation of higher order derivatives of sample x3
86 * collected at time=t3.
87 * Terms in parentheses are not stored (and not needed for calculations)
88 * t0 ----- t1 ----- t2 ----- t3
89 * (x0)-----(x1) ----- x2 ----- x3
90 * (x'0) --- x'1 --- x'2
91 * x''0 - x''1
92 * x'''0
93 *
94 * In this example:
95 * x'2 = (x3 - x2) / (t3 - t2)
96 * x''1 = (x'2 - x'1) / (t2 - t1)
97 * x'''0 = (x''1 - x''0) / (t1 - t0)
98 * Therefore, timestamp history is needed to calculate higher order derivatives,
99 * compared to just the last calculated derivative sample.
100 *
101 * If mNormalizedDt = true, then dt = 1 and the division is moot.
102 */
103 for (int i = 0; i < numSamples; ++i) {
104 if (i == 0) {
105 newXDerivatives[i] = xPos;
106 newYDerivatives[i] = yPos;
107 } else {
108 newXDerivatives[i] = newXDerivatives[i - 1] - mXDerivatives[i - 1];
109 newYDerivatives[i] = newYDerivatives[i - 1] - mYDerivatives[i - 1];
110 if (!mNormalizedDt) {
111 const float dt = mTimestamps[numSamples - i] - mTimestamps[numSamples - i - 1];
112 newXDerivatives[i] = newXDerivatives[i] / dt;
113 newYDerivatives[i] = newYDerivatives[i] / dt;
114 }
115 }
116 }
117
118 std::swap(newXDerivatives, mXDerivatives);
119 std::swap(newYDerivatives, mYDerivatives);
120}
121
122void JerkTracker::reset() {
123 mTimestamps.clear();
124}
125
126std::optional<float> JerkTracker::jerkMagnitude() const {
127 if (mTimestamps.size() == mTimestamps.capacity()) {
128 return std::hypot(mXDerivatives[3], mYDerivatives[3]);
129 }
130 return std::nullopt;
131}
132
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800133// --- MotionPredictor ---
134
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -0800135MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800136 std::function<bool()> checkMotionPredictionEnabled,
137 ReportAtomFunction reportAtomFunction)
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800138 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800139 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)),
140 mReportAtomFunction(reportAtomFunction) {}
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800141
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800142android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
143 if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
144 // We still have an active gesture for another device. The provided MotionEvent is not
Cody Heiner088c63e2023-06-15 12:06:09 -0700145 // consistent with the previous gesture.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800146 LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
147 << __func__ << " is called with " << event;
148 return android::base::Error()
149 << "Inconsistent event stream: still have an active gesture from device "
150 << mLastEvent->getDeviceId() << ", but received " << event;
151 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800152 if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
153 ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
154 inputEventSourceToString(event.getSource()).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800155 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800156 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800157
Philip Quinnbd66e622023-02-10 11:45:01 -0800158 // Initialise the model now that it's likely to be used.
159 if (!mModel) {
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -0800160 mModel = TfLiteMotionPredictorModel::create();
Cody Heiner088c63e2023-06-15 12:06:09 -0700161 LOG_ALWAYS_FATAL_IF(!mModel);
Philip Quinnbd66e622023-02-10 11:45:01 -0800162 }
163
Cody Heiner088c63e2023-06-15 12:06:09 -0700164 if (!mBuffers) {
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800165 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
166 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800167
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800168 // Pass input event to the MetricsManager.
169 if (!mMetricsManager) {
170 mMetricsManager.emplace(mModel->config().predictionInterval, mModel->outputLength(),
171 mReportAtomFunction);
172 }
173 mMetricsManager->onRecord(event);
174
Philip Quinn8f953ab2022-12-06 15:37:07 -0800175 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800176 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800177 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800178 mBuffers->reset();
Derek Wu705068d2024-03-20 10:41:37 -0700179 mJerkTracker.reset();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800180 mLastEvent.reset();
181 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800182 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
183 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
184 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800185 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800186 }
187
188 if (event.getPointerCount() != 1) {
189 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800190 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800191 }
192
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700193 const ToolType toolType = event.getPointerProperties(0)->toolType;
194 if (toolType != ToolType::STYLUS) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800195 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700196 ftl::enum_string(toolType).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800197 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800198 }
199
200 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
201 if (event.isResampled(0, i)) {
202 continue;
203 }
204 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800205 mBuffers->pushSample(event.getHistoricalEventTime(i),
206 {
207 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
208 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
209 .pressure = event.getHistoricalPressure(0, i),
210 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
211 0, i),
212 .orientation = event.getHistoricalOrientation(0, i),
213 });
Derek Wu705068d2024-03-20 10:41:37 -0700214 mJerkTracker.pushSample(event.getHistoricalEventTime(i),
215 coords->getAxisValue(AMOTION_EVENT_AXIS_X),
216 coords->getAxisValue(AMOTION_EVENT_AXIS_Y));
Philip Quinn8f953ab2022-12-06 15:37:07 -0800217 }
218
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800219 if (!mLastEvent) {
220 mLastEvent = MotionEvent();
221 }
222 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
Cody Heiner088c63e2023-06-15 12:06:09 -0700223
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800224 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800225}
226
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800227std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
228 if (mBuffers == nullptr || !mBuffers->isReady()) {
229 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800230 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800231
232 LOG_ALWAYS_FATAL_IF(!mModel);
233 mBuffers->copyTo(*mModel);
234 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
235
236 // Read out the predictions.
237 const std::span<const float> predictedR = mModel->outputR();
238 const std::span<const float> predictedPhi = mModel->outputPhi();
239 const std::span<const float> predictedPressure = mModel->outputPressure();
240
241 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
242 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
243
244 if (isDebug()) {
245 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
246 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
247 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
248 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
249 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
250 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
251 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
252 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
253 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
254 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
255 }
256
257 LOG_ALWAYS_FATAL_IF(!mLastEvent);
258 const MotionEvent& event = *mLastEvent;
259 bool hasPredictions = false;
260 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
261 int64_t predictionTime = mBuffers->lastTimestamp();
262 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
263
Derek Wuaaa47312024-03-26 15:53:44 -0700264 const float jerkMagnitude = mJerkTracker.jerkMagnitude().value_or(0);
265 const float fractionKept =
266 1 - normalizeRange(jerkMagnitude, mModel->config().lowJerk, mModel->config().highJerk);
267 // float to ensure proper division below.
268 const float predictionTimeWindow = futureTime - predictionTime;
269 const int maxNumPredictions = static_cast<int>(
270 std::ceil(predictionTimeWindow / mModel->config().predictionInterval * fractionKept));
271 ALOGD_IF(isDebug(),
272 "jerk (d^3p/normalizedDt^3): %f, fraction of prediction window pruned: %f, max number "
273 "of predictions: %d",
274 jerkMagnitude, 1 - fractionKept, maxNumPredictions);
Ryan Prichard5a8af502023-08-31 00:00:47 -0700275 for (size_t i = 0; i < static_cast<size_t>(predictedR.size()) && predictionTime <= futureTime;
276 ++i) {
Philip Quinn107ce702023-07-14 13:07:13 -0700277 if (predictedR[i] < mModel->config().distanceNoiseFloor) {
278 // Stop predicting when the predicted output is below the model's noise floor.
279 //
280 // We assume that all subsequent predictions in the batch are unreliable because later
281 // predictions are conditional on earlier predictions, and a state of noise is not a
282 // good basis for prediction.
283 //
284 // The UX trade-off is that this potentially sacrifices some predictions when the input
285 // device starts to speed up, but avoids producing noisy predictions as it slows down.
286 break;
287 }
Derek Wuea36ee72024-03-25 13:17:51 -0700288 if (input_flags::enable_prediction_pruning_via_jerk_thresholding()) {
Derek Wuaaa47312024-03-26 15:53:44 -0700289 if (i >= static_cast<size_t>(maxNumPredictions)) {
Derek Wuea36ee72024-03-25 13:17:51 -0700290 break;
291 }
292 }
Derek Wuaaa47312024-03-26 15:53:44 -0700293 // TODO(b/266747654): Stop predictions if confidence is < some
294 // threshold. Currently predictions are pruned via jerk thresholding.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800295
Cody Heiner088c63e2023-06-15 12:06:09 -0700296 const TfLiteMotionPredictorSample::Point predictedPoint =
297 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
298
Ryan Prichard5a8af502023-08-31 00:00:47 -0700299 ALOGD_IF(isDebug(), "prediction %zu: %f, %f", i, predictedPoint.x, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800300 PointerCoords coords;
301 coords.clear();
Cody Heiner088c63e2023-06-15 12:06:09 -0700302 coords.setAxisValue(AMOTION_EVENT_AXIS_X, predictedPoint.x);
303 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800304 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
Philip Quinn59fa9122023-09-18 13:35:54 -0700305 // Copy forward tilt and orientation from the last event until they are predicted
306 // (b/291789258).
307 coords.setAxisValue(AMOTION_EVENT_AXIS_TILT,
308 event.getAxisValue(AMOTION_EVENT_AXIS_TILT, 0));
309 coords.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION,
310 event.getRawPointerCoords(0)->getAxisValue(
311 AMOTION_EVENT_AXIS_ORIENTATION));
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800312
Philip Quinn107ce702023-07-14 13:07:13 -0700313 predictionTime += mModel->config().predictionInterval;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800314 if (i == 0) {
315 hasPredictions = true;
316 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
317 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
318 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
319 event.getMetaState(), event.getButtonState(),
320 event.getClassification(), event.getTransform(),
321 event.getXPrecision(), event.getYPrecision(),
322 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
323 event.getRawTransform(), event.getDownTime(), predictionTime,
324 event.getPointerCount(), event.getPointerProperties(), &coords);
325 } else {
326 prediction->addSample(predictionTime, &coords);
327 }
328
329 axisFrom = axisTo;
Cody Heiner088c63e2023-06-15 12:06:09 -0700330 axisTo = predictedPoint;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800331 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700332
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800333 if (!hasPredictions) {
334 return nullptr;
335 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700336
337 // Pass predictions to the MetricsManager.
338 LOG_ALWAYS_FATAL_IF(!mMetricsManager);
339 mMetricsManager->onPredict(*prediction);
340
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800341 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800342}
343
344bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
345 // Global flag override
346 if (!mCheckMotionPredictionEnabled()) {
347 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
348 return false;
349 }
350
351 // Prediction is only supported for stylus sources.
352 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
353 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
354 inputEventSourceToString(source).c_str());
355 return false;
356 }
357 return true;
358}
359
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800360} // namespace android