blob: c61d3943e07f249f5599d5725b36748b81a3dca8 [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
Derek Wucc6aec52024-07-30 11:59:56 +000075JerkTracker::JerkTracker(bool normalizedDt, float alpha)
76 : mNormalizedDt(normalizedDt), mAlpha(alpha) {}
Derek Wu705068d2024-03-20 10:41:37 -070077
78void JerkTracker::pushSample(int64_t timestamp, float xPos, float yPos) {
Derek Wu5e0e7cf2024-07-04 11:14:18 +000079 // If we previously had full samples, we have a previous jerk calculation
80 // to do weighted smoothing.
81 const bool applySmoothing = mTimestamps.size() == mTimestamps.capacity();
Derek Wu705068d2024-03-20 10:41:37 -070082 mTimestamps.pushBack(timestamp);
83 const int numSamples = mTimestamps.size();
84
85 std::array<float, 4> newXDerivatives;
86 std::array<float, 4> newYDerivatives;
87
88 /**
89 * Diagram showing the calculation of higher order derivatives of sample x3
90 * collected at time=t3.
91 * Terms in parentheses are not stored (and not needed for calculations)
92 * t0 ----- t1 ----- t2 ----- t3
93 * (x0)-----(x1) ----- x2 ----- x3
94 * (x'0) --- x'1 --- x'2
95 * x''0 - x''1
96 * x'''0
97 *
98 * In this example:
99 * x'2 = (x3 - x2) / (t3 - t2)
100 * x''1 = (x'2 - x'1) / (t2 - t1)
101 * x'''0 = (x''1 - x''0) / (t1 - t0)
102 * Therefore, timestamp history is needed to calculate higher order derivatives,
103 * compared to just the last calculated derivative sample.
104 *
105 * If mNormalizedDt = true, then dt = 1 and the division is moot.
106 */
107 for (int i = 0; i < numSamples; ++i) {
108 if (i == 0) {
109 newXDerivatives[i] = xPos;
110 newYDerivatives[i] = yPos;
111 } else {
112 newXDerivatives[i] = newXDerivatives[i - 1] - mXDerivatives[i - 1];
113 newYDerivatives[i] = newYDerivatives[i - 1] - mYDerivatives[i - 1];
114 if (!mNormalizedDt) {
115 const float dt = mTimestamps[numSamples - i] - mTimestamps[numSamples - i - 1];
116 newXDerivatives[i] = newXDerivatives[i] / dt;
117 newYDerivatives[i] = newYDerivatives[i] / dt;
118 }
119 }
120 }
121
Derek Wu5e0e7cf2024-07-04 11:14:18 +0000122 if (numSamples == static_cast<int>(mTimestamps.capacity())) {
123 float newJerkMagnitude = std::hypot(newXDerivatives[3], newYDerivatives[3]);
124 ALOGD_IF(isDebug(), "raw jerk: %f", newJerkMagnitude);
125 if (applySmoothing) {
Derek Wucc6aec52024-07-30 11:59:56 +0000126 mJerkMagnitude = mJerkMagnitude + (mAlpha * (newJerkMagnitude - mJerkMagnitude));
Derek Wu5e0e7cf2024-07-04 11:14:18 +0000127 } else {
128 mJerkMagnitude = newJerkMagnitude;
129 }
130 }
131
Derek Wu705068d2024-03-20 10:41:37 -0700132 std::swap(newXDerivatives, mXDerivatives);
133 std::swap(newYDerivatives, mYDerivatives);
134}
135
136void JerkTracker::reset() {
137 mTimestamps.clear();
138}
139
140std::optional<float> JerkTracker::jerkMagnitude() const {
141 if (mTimestamps.size() == mTimestamps.capacity()) {
Derek Wu5e0e7cf2024-07-04 11:14:18 +0000142 return mJerkMagnitude;
Derek Wu705068d2024-03-20 10:41:37 -0700143 }
144 return std::nullopt;
145}
146
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800147// --- MotionPredictor ---
148
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -0800149MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800150 std::function<bool()> checkMotionPredictionEnabled,
151 ReportAtomFunction reportAtomFunction)
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800152 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800153 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)),
154 mReportAtomFunction(reportAtomFunction) {}
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800155
Derek Wucc6aec52024-07-30 11:59:56 +0000156void MotionPredictor::initializeObjects() {
157 mModel = TfLiteMotionPredictorModel::create();
158 LOG_ALWAYS_FATAL_IF(!mModel);
159
160 // mJerkTracker assumes normalized dt = 1 between recorded samples because
161 // the underlying mModel input also assumes fixed-interval samples.
162 // Normalized dt as 1 is also used to correspond with the similar Jank
163 // implementation from the JetPack MotionPredictor implementation.
164 mJerkTracker = std::make_unique<JerkTracker>(/*normalizedDt=*/true, mModel->config().jerkAlpha);
165
166 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
167
168 mMetricsManager =
169 std::make_unique<MotionPredictorMetricsManager>(mModel->config().predictionInterval,
170 mModel->outputLength(),
171 mReportAtomFunction);
172}
173
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800174android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
175 if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
176 // We still have an active gesture for another device. The provided MotionEvent is not
Cody Heiner088c63e2023-06-15 12:06:09 -0700177 // consistent with the previous gesture.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800178 LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
179 << __func__ << " is called with " << event;
180 return android::base::Error()
181 << "Inconsistent event stream: still have an active gesture from device "
182 << mLastEvent->getDeviceId() << ", but received " << event;
183 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800184 if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
185 ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
186 inputEventSourceToString(event.getSource()).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800187 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800188 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800189
Philip Quinnbd66e622023-02-10 11:45:01 -0800190 if (!mModel) {
Derek Wucc6aec52024-07-30 11:59:56 +0000191 initializeObjects();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800192 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800193
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800194 // Pass input event to the MetricsManager.
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800195 mMetricsManager->onRecord(event);
196
Philip Quinn8f953ab2022-12-06 15:37:07 -0800197 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800198 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800199 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800200 mBuffers->reset();
Derek Wucc6aec52024-07-30 11:59:56 +0000201 mJerkTracker->reset();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800202 mLastEvent.reset();
203 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800204 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
205 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
206 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800207 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800208 }
209
210 if (event.getPointerCount() != 1) {
211 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800212 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800213 }
214
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700215 const ToolType toolType = event.getPointerProperties(0)->toolType;
216 if (toolType != ToolType::STYLUS) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800217 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700218 ftl::enum_string(toolType).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800219 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800220 }
221
222 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
223 if (event.isResampled(0, i)) {
224 continue;
225 }
226 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800227 mBuffers->pushSample(event.getHistoricalEventTime(i),
228 {
229 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
230 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
231 .pressure = event.getHistoricalPressure(0, i),
232 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
233 0, i),
234 .orientation = event.getHistoricalOrientation(0, i),
235 });
Derek Wucc6aec52024-07-30 11:59:56 +0000236 mJerkTracker->pushSample(event.getHistoricalEventTime(i),
237 coords->getAxisValue(AMOTION_EVENT_AXIS_X),
238 coords->getAxisValue(AMOTION_EVENT_AXIS_Y));
Philip Quinn8f953ab2022-12-06 15:37:07 -0800239 }
240
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800241 if (!mLastEvent) {
242 mLastEvent = MotionEvent();
243 }
244 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
Cody Heiner088c63e2023-06-15 12:06:09 -0700245
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800246 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800247}
248
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800249std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
250 if (mBuffers == nullptr || !mBuffers->isReady()) {
251 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800252 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800253
254 LOG_ALWAYS_FATAL_IF(!mModel);
255 mBuffers->copyTo(*mModel);
256 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
257
258 // Read out the predictions.
259 const std::span<const float> predictedR = mModel->outputR();
260 const std::span<const float> predictedPhi = mModel->outputPhi();
261 const std::span<const float> predictedPressure = mModel->outputPressure();
262
263 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
264 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
265
266 if (isDebug()) {
267 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
268 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
269 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
270 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
271 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
272 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
273 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
274 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
275 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
276 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
277 }
278
279 LOG_ALWAYS_FATAL_IF(!mLastEvent);
280 const MotionEvent& event = *mLastEvent;
281 bool hasPredictions = false;
282 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
283 int64_t predictionTime = mBuffers->lastTimestamp();
284 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
285
Derek Wucc6aec52024-07-30 11:59:56 +0000286 const float jerkMagnitude = mJerkTracker->jerkMagnitude().value_or(0);
Derek Wuaaa47312024-03-26 15:53:44 -0700287 const float fractionKept =
288 1 - normalizeRange(jerkMagnitude, mModel->config().lowJerk, mModel->config().highJerk);
289 // float to ensure proper division below.
290 const float predictionTimeWindow = futureTime - predictionTime;
291 const int maxNumPredictions = static_cast<int>(
292 std::ceil(predictionTimeWindow / mModel->config().predictionInterval * fractionKept));
293 ALOGD_IF(isDebug(),
294 "jerk (d^3p/normalizedDt^3): %f, fraction of prediction window pruned: %f, max number "
295 "of predictions: %d",
296 jerkMagnitude, 1 - fractionKept, maxNumPredictions);
Ryan Prichard5a8af502023-08-31 00:00:47 -0700297 for (size_t i = 0; i < static_cast<size_t>(predictedR.size()) && predictionTime <= futureTime;
298 ++i) {
Philip Quinn107ce702023-07-14 13:07:13 -0700299 if (predictedR[i] < mModel->config().distanceNoiseFloor) {
300 // Stop predicting when the predicted output is below the model's noise floor.
301 //
302 // We assume that all subsequent predictions in the batch are unreliable because later
303 // predictions are conditional on earlier predictions, and a state of noise is not a
304 // good basis for prediction.
305 //
306 // The UX trade-off is that this potentially sacrifices some predictions when the input
307 // device starts to speed up, but avoids producing noisy predictions as it slows down.
308 break;
309 }
Derek Wuea36ee72024-03-25 13:17:51 -0700310 if (input_flags::enable_prediction_pruning_via_jerk_thresholding()) {
Derek Wuaaa47312024-03-26 15:53:44 -0700311 if (i >= static_cast<size_t>(maxNumPredictions)) {
Derek Wuea36ee72024-03-25 13:17:51 -0700312 break;
313 }
314 }
Derek Wuaaa47312024-03-26 15:53:44 -0700315 // TODO(b/266747654): Stop predictions if confidence is < some
316 // threshold. Currently predictions are pruned via jerk thresholding.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800317
Cody Heiner088c63e2023-06-15 12:06:09 -0700318 const TfLiteMotionPredictorSample::Point predictedPoint =
319 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
320
Ryan Prichard5a8af502023-08-31 00:00:47 -0700321 ALOGD_IF(isDebug(), "prediction %zu: %f, %f", i, predictedPoint.x, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800322 PointerCoords coords;
323 coords.clear();
Cody Heiner088c63e2023-06-15 12:06:09 -0700324 coords.setAxisValue(AMOTION_EVENT_AXIS_X, predictedPoint.x);
325 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800326 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
Philip Quinn59fa9122023-09-18 13:35:54 -0700327 // Copy forward tilt and orientation from the last event until they are predicted
328 // (b/291789258).
329 coords.setAxisValue(AMOTION_EVENT_AXIS_TILT,
330 event.getAxisValue(AMOTION_EVENT_AXIS_TILT, 0));
331 coords.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION,
332 event.getRawPointerCoords(0)->getAxisValue(
333 AMOTION_EVENT_AXIS_ORIENTATION));
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800334
Philip Quinn107ce702023-07-14 13:07:13 -0700335 predictionTime += mModel->config().predictionInterval;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800336 if (i == 0) {
337 hasPredictions = true;
338 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
339 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
340 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
341 event.getMetaState(), event.getButtonState(),
342 event.getClassification(), event.getTransform(),
343 event.getXPrecision(), event.getYPrecision(),
344 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
345 event.getRawTransform(), event.getDownTime(), predictionTime,
346 event.getPointerCount(), event.getPointerProperties(), &coords);
347 } else {
jioana71c6f732024-07-16 15:42:56 +0000348 prediction->addSample(predictionTime, &coords, prediction->getId());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800349 }
350
351 axisFrom = axisTo;
Cody Heiner088c63e2023-06-15 12:06:09 -0700352 axisTo = predictedPoint;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800353 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700354
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800355 if (!hasPredictions) {
356 return nullptr;
357 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700358
359 // Pass predictions to the MetricsManager.
360 LOG_ALWAYS_FATAL_IF(!mMetricsManager);
361 mMetricsManager->onPredict(*prediction);
362
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800363 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800364}
365
366bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
367 // Global flag override
368 if (!mCheckMotionPredictionEnabled()) {
369 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
370 return false;
371 }
372
373 // Prediction is only supported for stylus sources.
374 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
375 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
376 inputEventSourceToString(source).c_str());
377 return false;
378 }
379 return true;
380}
381
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800382} // namespace android