forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

track.rs522 lines, 20.8 KiBHistoryRawDownload
1//! Motion tracking: a region of the picture followed from frame to frame, its centre
2//! written out as a path that a mask (or anything else with a position) can follow.
3//!
4//! The pipeline, per clip, over the source frames from the start frame to the end of
5//! the range:
6//!
7//! 1. **Reduce.** Each decoded frame is box-averaged to luma no wider than
8//! [`TRACK_W`], so the search and the template are sized in these small pixels.
9//! 2. **Match.** The template is the region's own luma at the start frame (its
10//! centre, at most [`MAX_TEMPLATE`] pixels a side). Each frame, the template is
11//! searched for by normalised cross-correlation in a window of [`SEARCH`] pixels
12//! around its last place, and the peak is refined to a sub-pixel position by a
13//! parabola through the three scores on each axis.
14//! 3. **Learn.** After a match the template takes in [`LEARN`] of the matched
15//! picture, so it follows slow change in the feature, yet keeps its identity.
16//! 4. **Stop.** When the best score falls below [`MIN_CONFIDENCE`] the feature is
17//! lost; the track ends there and says where.
18//!
19//! The matcher ([`Tracker`]) is a pure function over pictures, so it tests without a
20//! decode. [`start`] runs `analyse` on a thread of its own, polled by [`status`] and
21//! [`take`] and stopped by [`cancel`], the same way stabilisation runs. A backward
22//! track decodes its range first, since it walks the frames in reverse.
23
24use std::collections::HashMap;
25use std::path::Path;
26use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
27use std::sync::{Arc, Mutex, OnceLock};
28
29use crate::scale::{FitPolicy, canvas_to_picture, picture_to_canvas};
30use crate::transform::{TransformKey, TransformParams, evaluate};
31
32/// The width pictures are reduced to before they are matched.
33pub const TRACK_W: usize = 320;
34/// Below this normalised cross-correlation the feature is lost.
35pub const MIN_CONFIDENCE: f32 = 0.6;
36/// How far, in tracked pixels, the template may move between two frames.
37const SEARCH: i64 = 24;
38/// The largest template edge in tracked pixels; a bigger region is followed by its centre.
39const MAX_TEMPLATE: usize = 48;
40/// The smallest template edge in tracked pixels: a small box has too little texture to lock onto.
41const MIN_TEMPLATE: usize = 24;
42/// Below this standard deviation of luma, a template is flat or nearly so and has nothing to lock onto.
43const MIN_TEXTURE: f32 = 8.0;
44/// Matches within this many tracked pixels of the best one are the same match, not a rival.
45const RIVAL_RADIUS: i64 = 3;
46/// A best match this close to the best rival outside [`RIVAL_RADIUS`] is ambiguous (a
47/// line, a repeat pattern): the feature cannot be told from its surroundings, so it is lost.
48const MAX_RIVAL_RATIO: f32 = 0.9;
49/// The share of each matched picture that is learned into the template.
50const LEARN: f32 = 0.05;
51/// Most pictures a backward track holds in memory (it decodes its range first).
52pub const MAX_BACKWARD: usize = 2400;
53/// The most a dropped key may stray, in canvas fractions, from the path it stands for.
54pub const KEY_TOLERANCE: f32 = 0.002;
55
56/// A picture reduced to luma for tracking: `px` is `w * h` values, row by row.
57#[derive(Clone, Debug, PartialEq)]
58pub struct Plane {
59 pub w: usize,
60 pub h: usize,
61 pub px: Vec<u8>,
62}
63
64/// A region of the picture in canvas fractions, stated the way a rect mask states
65/// itself: its centre and its size, `0..=1` each.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct Region {
68 pub x: f32,
69 pub y: f32,
70 pub w: f32,
71 pub h: f32,
72}
73
74/// The luma of a full picture box-averaged down to [`TRACK_W`] wide (a narrower one
75/// is kept as it is).
76pub fn reduce(y: &[u8], w: usize, h: usize) -> Plane {
77 let f = (w / TRACK_W).max(1);
78 let (nw, nh) = (w / f, h / f);
79 let mut px = vec![0u8; nw * nh];
80 for r in 0..nh {
81 for c in 0..nw {
82 let mut sum = 0u32;
83 for dy in 0..f {
84 let row = (r * f + dy) * w + c * f;
85 sum += y[row..row + f].iter().map(|&v| u32::from(v)).sum::<u32>();
86 }
87 px[r * nw + c] = (sum / (f * f) as u32) as u8;
88 }
89 }
90 Plane { w: nw, h: nh, px }
91}
92
93/// Follows one template through successive pictures.
94pub struct Tracker {
95 tw: usize,
96 th: usize,
97 /// The learned template, raw luma.
98 tpl: Vec<f32>,
99 /// The template, zero-mean, and its norm: what the correlation is taken against.
100 zero_mean: Vec<f32>,
101 norm: f32,
102 /// The template's top-left corner in tracked pixels, sub-pixel.
103 top: (f32, f32),
104 /// How far the last step moved the template: the search is centred on where it goes next.
105 vel: (f32, f32),
106}
107
108impl Tracker {
109 /// Takes the template at `region` in `first`, or `None` when that patch is too flat
110 /// (see [`MIN_TEXTURE`]) to follow.
111 pub fn new(first: &Plane, region: Region) -> Option<Tracker> {
112 let (pw, ph) = (first.w as f32, first.h as f32);
113 let tw = ((region.w * pw).round() as usize).clamp(MIN_TEMPLATE, MAX_TEMPLATE).min(first.w);
114 let th = ((region.h * ph).round() as usize).clamp(MIN_TEMPLATE, MAX_TEMPLATE).min(first.h);
115 let x = (region.x * pw - tw as f32 / 2.0).clamp(0.0, (first.w - tw) as f32);
116 let y = (region.y * ph - th as f32 / 2.0).clamp(0.0, (first.h - th) as f32);
117 let mut t = Tracker { tw, th, tpl: Vec::new(), zero_mean: Vec::new(), norm: 0.0, top: (x, y), vel: (0.0, 0.0) };
118 let patch = patch(first, t.top.0.round() as usize, t.top.1.round() as usize, tw, th)?;
119 t.tpl = patch;
120 t.prepare();
121 let std = t.norm / (t.tpl.len() as f32).sqrt();
122 (std >= MIN_TEXTURE).then_some(t)
123 }
124
125 /// The template's centre in tracked pixels.
126 pub fn centre(&self) -> (f32, f32) {
127 (self.top.0 + self.tw as f32 / 2.0, self.top.1 + self.th as f32 / 2.0)
128 }
129
130 /// Finds the template in `plane`, learns the match, and returns the new centre; `None`
131 /// when the best match is below [`MIN_CONFIDENCE`].
132 pub fn step(&mut self, plane: &Plane) -> Option<(f32, f32)> {
133 let (bx, by) = ((self.top.0 + self.vel.0).round() as i64, (self.top.1 + self.vel.1).round() as i64);
134 let mut scores = Vec::with_capacity(((2 * SEARCH + 1) * (2 * SEARCH + 1)) as usize);
135 for dy in -SEARCH..=SEARCH {
136 for dx in -SEARCH..=SEARCH {
137 let (x, y) = (bx + dx, by + dy);
138 scores.push((self.score(plane, x, y), x, y));
139 }
140 }
141 let best = scores.iter().copied().fold((f32::MIN, bx, by), |a, b| if b.0 > a.0 { b } else { a });
142 let (score, x, y) = best;
143 if score < MIN_CONFIDENCE {
144 return None;
145 }
146 // The best rival outside the peak's own neighbourhood: a match that is nearly as
147 // good elsewhere means the picture cannot tell the feature from its surroundings.
148 let rival = scores
149 .iter()
150 .filter(|&&(_, rx, ry)| (rx - x).abs().max((ry - y).abs()) > RIVAL_RADIUS)
151 .map(|&(s, _, _)| s)
152 .fold(f32::MIN, f32::max);
153 if rival > MAX_RIVAL_RATIO * score {
154 return None;
155 }
156 let sx = peak(self.score(plane, x - 1, y), score, self.score(plane, x + 1, y));
157 let sy = peak(self.score(plane, x, y - 1), score, self.score(plane, x, y + 1));
158 let before = self.top;
159 self.top = (x as f32 + sx, y as f32 + sy);
160 self.vel = (self.top.0 - before.0, self.top.1 - before.1);
161 // Learn the matched picture, at the whole-pixel place it was found.
162 if let Some(matched) = patch(plane, x.max(0) as usize, y.max(0) as usize, self.tw, self.th) {
163 for (t, m) in self.tpl.iter_mut().zip(matched) {
164 *t += LEARN * (m - *t);
165 }
166 self.prepare();
167 }
168 Some(self.centre())
169 }
170
171 /// The zero-mean template and its norm, from the raw template.
172 fn prepare(&mut self) {
173 let n = self.tpl.len() as f32;
174 let mean = self.tpl.iter().sum::<f32>() / n;
175 self.zero_mean = self.tpl.iter().map(|v| v - mean).collect();
176 self.norm = self.zero_mean.iter().map(|v| v * v).sum::<f32>().sqrt();
177 }
178
179 /// The normalised cross-correlation of the template with the patch whose top-left
180 /// is `(x, y)`; `-1` when the patch leaves the picture, `0` when it is flat.
181 fn score(&self, plane: &Plane, x: i64, y: i64) -> f32 {
182 if x < 0 || y < 0 || x as usize + self.tw > plane.w || y as usize + self.th > plane.h {
183 return -1.0;
184 }
185 let (x, y) = (x as usize, y as usize);
186 let (mut sum, mut sq, mut dot) = (0.0f32, 0.0f32, 0.0f32);
187 for r in 0..self.th {
188 let row = (y + r) * plane.w + x;
189 for c in 0..self.tw {
190 let p = f32::from(plane.px[row + c]);
191 sum += p;
192 sq += p * p;
193 dot += self.zero_mean[r * self.tw + c] * p;
194 }
195 }
196 let var = sq - sum * sum / (self.tw * self.th) as f32;
197 if var <= 1e-6 {
198 return 0.0;
199 }
200 dot / (self.norm * var.sqrt())
201 }
202}
203
204/// The `w` by `h` luma patch at `(x, y)`, or `None` when it leaves the picture.
205fn patch(plane: &Plane, x: usize, y: usize, w: usize, h: usize) -> Option<Vec<f32>> {
206 if x + w > plane.w || y + h > plane.h {
207 return None;
208 }
209 Some((0..h).flat_map(|r| plane.px[(y + r) * plane.w + x..][..w].iter().map(|&v| f32::from(v))).collect())
210}
211
212/// The sub-pixel offset of a peak from its neighbours' scores, within half a pixel.
213fn peak(left: f32, mid: f32, right: f32) -> f32 {
214 let d = left - 2.0 * mid + right;
215 if left < -1.0 || right < -1.0 || d.abs() < 1e-9 {
216 return 0.0;
217 }
218 (0.5 * (left - right) / d).clamp(-0.5, 0.5)
219}
220
221/// The clip's placement as the renderer puts it on the canvas: the base transform and its
222/// keys (at source frames), the canvas size and the fit policy. A track matches the source
223/// picture and reports its path on the canvas, so each point goes through this frame's
224/// placement.
225#[derive(Clone)]
226pub struct Pose {
227 pub base: TransformParams,
228 pub keys: Vec<TransformKey>,
229 pub canvas: (u32, u32),
230 pub fit: FitPolicy,
231}
232
233impl Pose {
234 /// The placement at source frame `frame`.
235 fn at(&self, frame: u32) -> TransformParams {
236 evaluate(&self.base, &self.keys, f64::from(frame))
237 }
238}
239
240/// The box `region` (canvas fractions) covers, in picture fractions of a `src` picture
241/// placed under `t`: the bounding box of its four corners mapped back.
242fn picture_region(region: Region, src: (u32, u32), t: &TransformParams, canvas: (u32, u32), fit: FitPolicy) -> Region {
243 let (hw, hh) = (region.w / 2.0, region.h / 2.0);
244 let corners = [(-hw, -hh), (hw, -hh), (-hw, hh), (hw, hh)]
245 .map(|(dx, dy)| canvas_to_picture(src, t, canvas, fit, (region.x + dx, region.y + dy)));
246 let (lo_x, hi_x) = corners.iter().fold((f32::MAX, f32::MIN), |(l, h), c| (l.min(c.0), h.max(c.0)));
247 let (lo_y, hi_y) = corners.iter().fold((f32::MAX, f32::MIN), |(l, h), c| (l.min(c.1), h.max(c.1)));
248 Region { x: (lo_x + hi_x) / 2.0, y: (lo_y + hi_y) / 2.0, w: hi_x - lo_x, h: hi_y - lo_y }
249}
250
251/// The path of one track: `(frame, x, y)` in canvas fractions, in the order it was
252/// followed (ascending for a forward track, descending for a backward one), and the
253/// frame it was lost at when it stopped early.
254#[derive(Clone, Debug, PartialEq)]
255pub struct Track {
256 pub points: Vec<(u32, f32, f32)>,
257 pub lost_at: Option<u32>,
258}
259
260/// Steps a [`Tracker`] through pictures, numbering the points it makes.
261struct Walk {
262 /// The box to follow, in canvas fractions, as it is at the start frame.
263 region: Region,
264 pose: Pose,
265 tracker: Option<Tracker>,
266 points: Vec<(u32, f32, f32)>,
267 lost_at: Option<u32>,
268}
269
270impl Walk {
271 fn new(region: Region, pose: Pose) -> Walk {
272 Walk { region, pose, tracker: None, points: Vec::new(), lost_at: None }
273 }
274
275 /// Takes picture `plane` (of a source picture `src` pixels big) as frame `index`;
276 /// `false` when the feature is lost there. The first frame sets the template from
277 /// the box, and every point is recorded on the canvas.
278 fn push(&mut self, index: u32, plane: &Plane, src: (u32, u32)) -> bool {
279 let t = self.pose.at(index);
280 let centre = match self.tracker.as_mut() {
281 None => {
282 let box_ = picture_region(self.region, src, &t, self.pose.canvas, self.pose.fit);
283 self.tracker = Tracker::new(plane, box_);
284 self.tracker.as_ref().map(Tracker::centre)
285 }
286 Some(tr) => tr.step(plane),
287 };
288 match centre {
289 Some((x, y)) => {
290 let picture = (x / plane.w as f32, y / plane.h as f32);
291 let (cx, cy) = picture_to_canvas(src, &t, self.pose.canvas, self.pose.fit, picture);
292 self.points.push((index, cx, cy));
293 true
294 }
295 None => {
296 self.lost_at = Some(index);
297 false
298 }
299 }
300 }
301
302 fn finish(self) -> Track {
303 Track { points: self.points, lost_at: self.lost_at }
304 }
305}
306
307/// Tracks `region` from frame `start` through the frames `lo..hi` of `path`, forward
308/// (`start` to `hi`) or backward (`lo` to `start`). `progress` is set in thousandths of
309/// the range done; a set `cancel` stops it with an error.
310fn analyse(
311 path: &Path,
312 (lo, hi): (u32, u32),
313 start: u32,
314 forward: bool,
315 region: Region,
316 pose: Pose,
317 job: &Job,
318) -> crate::Result<Track> {
319 let (progress, cancel) = (&job.progress, &job.cancel);
320 if hi <= lo || start < lo || start >= hi {
321 return Err("nothing to track: the range is empty".into());
322 }
323 let span = u64::from(hi - lo);
324 let mut walk = Walk::new(region, pose);
325 let mut stopped = false;
326 if forward {
327 crate::export::each_layer_luma(path, start, hi, |index, y, w, h| {
328 if cancel.load(Ordering::Relaxed) {
329 stopped = true;
330 return false;
331 }
332 let more = walk.push(index, &reduce(y, w as usize, h as usize), (w, h));
333 progress.store(((index + 1 - lo) as u64 * 1000 / span) as u32, Ordering::Relaxed);
334 more
335 })?;
336 } else {
337 let mut held: Vec<(u32, Plane, (u32, u32))> = Vec::new();
338 let mut too_long = false;
339 crate::export::each_layer_luma(path, lo, start + 1, |index, y, w, h| {
340 if cancel.load(Ordering::Relaxed) {
341 stopped = true;
342 return false;
343 }
344 if held.len() >= MAX_BACKWARD {
345 too_long = true;
346 return false;
347 }
348 held.push((index, reduce(y, w as usize, h as usize), (w, h)));
349 progress.store(((index + 1 - lo) as u64 * 1000 / span) as u32, Ordering::Relaxed);
350 true
351 })?;
352 if too_long {
353 return Err(format!("a backward track holds at most {MAX_BACKWARD} frames: track the part nearer the start").into());
354 }
355 for (index, plane, src) in held.iter().rev() {
356 if cancel.load(Ordering::Relaxed) {
357 stopped = true;
358 break;
359 }
360 if !walk.push(*index, plane, *src) {
361 break;
362 }
363 }
364 }
365 if stopped {
366 return Err("tracking cancelled".into());
367 }
368 if walk.points.is_empty() {
369 return Err("the source gave no pictures to track".into());
370 }
371 progress.store(1000, Ordering::Relaxed);
372 Ok(walk.finish())
373}
374
375/// Reduces a track to keys: the points kept by Douglas-Peucker simplification, so that
376/// every dropped point lies within `tolerance` of the straight line between the kept
377/// ones. `points` must be in ascending frame order.
378pub fn simplify(points: &[(u32, f32, f32)], tolerance: f32) -> Vec<usize> {
379 let n = points.len();
380 if n <= 2 {
381 return (0..n).collect();
382 }
383 let mut keep = vec![false; n];
384 keep[0] = true;
385 keep[n - 1] = true;
386 let mut stack = vec![(0, n - 1)];
387 while let Some((a, b)) = stack.pop() {
388 let (fa, xa, ya) = points[a];
389 let (fb, xb, yb) = points[b];
390 let span = (fb - fa).max(1) as f32;
391 let mut worst = (0.0f32, a);
392 for (i, &(f, x, y)) in points.iter().enumerate().take(b).skip(a + 1) {
393 let t = (f - fa) as f32 / span;
394 let err = (x - (xa + (xb - xa) * t)).abs().max((y - (ya + (yb - ya) * t)).abs());
395 if err > worst.0 {
396 worst = (err, i);
397 }
398 }
399 if worst.0 > tolerance {
400 keep[worst.1] = true;
401 stack.push((a, worst.1));
402 stack.push((worst.1, b));
403 }
404 }
405 (0..n).filter(|&i| keep[i]).collect()
406}
407
408// ---- background jobs --------------------------------------------------------
409
410/// A running track, by its id.
411pub type JobId = u64;
412
413/// Where a track stands.
414#[derive(Clone, Debug, PartialEq)]
415pub enum Status {
416 /// Still running, this fraction done.
417 Running(f32),
418 /// Finished; [`take`] returns the outcome.
419 Finished,
420 /// Not known: taken already, or never started.
421 Gone,
422}
423
424struct Job {
425 progress: AtomicU32,
426 cancel: AtomicBool,
427 outcome: Mutex<Option<Result<Track, String>>>,
428}
429
430fn jobs() -> &'static Mutex<HashMap<JobId, Arc<Job>>> {
431 static JOBS: OnceLock<Mutex<HashMap<JobId, Arc<Job>>>> = OnceLock::new();
432 JOBS.get_or_init(Default::default)
433}
434
435/// Starts tracking `region` from frame `start` in the background; see `analyse`.
436pub fn start(path: &Path, range: (u32, u32), start: u32, forward: bool, region: Region, pose: Pose) -> JobId {
437 static NEXT: AtomicU64 = AtomicU64::new(1);
438 let id = NEXT.fetch_add(1, Ordering::Relaxed);
439 let job = Arc::new(Job { progress: AtomicU32::new(0), cancel: AtomicBool::new(false), outcome: Mutex::new(None) });
440 if let Ok(mut j) = jobs().lock() {
441 j.insert(id, job.clone());
442 }
443 let path = path.to_path_buf();
444 std::thread::spawn(move || {
445 let outcome = analyse(&path, range, start, forward, region, pose, &job);
446 let mut o = job.outcome.lock().unwrap_or_else(|e| e.into_inner());
447 *o = Some(outcome.map_err(|e| e.to_string()));
448 });
449 id
450}
451
452/// Where the track `id` stands.
453pub fn status(id: JobId) -> Status {
454 let Some(job) = jobs().lock().ok().and_then(|j| j.get(&id).cloned()) else {
455 return Status::Gone;
456 };
457 let done = job.outcome.lock().is_ok_and(|o| o.is_some());
458 if done {
459 Status::Finished
460 } else {
461 Status::Running(job.progress.load(Ordering::Relaxed) as f32 / 1000.0)
462 }
463}
464
465/// The outcome of the finished track `id`, which is then forgotten; `None` while it
466/// runs or when it is gone.
467pub fn take(id: JobId) -> Option<Result<Track, String>> {
468 let job = jobs().lock().ok().and_then(|j| j.get(&id).cloned())?;
469 let outcome = job.outcome.lock().ok()?.take()?;
470 if let Ok(mut j) = jobs().lock() {
471 j.remove(&id);
472 }
473 Some(outcome)
474}
475
476/// Stops the running track `id`. `false` when it is not running.
477pub fn cancel(id: JobId) -> bool {
478 let Some(job) = jobs().lock().ok().and_then(|j| j.get(&id).cloned()) else { return false };
479 let running = job.outcome.lock().is_ok_and(|o| o.is_none());
480 job.cancel.store(true, Ordering::Relaxed);
481 running
482}
483
484#[cfg(test)]
485mod tests {
486 use super::*;
487
488 /// A bright square drifting over a dark picture follows to within 1 % of the canvas.
489 #[test]
490 fn follows_a_moving_square_within_one_percent() {
491 let (w, h, side) = (160usize, 90usize, 24usize);
492 let frame = |f: usize| {
493 let (x0, y0) = (30 + 2 * f, 20 + f);
494 let mut px = vec![20u8; w * h];
495 for r in y0..y0 + side {
496 for c in x0..x0 + side {
497 px[r * w + c] = 230;
498 }
499 }
500 Plane { w, h, px }
501 };
502 let centre = |f: usize| ((30 + 2 * f + side / 2) as f32 / w as f32, (20 + f + side / 2) as f32 / h as f32);
503 let (cx, cy) = centre(0);
504 // A region a little wider than the square, so the template has edges to lock onto.
505 let grow = 12;
506 let region = Region { x: cx, y: cy, w: (side + grow) as f32 / w as f32, h: (side + grow) as f32 / h as f32 };
507 let pose = Pose { base: TransformParams::default(), keys: Vec::new(), canvas: (w as u32, h as u32), fit: FitPolicy::Fit };
508 let mut walk = Walk::new(region, pose.clone());
509 for f in 0..30 {
510 assert!(walk.push(f as u32, &frame(f), (w as u32, h as u32)), "lost at frame {f}");
511 }
512 let track = walk.finish();
513 assert_eq!(track.lost_at, None);
514 for &(f, x, y) in &track.points {
515 let (tx, ty) = centre(f as usize);
516 assert!((x - tx).abs() <= 0.01 && (y - ty).abs() <= 0.01, "frame {f}: ({x}, {y}) vs ({tx}, {ty})");
517 }
518 // A flat patch has nothing to follow: it is refused at once, not tracked to nowhere.
519 let flat = Plane { w, h, px: vec![90u8; w * h] };
520 assert!(!Walk::new(region, pose).push(0, &flat, (w as u32, h as u32)), "a flat region was accepted");
521 }
522}