forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6a8d990Tahinli15 days ago1049 commits

reframe.rs402 lines, 16.6 KiBHistoryRawDownload
1//! Auto reframe: follow the subject of a wide shot and write the clip's placement
2//! keys ([`crate::transform::TransformKey`]) so it fills a canvas of another shape.
3//!
4//! 1. **Subject.** A clip's frames are walked at a few samples a second, each
5//! reduced to a 64-cell-wide grey grid (a box average). Per cell a cheap
6//! saliency is scored from what moved since the last sample, the local contrast
7//! and a prior for the middle of the picture; the subject is the score-weighted
8//! centre of the cells near the peak. When nothing moves it stays where it was
9//! (a flat opening picture falls back to its contrast, and then the middle).
10//! No model, no colour: the luma planes are all the stabiliser's decoder gives.
11//! 2. **Path.** The subject's x and y are smoothed by a Gaussian (the stabiliser's,
12//! see [`crate::stabilise`]), pass through a dead zone -- the crop holds still
13//! until the subject nears the edge of the zone -- and are smoothed once more,
14//! so the crop never wanders on a still subject and never jerks.
15//! 3. **Keys.** The window is moved to the path inside the picture's bounds, scaled
16//! so the clip covers the whole canvas (the clip must be placed with
17//! [`crate::scale::FitPolicy::Fit`]); a position past what that scale can hide is
18//! clamped, so no key shows an edge, and neither does anything between two keys.
19//! Keys are kept only where the path turns (Ramer-Douglas-Peucker) and a path that
20//! never leaves its dead zone is one key.
21
22use std::path::Path;
23use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
24
25use crate::stabilise::smooth;
26use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, TransformKey, TransformParams};
27
28/// Samples a second the analysis takes, at most.
29pub const SAMPLE_HZ: f64 = 8.0;
30/// Default smoothness, `0.0..=1.0`.
31pub const DEFAULT_SMOOTHNESS: f32 = 0.5;
32
33const GRID_W: usize = 64;
34/// A key is dropped when the path stays this close (canvas fractions) to the line through its neighbours.
35const TOLERANCE: f64 = 0.003;
36/// Share of the visible window the subject may roam without the crop moving.
37const DEAD_ZONE: f64 = 0.12;
38
39/// The subject found in each sampled frame: positions as fractions of the picture,
40/// `0..=1` from the left and top.
41#[derive(Clone, Debug, PartialEq)]
42pub struct Subject {
43 /// Samples a second.
44 pub hz: f64,
45 /// File frame, x, y per sample, rising in frame.
46 pub samples: Vec<(u32, f64, f64)>,
47}
48
49/// Finds the subject frame by frame from grey pictures.
50#[derive(Default)]
51pub struct Tracker {
52 prev: Option<Vec<f32>>,
53 last: Option<(f64, f64)>,
54}
55
56impl Tracker {
57 /// The subject of the next sampled `w` x `h` luma picture, as fractions of it.
58 pub fn next(&mut self, y: &[u8], w: usize, h: usize) -> (f64, f64) {
59 let (gw, gh) = (GRID_W.min(w).max(1), (GRID_W * h / w.max(1)).clamp(1, h.max(1)));
60 let grid = reduce(y, w, h, gw, gh);
61 let mut score = vec![0.0f32; gw * gh];
62 let mut motion_peak = 0.0f32;
63 let mut motion = vec![0.0f32; gw * gh];
64 if let Some(prev) = self.prev.as_ref().filter(|p| p.len() == grid.len()) {
65 for (m, (a, b)) in motion.iter_mut().zip(grid.iter().zip(prev)) {
66 *m = ((a - b).abs() - 4.0).clamp(0.0, 64.0) / 64.0;
67 motion_peak = motion_peak.max(*m);
68 }
69 }
70 let at = |x: usize, yy: usize| grid[yy.min(gh - 1) * gw + x.min(gw - 1)];
71 for yy in 0..gh {
72 for x in 0..gw {
73 let grad = (at(x + 1, yy) - at(x, yy)).abs() + (at(x, yy + 1) - at(x, yy)).abs();
74 let contrast = (grad / 64.0).min(1.0);
75 let (dx, dy) = ((x as f32 + 0.5) / gw as f32 - 0.5, (yy as f32 + 0.5) / gh as f32 - 0.5);
76 let centre = 0.6 + 0.4 * (-(dx * dx + dy * dy) / (2.0 * 0.35 * 0.35)).exp();
77 // Motion is the subject; contrast only breaks the tie when nothing moves.
78 score[yy * gw + x] = (motion[yy * gw + x] + 0.5 * contrast) * centre;
79 }
80 }
81 let moving = motion_peak >= 0.05;
82 self.prev = Some(grid);
83 if !moving && let Some(last) = self.last {
84 return last;
85 }
86 let peak = score.iter().copied().fold(0.0f32, f32::max);
87 let found = if peak > 0.02 {
88 let (mut sx, mut sy, mut sw) = (0.0f64, 0.0f64, 0.0f64);
89 for yy in 0..gh {
90 for x in 0..gw {
91 let s = score[yy * gw + x];
92 if s >= 0.5 * peak {
93 let s = f64::from(s);
94 sx += s * (x as f64 + 0.5) / gw as f64;
95 sy += s * (yy as f64 + 0.5) / gh as f64;
96 sw += s;
97 }
98 }
99 }
100 (sx / sw, sy / sw)
101 } else {
102 (0.5, 0.5)
103 };
104 if moving {
105 self.last = Some(found);
106 }
107 found
108 }
109}
110
111/// A box average of a `w` x `h` plane down to `gw` x `gh`.
112fn reduce(y: &[u8], w: usize, h: usize, gw: usize, gh: usize) -> Vec<f32> {
113 let mut out = vec![0.0f32; gw * gh];
114 for gy in 0..gh {
115 let (y0, y1) = (gy * h / gh, ((gy + 1) * h / gh).max(gy * h / gh + 1).min(h));
116 for gx in 0..gw {
117 let (x0, x1) = (gx * w / gw, ((gx + 1) * w / gw).max(gx * w / gw + 1).min(w));
118 let mut sum = 0u32;
119 for row in y0..y1 {
120 sum += y[row * w + x0..row * w + x1].iter().map(|&v| u32::from(v)).sum::<u32>();
121 }
122 out[gy * gw + gx] = sum as f32 / ((y1 - y0) * (x1 - x0)) as f32;
123 }
124 }
125 out
126}
127
128/// Finds the subject of file frames `lo..hi` of `path`. `progress` is set in
129/// thousandths of the range done; a set `cancel` stops it with an error.
130pub fn analyse(path: &Path, lo: u32, hi: u32, progress: &AtomicU32, cancel: &AtomicBool) -> crate::Result<Subject> {
131 if hi <= lo {
132 return Err("nothing to analyse: the range is empty".into());
133 }
134 let (count, rate) = {
135 let meta = crate::demux::Demuxer::open(path)?.0;
136 (meta.frame_count, meta.frame_rate)
137 };
138 let hi = hi.min(count.max(lo + 1));
139 let step = ((rate / SAMPLE_HZ).round() as u32).max(1);
140 let mut tracker = Tracker::default();
141 let mut samples = Vec::new();
142 let mut stopped = false;
143 crate::export::each_layer_luma(path, lo, hi, |index, y, width, height| {
144 if cancel.load(Ordering::Relaxed) {
145 stopped = true;
146 return false;
147 }
148 if (index - lo).is_multiple_of(step) {
149 let (x, yy) = tracker.next(&y[..width as usize * height as usize], width as usize, height as usize);
150 samples.push((index, x, yy));
151 }
152 progress.store(((index + 1 - lo) as u64 * 1000 / u64::from(hi - lo)) as u32, Ordering::Relaxed);
153 true
154 })?;
155 if stopped {
156 return Err("reframe analysis cancelled".into());
157 }
158 let Some(&(_, x, y)) = samples.last() else {
159 return Err("the source gave no pictures to analyse".into());
160 };
161 // The clip's last frame holds where the subject ended.
162 if samples.last().is_some_and(|s| s.0 < hi - 1) {
163 samples.push((hi - 1, x, y));
164 }
165 progress.store(1000, Ordering::Relaxed);
166 Ok(Subject { hz: rate / f64::from(step), samples })
167}
168
169/// What the keys are computed for: the picture as the clip displays it, the
170/// project canvas, the clip's placement before the reframe and the clip's own
171/// key range (`in_frame..out_frame`, as [`crate::project::Clip`] numbers it).
172#[derive(Clone, Copy, Debug)]
173pub struct Target {
174 pub src_w: u32,
175 pub src_h: u32,
176 pub canvas_w: u32,
177 pub canvas_h: u32,
178 pub base: TransformParams,
179 pub in_frame: u32,
180 pub out_frame: u32,
181}
182
183/// The inputs of an auto reframe ([`crate::PlaybackSession::reframe_job`]): [`analyse`]
184/// `lo..hi` of `path`, then [`keys`] for `target`.
185#[derive(Clone, Debug)]
186pub struct ReframeJob {
187 pub path: std::path::PathBuf,
188 pub lo: u32,
189 pub hi: u32,
190 pub target: Target,
191}
192
193impl Target {
194 /// The scale that makes the fitted picture cover the canvas, and the size of
195 /// the scaled picture in canvas fractions of the canvas's own width and height.
196 fn cover(&self) -> (f64, f64, f64) {
197 let (sw, sh) = (f64::from(self.src_w.max(1)), f64::from(self.src_h.max(1)));
198 let (cw, ch) = (f64::from(self.canvas_w.max(1)), f64::from(self.canvas_h.max(1)));
199 let k = (cw / sw).min(ch / sh);
200 let (dw, dh) = (sw * k, sh * k);
201 let mut s = (cw / dw).max(ch / dh);
202 // The fit rect is rounded to the chroma grid, so a hair of margin keeps its edge off the canvas.
203 s = if s <= 1.0005 { 1.0 } else { s * 1.004 };
204 (s, dw * s / cw, dh * s / ch)
205 }
206}
207
208/// The placement keys that follow `subject` on `target`, with the crop held still
209/// while the subject stays near it. `smoothness` is `0.0..=1.0`: how slowly the
210/// crop follows (about `0.25 + 1.75 * smoothness` seconds of smoothing). The keys
211/// keep the clip's own rotation, crop and opacity and cover the canvas at every
212/// frame; there is always at least one.
213pub fn keys(subject: &Subject, target: &Target, smoothness: f32) -> Vec<TransformKey> {
214 let (scale, bw, bh) = target.cover();
215 // Window size as a fraction of the scaled picture, per axis, and the pan allowed to each side.
216 let (fx, fy) = ((1.0 / bw).min(1.0), (1.0 / bh).min(1.0));
217 let s = &subject.samples;
218 let sigma = (0.25 + 1.75 * f64::from(smoothness.clamp(0.0, 1.0))) * subject.hz;
219 let path = |sel: fn(&(u32, f64, f64)) -> f64, frac: f64| -> Vec<f64> {
220 let raw: Vec<f64> = s.iter().map(sel).collect();
221 let smoothed = smooth(&raw, sigma);
222 let mut c = *smoothed.first().unwrap_or(&0.5);
223 let dz = DEAD_ZONE * frac;
224 let held: Vec<f64> = smoothed
225 .iter()
226 .map(|&x| {
227 if x - c > dz {
228 c = x - dz;
229 } else if c - x > dz {
230 c = x + dz;
231 }
232 c
233 })
234 .collect();
235 smooth(&held, sigma / 2.0)
236 };
237 let (px, py) = (path(|t| t.1, fx), path(|t| t.2, fy));
238 let lim = |bs: f64| (bs - 1.0).max(0.0) / 2.0;
239 let place = |c: f64, bs: f64| ((0.5 - c) * bs).clamp(-lim(bs), lim(bs));
240 let pts: Vec<(f64, f64)> = px.iter().zip(&py).map(|(&x, &y)| (place(x, bw), place(y, bh))).collect();
241 // Source-position of each sample inside the clip's key range.
242 let (lo, hi) = (s.first().map_or(0, |t| t.0), s.last().map_or(1, |t| t.0));
243 let span = f64::from(target.out_frame.saturating_sub(1).saturating_sub(target.in_frame));
244 let at = |frame: u32| -> u32 {
245 let t = if hi > lo { f64::from(frame - lo) / f64::from(hi - lo) } else { 0.0 };
246 target.in_frame + (t * span).round() as u32
247 };
248 let mut keep = vec![false; pts.len()];
249 let mut tol = TOLERANCE;
250 loop {
251 keep.iter_mut().for_each(|k| *k = false);
252 simplify(&pts, tol, &mut keep);
253 if keep.iter().filter(|&&k| k).count() <= MAX_TRANSFORM_KEYS {
254 break;
255 }
256 tol *= 2.0;
257 }
258 let mut out: Vec<TransformKey> = Vec::new();
259 for (i, _) in keep.iter().enumerate().filter(|(_, k)| **k) {
260 let frame = at(s[i].0);
261 if out.last().is_some_and(|k| k.at == frame) {
262 continue;
263 }
264 let params = TransformParams { pos_x: pts[i].0 as f32, pos_y: pts[i].1 as f32, scale: scale as f32, ..target.base };
265 out.push(TransformKey { at: frame, params, ease: KeyEase::Linear });
266 }
267 if out.is_empty() {
268 let params = TransformParams { scale: scale as f32, ..target.base };
269 out.push(TransformKey { at: target.in_frame, params, ease: KeyEase::Linear });
270 }
271 out
272}
273
274/// Marks the points that must stay for a polyline to keep within `tol` of `pts`
275/// (Ramer-Douglas-Peucker, by index as time). A path that never leaves `tol` of
276/// its first point keeps that point alone.
277fn simplify(pts: &[(f64, f64)], tol: f64, keep: &mut [bool]) {
278 let Some(&first) = pts.first() else { return };
279 if pts.iter().all(|p| (p.0 - first.0).abs() <= tol && (p.1 - first.1).abs() <= tol) {
280 keep[0] = true;
281 return;
282 }
283 keep[0] = true;
284 keep[pts.len() - 1] = true;
285 let mut stack = vec![(0usize, pts.len() - 1)];
286 while let Some((a, b)) = stack.pop() {
287 let mut worst = (0.0f64, a);
288 for i in a + 1..b {
289 let t = (i - a) as f64 / (b - a) as f64;
290 let (ex, ey) = (pts[a].0 + t * (pts[b].0 - pts[a].0), pts[a].1 + t * (pts[b].1 - pts[a].1));
291 let d = (pts[i].0 - ex).abs().max((pts[i].1 - ey).abs());
292 if d > worst.0 {
293 worst = (d, i);
294 }
295 }
296 if worst.0 > tol {
297 keep[worst.1] = true;
298 stack.push((a, worst.1));
299 stack.push((worst.1, b));
300 }
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 /// A 160x90 grey picture with a bright `n`-pixel square at (`x`, `y`).
309 fn picture(x: usize, y: usize, n: usize) -> Vec<u8> {
310 let mut p = vec![30u8; 160 * 90];
311 for row in y..y + n {
312 for col in x..x + n {
313 p[row * 160 + col] = 235;
314 }
315 }
316 p
317 }
318
319 fn target() -> Target {
320 Target { src_w: 1920, src_h: 1080, canvas_w: 1080, canvas_h: 1920, base: TransformParams::default(), in_frame: 100, out_frame: 300 }
321 }
322
323 fn subject_of(frames: impl Iterator<Item = Vec<u8>>) -> Subject {
324 let mut t = Tracker::default();
325 let samples = frames.enumerate().map(|(i, f)| {
326 let (x, y) = t.next(&f, 160, 90);
327 (i as u32 * 3, x, y)
328 });
329 Subject { hz: 8.0, samples: samples.collect() }
330 }
331
332 #[test]
333 fn a_moving_bright_square_is_followed() {
334 let s = subject_of((0..40).map(|i| picture(4 + i * 3, 37, 16)));
335 let (first, last) = (s.samples[2], *s.samples.last().unwrap());
336 assert!(first.1 < 0.25 && last.1 > 0.7, "{first:?} {last:?}");
337 let k = keys(&s, &target(), 0.2);
338 assert!(k.len() >= 2, "{k:?}");
339 // The window starts on the left (the picture shifted right, positive) and ends on the right.
340 assert!(k[0].params.pos_x > 0.5 && k.last().unwrap().params.pos_x < -0.5, "{k:?}");
341 assert!(k.windows(2).all(|w| w[0].at < w[1].at));
342 assert_eq!((k[0].at, k.last().unwrap().at), (100, 299));
343 }
344
345 #[test]
346 fn a_static_scene_is_one_key() {
347 let s = subject_of((0..30).map(|_| picture(70, 37, 16)));
348 let k = keys(&s, &target(), 0.5);
349 assert_eq!(k.len(), 1, "{k:?}");
350 assert_eq!(k[0].at, 100);
351 // The square is a little left of centre: the crop sits on it, not at zero.
352 assert!(k[0].params.scale > 3.0);
353 }
354
355 #[test]
356 fn a_subject_that_stops_stays_found() {
357 let frames = (0..30).map(|i| picture(4 + i.min(15) * 6, 37, 16));
358 let s = subject_of(frames);
359 let (mid, end) = (s.samples[16], *s.samples.last().unwrap());
360 assert!((mid.1 - end.1).abs() < 0.02, "{mid:?} {end:?}");
361 }
362
363 #[test]
364 fn keys_never_expose_the_frame_edge() {
365 // A subject at the very edge of the picture, then the other.
366 let s = Subject {
367 hz: 8.0,
368 samples: (0..60).map(|i| (i, if i < 30 { 0.0 } else { 1.0 }, if i < 30 { 1.0 } else { 0.0 })).collect(),
369 };
370 for t in [target(), Target { src_w: 1080, src_h: 1920, canvas_w: 1920, canvas_h: 1080, ..target() }] {
371 let (scale, bw, bh) = t.cover();
372 let k = keys(&s, &t, 0.0);
373 for key in &k {
374 let p = key.params;
375 assert!((f64::from(p.pos_x)).abs() <= ((bw - 1.0) / 2.0).max(0.0) + 1e-6, "{p:?}");
376 assert!((f64::from(p.pos_y)).abs() <= ((bh - 1.0) / 2.0).max(0.0) + 1e-6, "{p:?}");
377 assert!(f64::from(p.scale) >= scale - 1e-6);
378 }
379 // The scaled picture covers the canvas on both axes.
380 assert!(bw >= 1.0 && bh >= 1.0, "{bw} {bh}");
381 }
382 }
383
384 #[test]
385 fn same_shape_needs_no_reframe() {
386 let t = Target { src_w: 1920, src_h: 1080, canvas_w: 1280, canvas_h: 720, ..target() };
387 let s = subject_of((0..20).map(|i| picture(4 + i * 6, 37, 16)));
388 let k = keys(&s, &t, 0.5);
389 assert!(k.iter().all(|k| k.params.scale == 1.0 && k.params.pos_x == 0.0 && k.params.pos_y == 0.0), "{k:?}");
390 assert_eq!(k.len(), 1);
391 }
392
393 #[test]
394 fn long_wandering_paths_stay_within_the_key_cap() {
395 let s = Subject {
396 hz: 8.0,
397 samples: (0..4000).map(|i| (i, 0.5 + 0.45 * (f64::from(i) * 0.37).sin(), 0.5)).collect(),
398 };
399 let t = Target { out_frame: 4001, ..target() };
400 assert!(keys(&s, &t, 0.0).len() <= MAX_TRANSFORM_KEYS);
401 }
402}