blob: 68e688817b40c938fb044861f7b685ccf32a6ae1 [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>
Siarhei Vishniakou6d73f832022-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,
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080063 std::function<bool()> checkMotionPredictionEnabled)
64 : mPredictionTimestampOffsetNanos(predictionTimestampOffsetNanos),
Philip Quinnbd66e622023-02-10 11:45:01 -080065 mCheckMotionPredictionEnabled(std::move(checkMotionPredictionEnabled)) {}
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080066
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080067android::base::Result<void> MotionPredictor::record(const MotionEvent& event) {
68 if (mLastEvent && mLastEvent->getDeviceId() != event.getDeviceId()) {
69 // We still have an active gesture for another device. The provided MotionEvent is not
Cody Heiner088c63e2023-06-15 12:06:09 -070070 // consistent with the previous gesture.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080071 LOG(ERROR) << "Inconsistent event stream: last event is " << *mLastEvent << ", but "
72 << __func__ << " is called with " << event;
73 return android::base::Error()
74 << "Inconsistent event stream: still have an active gesture from device "
75 << mLastEvent->getDeviceId() << ", but received " << event;
76 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080077 if (!isPredictionAvailable(event.getDeviceId(), event.getSource())) {
78 ALOGE("Prediction not supported for device %d's %s source", event.getDeviceId(),
79 inputEventSourceToString(event.getSource()).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080080 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080081 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080082
Philip Quinnbd66e622023-02-10 11:45:01 -080083 // Initialise the model now that it's likely to be used.
84 if (!mModel) {
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080085 mModel = TfLiteMotionPredictorModel::create();
Cody Heiner088c63e2023-06-15 12:06:09 -070086 LOG_ALWAYS_FATAL_IF(!mModel);
Philip Quinnbd66e622023-02-10 11:45:01 -080087 }
88
Cody Heiner088c63e2023-06-15 12:06:09 -070089 if (!mBuffers) {
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080090 mBuffers = std::make_unique<TfLiteMotionPredictorBuffers>(mModel->inputLength());
91 }
Philip Quinn8f953ab2022-12-06 15:37:07 -080092
93 const int32_t action = event.getActionMasked();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080094 if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) {
Philip Quinn8f953ab2022-12-06 15:37:07 -080095 ALOGD_IF(isDebug(), "End of event stream");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080096 mBuffers->reset();
97 mLastEvent.reset();
98 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -080099 } else if (action != AMOTION_EVENT_ACTION_DOWN && action != AMOTION_EVENT_ACTION_MOVE) {
100 ALOGD_IF(isDebug(), "Skipping unsupported %s action",
101 MotionEvent::actionToString(action).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800102 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800103 }
104
105 if (event.getPointerCount() != 1) {
106 ALOGD_IF(isDebug(), "Prediction not supported for multiple pointers");
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800107 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800108 }
109
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700110 const ToolType toolType = event.getPointerProperties(0)->toolType;
111 if (toolType != ToolType::STYLUS) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800112 ALOGD_IF(isDebug(), "Prediction not supported for non-stylus tool: %s",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700113 ftl::enum_string(toolType).c_str());
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800114 return {};
Philip Quinn8f953ab2022-12-06 15:37:07 -0800115 }
116
117 for (size_t i = 0; i <= event.getHistorySize(); ++i) {
118 if (event.isResampled(0, i)) {
119 continue;
120 }
121 const PointerCoords* coords = event.getHistoricalRawPointerCoords(0, i);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800122 mBuffers->pushSample(event.getHistoricalEventTime(i),
123 {
124 .position.x = coords->getAxisValue(AMOTION_EVENT_AXIS_X),
125 .position.y = coords->getAxisValue(AMOTION_EVENT_AXIS_Y),
126 .pressure = event.getHistoricalPressure(0, i),
127 .tilt = event.getHistoricalAxisValue(AMOTION_EVENT_AXIS_TILT,
128 0, i),
129 .orientation = event.getHistoricalOrientation(0, i),
130 });
Philip Quinn8f953ab2022-12-06 15:37:07 -0800131 }
132
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800133 if (!mLastEvent) {
134 mLastEvent = MotionEvent();
135 }
136 mLastEvent->copyFrom(&event, /*keepHistory=*/false);
Cody Heiner088c63e2023-06-15 12:06:09 -0700137
138 // Pass input event to the MetricsManager.
139 if (!mMetricsManager) {
140 mMetricsManager =
141 std::make_optional<MotionPredictorMetricsManager>(mModel->predictionInterval(),
142 mModel->outputLength());
143 }
144 mMetricsManager->onRecord(event);
145
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800146 return {};
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800147}
148
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800149std::unique_ptr<MotionEvent> MotionPredictor::predict(nsecs_t timestamp) {
150 if (mBuffers == nullptr || !mBuffers->isReady()) {
151 return nullptr;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800152 }
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800153
154 LOG_ALWAYS_FATAL_IF(!mModel);
155 mBuffers->copyTo(*mModel);
156 LOG_ALWAYS_FATAL_IF(!mModel->invoke());
157
158 // Read out the predictions.
159 const std::span<const float> predictedR = mModel->outputR();
160 const std::span<const float> predictedPhi = mModel->outputPhi();
161 const std::span<const float> predictedPressure = mModel->outputPressure();
162
163 TfLiteMotionPredictorSample::Point axisFrom = mBuffers->axisFrom().position;
164 TfLiteMotionPredictorSample::Point axisTo = mBuffers->axisTo().position;
165
166 if (isDebug()) {
167 ALOGD("axisFrom: %f, %f", axisFrom.x, axisFrom.y);
168 ALOGD("axisTo: %f, %f", axisTo.x, axisTo.y);
169 ALOGD("mInputR: %s", base::Join(mModel->inputR(), ", ").c_str());
170 ALOGD("mInputPhi: %s", base::Join(mModel->inputPhi(), ", ").c_str());
171 ALOGD("mInputPressure: %s", base::Join(mModel->inputPressure(), ", ").c_str());
172 ALOGD("mInputTilt: %s", base::Join(mModel->inputTilt(), ", ").c_str());
173 ALOGD("mInputOrientation: %s", base::Join(mModel->inputOrientation(), ", ").c_str());
174 ALOGD("predictedR: %s", base::Join(predictedR, ", ").c_str());
175 ALOGD("predictedPhi: %s", base::Join(predictedPhi, ", ").c_str());
176 ALOGD("predictedPressure: %s", base::Join(predictedPressure, ", ").c_str());
177 }
178
179 LOG_ALWAYS_FATAL_IF(!mLastEvent);
180 const MotionEvent& event = *mLastEvent;
181 bool hasPredictions = false;
182 std::unique_ptr<MotionEvent> prediction = std::make_unique<MotionEvent>();
183 int64_t predictionTime = mBuffers->lastTimestamp();
184 const int64_t futureTime = timestamp + mPredictionTimestampOffsetNanos;
185
186 for (int i = 0; i < predictedR.size() && predictionTime <= futureTime; ++i) {
Cody Heiner088c63e2023-06-15 12:06:09 -0700187 // TODO(b/266747654): Stop predictions if confidence and/or predicted pressure are below
188 // some thresholds.
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800189
Cody Heiner088c63e2023-06-15 12:06:09 -0700190 const TfLiteMotionPredictorSample::Point predictedPoint =
191 convertPrediction(axisFrom, axisTo, predictedR[i], predictedPhi[i]);
192
193 ALOGD_IF(isDebug(), "prediction %d: %f, %f", i, predictedPoint.x, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800194 PointerCoords coords;
195 coords.clear();
Cody Heiner088c63e2023-06-15 12:06:09 -0700196 coords.setAxisValue(AMOTION_EVENT_AXIS_X, predictedPoint.x);
197 coords.setAxisValue(AMOTION_EVENT_AXIS_Y, predictedPoint.y);
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800198 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, predictedPressure[i]);
199
Philip Quinnf84fa492023-06-26 14:15:15 -0700200 predictionTime += mModel->predictionInterval();
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800201 if (i == 0) {
202 hasPredictions = true;
203 prediction->initialize(InputEvent::nextId(), event.getDeviceId(), event.getSource(),
204 event.getDisplayId(), INVALID_HMAC, AMOTION_EVENT_ACTION_MOVE,
205 event.getActionButton(), event.getFlags(), event.getEdgeFlags(),
206 event.getMetaState(), event.getButtonState(),
207 event.getClassification(), event.getTransform(),
208 event.getXPrecision(), event.getYPrecision(),
209 event.getRawXCursorPosition(), event.getRawYCursorPosition(),
210 event.getRawTransform(), event.getDownTime(), predictionTime,
211 event.getPointerCount(), event.getPointerProperties(), &coords);
212 } else {
213 prediction->addSample(predictionTime, &coords);
214 }
215
216 axisFrom = axisTo;
Cody Heiner088c63e2023-06-15 12:06:09 -0700217 axisTo = predictedPoint;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800218 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700219
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800220 if (!hasPredictions) {
221 return nullptr;
222 }
Cody Heiner088c63e2023-06-15 12:06:09 -0700223
224 // Pass predictions to the MetricsManager.
225 LOG_ALWAYS_FATAL_IF(!mMetricsManager);
226 mMetricsManager->onPredict(*prediction);
227
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800228 return prediction;
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800229}
230
231bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
232 // Global flag override
233 if (!mCheckMotionPredictionEnabled()) {
234 ALOGD_IF(isDebug(), "Prediction not available due to flag override");
235 return false;
236 }
237
238 // Prediction is only supported for stylus sources.
239 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
240 ALOGD_IF(isDebug(), "Prediction not available for non-stylus source: %s",
241 inputEventSourceToString(source).c_str());
242 return false;
243 }
244 return true;
245}
246
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800247} // namespace android