blob: c4e3ff6deeacd6fc603ae3ddf5516d2b3cdb3a1f [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
Philip Quinn8f953ab2022-12-06 15:37:07 -080021#include <cinttypes>
22#include <cmath>
23#include <cstddef>
24#include <cstdint>
25#include <string>
26#include <vector>
27
Yeabkal Wubshit64f090f2023-03-03 17:35:11 -080028#include <android-base/logging.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080029#include <android-base/strings.h>
30#include <android/input.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080031
32#include <attestation/HmacKeyManager.h>
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -070033#include <ftl/enum.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080034#include <input/TfLiteMotionPredictor.h>
35
36namespace android {
37namespace {
38
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080039/**
40 * Log debug messages about predictions.
41 * Enable this via "adb shell setprop log.tag.MotionPredictor DEBUG"
42 */
Philip Quinn8f953ab2022-12-06 15:37:07 -080043bool isDebug() {
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080044 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
45}
46
Philip Quinn8f953ab2022-12-06 15:37:07 -080047// Converts a prediction of some polar (r, phi) to Cartesian (x, y) when applied to an axis.
48TfLiteMotionPredictorSample::Point convertPrediction(
49 const TfLiteMotionPredictorSample::Point& axisFrom,
50 const TfLiteMotionPredictorSample::Point& axisTo, float r, float phi) {
51 const TfLiteMotionPredictorSample::Point axis = axisTo - axisFrom;
52 const float axis_phi = std::atan2(axis.y, axis.x);
53 const float x_delta = r * std::cos(axis_phi + phi);
54 const float y_delta = r * std::sin(axis_phi + phi);
55 return {.x = axisTo.x + x_delta, .y = axisTo.y + y_delta};
56}
57
58} // namespace
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080059
60// --- MotionPredictor ---
61
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080062MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
Cody Heiner7b26dbe2023-11-14 14:47:10 -080063 std::function<bool()> checkMotionPredictionEnabled,
64 ReportAtomFunction reportAtomFunction)
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080065 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Cody Heiner7b26dbe2023-11-14 14:47:10 -080066 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)),
67 mReportAtomFunction(reportAtomFunction) {}
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080068
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080069android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
70 if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
71 // We still have an active gesture for another device. The provided MotionEvent is not
Cody Heiner088c63e2023-06-15 12:06:09 -070072 // consistent with the previous gesture.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080073 LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
74 << __func__ << " is called with " << event;
75 return android::base::Error()
76 << "Inconsistent event stream: still have an active gesture from device "
77 << mLastEvent->getDeviceId() << ", but received " << event;
78 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080079 if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
80 ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
81 inputEventSourceToString(event.getSource()).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080082 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080083 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080084
Philip Quinnbd66e622023-02-10 11:45:01 -080085 // Initialise the model now that it's likely to be used.
86 if (!mModel) {
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080087 mModel = TfLiteMotionPredictorModel::create();
Cody Heiner088c63e2023-06-15 12:06:09 -070088 LOG_ALWAYS_FATAL_IF(!mModel);
Philip Quinnbd66e622023-02-10 11:45:01 -080089 }
90
Cody Heiner088c63e2023-06-15 12:06:09 -070091 if (!mBuffers) {
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080092 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
93 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080094
Cody Heiner7b26dbe2023-11-14 14:47:10 -080095 // Pass input event to the MetricsManager.
96 if (!mMetricsManager) {
97 mMetricsManager.emplace(mModel->config().predictionInterval, mModel->outputLength(),
98 mReportAtomFunction);
99 }
100 mMetricsManager->onRecord(event);
101
Philip Quinn8f953ab2022-12-06 15:37:07 -0800102 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800103 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800104 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800105 mBuffers->reset();
106 mLastEvent.reset();
107 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800108 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
109 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
110 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800111 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800112 }
113
114 if (event.getPointerCount() != 1) {
115 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800116 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800117 }
118
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700119 const ToolType toolType = event.getPointerProperties(0)->toolType;
120 if (toolType != ToolType::STYLUS) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800121 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700122 ftl::enum_string(toolType).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800123 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800124 }
125
126 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
127 if (event.isResampled(0, i)) {
128 continue;
129 }
130 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800131 mBuffers->pushSample(event.getHistoricalEventTime(i),
132 {
133 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
134 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
135 .pressure = event.getHistoricalPressure(0, i),
136 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
137 0, i),
138 .orientation = event.getHistoricalOrientation(0, i),
139 });
Philip Quinn8f953ab2022-12-06 15:37:07 -0800140 }
141
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800142 if (!mLastEvent) {
143 mLastEvent = MotionEvent();
144 }
145 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
Cody Heiner088c63e2023-06-15 12:06:09 -0700146
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800147 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800148}
149
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800150std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
151 if (mBuffers == nullptr || !mBuffers->isReady()) {
152 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800153 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800154
155 LOG_ALWAYS_FATAL_IF(!mModel);
156 mBuffers->copyTo(*mModel);
157 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
158
159 // Read out the predictions.
160 const std::span<const float> predictedR = mModel->outputR();
161 const std::span<const float> predictedPhi = mModel->outputPhi();
162 const std::span<const float> predictedPressure = mModel->outputPressure();
163
164 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
165 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
166
167 if (isDebug()) {
168 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
169 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
170 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
171 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
172 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
173 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
174 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
175 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
176 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
177 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
178 }
179
180 LOG_ALWAYS_FATAL_IF(!mLastEvent);
181 const MotionEvent& event = *mLastEvent;
182 bool hasPredictions = false;
183 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
184 int64_t predictionTime = mBuffers->lastTimestamp();
185 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
186
Ryan Prichard5a8af502023-08-31 00:00:47 -0700187 for (size_t i = 0; i < static_cast<size_t>(predictedR.size()) && predictionTime <= futureTime;
188 ++i) {
Philip Quinn107ce702023-07-14 13:07:13 -0700189 if (predictedR[i] < mModel->config().distanceNoiseFloor) {
190 // Stop predicting when the predicted output is below the model's noise floor.
191 //
192 // We assume that all subsequent predictions in the batch are unreliable because later
193 // predictions are conditional on earlier predictions, and a state of noise is not a
194 // good basis for prediction.
195 //
196 // The UX trade-off is that this potentially sacrifices some predictions when the input
197 // device starts to speed up, but avoids producing noisy predictions as it slows down.
198 break;
199 }
200 // TODO(b/266747654): Stop predictions if confidence is < some threshold.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800201
Cody Heiner088c63e2023-06-15 12:06:09 -0700202 const TfLiteMotionPredictorSample::Point predictedPoint =
203 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
204
Ryan Prichard5a8af502023-08-31 00:00:47 -0700205 ALOGD_IF(isDebug(), "prediction %zu: %f, %f", i, predictedPoint.x, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800206 PointerCoords coords;
207 coords.clear();
Cody Heiner088c63e2023-06-15 12:06:09 -0700208 coords.setAxisValue(AMOTION_EVENT_AXIS_X, predictedPoint.x);
209 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800210 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
Philip Quinn59fa9122023-09-18 13:35:54 -0700211 // Copy forward tilt and orientation from the last event until they are predicted
212 // (b/291789258).
213 coords.setAxisValue(AMOTION_EVENT_AXIS_TILT,
214 event.getAxisValue(AMOTION_EVENT_AXIS_TILT, 0));
215 coords.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION,
216 event.getRawPointerCoords(0)->getAxisValue(
217 AMOTION_EVENT_AXIS_ORIENTATION));
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800218
Philip Quinn107ce702023-07-14 13:07:13 -0700219 predictionTime += mModel->config().predictionInterval;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800220 if (i == 0) {
221 hasPredictions = true;
222 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
223 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
224 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
225 event.getMetaState(), event.getButtonState(),
226 event.getClassification(), event.getTransform(),
227 event.getXPrecision(), event.getYPrecision(),
228 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
229 event.getRawTransform(), event.getDownTime(), predictionTime,
230 event.getPointerCount(), event.getPointerProperties(), &coords);
231 } else {
232 prediction->addSample(predictionTime, &coords);
233 }
234
235 axisFrom = axisTo;
Cody Heiner088c63e2023-06-15 12:06:09 -0700236 axisTo = predictedPoint;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800237 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700238
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800239 if (!hasPredictions) {
240 return nullptr;
241 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700242
243 // Pass predictions to the MetricsManager.
244 LOG_ALWAYS_FATAL_IF(!mMetricsManager);
245 mMetricsManager->onPredict(*prediction);
246
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800247 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800248}
249
250bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
251 // Global flag override
252 if (!mCheckMotionPredictionEnabled()) {
253 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
254 return false;
255 }
256
257 // Prediction is only supported for stylus sources.
258 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
259 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
260 inputEventSourceToString(source).c_str());
261 return false;
262 }
263 return true;
264}
265
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800266} // namespace android