blob: 8fe904f9a490c52f277d5424ca50e8626ab11b38 [file] [log] [blame]
Paul Ramirezbe9c5442024-07-10 00:12:41 +00001/**
2 * Copyright 2024 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 "LegacyResampler"
18
19#include <algorithm>
20#include <chrono>
Paul Ramirez4d3b03a2024-09-30 01:39:00 +000021#include <ostream>
Paul Ramirezbe9c5442024-07-10 00:12:41 +000022
23#include <android-base/logging.h>
24#include <android-base/properties.h>
Paul Ramirezcf1b06e2024-08-01 17:11:58 +000025#include <ftl/enum.h>
Paul Ramirezbe9c5442024-07-10 00:12:41 +000026
27#include <input/Resampler.h>
28#include <utils/Timers.h>
29
Paul Ramirezbe9c5442024-07-10 00:12:41 +000030namespace android {
Paul Ramirezbe9c5442024-07-10 00:12:41 +000031namespace {
32
33const bool IS_DEBUGGABLE_BUILD =
34#if defined(__ANDROID__)
35 android::base::GetBoolProperty("ro.debuggable", false);
36#else
37 true;
38#endif
39
40bool debugResampling() {
41 if (!IS_DEBUGGABLE_BUILD) {
42 static const bool DEBUG_TRANSPORT_RESAMPLING =
43 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
44 ANDROID_LOG_INFO);
45 return DEBUG_TRANSPORT_RESAMPLING;
46 }
47 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
48}
49
Paul Ramirez4d3b03a2024-09-30 01:39:00 +000050using std::chrono::nanoseconds;
51
Paul Ramirezbe9c5442024-07-10 00:12:41 +000052constexpr std::chrono::milliseconds RESAMPLE_LATENCY{5};
53
54constexpr std::chrono::milliseconds RESAMPLE_MIN_DELTA{2};
55
56constexpr std::chrono::milliseconds RESAMPLE_MAX_DELTA{20};
57
58constexpr std::chrono::milliseconds RESAMPLE_MAX_PREDICTION{8};
59
Paul Ramirezcf1b06e2024-08-01 17:11:58 +000060bool canResampleTool(ToolType toolType) {
61 return toolType == ToolType::FINGER || toolType == ToolType::MOUSE ||
62 toolType == ToolType::STYLUS || toolType == ToolType::UNKNOWN;
63}
64
Paul Ramirezbe9c5442024-07-10 00:12:41 +000065inline float lerp(float a, float b, float alpha) {
66 return a + alpha * (b - a);
67}
68
Paul Ramirez486ca6d2024-08-12 14:37:02 +000069PointerCoords calculateResampledCoords(const PointerCoords& a, const PointerCoords& b,
70 float alpha) {
Paul Ramirez68ca3d12024-08-12 23:00:50 +000071 // We use the value of alpha to initialize resampledCoords with the latest sample information.
72 PointerCoords resampledCoords = (alpha < 1.0f) ? a : b;
Paul Ramirezbe9c5442024-07-10 00:12:41 +000073 resampledCoords.isResampled = true;
74 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X, lerp(a.getX(), b.getX(), alpha));
75 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, lerp(a.getY(), b.getY(), alpha));
76 return resampledCoords;
77}
Paul Ramirez4d3b03a2024-09-30 01:39:00 +000078
79bool equalXY(const PointerCoords& a, const PointerCoords& b) {
80 return (a.getX() == b.getX()) && (a.getY() == b.getY());
81}
82
83void setMotionEventPointerCoords(MotionEvent& motionEvent, size_t sampleIndex, size_t pointerIndex,
84 const PointerCoords& pointerCoords) {
85 // Ideally, we should not cast away const. In this particular case, it's safe to cast away const
86 // and dereference getHistoricalRawPointerCoords returned pointer because motionEvent is a
87 // nonconst reference to a MotionEvent object, so mutating the object should not be undefined
88 // behavior; moreover, the invoked method guarantees to return a valid pointer. Otherwise, it
89 // fatally logs. Alternatively, we could've created a new MotionEvent from scratch, but this
90 // approach is simpler and more efficient.
91 PointerCoords& motionEventCoords = const_cast<PointerCoords&>(
92 *(motionEvent.getHistoricalRawPointerCoords(pointerIndex, sampleIndex)));
93 motionEventCoords.setAxisValue(AMOTION_EVENT_AXIS_X, pointerCoords.getX());
94 motionEventCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, pointerCoords.getY());
95 motionEventCoords.isResampled = pointerCoords.isResampled;
96}
97
98std::ostream& operator<<(std::ostream& os, const PointerCoords& pointerCoords) {
99 os << "(" << pointerCoords.getX() << ", " << pointerCoords.getY() << ")";
100 return os;
101}
102
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000103} // namespace
104
105void LegacyResampler::updateLatestSamples(const MotionEvent& motionEvent) {
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000106 const size_t numSamples = motionEvent.getHistorySize() + 1;
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000107 const size_t latestIndex = numSamples - 1;
108 const size_t secondToLatestIndex = (latestIndex > 0) ? (latestIndex - 1) : 0;
109 for (size_t sampleIndex = secondToLatestIndex; sampleIndex < numSamples; ++sampleIndex) {
110 std::vector<Pointer> pointers;
111 const size_t numPointers = motionEvent.getPointerCount();
112 for (size_t pointerIndex = 0; pointerIndex < numPointers; ++pointerIndex) {
Paul Ramirez4d3b03a2024-09-30 01:39:00 +0000113 pointers.push_back(Pointer{*(motionEvent.getPointerProperties(pointerIndex)),
114 *(motionEvent.getHistoricalRawPointerCoords(pointerIndex,
115 sampleIndex))});
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000116 }
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000117 mLatestSamples.pushBack(
Paul Ramirez698344a2024-08-20 00:58:55 +0000118 Sample{nanoseconds{motionEvent.getHistoricalEventTime(sampleIndex)}, pointers});
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000119 }
120}
121
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000122LegacyResampler::Sample LegacyResampler::messageToSample(const InputMessage& message) {
123 std::vector<Pointer> pointers;
124 for (uint32_t i = 0; i < message.body.motion.pointerCount; ++i) {
125 pointers.push_back(Pointer{message.body.motion.pointers[i].properties,
126 message.body.motion.pointers[i].coords});
127 }
Paul Ramirez698344a2024-08-20 00:58:55 +0000128 return Sample{nanoseconds{message.body.motion.eventTime}, pointers};
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000129}
130
131bool LegacyResampler::pointerPropertiesResampleable(const Sample& target, const Sample& auxiliary) {
132 if (target.pointers.size() > auxiliary.pointers.size()) {
133 LOG_IF(INFO, debugResampling())
134 << "Not resampled. Auxiliary sample has fewer pointers than target sample.";
135 return false;
136 }
137 for (size_t i = 0; i < target.pointers.size(); ++i) {
138 if (target.pointers[i].properties.id != auxiliary.pointers[i].properties.id) {
139 LOG_IF(INFO, debugResampling()) << "Not resampled. Pointer ID mismatch.";
140 return false;
141 }
142 if (target.pointers[i].properties.toolType != auxiliary.pointers[i].properties.toolType) {
143 LOG_IF(INFO, debugResampling()) << "Not resampled. Pointer ToolType mismatch.";
144 return false;
145 }
146 if (!canResampleTool(target.pointers[i].properties.toolType)) {
147 LOG_IF(INFO, debugResampling())
148 << "Not resampled. Cannot resample "
149 << ftl::enum_string(target.pointers[i].properties.toolType) << " ToolType.";
150 return false;
151 }
152 }
153 return true;
154}
155
156bool LegacyResampler::canInterpolate(const InputMessage& message) const {
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000157 LOG_IF(FATAL, mLatestSamples.empty())
158 << "Not resampled. mLatestSamples must not be empty to interpolate.";
159
160 const Sample& pastSample = *(mLatestSamples.end() - 1);
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000161 const Sample& futureSample = messageToSample(message);
162
163 if (!pointerPropertiesResampleable(pastSample, futureSample)) {
164 return false;
165 }
166
167 const nanoseconds delta = futureSample.eventTime - pastSample.eventTime;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000168 if (delta < RESAMPLE_MIN_DELTA) {
169 LOG_IF(INFO, debugResampling()) << "Not resampled. Delta is too small: " << delta << "ns.";
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000170 return false;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000171 }
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000172 return true;
173}
174
175std::optional<LegacyResampler::Sample> LegacyResampler::attemptInterpolation(
176 nanoseconds resampleTime, const InputMessage& futureSample) const {
177 if (!canInterpolate(futureSample)) {
178 return std::nullopt;
179 }
180 LOG_IF(FATAL, mLatestSamples.empty())
181 << "Not resampled. mLatestSamples must not be empty to interpolate.";
182
183 const Sample& pastSample = *(mLatestSamples.end() - 1);
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000184
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000185 const nanoseconds delta =
Paul Ramirez698344a2024-08-20 00:58:55 +0000186 nanoseconds{futureSample.body.motion.eventTime} - pastSample.eventTime;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000187 const float alpha =
188 std::chrono::duration<float, std::milli>(resampleTime - pastSample.eventTime) / delta;
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000189
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000190 std::vector<Pointer> resampledPointers;
191 for (size_t i = 0; i < pastSample.pointers.size(); ++i) {
192 const PointerCoords& resampledCoords =
193 calculateResampledCoords(pastSample.pointers[i].coords,
194 futureSample.body.motion.pointers[i].coords, alpha);
195 resampledPointers.push_back(Pointer{pastSample.pointers[i].properties, resampledCoords});
196 }
197 return Sample{resampleTime, resampledPointers};
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000198}
199
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000200bool LegacyResampler::canExtrapolate() const {
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000201 if (mLatestSamples.size() < 2) {
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000202 LOG_IF(INFO, debugResampling()) << "Not resampled. Not enough data.";
203 return false;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000204 }
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000205
206 const Sample& pastSample = *(mLatestSamples.end() - 2);
207 const Sample& presentSample = *(mLatestSamples.end() - 1);
208
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000209 if (!pointerPropertiesResampleable(presentSample, pastSample)) {
210 return false;
211 }
212
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000213 const nanoseconds delta = presentSample.eventTime - pastSample.eventTime;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000214 if (delta < RESAMPLE_MIN_DELTA) {
215 LOG_IF(INFO, debugResampling()) << "Not resampled. Delta is too small: " << delta << "ns.";
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000216 return false;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000217 } else if (delta > RESAMPLE_MAX_DELTA) {
218 LOG_IF(INFO, debugResampling()) << "Not resampled. Delta is too large: " << delta << "ns.";
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000219 return false;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000220 }
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000221 return true;
222}
223
224std::optional<LegacyResampler::Sample> LegacyResampler::attemptExtrapolation(
225 nanoseconds resampleTime) const {
226 if (!canExtrapolate()) {
227 return std::nullopt;
228 }
229 LOG_IF(FATAL, mLatestSamples.size() < 2)
230 << "Not resampled. mLatestSamples must have at least two samples to extrapolate.";
231
232 const Sample& pastSample = *(mLatestSamples.end() - 2);
233 const Sample& presentSample = *(mLatestSamples.end() - 1);
234
235 const nanoseconds delta = presentSample.eventTime - pastSample.eventTime;
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000236 // The farthest future time to which we can extrapolate. If the given resampleTime exceeds this,
237 // we use this value as the resample time target.
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000238 const nanoseconds farthestPrediction =
239 presentSample.eventTime + std::min<nanoseconds>(delta / 2, RESAMPLE_MAX_PREDICTION);
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000240 const nanoseconds newResampleTime =
241 (resampleTime > farthestPrediction) ? (farthestPrediction) : (resampleTime);
242 LOG_IF(INFO, debugResampling() && newResampleTime == farthestPrediction)
243 << "Resample time is too far in the future. Adjusting prediction from "
244 << (resampleTime - presentSample.eventTime) << " to "
245 << (farthestPrediction - presentSample.eventTime) << "ns.";
246 const float alpha =
247 std::chrono::duration<float, std::milli>(newResampleTime - pastSample.eventTime) /
248 delta;
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000249
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000250 std::vector<Pointer> resampledPointers;
251 for (size_t i = 0; i < presentSample.pointers.size(); ++i) {
252 const PointerCoords& resampledCoords =
253 calculateResampledCoords(pastSample.pointers[i].coords,
254 presentSample.pointers[i].coords, alpha);
255 resampledPointers.push_back(Pointer{presentSample.pointers[i].properties, resampledCoords});
256 }
257 return Sample{newResampleTime, resampledPointers};
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000258}
259
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000260inline void LegacyResampler::addSampleToMotionEvent(const Sample& sample,
261 MotionEvent& motionEvent) {
Paul Ramirezcf1b06e2024-08-01 17:11:58 +0000262 motionEvent.addSample(sample.eventTime.count(), sample.asPointerCoords().data(),
263 motionEvent.getId());
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000264}
265
Paul Ramirezcd7488c2024-09-13 23:01:12 +0000266nanoseconds LegacyResampler::getResampleLatency() const {
267 return RESAMPLE_LATENCY;
268}
269
Paul Ramirez4d3b03a2024-09-30 01:39:00 +0000270void LegacyResampler::overwriteMotionEventSamples(MotionEvent& motionEvent) const {
271 const size_t numSamples = motionEvent.getHistorySize() + 1;
272 for (size_t sampleIndex = 0; sampleIndex < numSamples; ++sampleIndex) {
273 overwriteStillPointers(motionEvent, sampleIndex);
274 }
275}
276
277void LegacyResampler::overwriteStillPointers(MotionEvent& motionEvent, size_t sampleIndex) const {
278 for (size_t pointerIndex = 0; pointerIndex < motionEvent.getPointerCount(); ++pointerIndex) {
279 const PointerCoords& pointerCoords =
280 *(motionEvent.getHistoricalRawPointerCoords(pointerIndex, sampleIndex));
281 if (equalXY(mLastRealSample->pointers[pointerIndex].coords, pointerCoords)) {
282 LOG_IF(INFO, debugResampling())
283 << "Pointer ID: " << motionEvent.getPointerId(pointerIndex)
284 << " did not move. Overwriting its coordinates from " << pointerCoords << " to "
285 << mLastRealSample->pointers[pointerIndex].coords;
286 setMotionEventPointerCoords(motionEvent, sampleIndex, pointerIndex,
287 mPreviousPrediction->pointers[pointerIndex].coords);
288 }
289 }
290}
291
Paul Ramirez6affbdb2024-09-11 22:20:26 +0000292void LegacyResampler::resampleMotionEvent(nanoseconds frameTime, MotionEvent& motionEvent,
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000293 const InputMessage* futureSample) {
Paul Ramirez6affbdb2024-09-11 22:20:26 +0000294 const nanoseconds resampleTime = frameTime - RESAMPLE_LATENCY;
295
Paul Ramirez7f1efed2024-09-29 23:55:23 +0000296 if (resampleTime.count() == motionEvent.getEventTime()) {
297 LOG_IF(INFO, debugResampling()) << "Not resampled. Resample time equals motion event time.";
298 return;
299 }
300
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000301 updateLatestSamples(motionEvent);
Paul Ramirez486ca6d2024-08-12 14:37:02 +0000302
303 const std::optional<Sample> sample = (futureSample != nullptr)
304 ? (attemptInterpolation(resampleTime, *futureSample))
305 : (attemptExtrapolation(resampleTime));
306 if (sample.has_value()) {
307 addSampleToMotionEvent(*sample, motionEvent);
Paul Ramirez4d3b03a2024-09-30 01:39:00 +0000308 if (mPreviousPrediction.has_value()) {
309 overwriteMotionEventSamples(motionEvent);
310 }
311 // mPreviousPrediction is only updated whenever extrapolation occurs because extrapolation
312 // is about predicting upcoming scenarios.
313 if (futureSample == nullptr) {
314 mPreviousPrediction = sample;
315 }
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000316 }
Paul Ramirez4d3b03a2024-09-30 01:39:00 +0000317 mLastRealSample = *(mLatestSamples.end() - 1);
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000318}
Paul Ramirez4d3b03a2024-09-30 01:39:00 +0000319
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000320} // namespace android