blob: 200c301ffebaa4821ad6f3fc1b8b43fc8eb94c3b [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#pragma once
18
Derek Wu705068d2024-03-20 10:41:37 -070019#include <array>
Philip Quinn8f953ab2022-12-06 15:37:07 -080020#include <cstdint>
21#include <memory>
22#include <mutex>
Cody Heiner7b26dbe2023-11-14 14:47:10 -080023#include <optional>
Philip Quinnbd66e622023-02-10 11:45:01 -080024#include <string>
Philip Quinn8f953ab2022-12-06 15:37:07 -080025#include <unordered_map>
26
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -080027#include <android-base/result.h>
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080028#include <android-base/thread_annotations.h>
29#include <android/sysprop/InputProperties.sysprop.h>
30#include <input/Input.h>
Cody Heiner088c63e2023-06-15 12:06:09 -070031#include <input/MotionPredictorMetricsManager.h>
Derek Wu705068d2024-03-20 10:41:37 -070032#include <input/RingBuffer.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080033#include <input/TfLiteMotionPredictor.h>
Cody Heiner088c63e2023-06-15 12:06:09 -070034#include <utils/Timers.h> // for nsecs_t
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080035
36namespace android {
37
38static inline bool isMotionPredictionEnabled() {
39 return sysprop::InputProperties::enable_motion_prediction().value_or(true);
40}
41
Derek Wu705068d2024-03-20 10:41:37 -070042// Tracker to calculate jerk from motion position samples.
43class JerkTracker {
44public:
45 // Initialize the tracker. If normalizedDt is true, assume that each sample pushed has dt=1.
Derek Wucc6aec52024-07-30 11:59:56 +000046 // alpha is the coefficient of the first-order IIR filter for jerk. A factor of 1 results
47 // in no smoothing.
48 JerkTracker(bool normalizedDt, float alpha);
Derek Wu705068d2024-03-20 10:41:37 -070049
50 // Add a position to the tracker and update derivative estimates.
51 void pushSample(int64_t timestamp, float xPos, float yPos);
52
53 // Reset JerkTracker for a new motion input.
54 void reset();
55
56 // Return last jerk calculation, if enough samples have been collected.
57 // Jerk is defined as the 3rd derivative of position (change in
58 // acceleration) and has the units of d^3p/dt^3.
59 std::optional<float> jerkMagnitude() const;
60
61private:
62 const bool mNormalizedDt;
Derek Wu5e0e7cf2024-07-04 11:14:18 +000063 // Coefficient of first-order IIR filter to smooth jerk calculation.
Derek Wucc6aec52024-07-30 11:59:56 +000064 const float mAlpha;
Derek Wu705068d2024-03-20 10:41:37 -070065
66 RingBuffer<int64_t> mTimestamps{4};
67 std::array<float, 4> mXDerivatives{}; // [x, x', x'', x''']
68 std::array<float, 4> mYDerivatives{}; // [y, y', y'', y''']
Derek Wu5e0e7cf2024-07-04 11:14:18 +000069 float mJerkMagnitude;
Derek Wu705068d2024-03-20 10:41:37 -070070};
71
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080072/**
73 * Given a set of MotionEvents for the current gesture, predict the motion. The returned MotionEvent
Philip Quinn8f953ab2022-12-06 15:37:07 -080074 * contains a set of samples in the future.
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080075 *
76 * The typical usage is like this:
77 *
78 * MotionPredictor predictor(offset = MY_OFFSET);
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080079 * predictor.record(DOWN_MOTION_EVENT);
80 * predictor.record(MOVE_MOTION_EVENT);
Philip Quinn8f953ab2022-12-06 15:37:07 -080081 * prediction = predictor.predict(futureTime);
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080082 *
Philip Quinn8f953ab2022-12-06 15:37:07 -080083 * The resulting motion event will have eventTime <= (futureTime + MY_OFFSET). It might contain
84 * historical data, which are additional samples from the latest recorded MotionEvent's eventTime
85 * to the futureTime + MY_OFFSET.
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080086 *
87 * The offset is used to provide additional flexibility to the caller, in case the default present
88 * time (typically provided by the choreographer) does not account for some delays, or to simply
Philip Quinn8f953ab2022-12-06 15:37:07 -080089 * reduce the aggressiveness of the prediction. Offset can be positive or negative.
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080090 */
91class MotionPredictor {
92public:
Cody Heiner7b26dbe2023-11-14 14:47:10 -080093 using ReportAtomFunction = MotionPredictorMetricsManager::ReportAtomFunction;
94
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080095 /**
96 * Parameters:
97 * predictionTimestampOffsetNanos: additional, constant shift to apply to the target
Philip Quinn8f953ab2022-12-06 15:37:07 -080098 * prediction time. The prediction will target the time t=(prediction time +
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -080099 * predictionTimestampOffsetNanos).
100 *
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800101 * checkEnableMotionPrediction: the function to check whether the prediction should run. Used to
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800102 * provide an additional way of turning prediction on and off. Can be toggled at runtime.
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800103 *
104 * reportAtomFunction: the function that will be called to report prediction metrics. If
105 * omitted, the implementation will choose a default metrics reporting mechanism.
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800106 */
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -0800107 MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800108 std::function<bool()> checkEnableMotionPrediction = isMotionPredictionEnabled,
109 ReportAtomFunction reportAtomFunction = {});
Cody Heiner088c63e2023-06-15 12:06:09 -0700110
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800111 /**
112 * Record the actual motion received by the view. This event will be used for calculating the
113 * predictions.
114 *
115 * @return empty result if the event was processed correctly, error if the event is not
116 * consistent with the previously recorded events.
117 */
118 android::base::Result<void> record(const MotionEvent& event);
Cody Heiner088c63e2023-06-15 12:06:09 -0700119
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800120 std::unique_ptr<MotionEvent> predict(nsecs_t timestamp);
Cody Heiner088c63e2023-06-15 12:06:09 -0700121
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800122 bool isPredictionAvailable(int32_t deviceId, int32_t source);
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800123
124private:
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800125 const nsecs_t mPredictionTimestampOffsetNanos;
126 const std::function<bool()> mCheckMotionPredictionEnabled;
Philip Quinn8f953ab2022-12-06 15:37:07 -0800127
128 std::unique_ptr<TfLiteMotionPredictorModel> mModel;
Siarhei Vishniakou33cb38b2023-02-23 18:52:34 -0800129
130 std::unique_ptr<TfLiteMotionPredictorBuffers> mBuffers;
131 std::optional<MotionEvent> mLastEvent;
Cody Heiner088c63e2023-06-15 12:06:09 -0700132
Derek Wucc6aec52024-07-30 11:59:56 +0000133 std::unique_ptr<JerkTracker> mJerkTracker;
134
135 std::unique_ptr<MotionPredictorMetricsManager> mMetricsManager;
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800136
137 const ReportAtomFunction mReportAtomFunction;
Derek Wucc6aec52024-07-30 11:59:56 +0000138
139 // Initialize prediction model and associated objects.
140 // Called during lazy initialization.
141 // TODO: b/210158587 Consider removing lazy initialization.
142 void initializeObjects();
Siarhei Vishniakou39147ce2022-11-15 12:13:04 -0800143};
144
145} // namespace android