What you’ll study
- Why raw samples need work: a still pen jitters, and a moving pen is ahead of its ink.
- Smoothing filters and their price: moving average, exponential smoothing and the One Euro filter.
- The Kalman filter: a state, a prediction and a correction, and the two noise numbers that tune it.
- Prediction: guessing a few milliseconds ahead, and why the obvious method fails on noise and corners.
- Android’s two predictors, the AndroidX library and the platform
MotionPredictor, and how the library chooses. - Using them: record every event, draw the predicted tail, and never save it.
How it connects
Guide 1 used the One Euro filter in its ink lab and named prediction as one of the fixes for a line that trails the pen. Guide 4 showed that the system already resamples touch to just before the frame, and guide 5 showed how to read every sample in an event, which is what a filter needs. This guide is about what to do with those samples before they become ink. The next one turns the points into a stroke mesh.
Read it at your level
| Level | Read | You should be able to |
|---|---|---|
| Student | The basics, the lab | Say why smoothing makes a line lag, and what prediction guesses |
| Fresher | + The high level, exponential smoothing | Smooth a stroke, and explain what the smoothing factor trades |
| Junior | + One Euro, the Kalman filter | Tune a One Euro filter, and say what a Kalman filter’s state and noise values mean |
| Mid | + Android’s predictors, using them | Add MotionEventPredictor, draw a temporary tail, and know when the system model is used |
| Senior | + Edge cases, cross questions | Reason about when prediction hurts, and about timing, devices and tool types |
The basics
A pen touches glass at one place, and the digitizer reports somewhere near it. Two problems follow.
- Noise. Hold the pen still and the reported points scatter by a pixel or two. Draw a straight line and it wobbles. At high zoom or on a big board you see it.
- Latency. A sample takes several milliseconds to become a frame on the screen (guides 3 and 4). By then the pen has moved on, so the ink trails behind its tip. In the lab below, a 16 ms delay leaves the ink 13 px behind the pen on average, and 36 px at the worst moment.
Both are fixed by estimating. A filter estimates where the pen is, with the noise removed. A predictor estimates where it will be when the frame lands. They pull in opposite directions: every filter adds lag, because it averages in the past, and a predictor takes some of that lag back by guessing ahead. Knowing what each costs is the whole skill.
Try it: the smoothing and prediction lab
A cursive stroke whose true path is known exactly, sampled with noise like a digitizer. The dashed line is the truth, the dots are the raw samples, the green line is the filtered stroke, the orange line is the predicted tail, and the ring is where the pen actually is when the frame lands. Every number is a distance from the truth.
Things to try:
- Set Filter to Moving average and raise the window. The fast part of the stroke lags more with every sample you add, and the number under error, fast part grows.
- Set Noise to 1 px. A 5-sample moving average is now worse than no filter at all, even on the slow part. Raise the noise to 4 px: on the slow part it now beats the raw samples (4.0 against 5.9 px), but the fast part is still far worse (12.8 against 5.5 px). The lag doesn’t depend on the noise.
- Switch to One Euro and start with Beta at 0: the cutoff stays at its minimum, and the line lags badly everywhere. Raise it and the lag collapses; past about 0.2 the slow part gets a little noisier again, because the filter lets more through.
- Switch to Kalman and leave the noise values alone: both numbers go down together. Then set the process noise to 1 and the filter trusts every sample, so its errors move back toward the raw ones.
- With Predictor on Constant velocity and Noise at 1 px, move the pen to 470 ms (fast and almost straight): the ring sits on the tail. Move to 500 ms (a tight turn): the tail overshoots. Compare Kalman, pen, which draws a shorter tail there, or none.
- Raise Noise to 3 px with Constant velocity and look at mean gap along the stroke: the tail is now worse than no tail.
The lab runs a TypeScript model of the algorithms below. It is not the Android library, and the section on Kalman filters says how it was checked.
The high level
| Tool | What it does | What it costs |
|---|---|---|
| Moving average | the mean of the last N samples | lag of (N - 1) / 2 samples |
| Exponential smoothing | moves a fraction α of the way to each new sample | lag of (1 - α) / α samples |
| One Euro filter | exponential smoothing whose cutoff rises with speed: heavy smoothing when slow, little when fast | two numbers to tune; some lag on fast strokes |
| Kalman filter | combines a physical model of the pen with each noisy measurement, weighting each by how much it is trusted | a model that can be wrong (a sharp turn), and noise values to tune |
| Constant-velocity prediction | extends the last two samples in a straight line | amplifies noise; overshoots corners |
| Kalman prediction | steps the filter’s estimated state forward, scaled by a confidence | shorter tails when unsure; still overshoots a turn it hasn’t seen |
| Learned prediction | a trained model predicts the next points | needs the model; on Android only for styluses |
The low level
Excerpts are from the AndroidX input-motionprediction source (androidx-main, November 2026) and AOSP main,
trimmed with …. The released library is 1.0.1, and the snippets below compile against it. Links are in The map.
1. Moving average and exponential smoothing: the lag
A moving average of the last N samples, for steady movement at v pixels per sample, is behind by (N - 1) / 2 samples:
v × (N - 1) / 2 pixels. Five samples at 240 Hz (4.2 ms apart) is 8 ms of lag, whatever the pen is doing. At
120 Hz the same five samples are 17 ms. A window counted in samples is a different amount of time on every device.
Exponential smoothing keeps one number and moves it a fraction α towards each new sample, s += α (x - s). It is
cheap and has no window, but its steady-state lag is (1 - α) / α samples: α = 0.25 lags by 3 samples,
α = 0.1 by 9. A smaller α removes more noise and adds more lag. Both filters are the same trade: they know nothing
about speed, so they lag a fast stroke exactly as much as a slow one.
class ExponentialSmoother(private val alpha: Float) {
private var x = Float.NaN
private var y = Float.NaN
/** The smoothed position after this sample. */
fun smooth(px: Float, py: Float): Pair<Float, Float> {
if (x.isNaN()) {
x = px
y = py
} else {
x += alpha * (px - x)
y += alpha * (py - y)
}
return x to y
}
}
2. The One Euro filter: smooth when slow, follow when fast
The One Euro filter (Casiez, Roussel and Vogel, CHI 2012) is exponential smoothing whose α is recomputed for every
sample from a cutoff frequency that grows with speed. This is the reference implementation’s arithmetic:
te = 1 / freq time between samples
tau = 1 / (2 * pi * cutoff)
alpha = 1 / (1 + tau / te) the weight of the newest sample
dx = (x - previousFilteredX) * freq speed
edx = lowpass(dx, alpha(dcutoff)) the speed, smoothed
cutoff = mincutoff + beta * |edx| faster means a higher cutoff
output = lowpass(x, alpha(cutoff))
The defaults in the reference code are mincutoff = 1.0, beta = 0.0 and dcutoff = 1.0. At rest, the cutoff is
mincutoff: heavy smoothing, so the jitter goes. As the pen speeds up, edx grows, the cutoff rises, α approaches 1
and the output follows the pen closely. The author’s page gives a two-step way to tune it: set beta to 0 and
mincutoff near 1 Hz; hold the pen still or move it very slowly and lower mincutoff until the jitter is gone
without too much lag; then move quickly and raise beta until the lag on fast strokes is acceptable. In the author’s
words, if high-speed lag is a problem, increase beta; if low-speed jitter is a problem, decrease mincutoff. His
page also lists Chrome on Android among the users of the filter.
The right beta depends on the units of your data: the author says to find its order of magnitude first, and not to hesitate to start
from values like 0.001 or 0.0001. Guide 1 measured values for a pen in pixels at 120 to 240 Hz: minCutoff = 1,
beta = 0.2, dCutoff = 5 trail a fast handwritten loop by about 8 px, where beta = 0.007 and dCutoff = 1 trailed it by about 55 px.
In Kotlin, one filter per axis:
class OneEuroFilter(
private val minCutoff: Double = 1.0,
private val beta: Double = 0.0,
private val dCutoff: Double = 1.0,
) {
private var x: Double? = null
private var dx = 0.0
private var lastTimeMs = 0L
/** The filtered value of [value], measured at [timeMs] (for example MotionEvent.getEventTime()). */
fun filter(value: Double, timeMs: Long): Double {
val previous = x
if (previous == null) {
x = value
lastTimeMs = timeMs
return value
}
val dt = maxOf((timeMs - lastTimeMs) / 1000.0, 1e-3)
lastTimeMs = timeMs
dx += alpha(dCutoff, dt) * ((value - previous) / dt - dx)
val cutoff = minCutoff + beta * kotlin.math.abs(dx)
val filtered = previous + alpha(cutoff, dt) * (value - previous)
x = filtered
return filtered
}
private fun alpha(cutoffHz: Double, dtSeconds: Double): Double {
val tau = 1.0 / (2 * Math.PI * cutoffHz)
return 1.0 / (1.0 + tau / dtSeconds)
}
}
Because it takes the time of each sample, one set of numbers works across report rates. That is the practical advantage over a window counted in samples.
3. The Kalman filter: a model, a guess, a correction
A Kalman filter keeps an estimate of a hidden state, here the pen, and a measure of how unsure it is. For every
sample it does two things: predict (move the estimate forward with a model of how the pen moves, and grow the
uncertainty) and update (compare the prediction with the new measurement and move the estimate toward it, by
an amount that depends on how much each is trusted). The library’s KalmanFilter says it follows the Python
library filterpy, and these are its two steps:
predict x = F x P = F P F^T + Q
update y = z - H x S = H P H^T + R
K = P H^T S^-1 x = x + K y P = P - K H P
x is the state, P how unsure it is, F the model, Q the noise in the model, H which part of the state is
measured, R the noise in the measurement, z the measurement and K the gain: how far to move toward it. What
makes it a pen filter is what the library puts in those matrices (PointerKalmanFilter, trimmed):
// We tune the filter with a normalized dt=1, then apply the actual report rate during prediction.
final double dt = 1.0;
…
// State transition matrix is derived from basic physics:
// new_x = x + v * dt + 1/2 * a * dt^2 + 1/6 * jank * dt^3
// …
kalman.F = new Matrix(4,
new double[]{
1.0, dt, 0.5 * dt * dt, 0.16 * dt * dt * dt,
0.0, 1.0, dt, 0.5 * dt * dt,
0.0, 0.0, 1.0, dt,
0, 0, 0, 1.0
});
// We model the system noise as a noisy force on the pen.
final Matrix g = new Matrix(1, new double[] {0.16 * dt * dt * dt, 0.5 * dt * dt, dt, 1});
g.dotTranspose(g, kalman.Q);
kalman.Q.scale(mSigmaProcess);
// Measurements only impact the location
kalman.H = new Matrix(4, new double[] {1.0, 0.0, 0.0, 0.0});
kalman.R.put(0, 0, mSigmaMeasurement);
Read it as physics, as its comment says: the new position is the old position plus velocity × dt, plus half
acceleration × dt², plus a sixth of the jank times dt³ (the matrix writes that sixth as 0.16). The state is
four numbers per axis (position, velocity, acceleration and the next derivative, which the library calls “jank”), x and y
get a filter each, and time is counted in samples, not milliseconds. Only the position is measured (H). A
filter made like this knows that pens keep moving, so on a straight stroke it has learned the velocity and has no lag.
The two noise values are the tuning:
| Value | Library setting | Effect |
|---|---|---|
sigmaProcess, how much the pen’s motion departs from the model |
0.01 | “lower value = more filtering”: trust the model, ignore bumps |
sigmaMeasurement, how noisy the samples are |
1.0 | “higher value = more filtering”: distrust the samples |
The library’s predictor uses PointerKalmanFilter(0.01, 1.0), and the lab’s Kalman filter starts at those values.
How this was checked. The lab’s Kalman filter is a TypeScript translation of that Java. I translated it a second
time in Python, with generic matrix arithmetic in the order the Java uses, ran both on one fixed sequence, and the
states agree to 6 decimals (the test is in the repository). Both translations rest on how the library’s Matrix
class works (its constructor takes the column count first, plus and minus change the matrix in place, and inverse
writes into itself), which I read in its source. I could not run the released library against the translations, so the
lab is a model of the library’s algorithm, not the library.
Here is what the filters scored in the lab: the root-mean-square distance from the true path over the slow part of the stroke and over the fast part, at 240 Hz, as the mean of 8 different noise sequences (the lab shows one of them, so its numbers differ a little):
| Filter | 1 px noise, slow / fast | 2 px noise, slow / fast |
|---|---|---|
| none (raw samples) | 1.4 / 1.4 px | 2.9 / 2.8 px |
| moving average, 5 samples | 3.3 / 12.9 px | 3.5 / 13.0 px |
| exponential, α = 0.3 | 3.8 / 13.9 px | 3.9 / 14.0 px |
| One Euro, 1 Hz, β = 0.2 | 1.4 / 2.5 px | 2.2 / 3.2 px |
| Kalman, library values | 1.2 / 1.2 px | 2.5 / 2.3 px |
At these noise levels the two simple filters lose to doing nothing: their lag costs more than the noise they remove. One Euro matches the raw samples on the slow part at 1 px and beats them at 2 px, and pays on the fast part. The Kalman filter is better than raw on both parts at both levels, by 12 to 16% on average, because it learned the velocity (on one of the eight sequences, at 1 px, its fast part was level with the raw samples). More noise changes the picture, which is why the lab lets you set it.
4. Prediction: guessing the next few milliseconds
The simplest predictor takes the velocity from the last two samples and extends it. It is exact on a clean straight line. On real samples it divides noise by the time between them: at 240 Hz and 2 px of noise, two samples give a velocity that is off by about 0.7 px/ms, which is 11 px over a 16 ms prediction. And at a corner it keeps going straight.
The Kalman predictor starts from the filtered velocity, acceleration and jank, and scales how far it trusts them.
This is SinglePointerPredictor.predict(). The ranges are the library’s constants:
// Range of jank values to expect.
// Low value will use maximum prediction, high value will use no prediction.
private static final float LOW_JANK = 0.02f;
private static final float HIGH_JANK = 0.2f;
private static final float ACCURATE_LOW_JANK = 0.1f;
private static final float ACCURATE_HIGH_JANK = 0.2f;
// Range of pen speed to expect (in dp / ms).
// Low value will not use prediction, high value will use full prediction.
private static final float LOW_SPEED = 0.0f;
private static final float HIGH_SPEED = 2.0f;
private static final float ACCURATE_LOW_SPEED = 0.0f;
private static final float ACCURATE_HIGH_SPEED = 0.0f;
…
double speedFactor = normalizeRange(speedAbs, lowSpeed, highSpeed);
double jankFactor = 1.0 - normalizeRange(jankAbs, lowJank, highJank);
double confidenceFactor = speedFactor * jankFactor;
…
int predictionTargetInSamples =
(int) Math.ceil(predictionTargetMs / mReportRateMs * confidenceFactor);
So the length of the tail is the target time, in samples, times a confidence between 0 and 1: the pen should be moving
(speed factor) and the filter should not be surprised (jank factor). A tool that is not a finger counts as “accurate”
and uses the ACCURATE_* limits: its speed range is 0 to 0, so any movement counts as full speed, and its jank range
starts at 0.1. Each predicted sample then steps the state forward:
mAcceleration.a1 += mJank.a1 * JANK_INFLUENCE;
mVelocity.a1 += mAcceleration.a1 * ACCELERATION_INFLUENCE;
mPosition.a1 += mVelocity.a1 * VELOCITY_INFLUENCE;
(the same for a2, the y axis; the three influence constants are 0.1, 0.5 and 1.0). The projection begins at the last real position, not the filtered one. Other rules
in the same file, each visible in the lab:
- At least four filter updates are needed before it predicts, and the jank estimate starts high in proportion to the speed: for a perfectly straight line at 4 px per sample it stays above 0.2 until the eighth sample, so the start of a stroke gets no tail; at 1 px per sample it peaks at 0.18, so only the four-update rule delays it. After a sharp reversal the jank estimate jumps again, and the predictor goes quiet for a few samples.
- A sample at the same place within 20 ms of the previous one is ignored.
- The report rate is estimated from the first 20 gaps between samples. The comment in the code says why it is only an estimate: most sensors “do not report at an even interval”.
ACTION_CANCELresets the filter.- The comments say the filter “can provide solid prediction up to 25ms into the future”, and that the target should be reduced to 20 ms if close-to-zero latency isn’t achieved. That is guidance for whoever sets the target, and an app doesn’t: the library derives it, as described next.
How far ahead to predict is the library’s job too. PredictionEstimator takes “the estimated amount of time it will
take to land the information on the screen from now, plus the time since the last recorded MotionEvent”: the time since
the last event plus the frame time of the fastest refresh rate the display supports, never more than 32 ms.
One thing to know about the numbers: the comments call the speed limits “dp / ms”, but the code reads the
coordinates of the MotionEvent directly, which are pixels, and in the four files I read nothing converts them. On a dense screen the
same pen speed is a different number.
How it scored in the lab (240 Hz, 16 ms ahead, the mean distance between the end of the ink and where the pen is when the frame lands, over 86 positions along the stroke, as the mean of 8 noise sequences):
| Noise | 0.5 px | 1 px | 2 px | 3 px |
|---|---|---|---|---|
| no prediction | 13.4 | 13.5 | 13.6 | 14.0 |
| constant velocity | 5.9 | 9.3 | 16.9 | 24.7 |
| Kalman, pen | 6.5 | 8.6 | 11.4 | 13.7 |
| positions where the Kalman predictor drew nothing, of 86 | 10 | 10 | 16 | 35 |
Constant velocity is best on very clean data (5.9 against 6.5 px at 0.5 px of noise), is overtaken by the Kalman predictor from about 1 px of noise, and is worse than drawing nothing from 2 px. The Kalman predictor’s advantage shrinks as the noise grows, because its confidence falls and it stays silent more: at 3 px it is only 0.3 px better than no tail. At 120 Hz the Kalman mean was 10.8 to 13.6 px against 13.3 to 13.9 for no prediction, but at 0.5 and 1 px of noise its worst position was about 64 px, against 35 to 36 for no prediction, at a tight turn. A predictor can make the worst moment worse. These are numbers for one synthetic stroke and a model of the algorithm. Real pens differ, so measure on a device before you tune.
5. The platform predictor: a learned model, for styluses
Android 14 (API 34) added android.view.MotionPredictor. Its reference says what to do: send “all of the events that
were received from the system” to record(), ask predict(long) for a predicted event, and “consider all of the
historical samples” in it. Three methods matter:
| Method | What it does |
|---|---|
record(MotionEvent) |
stores a movement; only gestures from one input device at a time should be recorded in one instance |
predict(long) |
a predicted event. The reference warns: “Predictions may not reach the requested timestamp if the confidence in the prediction results is low.” |
isPredictionAvailable(int, int) |
whether this device and source support prediction |
Underneath is native code in libs/input/MotionPredictor.cpp, which runs a TensorFlow Lite model. The model is read
from /vendor/etc/motion_predictor_model.tflite if that file exists (a device maker can ship its own), and otherwise from
/system/etc/motion_predictor_model.tflite, with a config file next to it. For each future step the model outputs a
distance r, an angle phi and a pressure; the code converts them to positions along the last movement. It stops
early when the predicted distance falls under the model’s noise floor, and it has a jerk-based pruning step like the
Kalman confidence, which the source puts behind a feature flag. Availability is narrow:
bool MotionPredictor::isPredictionAvailable(int32_t /*deviceId*/, int32_t source) {
// Global flag override
if (!mCheckMotionPredictionEnabled()) {
…
return false;
}
// Prediction is only supported for stylus sources.
if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
…
return false;
}
return true;
}
Stylus sources only, and a global flag can turn it off. A gesture’s end (ACTION_UP or ACTION_CANCEL) resets the model’s
buffers.
6. The AndroidX wrapper chooses for you
You normally don’t call either predictor directly. MotionEventPredictor.newInstance(view) in AndroidX decides:
if (Build.VERSION.SDK_INT >= 34
&& !configuration.preferLibraryPrediction()) {
return SystemMotionEventPredictor.newInstance(context, configuration.predictionStrategy());
} else {
return new KalmanMotionEventPredictor(context, configuration.predictionStrategy());
}
and on API 34 and later the system wrapper checks the stroke each time the device or source changes:
if (mLastRecordedSource != source || mLastRecordedDeviceId != deviceId) {
mUsingSystemPredictor = mSystemPredictor.isPredictionAvailable(deviceId, source);
…
}
if (mUsingSystemPredictor) {
mSystemPredictor.record(event);
} else {
getKalmanPredictor().onTouchEvent(event);
}
Putting the two together:
| Device and tool | Which predictor |
|---|---|
| API 33 and below, any tool | the Kalman library (with the “accurate tool” limits for a pen) |
| API 34 and later, a stylus, if the system supports it | the platform model |
| API 34 and later, a finger or mouse, or a stylus the system doesn’t support | the Kalman library |
The library’s behaviour settings, a strategy (balanced, safe, aggressive), an offset in milliseconds, whether to
predict a lift, and whether to prefer the library, are debug.input.androidx_* system properties read through
reflection, and all of them default to zero or false. They are not something an app sets: an app gets record() and
predict().
7. Using it: record every event, draw a temporary tail, save only the real points
Add the library:
implementation("androidx.input:input-motionprediction:1.0.1")
Android’s stylus guide describes the contract: predicted events “are only estimates”, and “predicted data must be replaced with actual MotionEvent data once it is received”. So keep two paths, the real stroke you save and a prediction you rebuild on every event:
class PredictiveInkView(context: Context) : View(context) {
private val predictor = MotionEventPredictor.newInstance(this)
private val ink = Path() // real samples only: this is what you keep
private val tail = Path() // the prediction: rebuilt on every event, never saved
private val inkPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = 6f
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
}
private val tailPaint = Paint(inkPaint).apply { alpha = 160 }
override fun onTouchEvent(event: MotionEvent): Boolean {
predictor.record(event) // every event the view receives, as the documentation asks
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
ink.moveTo(event.x, event.y)
tail.rewind()
}
MotionEvent.ACTION_MOVE -> {
for (h in 0 until event.historySize) ink.lineTo(event.getHistoricalX(h), event.getHistoricalY(h))
ink.lineTo(event.x, event.y)
rebuildTail(event.x, event.y)
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> tail.rewind()
}
invalidate()
return true
}
private fun rebuildTail(fromX: Float, fromY: Float) {
tail.rewind()
val predicted = predictor.predict() ?: return // null: no prediction right now
tail.moveTo(fromX, fromY)
// A predicted event carries its extra samples as history too: read those first, then the current one.
for (h in 0 until predicted.historySize) tail.lineTo(predicted.getHistoricalX(h), predicted.getHistoricalY(h))
tail.lineTo(predicted.x, predicted.y)
}
override fun onDraw(canvas: Canvas) {
canvas.drawPath(ink, inkPaint)
canvas.drawPath(tail, tailPaint)
}
}
Three details from the source. The Kalman path builds its single-pointer predicted event with device ID 0 and source 0,
so use only its coordinates and times, and don’t key anything by its device or source (guide 5 advised keying by
device and pointer). Its extra predicted samples are in the history of that event, which is why the loop above reads
the history first. And predict() returns null for several reasons (the filter hasn’t settled, the confidence is
zero, the stroke ended), so no tail is a normal state.
To use the platform class directly, for example to ask isPredictionAvailable() first, the AndroidX wrapper calls
predict() with an absolute time, in nanoseconds, a few milliseconds ahead of now:
@RequiresApi(34)
class PlatformPredictor(context: Context) {
private val predictor = MotionPredictor(context)
/** A predicted event for this stroke, or null when the system cannot predict it. */
fun onEvent(event: MotionEvent, aheadMs: Long = 16): MotionEvent? {
if (!predictor.isPredictionAvailable(event.deviceId, event.source)) return null
predictor.record(event)
return predictor.predict(TimeUnit.MILLISECONDS.toNanos(SystemClock.uptimeMillis() + aheadMs))
}
}
Checkpoint
You should be able to say:
- A filter removes noise and adds lag; a predictor removes lag by guessing, and can add error.
- A moving average lags by
(N - 1) / 2samples and exponential smoothing by(1 - α) / α, whatever the speed. - One Euro raises its cutoff with speed, so it smooths a still pen hard and follows a fast one.
- The Kalman filter keeps a state of position, velocity, acceleration and jank, and two noise values tune it.
- The library’s predictor steps that state forward and shortens the tail when the pen is slow or the jank is high.
- On Android 14 and later, a stylus uses the system’s learned model when available; everything else uses the Kalman library.
- Predicted points are temporary: draw them, never save them, and replace them with the real ones.
Why it helps
| Symptom | What is happening | What to do |
|---|---|---|
| The ink trembles when the pen is still | Sensor noise reaches the stroke unfiltered | One Euro or the Kalman filter: a low minCutoff, or the library’s noise values |
| After adding smoothing, fast strokes trail the pen | The filter is a fixed window or a small α, which lags at every speed |
A speed-adaptive filter: raise beta |
| The same smoothing feels different on two tablets | A window of N samples is N × the report period | A filter that takes timestamps, such as One Euro |
| The ink trails the pen by a frame or two | Touch to display latency | Predict ahead with MotionEventPredictor, and draw the tail temporarily |
| The tail jumps or overshoots at corners and quick reversals | Extrapolation can’t know about a turn; the library lowers its confidence only after it sees one | Rebuild the tail on every event, draw only its first few samples, and make it fainter than the ink |
| Predicted ink ended up in the saved file | The tail was added to the stroke | Keep the real stroke and the tail in separate paths |
| Prediction works with a pen but is shorter with a finger | A finger’s confidence needs a speed up to 2 px/ms, and it falls from a jank of 0.02 where a pen’s falls from 0.1 | Expected; see section 4 |
The map
| Topic | Code | Where |
|---|---|---|
| One Euro: the paper | CHI 2012 | dl.acm.org, author’s page |
| One Euro: reference code | OneEuroFilter.py |
github.com/casiez/OneEuroFilter |
| AndroidX entry point | MotionEventPredictor.newInstance() |
MotionEventPredictor.java |
| System or Kalman | SystemMotionEventPredictor |
SystemMotionEventPredictor.java |
| The filter | KalmanFilter, PointerKalmanFilter |
kalman/ |
| The prediction | SinglePointerPredictor.predict() |
SinglePointerPredictor.java |
| How far ahead | PredictionEstimator.estimate() |
PredictionEstimator.java |
| Platform model | MotionPredictor::predict(), isPredictionAvailable() |
MotionPredictor.cpp, TfLiteMotionPredictor.cpp |
Edge cases
- The filter runs in samples, the predictor in milliseconds. The Kalman filter assumes one sample per step
(
dt = 1) and the predictor then converts with an estimated report rate. A device with uneven timestamps gets a wrong rate, and the library’s comment says it is only an estimate. - Multiple pointers. The library keeps one single-pointer predictor per pointer ID, creates it at
ACTION_DOWNorACTION_POINTER_DOWNwith that pointer’s tool type, and clears them all onACTION_CANCEL. With several pointers it merges the predictions into one event. - The tool type is read once. It is taken from the pointer at the moment it goes down.
- Resampled input. The system’s resampling (guide 4) puts computed points in the stream as well. The documentation doesn’t say how the predictor treats them: feed it the events as they arrive.
- The target time is not yours to set. It is the library’s estimate of the time to the screen, up to 32 ms. An app can only draw fewer of the predicted samples.
- The platform model is per device. A device maker can ship its own
motion_predictor_model.tflitein/vendor/etc. - Numbers don’t transfer. The lab uses one synthetic stroke. Measure on your own devices before you tune.
Cross questions
You smooth with a 5-sample moving average at 240 Hz, then run the app on a 120 Hz pen. Is the smoothing the same?
No. The lag is (N - 1) / 2 samples, which is 8 ms at 240 Hz and 17 ms at 120 Hz. A filter counted in samples is a different amount of time on every device. Use one that takes timestamps, such as One Euro, or choose N from the report rate.
How can smoothing make a drawing less accurate?
A filter's error is the noise it leaves plus the lag it adds. When the noise is small, the lag is the bigger part. In the lab, a 5-sample average at 1 px of noise scores 3.3 px on the slow part against 1.4 px for the raw samples, and 12.9 px on the fast part against 1.4 px (means of 8 noise sequences).
How does One Euro decide when to smooth less?
It estimates the speed from the samples, smooths that estimate a little, and sets the cutoff to mincutoff + beta × speed. A higher cutoff means a larger α, so the output follows the newest sample more closely. A still pen gets mincutoff; a fast one gets a cutoff so high that the filter barely smooths.
Why does a Kalman filter lag less than exponential smoothing on a straight stroke?
Because its model includes velocity. Once it has learned the speed, a constant-velocity movement is exactly what it predicts, so the correction at each sample is tiny and there is no lag. Exponential smoothing has no model, so it always trails by (1 - α) / α samples.
Why does constant-velocity prediction get worse as the noise grows?
Its velocity comes from two samples, so the velocity error is about the noise divided by the time between them, and the prediction multiplies that by the time ahead. More noise or a faster report rate means a worse guess. In the lab at 240 Hz, its mean gap grows from 5.9 px at 0.5 px of noise to 24.7 px at 3 px, while drawing nothing stays at 13 to 14 px.
On Android 14, which predictor does a stylus stroke use, and which does a finger use?
The AndroidX wrapper asks the platform MotionPredictor whether it supports the stroke's device and source. The native code only supports stylus sources, and a global flag can disable it, so a supported stylus uses the learned model and everything else, including every finger stroke, uses the Kalman library.
Why must predicted points never be saved?
They are guesses. Android's stylus guide says predicted events are "only estimates" and that predicted data must be replaced with real data once it arrives. Save only the real samples, and rebuild the tail on every event.
predict() returned null in the middle of a stroke. Is something wrong?
Probably not. It returns null when fewer than four filter updates have been recorded, when the confidence works out to zero (a slow pen, or a high jank estimate after a sharp turn), or when there is no pointer being tracked. Draw no tail and carry on.
Revision: key points
- Noise makes a still pen jitter; latency makes the ink trail a moving pen. Filters fix the first and add to the second; predictors do the reverse.
- A moving average lags by
(N - 1) / 2samples, exponential smoothing by(1 - α) / α, at every speed. - One Euro:
cutoff = mincutoff + beta × speed. Tunemincutofffor jitter, thenbetafor lag. - The Kalman filter keeps position, velocity, acceleration and jank, measures only position, and is tuned by a process noise and a measurement noise (0.01 and 1.0 in the library).
- The library’s predictor scales the tail by a confidence from speed and jank, starts from the last real position, and needs four updates.
- Constant velocity is best on clean data and worse than nothing on noisy data; the Kalman predictor is cautious and stays silent more as noise grows.
- The platform
MotionPredictor(API 34) is a TFLite model, stylus only; the AndroidX wrapper falls back to Kalman for everything else. - Record every event, rebuild a temporary tail from the predicted event’s history and current point, and save only the real samples.
Cheat sheet
Each concept in a few words.
| Concept | In a few words |
|---|---|
| Noise and latency | Noise makes a still pen jitter; latency makes ink trail a moving pen. |
| Moving average | Mean of the last N samples; lags (N - 1) / 2 samples. |
| Exponential smoothing | Blends new with old; lags (1 - α) / α samples. |
| One Euro filter | Smooths hard when slow, lightly when fast. |
mincutoff and beta |
Tune jitter at rest first, then lag in motion. |
| Kalman filter | Tracks position and velocity; weighs its model against each measurement. |
| Process and measurement noise | How far to trust the model and the sensor (0.01 and 1.0). |
| Predictor | Guesses the pen’s next few milliseconds to cover latency. |
| Prediction tail | A temporary segment: draw it, never save it. |
Platform MotionPredictor |
API 34, a TFLite model, stylus only; AndroidX falls back to Kalman. |
Read next
- The One Euro filter: Casiez, Roussel and Vogel, CHI 2012 and the author’s page, with tuning advice and code in several languages
- References:
MotionEventPredictor,MotionPredictor, and Android’s advanced stylus features - The source, in The map above
Search terms that find more: One Euro filter pen jitter, Kalman filter state transition matrix tutorial, filterpy Kalman, MotionEventPredictor record predict, input-motionprediction, MotionPredictor isPredictionAvailable.
The fine print
The library excerpts are from AndroidX androidx-main and AOSP main in November 2026; the snippets compile against
androidx.input:input-motionprediction:1.0.1. The lab is a TypeScript model of the library’s filter and predictor,
cross-checked against a second, independent translation of the same Java, and it was not run against the released library.
Its stroke and every figure in the tables are the lab’s own (one synthetic stroke; the tables are means of 8 noise
sequences, the lab shows one of them), not a measurement of a device. The lab calls predict() after every sample, while an app calls it
once per event, and the library’s “the tail never gets shorter” rule depends on those calls, so an app sees different tails
from the same samples. The platform model’s behaviour is described from the native source, not from running it; its pruning is behind
a feature flag, and the model file and its numbers differ between devices. The One Euro description is from the author’s
page and reference code.
Part of the ink series: 1. Why naive drawing feels bad, 2. Canvas, Paint and Path, 3. Looper, epoll and vsync, 4. From glass to your app, 5. Reading a MotionEvent.