1 /*
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
19 #include <array>
20 #include <cstdint>
21 #include <memory>
22 #include <mutex>
23 #include <optional>
24 #include <string>
25 #include <unordered_map>
26
27 #include <android-base/result.h>
28 #include <android-base/thread_annotations.h>
29 #include <android/sysprop/InputProperties.sysprop.h>
30 #include <input/Input.h>
31 #include <input/MotionPredictorMetricsManager.h>
32 #include <input/RingBuffer.h>
33 #include <input/TfLiteMotionPredictor.h>
34 #include <utils/Timers.h> // for nsecs_t
35
36 namespace android {
37
isMotionPredictionEnabled()38 static inline bool isMotionPredictionEnabled() {
39 return sysprop::InputProperties::enable_motion_prediction().value_or(true);
40 }
41
42 // Tracker to calculate jerk from motion position samples.
43 class JerkTracker {
44 public:
45 // Initialize the tracker. If normalizedDt is true, assume that each sample pushed has dt=1.
46 JerkTracker(bool normalizedDt);
47
48 // Add a position to the tracker and update derivative estimates.
49 void pushSample(int64_t timestamp, float xPos, float yPos);
50
51 // Reset JerkTracker for a new motion input.
52 void reset();
53
54 // Return last jerk calculation, if enough samples have been collected.
55 // Jerk is defined as the 3rd derivative of position (change in
56 // acceleration) and has the units of d^3p/dt^3.
57 std::optional<float> jerkMagnitude() const;
58
59 private:
60 const bool mNormalizedDt;
61
62 RingBuffer<int64_t> mTimestamps{4};
63 std::array<float, 4> mXDerivatives{}; // [x, x', x'', x''']
64 std::array<float, 4> mYDerivatives{}; // [y, y', y'', y''']
65 };
66
67 /**
68 * Given a set of MotionEvents for the current gesture, predict the motion. The returned MotionEvent
69 * contains a set of samples in the future.
70 *
71 * The typical usage is like this:
72 *
73 * MotionPredictor predictor(offset = MY_OFFSET);
74 * predictor.record(DOWN_MOTION_EVENT);
75 * predictor.record(MOVE_MOTION_EVENT);
76 * prediction = predictor.predict(futureTime);
77 *
78 * The resulting motion event will have eventTime <= (futureTime + MY_OFFSET). It might contain
79 * historical data, which are additional samples from the latest recorded MotionEvent's eventTime
80 * to the futureTime + MY_OFFSET.
81 *
82 * The offset is used to provide additional flexibility to the caller, in case the default present
83 * time (typically provided by the choreographer) does not account for some delays, or to simply
84 * reduce the aggressiveness of the prediction. Offset can be positive or negative.
85 */
86 class MotionPredictor {
87 public:
88 using ReportAtomFunction = MotionPredictorMetricsManager::ReportAtomFunction;
89
90 /**
91 * Parameters:
92 * predictionTimestampOffsetNanos: additional, constant shift to apply to the target
93 * prediction time. The prediction will target the time t=(prediction time +
94 * predictionTimestampOffsetNanos).
95 *
96 * checkEnableMotionPrediction: the function to check whether the prediction should run. Used to
97 * provide an additional way of turning prediction on and off. Can be toggled at runtime.
98 *
99 * reportAtomFunction: the function that will be called to report prediction metrics. If
100 * omitted, the implementation will choose a default metrics reporting mechanism.
101 */
102 MotionPredictor(nsecs_t predictionTimestampOffsetNanos,
103 std::function<bool()> checkEnableMotionPrediction = isMotionPredictionEnabled,
104 ReportAtomFunction reportAtomFunction = {});
105
106 /**
107 * Record the actual motion received by the view. This event will be used for calculating the
108 * predictions.
109 *
110 * @return empty result if the event was processed correctly, error if the event is not
111 * consistent with the previously recorded events.
112 */
113 android::base::Result<void> record(const MotionEvent& event);
114
115 std::unique_ptr<MotionEvent> predict(nsecs_t timestamp);
116
117 bool isPredictionAvailable(int32_t deviceId, int32_t source);
118
119 private:
120 const nsecs_t mPredictionTimestampOffsetNanos;
121 const std::function<bool()> mCheckMotionPredictionEnabled;
122
123 std::unique_ptr<TfLiteMotionPredictorModel> mModel;
124
125 std::unique_ptr<TfLiteMotionPredictorBuffers> mBuffers;
126 std::optional<MotionEvent> mLastEvent;
127 // mJerkTracker assumes normalized dt = 1 between recorded samples because
128 // the underlying mModel input also assumes fixed-interval samples.
129 // Normalized dt as 1 is also used to correspond with the similar Jank
130 // implementation from the JetPack MotionPredictor implementation.
131 JerkTracker mJerkTracker{true};
132
133 std::optional<MotionPredictorMetricsManager> mMetricsManager;
134
135 const ReportAtomFunction mReportAtomFunction;
136 };
137
138 } // namespace android
139