blob: b4151c6ea1478a869120875536b6b9dd0f3f1e70 [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
Philip Quinn8f953ab2022-12-06 15:37:07 -080038const int64_t PREDICTION_INTERVAL_NANOS =
39 12500000 / 3; // TODO(b/266747937): Get this from the model.
40
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080041/**
42 * Log debug messages about predictions.
43 * Enable this via "adb shell setprop log.tag.MotionPredictor DEBUG"
44 */
Philip Quinn8f953ab2022-12-06 15:37:07 -080045bool isDebug() {
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080046 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
47}
48
Philip Quinn8f953ab2022-12-06 15:37:07 -080049// Converts a prediction of some polar (r, phi) to Cartesian (x, y) when applied to an axis.
50TfLiteMotionPredictorSample::Point convertPrediction(
51 const TfLiteMotionPredictorSample::Point& axisFrom,
52 const TfLiteMotionPredictorSample::Point& axisTo, float r, float phi) {
53 const TfLiteMotionPredictorSample::Point axis = axisTo - axisFrom;
54 const float axis_phi = std::atan2(axis.y, axis.x);
55 const float x_delta = r * std::cos(axis_phi + phi);
56 const float y_delta = r * std::sin(axis_phi + phi);
57 return {.x = axisTo.x + x_delta, .y = axisTo.y + y_delta};
58}
59
60} // namespace
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080061
62// --- MotionPredictor ---
63
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080064MotionPredictor::MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080065 std::function<bool()> checkMotionPredictionEnabled)
66 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Philip Quinnbd66e622023-02-10 11:45:01 -080067 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)) {}
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
72 // consistent the previous gesture.
73 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();
Philip Quinnbd66e622023-02-10 11:45:01 -080088 }
89
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080090 if (mBuffers == nullptr) {
91 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
92 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080093
94 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080095 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -080096 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080097 mBuffers->reset();
98 mLastEvent.reset();
99 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800100 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
101 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
102 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800103 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800104 }
105
106 if (event.getPointerCount() != 1) {
107 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800108 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800109 }
110
111 const int32_t toolType = event.getPointerProperties(0)->toolType;
112 if (toolType != AMOTION_EVENT_TOOL_TYPE_STYLUS) {
113 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
114 motionToolTypeToString(toolType));
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800115 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800116 }
117
118 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
119 if (event.isResampled(0, i)) {
120 continue;
121 }
122 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800123 mBuffers->pushSample(event.getHistoricalEventTime(i),
124 {
125 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
126 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
127 .pressure = event.getHistoricalPressure(0, i),
128 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
129 0, i),
130 .orientation = event.getHistoricalOrientation(0, i),
131 });
Philip Quinn8f953ab2022-12-06 15:37:07 -0800132 }
133
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800134 if (!mLastEvent) {
135 mLastEvent = MotionEvent();
136 }
137 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
138 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800139}
140
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800141std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
142 if (mBuffers == nullptr || !mBuffers->isReady()) {
143 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800144 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800145
146 LOG_ALWAYS_FATAL_IF(!mModel);
147 mBuffers->copyTo(*mModel);
148 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
149
150 // Read out the predictions.
151 const std::span<const float> predictedR = mModel->outputR();
152 const std::span<const float> predictedPhi = mModel->outputPhi();
153 const std::span<const float> predictedPressure = mModel->outputPressure();
154
155 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
156 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
157
158 if (isDebug()) {
159 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
160 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
161 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
162 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
163 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
164 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
165 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
166 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
167 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
168 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
169 }
170
171 LOG_ALWAYS_FATAL_IF(!mLastEvent);
172 const MotionEvent& event = *mLastEvent;
173 bool hasPredictions = false;
174 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
175 int64_t predictionTime = mBuffers->lastTimestamp();
176 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
177
178 for (int i = 0; i < predictedR.size() && predictionTime <= futureTime; ++i) {
179 const TfLiteMotionPredictorSample::Point point =
180 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
181 // TODO(b/266747654): Stop predictions if confidence is < some threshold.
182
183 ALOGD_IF(isDebug(), "prediction %d: %f, %f", i, point.x, point.y);
184 PointerCoords coords;
185 coords.clear();
186 coords.setAxisValue(AMOTION_EVENT_AXIS_X, point.x);
187 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, point.y);
188 // TODO(b/266747654): Stop predictions if predicted pressure is < some threshold.
189 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
190
191 predictionTime += PREDICTION_INTERVAL_NANOS;
192 if (i == 0) {
193 hasPredictions = true;
194 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
195 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
196 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
197 event.getMetaState(), event.getButtonState(),
198 event.getClassification(), event.getTransform(),
199 event.getXPrecision(), event.getYPrecision(),
200 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
201 event.getRawTransform(), event.getDownTime(), predictionTime,
202 event.getPointerCount(), event.getPointerProperties(), &coords);
203 } else {
204 prediction->addSample(predictionTime, &coords);
205 }
206
207 axisFrom = axisTo;
208 axisTo = point;
209 }
210 // TODO(b/266747511): Interpolate to futureTime?
211 if (!hasPredictions) {
212 return nullptr;
213 }
214 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800215}
216
217bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
218 // Global flag override
219 if (!mCheckMotionPredictionEnabled()) {
220 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
221 return false;
222 }
223
224 // Prediction is only supported for stylus sources.
225 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
226 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
227 inputEventSourceToString(source).c_str());
228 return false;
229 }
230 return true;
231}
232
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800233} // namespace android