blob: 4b36eae6f65d507e8d2a0f63a28da62fe134c526 [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
28#include <android-base/strings.h>
29#include <android/input.h>
30#include <log/log.h>
31
32#include <attestation/HmacKeyManager.h>
33#include <input/TfLiteMotionPredictor.h>
34
35namespace android {
36namespace {
37
38const char DEFAULT_MODEL_PATH[] = "/system/etc/motion_predictor_model.fb";
39const int64_t PREDICTION_INTERVAL_NANOS =
40 12500000 / 3; // TODO(b/266747937): Get this from the model.
41
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080042/**
43 * Log debug messages about predictions.
44 * Enable this via "adb shell setprop log.tag.MotionPredictor DEBUG"
45 */
Philip Quinn8f953ab2022-12-06 15:37:07 -080046bool isDebug() {
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080047 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
48}
49
Philip Quinn8f953ab2022-12-06 15:37:07 -080050// Converts a prediction of some polar (r, phi) to Cartesian (x, y) when applied to an axis.
51TfLiteMotionPredictorSample::Point convertPrediction(
52 const TfLiteMotionPredictorSample::Point& axisFrom,
53 const TfLiteMotionPredictorSample::Point& axisTo, float r, float phi) {
54 const TfLiteMotionPredictorSample::Point axis = axisTo - axisFrom;
55 const float axis_phi = std::atan2(axis.y, axis.x);
56 const float x_delta = r * std::cos(axis_phi + phi);
57 const float y_delta = r * std::sin(axis_phi + phi);
58 return {.x = axisTo.x + x_delta, .y = axisTo.y + y_delta};
59}
60
61} // namespace
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080062
63// --- MotionPredictor ---
64
Philip Quinn8f953ab2022-12-06 15:37:07 -080065MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos, const char* modelPath,
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080066 std::function<bool()> checkMotionPredictionEnabled)
67 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Philip Quinnbd66e622023-02-10 11:45:01 -080068 mModelPath(modelPath == nullptr ? DEFAULT_MODEL_PATH : modelPath),
69 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)) {}
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080070
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080071android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
72 if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
73 // We still have an active gesture for another device. The provided MotionEvent is not
74 // consistent the previous gesture.
75 LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
76 << __func__ << " is called with " << event;
77 return android::base::Error()
78 << "Inconsistent event stream: still have an active gesture from device "
79 << mLastEvent->getDeviceId() << ", but received " << event;
80 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080081 if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
82 ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
83 inputEventSourceToString(event.getSource()).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080084 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080085 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080086
Philip Quinnbd66e622023-02-10 11:45:01 -080087 // Initialise the model now that it's likely to be used.
88 if (!mModel) {
89 mModel = TfLiteMotionPredictorModel::create(mModelPath.c_str());
90 }
91
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080092 if (mBuffers == nullptr) {
93 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
94 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080095
96 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080097 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -080098 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080099 mBuffers->reset();
100 mLastEvent.reset();
101 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800102 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
103 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
104 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800105 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800106 }
107
108 if (event.getPointerCount() != 1) {
109 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800110 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800111 }
112
113 const int32_t toolType = event.getPointerProperties(0)->toolType;
114 if (toolType != AMOTION_EVENT_TOOL_TYPE_STYLUS) {
115 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
116 motionToolTypeToString(toolType));
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800117 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800118 }
119
120 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
121 if (event.isResampled(0, i)) {
122 continue;
123 }
124 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800125 mBuffers->pushSample(event.getHistoricalEventTime(i),
126 {
127 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
128 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
129 .pressure = event.getHistoricalPressure(0, i),
130 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
131 0, i),
132 .orientation = event.getHistoricalOrientation(0, i),
133 });
Philip Quinn8f953ab2022-12-06 15:37:07 -0800134 }
135
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800136 if (!mLastEvent) {
137 mLastEvent = MotionEvent();
138 }
139 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
140 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800141}
142
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800143std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
144 if (mBuffers == nullptr || !mBuffers->isReady()) {
145 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800146 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800147
148 LOG_ALWAYS_FATAL_IF(!mModel);
149 mBuffers->copyTo(*mModel);
150 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
151
152 // Read out the predictions.
153 const std::span<const float> predictedR = mModel->outputR();
154 const std::span<const float> predictedPhi = mModel->outputPhi();
155 const std::span<const float> predictedPressure = mModel->outputPressure();
156
157 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
158 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
159
160 if (isDebug()) {
161 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
162 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
163 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
164 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
165 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
166 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
167 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
168 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
169 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
170 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
171 }
172
173 LOG_ALWAYS_FATAL_IF(!mLastEvent);
174 const MotionEvent& event = *mLastEvent;
175 bool hasPredictions = false;
176 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
177 int64_t predictionTime = mBuffers->lastTimestamp();
178 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
179
180 for (int i = 0; i < predictedR.size() && predictionTime <= futureTime; ++i) {
181 const TfLiteMotionPredictorSample::Point point =
182 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
183 // TODO(b/266747654): Stop predictions if confidence is < some threshold.
184
185 ALOGD_IF(isDebug(), "prediction %d: %f, %f", i, point.x, point.y);
186 PointerCoords coords;
187 coords.clear();
188 coords.setAxisValue(AMOTION_EVENT_AXIS_X, point.x);
189 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, point.y);
190 // TODO(b/266747654): Stop predictions if predicted pressure is < some threshold.
191 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
192
193 predictionTime += PREDICTION_INTERVAL_NANOS;
194 if (i == 0) {
195 hasPredictions = true;
196 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
197 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
198 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
199 event.getMetaState(), event.getButtonState(),
200 event.getClassification(), event.getTransform(),
201 event.getXPrecision(), event.getYPrecision(),
202 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
203 event.getRawTransform(), event.getDownTime(), predictionTime,
204 event.getPointerCount(), event.getPointerProperties(), &coords);
205 } else {
206 prediction->addSample(predictionTime, &coords);
207 }
208
209 axisFrom = axisTo;
210 axisTo = point;
211 }
212 // TODO(b/266747511): Interpolate to futureTime?
213 if (!hasPredictions) {
214 return nullptr;
215 }
216 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800217}
218
219bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
220 // Global flag override
221 if (!mCheckMotionPredictionEnabled()) {
222 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
223 return false;
224 }
225
226 // Prediction is only supported for stylus sources.
227 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
228 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
229 inputEventSourceToString(source).c_str());
230 return false;
231 }
232 return true;
233}
234
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800235} // namespace android