blob: a425b936ca4236e631059484d78ce4443dbb344d [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
Philip Quinn8f953ab2022-12-06 15:37:07 -080039const 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
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080065MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080066 std::function<bool()> checkMotionPredictionEnabled)
67 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Philip Quinnbd66e622023-02-10 11:45:01 -080068 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)) {}
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080069
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080070android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
71 if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
72 // We still have an active gesture for another device. The provided MotionEvent is not
73 // consistent the previous gesture.
74 LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
75 << __func__ << " is called with " << event;
76 return android::base::Error()
77 << "Inconsistent event stream: still have an active gesture from device "
78 << mLastEvent->getDeviceId() << ", but received " << event;
79 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080080 if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
81 ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
82 inputEventSourceToString(event.getSource()).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080083 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080084 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080085
Philip Quinnbd66e622023-02-10 11:45:01 -080086 // Initialise the model now that it's likely to be used.
87 if (!mModel) {
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080088 mModel = TfLiteMotionPredictorModel::create();
Philip Quinnbd66e622023-02-10 11:45:01 -080089 }
90
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080091 if (mBuffers == nullptr) {
92 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
93 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080094
95 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080096 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -080097 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080098 mBuffers->reset();
99 mLastEvent.reset();
100 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800101 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
102 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
103 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800104 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800105 }
106
107 if (event.getPointerCount() != 1) {
108 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800109 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800110 }
111
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700112 const ToolType toolType = event.getPointerProperties(0)->toolType;
113 if (toolType != ToolType::STYLUS) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800114 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -0700115 ftl::enum_string(toolType).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800116 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800117 }
118
119 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
120 if (event.isResampled(0, i)) {
121 continue;
122 }
123 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800124 mBuffers->pushSample(event.getHistoricalEventTime(i),
125 {
126 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
127 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
128 .pressure = event.getHistoricalPressure(0, i),
129 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
130 0, i),
131 .orientation = event.getHistoricalOrientation(0, i),
132 });
Philip Quinn8f953ab2022-12-06 15:37:07 -0800133 }
134
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800135 if (!mLastEvent) {
136 mLastEvent = MotionEvent();
137 }
138 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
139 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800140}
141
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800142std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
143 if (mBuffers == nullptr || !mBuffers->isReady()) {
144 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800145 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800146
147 LOG_ALWAYS_FATAL_IF(!mModel);
148 mBuffers->copyTo(*mModel);
149 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
150
151 // Read out the predictions.
152 const std::span<const float> predictedR = mModel->outputR();
153 const std::span<const float> predictedPhi = mModel->outputPhi();
154 const std::span<const float> predictedPressure = mModel->outputPressure();
155
156 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
157 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
158
159 if (isDebug()) {
160 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
161 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
162 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
163 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
164 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
165 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
166 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
167 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
168 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
169 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
170 }
171
172 LOG_ALWAYS_FATAL_IF(!mLastEvent);
173 const MotionEvent& event = *mLastEvent;
174 bool hasPredictions = false;
175 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
176 int64_t predictionTime = mBuffers->lastTimestamp();
177 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
178
179 for (int i = 0; i < predictedR.size() && predictionTime <= futureTime; ++i) {
180 const TfLiteMotionPredictorSample::Point point =
181 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
182 // TODO(b/266747654): Stop predictions if confidence is < some threshold.
183
184 ALOGD_IF(isDebug(), "prediction %d: %f, %f", i, point.x, point.y);
185 PointerCoords coords;
186 coords.clear();
187 coords.setAxisValue(AMOTION_EVENT_AXIS_X, point.x);
188 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, point.y);
189 // TODO(b/266747654): Stop predictions if predicted pressure is < some threshold.
190 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
191
192 predictionTime += PREDICTION_INTERVAL_NANOS;
193 if (i == 0) {
194 hasPredictions = true;
195 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
196 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
197 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
198 event.getMetaState(), event.getButtonState(),
199 event.getClassification(), event.getTransform(),
200 event.getXPrecision(), event.getYPrecision(),
201 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
202 event.getRawTransform(), event.getDownTime(), predictionTime,
203 event.getPointerCount(), event.getPointerProperties(), &coords);
204 } else {
205 prediction->addSample(predictionTime, &coords);
206 }
207
208 axisFrom = axisTo;
209 axisTo = point;
210 }
211 // TODO(b/266747511): Interpolate to futureTime?
212 if (!hasPredictions) {
213 return nullptr;
214 }
215 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800216}
217
218bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
219 // Global flag override
220 if (!mCheckMotionPredictionEnabled()) {
221 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
222 return false;
223 }
224
225 // Prediction is only supported for stylus sources.
226 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
227 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
228 inputEventSourceToString(source).c_str());
229 return false;
230 }
231 return true;
232}
233
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800234} // namespace android