1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
|
/**
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "LegacyResampler"
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <ostream>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <ftl/enum.h>
#include <input/Resampler.h>
#include <utils/Timers.h>
namespace android {
namespace {
const bool IS_DEBUGGABLE_BUILD =
#if defined(__ANDROID__)
android::base::GetBoolProperty("ro.debuggable", false);
#else
true;
#endif
/**
* Log debug messages about timestamp and coordinates of event resampling.
* Enable this via "adb shell setprop log.tag.LegacyResamplerResampling DEBUG"
* (requires restart)
*/
bool debugResampling() {
if (!IS_DEBUGGABLE_BUILD) {
static const bool DEBUG_TRANSPORT_RESAMPLING =
__android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
ANDROID_LOG_INFO);
return DEBUG_TRANSPORT_RESAMPLING;
}
return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
}
using std::chrono::nanoseconds;
constexpr std::chrono::milliseconds RESAMPLE_LATENCY{5};
constexpr std::chrono::milliseconds RESAMPLE_MIN_DELTA{2};
constexpr std::chrono::milliseconds RESAMPLE_MAX_DELTA{20};
constexpr std::chrono::milliseconds RESAMPLE_MAX_PREDICTION{8};
bool canResampleTool(ToolType toolType) {
return toolType == ToolType::FINGER || toolType == ToolType::MOUSE ||
toolType == ToolType::STYLUS || toolType == ToolType::UNKNOWN;
}
inline float lerp(float a, float b, float alpha) {
return a + alpha * (b - a);
}
PointerCoords calculateResampledCoords(const PointerCoords& a, const PointerCoords& b,
float alpha) {
// We use the value of alpha to initialize resampledCoords with the latest sample information.
PointerCoords resampledCoords = (alpha < 1.0f) ? a : b;
resampledCoords.isResampled = true;
resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X, lerp(a.getX(), b.getX(), alpha));
resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, lerp(a.getY(), b.getY(), alpha));
return resampledCoords;
}
bool equalXY(const PointerCoords& a, const PointerCoords& b) {
return (a.getX() == b.getX()) && (a.getY() == b.getY());
}
void setMotionEventPointerCoords(MotionEvent& motionEvent, size_t sampleIndex, size_t pointerIndex,
const PointerCoords& pointerCoords) {
// Ideally, we should not cast away const. In this particular case, it's safe to cast away const
// and dereference getHistoricalRawPointerCoords returned pointer because motionEvent is a
// nonconst reference to a MotionEvent object, so mutating the object should not be undefined
// behavior; moreover, the invoked method guarantees to return a valid pointer. Otherwise, it
// fatally logs. Alternatively, we could've created a new MotionEvent from scratch, but this
// approach is simpler and more efficient.
PointerCoords& motionEventCoords = const_cast<PointerCoords&>(
*(motionEvent.getHistoricalRawPointerCoords(pointerIndex, sampleIndex)));
motionEventCoords.setAxisValue(AMOTION_EVENT_AXIS_X, pointerCoords.getX());
motionEventCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, pointerCoords.getY());
motionEventCoords.isResampled = pointerCoords.isResampled;
}
std::ostream& operator<<(std::ostream& os, const PointerCoords& pointerCoords) {
os << "(" << pointerCoords.getX() << ", " << pointerCoords.getY() << ")";
return os;
}
} // namespace
void LegacyResampler::updateLatestSamples(const MotionEvent& motionEvent) {
const size_t numSamples = motionEvent.getHistorySize() + 1;
const size_t latestIndex = numSamples - 1;
const size_t secondToLatestIndex = (latestIndex > 0) ? (latestIndex - 1) : 0;
for (size_t sampleIndex = secondToLatestIndex; sampleIndex < numSamples; ++sampleIndex) {
PointerMap pointerMap;
for (size_t pointerIndex = 0; pointerIndex < motionEvent.getPointerCount();
++pointerIndex) {
pointerMap.insert(Pointer{*(motionEvent.getPointerProperties(pointerIndex)),
*(motionEvent.getHistoricalRawPointerCoords(pointerIndex,
sampleIndex))});
}
mLatestSamples.pushBack(
Sample{nanoseconds{motionEvent.getHistoricalEventTime(sampleIndex)}, pointerMap});
}
}
LegacyResampler::Sample LegacyResampler::messageToSample(const InputMessage& message) {
PointerMap pointerMap;
for (uint32_t i = 0; i < message.body.motion.pointerCount; ++i) {
pointerMap.insert(Pointer{message.body.motion.pointers[i].properties,
message.body.motion.pointers[i].coords});
}
return Sample{nanoseconds{message.body.motion.eventTime}, pointerMap};
}
bool LegacyResampler::pointerPropertiesResampleable(const Sample& target, const Sample& auxiliary) {
for (const Pointer& pointer : target.pointerMap) {
const std::optional<Pointer> auxiliaryPointer =
auxiliary.pointerMap.find(PointerMap::PointerId{pointer.properties.id});
if (!auxiliaryPointer.has_value()) {
LOG_IF(INFO, debugResampling())
<< "Not resampled. Auxiliary sample does not contain all pointers from target.";
return false;
}
if (pointer.properties.toolType != auxiliaryPointer->properties.toolType) {
LOG_IF(INFO, debugResampling()) << "Not resampled. Pointer ToolType mismatch.";
return false;
}
if (!canResampleTool(pointer.properties.toolType)) {
LOG_IF(INFO, debugResampling())
<< "Not resampled. Cannot resample "
<< ftl::enum_string(pointer.properties.toolType) << " ToolType.";
return false;
}
}
return true;
}
bool LegacyResampler::canInterpolate(const InputMessage& message) const {
LOG_IF(FATAL, mLatestSamples.empty())
<< "Not resampled. mLatestSamples must not be empty to interpolate.";
const Sample& pastSample = *(mLatestSamples.end() - 1);
const Sample& futureSample = messageToSample(message);
if (!pointerPropertiesResampleable(pastSample, futureSample)) {
return false;
}
const nanoseconds delta = futureSample.eventTime - pastSample.eventTime;
if (delta < RESAMPLE_MIN_DELTA) {
LOG_IF(INFO, debugResampling())
<< "Not resampled. Delta is too small: " << std::setprecision(3)
<< std::chrono::duration<double, std::milli>{delta}.count() << "ms";
return false;
}
return true;
}
std::optional<LegacyResampler::Sample> LegacyResampler::attemptInterpolation(
nanoseconds resampleTime, const InputMessage& futureMessage) const {
if (!canInterpolate(futureMessage)) {
return std::nullopt;
}
LOG_IF(FATAL, mLatestSamples.empty())
<< "Not resampled. mLatestSamples must not be empty to interpolate.";
const Sample& pastSample = *(mLatestSamples.end() - 1);
const Sample& futureSample = messageToSample(futureMessage);
const nanoseconds delta = nanoseconds{futureSample.eventTime} - pastSample.eventTime;
const float alpha =
std::chrono::duration<float, std::nano>(resampleTime - pastSample.eventTime) / delta;
PointerMap resampledPointerMap;
for (const Pointer& pointer : pastSample.pointerMap) {
if (std::optional<Pointer> futureSamplePointer =
futureSample.pointerMap.find(PointerMap::PointerId{pointer.properties.id});
futureSamplePointer.has_value()) {
const PointerCoords& resampledCoords =
calculateResampledCoords(pointer.coords, futureSamplePointer->coords, alpha);
resampledPointerMap.insert(Pointer{pointer.properties, resampledCoords});
}
}
return Sample{resampleTime, resampledPointerMap};
}
bool LegacyResampler::canExtrapolate() const {
if (mLatestSamples.size() < 2) {
LOG_IF(INFO, debugResampling()) << "Not resampled. Not enough data.";
return false;
}
const Sample& pastSample = *(mLatestSamples.end() - 2);
const Sample& presentSample = *(mLatestSamples.end() - 1);
if (!pointerPropertiesResampleable(presentSample, pastSample)) {
return false;
}
const nanoseconds delta = presentSample.eventTime - pastSample.eventTime;
if (delta < RESAMPLE_MIN_DELTA) {
LOG_IF(INFO, debugResampling())
<< "Not resampled. Delta is too small: " << std::setprecision(3)
<< std::chrono::duration<double, std::milli>{delta}.count() << "ms";
return false;
} else if (delta > RESAMPLE_MAX_DELTA) {
LOG_IF(INFO, debugResampling())
<< "Not resampled. Delta is too large: " << std::setprecision(3)
<< std::chrono::duration<double, std::milli>{delta}.count() << "ms";
return false;
}
return true;
}
std::optional<LegacyResampler::Sample> LegacyResampler::attemptExtrapolation(
nanoseconds resampleTime) const {
if (!canExtrapolate()) {
return std::nullopt;
}
LOG_IF(FATAL, mLatestSamples.size() < 2)
<< "Not resampled. mLatestSamples must have at least two samples to extrapolate.";
const Sample& pastSample = *(mLatestSamples.end() - 2);
const Sample& presentSample = *(mLatestSamples.end() - 1);
const nanoseconds delta = presentSample.eventTime - pastSample.eventTime;
// The farthest future time to which we can extrapolate. If the given resampleTime exceeds this,
// we use this value as the resample time target.
const nanoseconds farthestPrediction =
presentSample.eventTime + std::min<nanoseconds>(delta / 2, RESAMPLE_MAX_PREDICTION);
const nanoseconds newResampleTime =
(resampleTime > farthestPrediction) ? (farthestPrediction) : (resampleTime);
LOG_IF(INFO, debugResampling() && newResampleTime == farthestPrediction)
<< "Resample time is too far in the future. Adjusting prediction from "
<< std::setprecision(3)
<< std::chrono::duration<double, std::milli>{resampleTime - presentSample.eventTime}
.count()
<< "ms to "
<< std::chrono::duration<double, std::milli>{farthestPrediction -
presentSample.eventTime}
.count()
<< "ms";
const float alpha =
std::chrono::duration<float, std::nano>(newResampleTime - pastSample.eventTime) / delta;
PointerMap resampledPointerMap;
for (const Pointer& pointer : presentSample.pointerMap) {
if (std::optional<Pointer> pastSamplePointer =
pastSample.pointerMap.find(PointerMap::PointerId{pointer.properties.id});
pastSamplePointer.has_value()) {
const PointerCoords& resampledCoords =
calculateResampledCoords(pastSamplePointer->coords, pointer.coords, alpha);
resampledPointerMap.insert(Pointer{pointer.properties, resampledCoords});
}
}
return Sample{newResampleTime, resampledPointerMap};
}
inline void LegacyResampler::addSampleToMotionEvent(const Sample& sample,
MotionEvent& motionEvent) {
motionEvent.addSample(sample.eventTime.count(), sample.asPointerCoords().data(),
motionEvent.getId());
}
nanoseconds LegacyResampler::getResampleLatency() const {
return RESAMPLE_LATENCY;
}
/**
* The resampler is unaware of ACTION_DOWN. Thus, it needs to constantly check for pointer IDs
* occurrences. This problem could be fixed if the resampler has access to the entire stream of
* MotionEvent actions. That way, both ACTION_DOWN and ACTION_UP will be visible; therefore,
* facilitating pointer tracking between samples.
*/
void LegacyResampler::overwriteMotionEventSamples(MotionEvent& motionEvent) const {
const size_t numSamples = motionEvent.getHistorySize() + 1;
for (size_t sampleIndex = 0; sampleIndex < numSamples; ++sampleIndex) {
overwriteStillPointers(motionEvent, sampleIndex);
overwriteOldPointers(motionEvent, sampleIndex);
}
}
void LegacyResampler::overwriteStillPointers(MotionEvent& motionEvent, size_t sampleIndex) const {
if (!mLastRealSample.has_value() || !mPreviousPrediction.has_value()) {
LOG_IF(INFO, debugResampling()) << "Still pointers not overwritten. Not enough data.";
return;
}
for (size_t pointerIndex = 0; pointerIndex < motionEvent.getPointerCount(); ++pointerIndex) {
const std::optional<Pointer> lastRealPointer = mLastRealSample->pointerMap.find(
PointerMap::PointerId{motionEvent.getPointerId(pointerIndex)});
const std::optional<Pointer> previousPointer = mPreviousPrediction->pointerMap.find(
PointerMap::PointerId{motionEvent.getPointerId(pointerIndex)});
// This could happen because resampler only receives ACTION_MOVE events.
if (!lastRealPointer.has_value() || !previousPointer.has_value()) {
continue;
}
const PointerCoords& pointerCoords =
*(motionEvent.getHistoricalRawPointerCoords(pointerIndex, sampleIndex));
if (equalXY(pointerCoords, lastRealPointer->coords)) {
LOG_IF(INFO, debugResampling())
<< "Pointer ID: " << motionEvent.getPointerId(pointerIndex)
<< " did not move. Overwriting its coordinates from " << pointerCoords << " to "
<< previousPointer->coords;
setMotionEventPointerCoords(motionEvent, sampleIndex, pointerIndex,
previousPointer->coords);
}
}
}
void LegacyResampler::overwriteOldPointers(MotionEvent& motionEvent, size_t sampleIndex) const {
if (!mPreviousPrediction.has_value()) {
LOG_IF(INFO, debugResampling()) << "Old sample not overwritten. Not enough data.";
return;
}
if (nanoseconds{motionEvent.getHistoricalEventTime(sampleIndex)} <
mPreviousPrediction->eventTime) {
LOG_IF(INFO, debugResampling())
<< "Motion event sample older than predicted sample. Overwriting event time from "
<< std::setprecision(3)
<< std::chrono::duration<double,
std::milli>{nanoseconds{motionEvent.getHistoricalEventTime(
sampleIndex)}}
.count()
<< "ms to "
<< std::chrono::duration<double, std::milli>{mPreviousPrediction->eventTime}.count()
<< "ms";
for (size_t pointerIndex = 0; pointerIndex < motionEvent.getPointerCount();
++pointerIndex) {
const std::optional<Pointer> previousPointer = mPreviousPrediction->pointerMap.find(
PointerMap::PointerId{motionEvent.getPointerId(pointerIndex)});
// This could happen because resampler only receives ACTION_MOVE events.
if (!previousPointer.has_value()) {
continue;
}
setMotionEventPointerCoords(motionEvent, sampleIndex, pointerIndex,
previousPointer->coords);
}
}
}
void LegacyResampler::resampleMotionEvent(nanoseconds frameTime, MotionEvent& motionEvent,
const InputMessage* futureSample) {
const nanoseconds resampleTime = frameTime - RESAMPLE_LATENCY;
if (resampleTime.count() == motionEvent.getEventTime()) {
LOG_IF(INFO, debugResampling()) << "Not resampled. Resample time equals motion event time.";
return;
}
updateLatestSamples(motionEvent);
const std::optional<Sample> sample = (futureSample != nullptr)
? (attemptInterpolation(resampleTime, *futureSample))
: (attemptExtrapolation(resampleTime));
if (sample.has_value()) {
addSampleToMotionEvent(*sample, motionEvent);
if (mPreviousPrediction.has_value()) {
overwriteMotionEventSamples(motionEvent);
}
// mPreviousPrediction is only updated whenever extrapolation occurs because extrapolation
// is about predicting upcoming scenarios.
if (futureSample == nullptr) {
mPreviousPrediction = sample;
}
}
LOG_IF(FATAL, mLatestSamples.empty()) << "mLatestSamples must contain at least one sample.";
mLastRealSample = *(mLatestSamples.end() - 1);
}
} // namespace android
|