forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

stabilise.rs1124 lines, 43.9 KiBHistoryRawDownload
1//! Video stabilisation: the camera's shake measured from the picture, smoothed, and
2//! taken back out of each frame before the clip's own placement is applied.
3//!
4//! The pipeline, per clip, over the source frames it plays:
5//!
6//! 1. **Motion.** Each decoded frame is reduced to luma at no more than
7//! [`ANALYSIS_W`] wide (a box average, so the reduction is also the noise
8//! filter), and a three-level pyramid is built. Up to 20x12 Shi-Tomasi corners
9//! (the strongest in each grid cell) are tracked from the previous frame by
10//! pyramidal Lucas-Kanade, and a similarity transform (shift, turn, scale) is
11//! fitted to the tracks by RANSAC and refitted by least squares on the inliers,
12//! so a walker crossing the shot does not move the estimate.
13//! 2. **Path.** The frame-to-frame transforms are chained into the camera's path,
14//! and each of its four parameters (angle, log scale, x, y) is smoothed by a
15//! Gaussian whose width the strength sets. The ends are padded by point
16//! reflection, so a steady pan -- a straight line -- comes out of the smoother
17//! exactly as it went in and is kept, while the shake around it is removed.
18//! 3. **Correction.** Each frame is moved from where the camera was to where the
19//! smoothed camera is. In [`Crop::Zoom`] the picture is enlarged about its
20//! centre by the one factor that keeps every corrected frame of the clip
21//! covering the whole picture (no black edge anywhere, capped at [`MAX_ZOOM`]);
22//! [`Crop::Full`] keeps the frame's size and lets the edges show black.
23//!
24//! The measured motion is cached per source and per analysed range of its frames
25//! (see [`cache_path`]): the key is the source's path, length and modification
26//! time, so a changed file is a new analysis and re-opening a project is not. Only
27//! the raw frame-to-frame motion is stored; the strength and crop are applied on
28//! load, so changing them never re-analyses. The correction is indexed by the
29//! file's own frame numbers, so it is the same picture whatever speed, ramp,
30//! direction or trim the clip plays that footage at.
31//!
32//! Analysis runs on a thread of its own ([`start`]), polled by [`status`] and
33//! stopped by [`cancel`]; the renderer only ever reads a finished analysis
34//! ([`correction`]) and plays the clip unstabilised until there is one.
35
36use std::collections::HashMap;
37use std::path::{Path, PathBuf};
38use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
39use std::sync::{Arc, Mutex, OnceLock};
40use std::time::UNIX_EPOCH;
41
42
43/// The widest picture the motion is measured on; wider sources are box-averaged
44/// down by a whole factor first.
45pub const ANALYSIS_W: u32 = 640;
46/// The most [`Crop::Zoom`] enlarges a picture to hide the corrected edges.
47pub const MAX_ZOOM: f64 = 1.5;
48/// The strength a clip is stabilised at when nothing else is asked for.
49pub const DEFAULT_STRENGTH: f32 = 0.5;
50/// Bumped when the analysis changes what it stores, so an old cache is a miss.
51const ALGO: u32 = 1;
52const MAGIC: &[u8; 8] = b"EDSTAB1\n";
53
54/// How the corrected frame meets the edges it moved away from.
55#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
56pub enum Crop {
57 /// Enlarged just enough that no frame shows an edge.
58 #[default]
59 Zoom,
60 /// Kept at its size; the edges show black where the frame moved off them.
61 Full,
62}
63
64impl Crop {
65 pub fn name(self) -> &'static str {
66 match self {
67 Crop::Zoom => "zoom",
68 Crop::Full => "full",
69 }
70 }
71
72 pub fn from_name(s: &str) -> Option<Crop> {
73 match s {
74 "zoom" => Some(Crop::Zoom),
75 "full" => Some(Crop::Full),
76 _ => None,
77 }
78 }
79}
80
81/// One clip's stabilisation settings ([`crate::project::Clip::stabilise`]): a strength
82/// in whole percent and a [`Crop`], packed into one non-zero byte so `Option<Stabilise>`
83/// costs the clip a single byte.
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
85pub struct Stabilise(std::num::NonZeroU8);
86
87impl Default for Stabilise {
88 fn default() -> Self {
89 Self::new(DEFAULT_STRENGTH, Crop::Zoom)
90 }
91}
92
93impl Stabilise {
94 /// A setting at `strength` `0.0..=1.0` (clamped, to the nearest percent). How smooth
95 /// the camera path is made: the Gaussian's width is `strength` x 2 seconds of frames
96 /// (at least half a frame).
97 pub fn new(strength: f32, crop: Crop) -> Self {
98 let s = if strength.is_finite() { strength.clamp(0.0, 1.0) } else { DEFAULT_STRENGTH };
99 Self::with_percent((s * 100.0).round() as u8, crop)
100 }
101
102 /// A setting at `percent` (clamped to 100).
103 pub fn with_percent(percent: u8, crop: Crop) -> Self {
104 let code = 1 + percent.min(100) + if crop == Crop::Full { 101 } else { 0 };
105 Self(std::num::NonZeroU8::new(code).expect("at least 1"))
106 }
107
108 /// The strength in whole percent, `0..=100`.
109 pub fn strength(self) -> u8 {
110 (self.0.get() - 1) % 101
111 }
112
113 /// The strength as a fraction, `0.0..=1.0`.
114 pub fn amount(self) -> f32 {
115 f32::from(self.strength()) / 100.0
116 }
117
118 pub fn crop(self) -> Crop {
119 if self.0.get() > 101 { Crop::Full } else { Crop::Zoom }
120 }
121}
122
123/// A similarity transform on centred pixel coordinates: `q = [a -b; b a] p + t`.
124#[derive(Clone, Copy, Debug, PartialEq)]
125pub struct Sim {
126 pub a: f64,
127 pub b: f64,
128 pub tx: f64,
129 pub ty: f64,
130}
131
132impl Sim {
133 pub const IDENTITY: Sim = Sim { a: 1.0, b: 0.0, tx: 0.0, ty: 0.0 };
134
135 pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
136 (self.a * x - self.b * y + self.tx, self.b * x + self.a * y + self.ty)
137 }
138
139 /// `self` first, then `next`.
140 pub fn then(self, next: Sim) -> Sim {
141 let (tx, ty) = next.apply(self.tx, self.ty);
142 Sim { a: next.a * self.a - next.b * self.b, b: next.a * self.b + next.b * self.a, tx, ty }
143 }
144
145 pub fn inverse(self) -> Sim {
146 let d = self.a * self.a + self.b * self.b;
147 let (a, b) = (self.a / d, -self.b / d);
148 let r = Sim { a, b, tx: 0.0, ty: 0.0 };
149 let (tx, ty) = r.apply(-self.tx, -self.ty);
150 Sim { a, b, tx, ty }
151 }
152
153 /// Radians, positive turning +x toward +y (clockwise on a y-down picture).
154 pub fn angle(&self) -> f64 {
155 self.b.atan2(self.a)
156 }
157
158 pub fn scale(&self) -> f64 {
159 self.a.hypot(self.b)
160 }
161
162 fn params(&self) -> [f64; 4] {
163 [self.angle(), self.scale().ln(), self.tx, self.ty]
164 }
165
166 fn from_params(p: [f64; 4]) -> Sim {
167 let s = p[1].exp();
168 Sim { a: s * p[0].cos(), b: s * p[0].sin(), tx: p[2], ty: p[3] }
169 }
170
171 /// The same transform for a picture `k` times the size.
172 fn scaled(self, k: f64) -> Sim {
173 Sim { tx: self.tx * k, ty: self.ty * k, ..self }
174 }
175}
176
177// ---- motion ---------------------------------------------------------------
178
179struct Level {
180 w: usize,
181 h: usize,
182 px: Vec<f32>,
183 gx: Vec<f32>,
184 gy: Vec<f32>,
185}
186
187impl Level {
188 fn new(w: usize, h: usize, px: Vec<f32>) -> Level {
189 let (mut gx, mut gy) = (vec![0.0; w * h], vec![0.0; w * h]);
190 for y in 1..h.saturating_sub(1) {
191 for x in 1..w.saturating_sub(1) {
192 let i = y * w + x;
193 gx[i] = 0.5 * (px[i + 1] - px[i - 1]);
194 gy[i] = 0.5 * (px[i + w] - px[i - w]);
195 }
196 }
197 Level { w, h, px, gx, gy }
198 }
199
200 fn half(&self) -> Level {
201 let (w, h) = (self.w / 2, self.h / 2);
202 let mut px = vec![0.0; w * h];
203 for y in 0..h {
204 for x in 0..w {
205 let i = 2 * y * self.w + 2 * x;
206 px[y * w + x] = 0.25 * (self.px[i] + self.px[i + 1] + self.px[i + self.w] + self.px[i + self.w + 1]);
207 }
208 }
209 Level::new(w, h, px)
210 }
211
212 /// Bilinear sample of `plane` at `(x, y)`, which must be inside `0..w-1`.
213 fn at(&self, plane: &[f32], x: f32, y: f32) -> f32 {
214 let (x0, y0) = (x.floor(), y.floor());
215 let (fx, fy) = (x - x0, y - y0);
216 let i = y0 as usize * self.w + x0 as usize;
217 let top = plane[i] + (plane[i + 1] - plane[i]) * fx;
218 let bot = plane[i + self.w] + (plane[i + self.w + 1] - plane[i + self.w]) * fx;
219 top + (bot - top) * fy
220 }
221}
222
223const LEVELS: usize = 4;
224/// How far, in top-of-pyramid pixels, [`coarse_shift`] looks.
225const COARSE: usize = 6;
226const HALF_WIN: i32 = 7;
227const GRID: (usize, usize) = (20, 12);
228
229/// One frame, reduced, ready to be tracked from and to.
230struct Pyramid {
231 levels: Vec<Level>,
232 /// Source pixels per analysis pixel.
233 factor: f64,
234}
235
236impl Pyramid {
237 fn of(luma: &[u8], w: usize, h: usize) -> Option<Pyramid> {
238 let f = (w as u32).div_ceil(ANALYSIS_W).max(1) as usize;
239 let (aw, ah) = (w / f, h / f);
240 if aw < 64 || ah < 36 {
241 return None;
242 }
243 let mut px = vec![0.0f32; aw * ah];
244 let norm = 1.0 / (f * f) as f32;
245 for y in 0..ah {
246 for x in 0..aw {
247 let mut s = 0u32;
248 for dy in 0..f {
249 let row = &luma[(y * f + dy) * w + x * f..][..f];
250 s += row.iter().map(|&v| u32::from(v)).sum::<u32>();
251 }
252 px[y * aw + x] = s as f32 * norm;
253 }
254 }
255 let mut levels = vec![Level::new(aw, ah, px)];
256 for _ in 1..LEVELS {
257 let next = levels.last().expect("one level").half();
258 levels.push(next);
259 }
260 Some(Pyramid { levels, factor: f as f64 })
261 }
262
263 /// The strongest corner of each grid cell, as level-0 coordinates.
264 fn corners(&self) -> Vec<(f32, f32)> {
265 let l = &self.levels[0];
266 let m = (HALF_WIN as usize + 2) << (LEVELS - 1);
267 if l.w <= 2 * m || l.h <= 2 * m {
268 return Vec::new();
269 }
270 let (cw, ch) = ((l.w - 2 * m) / GRID.0, (l.h - 2 * m) / GRID.1);
271 let mut best: Vec<(f32, f32, f32)> = Vec::new();
272 for gy in 0..GRID.1 {
273 for gx in 0..GRID.0 {
274 let mut cell = (0.0f32, 0.0, 0.0);
275 for y in (m + gy * ch..m + (gy + 1) * ch).step_by(2) {
276 for x in (m + gx * cw..m + (gx + 1) * cw).step_by(2) {
277 let (mut xx, mut xy, mut yy) = (0.0f32, 0.0, 0.0);
278 for dy in -2i32..=2 {
279 for dx in -2i32..=2 {
280 let i = (y as i32 + dy) as usize * l.w + (x as i32 + dx) as usize;
281 xx += l.gx[i] * l.gx[i];
282 xy += l.gx[i] * l.gy[i];
283 yy += l.gy[i] * l.gy[i];
284 }
285 }
286 let tr = 0.5 * (xx + yy);
287 let lam = tr - (0.25 * (xx - yy) * (xx - yy) + xy * xy).sqrt();
288 if lam > cell.0 {
289 cell = (lam, x as f32, y as f32);
290 }
291 }
292 }
293 best.push(cell);
294 }
295 }
296 let top = best.iter().map(|c| c.0).fold(0.0, f32::max);
297 best.into_iter().filter(|c| c.0 > 0.02 * top && c.0 > 1.0).map(|c| (c.1, c.2)).collect()
298 }
299}
300
301/// Pyramidal Lucas-Kanade: where each of `pts` in `a` is in `b`, or `None` for a
302/// point that left the picture or would not converge.
303fn track(a: &Pyramid, b: &Pyramid, pts: &[(f32, f32)], guess: (f32, f32)) -> Vec<Option<(f32, f32)>> {
304 let n = (2 * HALF_WIN + 1) as usize;
305 let mut pw = vec![0.0f32; n * n];
306 let mut gxw = vec![0.0f32; n * n];
307 let mut gyw = vec![0.0f32; n * n];
308 pts.iter()
309 .map(|&(px, py)| {
310 let mut g = (guess.0 / (1 << (LEVELS - 1)) as f32, guess.1 / (1 << (LEVELS - 1)) as f32);
311 for lvl in (0..LEVELS).rev() {
312 let (la, lb) = (&a.levels[lvl], &b.levels[lvl]);
313 let k = 1.0 / (1 << lvl) as f32;
314 let (ux, uy) = (px * k, py * k);
315 let hw = HALF_WIN as f32;
316 let inside = |l: &Level, x: f32, y: f32| x >= hw && y >= hw && x < l.w as f32 - hw - 1.0 && y < l.h as f32 - hw - 1.0;
317 // A coarse level that cannot place the point (too near the edge, or
318 // too flat once halved) hands its start down unrefined.
319 let skip = |g: (f32, f32)| if lvl == 0 { None } else { Some((2.0 * g.0, 2.0 * g.1)) };
320 if !inside(la, ux, uy) {
321 g = skip(g)?;
322 continue;
323 }
324 let (mut sxx, mut sxy, mut syy) = (0.0f32, 0.0, 0.0);
325 for (j, dy) in (-HALF_WIN..=HALF_WIN).enumerate() {
326 for (i, dx) in (-HALF_WIN..=HALF_WIN).enumerate() {
327 let (x, y) = (ux + dx as f32, uy + dy as f32);
328 let o = j * n + i;
329 pw[o] = la.at(&la.px, x, y);
330 gxw[o] = la.at(&la.gx, x, y);
331 gyw[o] = la.at(&la.gy, x, y);
332 sxx += gxw[o] * gxw[o];
333 sxy += gxw[o] * gyw[o];
334 syy += gyw[o] * gyw[o];
335 }
336 }
337 let det = sxx * syy - sxy * sxy;
338 if det < 1e-6 || det < 1e-4 * (sxx + syy) * (sxx + syy) {
339 g = skip(g)?;
340 continue;
341 }
342 let mut d = g;
343 let mut lost = false;
344 for _ in 0..30 {
345 let (cx, cy) = (ux + d.0, uy + d.1);
346 if !inside(lb, cx, cy) {
347 lost = true;
348 break;
349 }
350 let (mut ex, mut ey) = (0.0f32, 0.0);
351 for (j, dy) in (-HALF_WIN..=HALF_WIN).enumerate() {
352 for (i, dx) in (-HALF_WIN..=HALF_WIN).enumerate() {
353 let o = j * n + i;
354 let e = pw[o] - lb.at(&lb.px, cx + dx as f32, cy + dy as f32);
355 ex += e * gxw[o];
356 ey += e * gyw[o];
357 }
358 }
359 let (sx, sy) = ((syy * ex - sxy * ey) / det, (sxx * ey - sxy * ex) / det);
360 d = (d.0 + sx, d.1 + sy);
361 if sx * sx + sy * sy < 1e-6 {
362 break;
363 }
364 }
365 if lost {
366 g = skip(g)?;
367 continue;
368 }
369 g = if lvl == 0 { d } else { (2.0 * d.0, 2.0 * d.1) };
370 }
371 Some((px + g.0, py + g.1))
372 })
373 .collect()
374}
375
376/// The least-squares similarity taking `p` to `q`.
377fn fit(p: &[(f64, f64)], q: &[(f64, f64)]) -> Option<Sim> {
378 let n = p.len() as f64;
379 if p.len() < 2 {
380 return None;
381 }
382 let (mut px, mut py, mut qx, mut qy) = (0.0, 0.0, 0.0, 0.0);
383 for (a, b) in p.iter().zip(q) {
384 px += a.0;
385 py += a.1;
386 qx += b.0;
387 qy += b.1;
388 }
389 let (px, py, qx, qy) = (px / n, py / n, qx / n, qy / n);
390 let (mut sa, mut sb, mut ss) = (0.0, 0.0, 0.0);
391 for (a, b) in p.iter().zip(q) {
392 let (ax, ay, bx, by) = (a.0 - px, a.1 - py, b.0 - qx, b.1 - qy);
393 sa += ax * bx + ay * by;
394 sb += ax * by - ay * bx;
395 ss += ax * ax + ay * ay;
396 }
397 if ss < 1e-9 {
398 return None;
399 }
400 let r = Sim { a: sa / ss, b: sb / ss, tx: 0.0, ty: 0.0 };
401 let (rx, ry) = r.apply(px, py);
402 Some(Sim { tx: qx - rx, ty: qy - ry, ..r })
403}
404
405fn residual(m: &Sim, p: (f64, f64), q: (f64, f64)) -> f64 {
406 let (x, y) = m.apply(p.0, p.1);
407 (x - q.0).hypot(y - q.1)
408}
409
410/// RANSAC over two-point similarities, then least squares on the inliers, twice.
411fn robust(p: &[(f64, f64)], q: &[(f64, f64)]) -> Option<Sim> {
412 if p.len() < 6 {
413 return None;
414 }
415 let mut seed = 0x9e37_79b9_7f4a_7c15u64;
416 let mut rnd = |n: usize| {
417 seed ^= seed << 13;
418 seed ^= seed >> 7;
419 seed ^= seed << 17;
420 (seed % n as u64) as usize
421 };
422 let mut best: (usize, Sim) = (0, Sim::IDENTITY);
423 for _ in 0..200 {
424 let (i, j) = (rnd(p.len()), rnd(p.len()));
425 if i == j {
426 continue;
427 }
428 let Some(m) = fit(&[p[i], p[j]], &[q[i], q[j]]) else { continue };
429 let count = p.iter().zip(q).filter(|(a, b)| residual(&m, **a, **b) < 1.0).count();
430 if count > best.0 {
431 best = (count, m);
432 }
433 }
434 if best.0 < 6 {
435 return None;
436 }
437 let mut m = best.1;
438 for thr in [1.0, 0.5] {
439 let (ip, iq): (Vec<_>, Vec<_>) = p.iter().zip(q).filter(|(a, b)| residual(&m, **a, **b) < thr).map(|(a, b)| (*a, *b)).unzip();
440 if ip.len() < 6 {
441 break;
442 }
443 m = fit(&ip, &iq)?;
444 }
445 Some(m)
446}
447
448/// The motion from frame `a` to frame `b`, as the similarity taking a point of
449/// `a` to where it is in `b`, in centred **source** pixels.
450fn motion(a: &Pyramid, b: &Pyramid) -> Option<Sim> {
451 let l = &a.levels[0];
452 let (cx, cy) = ((l.w as f64 - 1.0) / 2.0, (l.h as f64 - 1.0) / 2.0);
453 let pts = a.corners();
454 let guess = coarse_shift(a, b);
455 // The points are independent: tracked on a few threads at once.
456 let per = pts.len().div_ceil(4).max(1);
457 let tracked: Vec<Option<(f32, f32)>> = std::thread::scope(|s| {
458 let parts: Vec<_> = pts.chunks(per).map(|c| s.spawn(move || track(a, b, c, guess))).collect();
459 parts.into_iter().flat_map(|h| h.join().expect("a tracker thread")).collect()
460 });
461 let (mut p, mut q) = (Vec::new(), Vec::new());
462 for (s, t) in pts.iter().zip(tracked) {
463 if let Some(t) = t {
464 p.push((f64::from(s.0) - cx, f64::from(s.1) - cy));
465 q.push((f64::from(t.0) - cx, f64::from(t.1) - cy));
466 }
467 }
468 robust(&p, &q).map(|m| m.scaled(a.factor))
469}
470
471/// The whole-picture shift from `a` to `b` found by trying every whole-pixel
472/// shift up to [`COARSE`] one level below the top of the pyramid: the start the tracker
473/// refines from, so a jolt bigger than its window is still found.
474fn coarse_shift(a: &Pyramid, b: &Pyramid) -> (f32, f32) {
475 let top = LEVELS - 2;
476 let (la, lb) = (&a.levels[top], &b.levels[top]);
477 let r = COARSE;
478 if la.w <= 4 * r || la.h <= 4 * r {
479 return (0.0, 0.0);
480 }
481 let mut best = (f32::MAX, 0i64, 0i64);
482 for dy in -(r as i64)..=r as i64 {
483 for dx in -(r as i64)..=r as i64 {
484 let mut sad = 0.0f32;
485 for y in 2 * r..la.h - 2 * r {
486 let ra = &la.px[y * la.w + 2 * r..(y + 1) * la.w - 2 * r];
487 let yb = (y as i64 + dy) as usize;
488 let xb = (2 * r) as i64 + dx;
489 let rb = &lb.px[yb * lb.w + xb as usize..][..ra.len()];
490 sad += ra.iter().zip(rb).map(|(p, q)| (p - q).abs()).sum::<f32>();
491 }
492 if sad < best.0 {
493 best = (sad, dx, dy);
494 }
495 }
496 }
497 let k = (1 << top) as f32;
498 (best.1 as f32 * k, best.2 as f32 * k)
499}
500
501/// BT.601 luma of a BGRA picture, one byte a pixel.
502pub fn luma_from_bgra(bgra: &[u8], w: usize, h: usize) -> Vec<u8> {
503 bgra.as_chunks::<4>()
504 .0
505 .iter()
506 .take(w * h)
507 .map(|p| ((29 * u32::from(p[0]) + 150 * u32::from(p[1]) + 77 * u32::from(p[2])) >> 8) as u8)
508 .collect()
509}
510
511/// The motion between two `w` x `h` luma pictures: the similarity taking a point
512/// of `a` to where it is in `b`, on pixel coordinates centred on the picture.
513/// `None` where too little of the picture could be tracked.
514pub fn estimate(a: &[u8], b: &[u8], w: usize, h: usize) -> Option<Sim> {
515 motion(&Pyramid::of(a, w, h)?, &Pyramid::of(b, w, h)?)
516}
517
518// ---- the stored analysis --------------------------------------------------
519
520/// One source range's measured motion: `steps[i]` takes frame `lo + i - 1` to
521/// frame `lo + i` (the first is the identity), in centred pixels of a picture
522/// `w` x `h`.
523#[derive(Clone, Debug, PartialEq)]
524pub struct Track {
525 pub w: u32,
526 pub h: u32,
527 pub lo: u32,
528 pub steps: Vec<Sim>,
529}
530
531impl Track {
532 fn to_bytes(&self) -> Vec<u8> {
533 let mut out = MAGIC.to_vec();
534 for v in [self.w, self.h, self.lo, self.steps.len() as u32] {
535 out.extend_from_slice(&v.to_le_bytes());
536 }
537 for s in &self.steps {
538 for v in [s.a, s.b, s.tx, s.ty] {
539 out.extend_from_slice(&v.to_le_bytes());
540 }
541 }
542 out
543 }
544
545 fn from_bytes(b: &[u8]) -> Option<Track> {
546 let rest = b.strip_prefix(MAGIC)?;
547 let u = |i: usize| rest.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes(s.try_into().expect("4")));
548 let (w, h, lo, n) = (u(0)?, u(1)?, u(2)?, u(3)? as usize);
549 let body = &rest[16..];
550 if body.len() != n * 32 {
551 return None;
552 }
553 let f = |i: usize| f64::from_le_bytes(body[i * 8..i * 8 + 8].try_into().expect("8"));
554 let steps = (0..n).map(|k| Sim { a: f(4 * k), b: f(4 * k + 1), tx: f(4 * k + 2), ty: f(4 * k + 3) }).collect();
555 Some(Track { w, h, lo, steps })
556 }
557}
558
559/// Measures the motion of source frames `lo..hi` of `path`. `progress` is set in
560/// thousandths of the range done; a set `cancel` stops it with an error.
561///
562/// The frames measured are the very planes a layer's decoder hands the warp
563/// ([`crate::export::each_layer_luma`]): the file's own, before its display turn
564/// and pixel stretch, so the maps and the pictures they move share their axes.
565pub fn analyse(path: &Path, lo: u32, hi: u32, progress: &AtomicU32, cancel: &AtomicBool) -> crate::Result<Track> {
566 if hi <= lo {
567 return Err("nothing to analyse: the range is empty".into());
568 }
569 let count = crate::demux::Demuxer::open(path)?.0.frame_count;
570 let hi = hi.min(count.max(lo + 1));
571 let mut steps: Vec<Sim> = Vec::with_capacity((hi - lo) as usize);
572 let mut prev: Option<Pyramid> = None;
573 let mut size = (0, 0);
574 let mut stopped = false;
575 crate::export::each_layer_luma(path, lo, hi, |index, y, width, height| {
576 if cancel.load(Ordering::Relaxed) {
577 stopped = true;
578 return false;
579 }
580 let (w, h) = (width as usize, height as usize);
581 let pyr = Pyramid::of(&y[..w * h], w, h);
582 let step = match (&prev, &pyr) {
583 (Some(a), Some(b)) if size == (width, height) => motion(a, b).unwrap_or(Sim::IDENTITY),
584 _ => Sim::IDENTITY,
585 };
586 // The first frame is where the path starts: no step into it.
587 steps.push(if steps.is_empty() { Sim::IDENTITY } else { step });
588 size = (width, height);
589 prev = pyr;
590 progress.store(((index + 1 - lo) as u64 * 1000 / u64::from(hi - lo)) as u32, Ordering::Relaxed);
591 true
592 })?;
593 if stopped {
594 return Err("stabilise analysis cancelled".into());
595 }
596 if steps.is_empty() {
597 return Err("the source gave no pictures to analyse".into());
598 }
599 // A file shorter than its header says holds its last frame still.
600 while steps.len() < (hi - lo) as usize {
601 steps.push(Sim::IDENTITY);
602 }
603 progress.store(1000, Ordering::Relaxed);
604 Ok(Track { w: size.0, h: size.1, lo, steps })
605}
606
607// ---- smoothing and the correction ------------------------------------------
608
609/// Gaussian smoothing of `xs` with point-reflected ends, which keeps a straight
610/// line straight.
611pub(crate) fn smooth(xs: &[f64], sigma: f64) -> Vec<f64> {
612 let n = xs.len();
613 if n < 2 || sigma <= 0.0 {
614 return xs.to_vec();
615 }
616 let r = (3.0 * sigma).ceil() as i64;
617 let kernel: Vec<f64> = (-r..=r).map(|i| (-(i * i) as f64 / (2.0 * sigma * sigma)).exp()).collect();
618 let total: f64 = kernel.iter().sum();
619 let last = n as i64 - 1;
620 let at = |i: i64| -> f64 {
621 // Point reflection about the end samples, repeated for a kernel wider
622 // than the clip: x[-i] = 2 x[0] - x[i], x[n-1+i] = 2 x[n-1] - x[n-1-i].
623 let (mut i, mut off, mut sign) = (i, 0.0, 1.0);
624 loop {
625 if i < 0 {
626 off += sign * 2.0 * xs[0];
627 sign = -sign;
628 i = -i;
629 } else if i > last {
630 off += sign * 2.0 * xs[last as usize];
631 sign = -sign;
632 i = 2 * last - i;
633 } else {
634 return off + sign * xs[i as usize];
635 }
636 }
637 };
638 (0..n as i64)
639 .map(|k| kernel.iter().zip(-r..=r).map(|(w, i)| w * at(k + i)).sum::<f64>() / total)
640 .collect()
641}
642
643/// The per-frame correction of one analysed range at one setting: for each file
644/// frame, the map from a centred pixel of the stabilised picture to the centred
645/// pixel of the decoded one it shows, zoom included.
646#[derive(Clone, Debug)]
647pub struct Correction {
648 lo: u32,
649 w: u32,
650 h: u32,
651 maps: Vec<Sim>,
652 /// The enlargement [`Crop::Zoom`] chose, `1.0` for [`Crop::Full`].
653 pub zoom: f64,
654}
655
656impl Correction {
657 /// The map for file frame `frame` on a `w`-wide picture (the analysed size or
658 /// any other, a stand-in's), or `None` before the analysed range. A frame past
659 /// its end -- a file longer than its header said -- keeps the last map.
660 pub fn at(&self, frame: u32, w: u32) -> Option<Sim> {
661 let i = (frame.checked_sub(self.lo)? as usize).min(self.maps.len().checked_sub(1)?);
662 let m = self.maps[i];
663 Some(m.scaled(f64::from(w) / f64::from(self.w.max(1))))
664 }
665
666 /// The analysed picture's size.
667 pub fn size(&self) -> (u32, u32) {
668 (self.w, self.h)
669 }
670}
671
672/// The correction `track` gives at `s`, for a source at `fps` frames a second.
673pub fn correct(track: &Track, s: Stabilise, fps: f64) -> Correction {
674 let mut path = Vec::with_capacity(track.steps.len());
675 let mut c = Sim::IDENTITY;
676 for (i, step) in track.steps.iter().enumerate() {
677 if i > 0 {
678 c = c.then(*step);
679 }
680 path.push(c);
681 }
682 let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };
683 let sigma = (f64::from(s.amount()) * 2.0 * fps).max(0.5);
684 let mut params: [Vec<f64>; 4] = Default::default();
685 let mut unwrap = 0.0f64;
686 let mut prev_angle = 0.0;
687 for m in &path {
688 let mut p = m.params();
689 // Keep the angle continuous past a half turn.
690 let mut a = p[0] + unwrap;
691 while a - prev_angle > std::f64::consts::PI {
692 a -= 2.0 * std::f64::consts::PI;
693 unwrap -= 2.0 * std::f64::consts::PI;
694 }
695 while a - prev_angle < -std::f64::consts::PI {
696 a += 2.0 * std::f64::consts::PI;
697 unwrap += 2.0 * std::f64::consts::PI;
698 }
699 prev_angle = a;
700 p[0] = a;
701 for (dst, v) in params.iter_mut().zip(p) {
702 dst.push(v);
703 }
704 }
705 let smoothed: Vec<Vec<f64>> = params.iter().map(|xs| smooth(xs, sigma)).collect();
706 let maps: Vec<Sim> = path
707 .iter()
708 .enumerate()
709 .map(|(k, c)| {
710 let sm = Sim::from_params([smoothed[0][k], smoothed[1][k], smoothed[2][k], smoothed[3][k]]);
711 sm.inverse().then(*c)
712 })
713 .collect();
714 let zoom = match s.crop() {
715 Crop::Full => 1.0,
716 Crop::Zoom => maps.iter().map(|m| zoom_for(m, track.w, track.h)).fold(1.0, f64::max),
717 };
718 let maps = maps.into_iter().map(|m| Sim { a: m.a / zoom, b: m.b / zoom, ..m }).collect();
719 Correction { lo: track.lo, w: track.w, h: track.h, maps, zoom }
720}
721
722/// The least enlargement `z` for which `m(p / z)` stays inside a `w` x `h`
723/// picture for every `p` of it, capped at [`MAX_ZOOM`].
724fn zoom_for(m: &Sim, w: u32, h: u32) -> f64 {
725 let (hw, hh) = ((f64::from(w) - 1.0) / 2.0, (f64::from(h) - 1.0) / 2.0);
726 // The corners map to u * (R c) + t with u = 1 / z; each picture edge bounds u.
727 let mut u: f64 = 1.0;
728 for (cx, cy) in [(-hw, -hh), (hw, -hh), (-hw, hh), (hw, hh)] {
729 let r = Sim { tx: 0.0, ty: 0.0, ..*m }.apply(cx, cy);
730 for (a, t, lim) in [(r.0, m.tx, hw), (r.1, m.ty, hh)] {
731 if a > 1e-9 {
732 u = u.min((lim - t) / a);
733 } else if a < -1e-9 {
734 u = u.min((-lim - t) / a);
735 }
736 }
737 }
738 if u <= 1.0 / MAX_ZOOM { MAX_ZOOM } else { (1.0 / u).max(1.0) }
739}
740
741// ---- applying it ----------------------------------------------------------
742
743/// Draws the stabilised picture: each pixel of the `w` x `h` I420 output is the
744/// bilinear sample of the input at `m` of its centred position (chroma at half
745/// the shift). Outside the input is black.
746#[allow(clippy::too_many_arguments)]
747pub fn warp_i420<T: crate::scale::Sample>(y: &[T], u: &[T], v: &[T], w: u32, h: u32, m: Sim, out: &mut (Vec<T>, Vec<T>, Vec<T>)) {
748 let (w, h) = (w as usize, h as usize);
749 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
750 out.0.resize(w * h, T::BLACK);
751 out.1.resize(cw * ch, T::NEUTRAL);
752 out.2.resize(cw * ch, T::NEUTRAL);
753 let half = Sim { tx: m.tx / 2.0, ty: m.ty / 2.0, ..m };
754 std::thread::scope(|s| {
755 s.spawn(|| warp_plane(y, w, h, m, T::BLACK, &mut out.0));
756 s.spawn(|| warp_plane(u, cw, ch, half, T::NEUTRAL, &mut out.1));
757 warp_plane(v, cw, ch, half, T::NEUTRAL, &mut out.2);
758 });
759}
760
761fn warp_plane<T: crate::scale::Sample>(src: &[T], w: usize, h: usize, m: Sim, black: T, dst: &mut [T]) {
762 let (cx, cy) = ((w as f64 - 1.0) / 2.0, (h as f64 - 1.0) / 2.0);
763 let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 8);
764 let rows = h.div_ceil(threads).max(1);
765 std::thread::scope(|s| {
766 for (chunk, part) in dst.chunks_mut(rows * w).enumerate() {
767 s.spawn(move || {
768 for (r, line) in part.chunks_mut(w).enumerate() {
769 let oy = (chunk * rows + r) as f64 - cy;
770 let (mut sx, mut sy) = m.apply(-cx, oy);
771 (sx, sy) = (sx + cx, sy + cy);
772 let (dx, dy) = (m.a, m.b);
773 for px in line.iter_mut() {
774 *px = sample(src, w, h, sx, sy).unwrap_or(black);
775 sx += dx;
776 sy += dy;
777 }
778 }
779 });
780 }
781 });
782}
783
784#[inline]
785fn sample<T: crate::scale::Sample>(src: &[T], w: usize, h: usize, x: f64, y: f64) -> Option<T> {
786 if x < -0.5 || y < -0.5 || x > w as f64 - 0.5 || y > h as f64 - 0.5 {
787 return None;
788 }
789 let x = x.clamp(0.0, (w - 1) as f64);
790 let y = y.clamp(0.0, (h - 1) as f64);
791 let (x0, y0) = (x as usize, y as usize);
792 let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
793 let (fx, fy) = ((x - x0 as f64) as f32, (y - y0 as f64) as f32);
794 let p = |xx: usize, yy: usize| src[yy * w + xx].code() as f32;
795 let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * fx;
796 let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * fx;
797 Some(T::from_code((top + (bot - top) * fy + 0.5) as u32))
798}
799
800// ---- the cache ------------------------------------------------------------
801
802/// The source's identity: its canonical path, length and modification time, as
803/// a proxy's name is made ([`crate::proxy::path_for`]).
804fn source_key(source: &Path) -> Option<u64> {
805 let meta = std::fs::metadata(source).ok()?;
806 let mtime = meta.modified().ok()?.duration_since(UNIX_EPOCH).map_or((0, 0), |d| (d.as_secs(), d.subsec_nanos()));
807 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());
808 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();
809 bytes.extend_from_slice(&meta.len().to_le_bytes());
810 bytes.extend_from_slice(&mtime.0.to_le_bytes());
811 bytes.extend_from_slice(&mtime.1.to_le_bytes());
812 bytes.extend_from_slice(&ALGO.to_le_bytes());
813 Some(crate::demux::fnv1a(&bytes))
814}
815
816fn cache_dir() -> Option<PathBuf> {
817 crate::demux::cache_dir(crate::envcfg::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"), "stabilise")
818}
819
820/// Where the analysis of source frames `lo..hi` of `source` is kept.
821pub fn cache_path(source: &Path, lo: u32, hi: u32) -> Option<PathBuf> {
822 Some(cache_dir()?.join(format!("{:016x}-{lo}-{hi}.stab", source_key(source)?)))
823}
824
825/// A finished analysis of `source` that covers `lo..hi`: the exact range, or the
826/// smallest wider one (a clip trimmed after it was analysed).
827fn find(source: &Path, lo: u32, hi: u32) -> Option<PathBuf> {
828 let exact = cache_path(source, lo, hi)?;
829 if exact.is_file() {
830 return Some(exact);
831 }
832 let prefix = format!("{:016x}-", source_key(source)?);
833 let mut best: Option<(u32, PathBuf)> = None;
834 for e in std::fs::read_dir(cache_dir()?).ok()?.flatten() {
835 let name = e.file_name();
836 let Some(rest) = name.to_str().and_then(|n| n.strip_prefix(&prefix)).and_then(|n| n.strip_suffix(".stab")) else {
837 continue;
838 };
839 let Some((a, b)) = rest.split_once('-') else { continue };
840 let (Ok(a), Ok(b)) = (a.parse::<u32>(), b.parse::<u32>()) else { continue };
841 if a <= lo && hi <= b && best.as_ref().is_none_or(|(span, _)| b - a < *span) {
842 best = Some((b - a, e.path()));
843 }
844 }
845 best.map(|(_, p)| p)
846}
847
848fn write_track(path: &Path, t: &Track) -> std::io::Result<()> {
849 if let Some(dir) = path.parent() {
850 std::fs::create_dir_all(dir)?;
851 }
852 let part = path.with_extension("part");
853 std::fs::write(&part, t.to_bytes())?;
854 std::fs::rename(&part, path)
855}
856
857/// The analysis covering `lo..hi` of `source`, read from the cache.
858pub fn cached_track(source: &Path, lo: u32, hi: u32) -> Option<Track> {
859 Track::from_bytes(&std::fs::read(find(source, lo, hi)?).ok()?)
860}
861
862/// The correction of source frames `lo..hi` of `source` at `s`, from a finished
863/// analysis, or `None` while there is none. Remembered per analysis file and
864/// setting, so a renderer reopening a span pays for it once.
865pub fn correction(source: &Path, lo: u32, hi: u32, s: Stabilise, fps: f64) -> Option<Arc<Correction>> {
866 type Memo = Mutex<HashMap<(PathBuf, u32, Crop, u64), Arc<Correction>>>;
867 static MEMO: OnceLock<Memo> = OnceLock::new();
868 let file = find(source, lo, hi)?;
869 let key = (file.clone(), u32::from(s.0.get()), s.crop(), fps.to_bits());
870 let memo = MEMO.get_or_init(Default::default);
871 if let Some(c) = memo.lock().ok()?.get(&key) {
872 return Some(c.clone());
873 }
874 let track = Track::from_bytes(&std::fs::read(&file).ok()?)?;
875 let c = Arc::new(correct(&track, s, fps));
876 let mut m = memo.lock().ok()?;
877 if m.len() > 64 {
878 m.clear();
879 }
880 m.insert(key, c.clone());
881 Some(c)
882}
883
884/// [`correction`] without waiting, for a picture that must come at once (the
885/// viewer, a still): `None` while none is finished, and the analysis is started
886/// in the background when none was asked for yet -- not again after a failure,
887/// which the editor says and retries on request.
888pub fn correction_or_start(source: &Path, lo: u32, hi: u32, s: Stabilise, fps: f64) -> Option<Arc<Correction>> {
889 let c = correction(source, lo, hi, s, fps);
890 if c.is_none() && status(source, lo, hi) == Status::Missing {
891 start(source, lo, hi);
892 }
893 c
894}
895
896/// [`correction`], analysing first when no finished analysis covers `lo..hi`:
897/// what an export asks, which must never write a stabilised clip unstabilised.
898/// An analysis already running for the range (the one the editor started) is
899/// waited on rather than run twice; `cancel` stops the waiting, not that job.
900/// `progress` is told the fraction measured, `0.0..=1.0`, while it waits; it is
901/// never called when a finished analysis was there. Every way it can fail is an
902/// error that names the file.
903pub fn ensure(
904 source: &Path,
905 lo: u32,
906 hi: u32,
907 s: Stabilise,
908 fps: f64,
909 progress: &mut dyn FnMut(f32),
910 cancel: &AtomicBool,
911) -> crate::Result<Arc<Correction>> {
912 let named = |why: String| -> crate::Error { format!("cannot stabilise {}: {why}", source.display()).into() };
913 if let Some(c) = correction(source, lo, hi, s, fps) {
914 return Ok(c);
915 }
916 let mut now = start(source, lo, hi);
917 while let Status::Running(done) = now {
918 if cancel.load(Ordering::Relaxed) {
919 return Err(named("cancelled while its motion was being measured".into()));
920 }
921 progress(done);
922 std::thread::sleep(std::time::Duration::from_millis(20));
923 now = status(source, lo, hi);
924 }
925 match now {
926 Status::Ready => correction(source, lo, hi, s, fps)
927 .ok_or_else(|| named("its finished analysis cannot be read back from the cache".into())),
928 Status::Failed(e) => Err(named(e)),
929 Status::Missing | Status::Running(_) => Err(named("its analysis did not start".into())),
930 }
931}
932
933// ---- background jobs --------------------------------------------------------
934
935/// Where one source range's analysis stands.
936#[derive(Clone, Debug, PartialEq)]
937pub enum Status {
938 /// Finished and cached.
939 Ready,
940 /// Running, this fraction done.
941 Running(f32),
942 /// Stopped by an error or a cancel; [`start`] tries again.
943 Failed(String),
944 /// Never asked for.
945 Missing,
946}
947
948struct Job {
949 progress: AtomicU32,
950 cancel: AtomicBool,
951 outcome: Mutex<Option<Result<(), String>>>,
952}
953
954fn jobs() -> &'static Mutex<HashMap<PathBuf, Arc<Job>>> {
955 static JOBS: OnceLock<Mutex<HashMap<PathBuf, Arc<Job>>>> = OnceLock::new();
956 JOBS.get_or_init(Default::default)
957}
958
959/// Where the analysis of `lo..hi` of `source` stands.
960pub fn status(source: &Path, lo: u32, hi: u32) -> Status {
961 let Some(key) = cache_path(source, lo, hi) else {
962 return Status::Failed("the source cannot be read, or there is no cache directory".into());
963 };
964 let job = jobs().lock().ok().and_then(|j| j.get(&key).cloned());
965 // A job holds its outcome lock while it writes the file, so the file and the
966 // outcome are seen together: never a file that is there before the job says it
967 // is done (which would read as running once the file is cleared).
968 let outcome = job.as_ref().map(|j| j.outcome.lock().ok().and_then(|o| o.clone()));
969 if find(source, lo, hi).is_some() {
970 return Status::Ready;
971 }
972 match (job, outcome) {
973 (Some(job), Some(None)) => Status::Running(job.progress.load(Ordering::Relaxed) as f32 / 1000.0),
974 // Finished, but its file is gone (a cleared cache): measured again on start.
975 (Some(_), Some(Some(Ok(())))) | (None, _) | (Some(_), None) => Status::Missing,
976 (Some(_), Some(Some(Err(e)))) => Status::Failed(e),
977 }
978}
979
980/// Starts analysing `lo..hi` of `source` in the background unless it is cached
981/// or already running, and says where it stands.
982pub fn start(source: &Path, lo: u32, hi: u32) -> Status {
983 match status(source, lo, hi) {
984 s @ (Status::Ready | Status::Running(_)) => return s,
985 Status::Failed(_) | Status::Missing => {}
986 }
987 let Some(key) = cache_path(source, lo, hi) else {
988 return status(source, lo, hi);
989 };
990 let job = Arc::new(Job { progress: AtomicU32::new(0), cancel: AtomicBool::new(false), outcome: Mutex::new(None) });
991 // The check and the insert share one lock, so two starts cannot both see the range as missing.
992 let mut map = jobs().lock().unwrap_or_else(|e| e.into_inner());
993 if let Some(running) = map.get(&key).filter(|j| j.outcome.lock().unwrap_or_else(|e| e.into_inner()).is_none()) {
994 return Status::Running(running.progress.load(Ordering::Relaxed) as f32 / 1000.0);
995 }
996 map.insert(key.clone(), job.clone());
997 drop(map);
998 let source = source.to_path_buf();
999 std::thread::spawn(move || {
1000 let measured = analyse(&source, lo, hi, &job.progress, &job.cancel);
1001 // Written and recorded under one lock, so [`status`] sees both or neither.
1002 let mut o = job.outcome.lock().unwrap_or_else(|e| e.into_inner());
1003 *o = Some(measured.and_then(|t| write_track(&key, &t).map_err(Into::into)).map_err(|e| e.to_string()));
1004 });
1005 Status::Running(0.0)
1006}
1007
1008/// Stops a running analysis of `lo..hi` of `source`. `false` when none runs.
1009pub fn cancel(source: &Path, lo: u32, hi: u32) -> bool {
1010 let Some(key) = cache_path(source, lo, hi) else { return false };
1011 let Some(job) = jobs().lock().ok().and_then(|j| j.get(&key).cloned()) else { return false };
1012 let running = job.outcome.lock().is_ok_and(|o| o.is_none());
1013 job.cancel.store(true, Ordering::Relaxed);
1014 running
1015}
1016
1017/// Waits for the analysis of `lo..hi` of `source` to finish, starting it if it
1018/// is not running, and says how it ended.
1019pub fn wait(source: &Path, lo: u32, hi: u32) -> Status {
1020 let mut s = start(source, lo, hi);
1021 while let Status::Running(_) = s {
1022 std::thread::sleep(std::time::Duration::from_millis(20));
1023 s = status(source, lo, hi);
1024 }
1025 s
1026}
1027
1028/// The source frames `lo..hi` a clip plays, in the file's own numbering, for a
1029/// source at `rate` against the timeline ([`crate::project::Rate`]).
1030pub fn file_range(clip: &crate::project::Clip, rate: crate::project::Rate) -> (u32, u32) {
1031 let lo = rate.source_at(clip.in_frame);
1032 let hi = rate.source_at(clip.out_frame.saturating_sub(1)) + 1;
1033 (lo, hi.max(lo + 1))
1034}
1035
1036/// [`file_range`] for a clip of the source at `source`, on a timeline at `fps`:
1037/// the file's own rate read from its header (remembered per path).
1038pub fn clip_range(source: &Path, clip: &crate::project::Clip, fps: f64) -> (u32, u32) {
1039 static RATES: OnceLock<Mutex<HashMap<PathBuf, f64>>> = OnceLock::new();
1040 let rates = RATES.get_or_init(Default::default);
1041 let known = rates.lock().ok().and_then(|r| r.get(source).copied());
1042 let file_fps = known.or_else(|| {
1043 let f = crate::demux::Demuxer::open(source).ok()?.0.frame_rate;
1044 if let Ok(mut r) = rates.lock() {
1045 r.insert(source.to_path_buf(), f);
1046 }
1047 Some(f)
1048 });
1049 let rate = file_fps
1050 .and_then(|f| crate::project::Rate::from_fps(f, fps).ok())
1051 .unwrap_or(crate::project::Rate::REAL_TIME);
1052 file_range(clip, rate)
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058
1059 #[test]
1060 fn a_setting_packs_into_one_byte_and_reads_back() {
1061 assert_eq!(std::mem::size_of::<Option<Stabilise>>(), 1);
1062 for (p, c) in [(0, Crop::Zoom), (100, Crop::Zoom), (0, Crop::Full), (37, Crop::Full), (100, Crop::Full)] {
1063 let s = Stabilise::with_percent(p, c);
1064 assert_eq!((s.strength(), s.crop()), (p, c));
1065 }
1066 assert_eq!(Stabilise::new(0.756, Crop::Zoom).strength(), 76);
1067 assert_eq!(Stabilise::with_percent(250, Crop::Full).strength(), 100);
1068 }
1069
1070 #[test]
1071 fn smoothing_keeps_a_straight_line() {
1072 let xs: Vec<f64> = (0..50).map(|i| 3.0 + 2.0 * f64::from(i)).collect();
1073 for (a, b) in smooth(&xs, 20.0).iter().zip(&xs) {
1074 assert!((a - b).abs() < 1e-9, "{a} vs {b}");
1075 }
1076 }
1077
1078 #[test]
1079 fn sim_inverse_and_compose() {
1080 let m = Sim::from_params([0.1, 0.02, 5.0, -3.0]);
1081 let id = m.then(m.inverse());
1082 assert!((id.a - 1.0).abs() < 1e-12 && id.b.abs() < 1e-12 && id.tx.abs() < 1e-9 && id.ty.abs() < 1e-9);
1083 }
1084
1085 #[test]
1086 fn track_round_trips_its_bytes() {
1087 let t = Track { w: 640, h: 360, lo: 7, steps: vec![Sim::IDENTITY, Sim::from_params([0.01, 0.0, 1.5, -2.0])] };
1088 assert_eq!(Track::from_bytes(&t.to_bytes()), Some(t));
1089 }
1090
1091 #[test]
1092 fn zoom_hides_a_shift() {
1093 // A 10 px shift on a 101 px wide picture: the corner at 50 lands at 50 / z + 10,
1094 // inside the 50 half-width for z = 50 / 40 = 1.25.
1095 let z = zoom_for(&Sim { tx: 10.0, ..Sim::IDENTITY }, 101, 101);
1096 assert!((z - 1.25).abs() < 1e-9, "{z}");
1097 assert_eq!(zoom_for(&Sim::IDENTITY, 100, 100), 1.0);
1098 }
1099
1100 #[test]
1101 fn warp_by_identity_is_a_copy_and_a_shift_moves_the_picture() {
1102 let (w, h) = (16u32, 8u32);
1103 let y: Vec<u8> = (0..w * h).map(|i| (i % w * 10) as u8).collect();
1104 let c = vec![128u8; 8 * 4];
1105 let mut out = Default::default();
1106 warp_i420(&y, &c, &c, w, h, Sim::IDENTITY, &mut out);
1107 assert_eq!(out.0, y);
1108 warp_i420(&y, &c, &c, w, h, Sim { tx: 1.0, ..Sim::IDENTITY }, &mut out);
1109 assert_eq!(out.0[0], y[1], "each pixel shows the one to its right");
1110 assert_eq!(out.0[w as usize - 1], 16, "the right edge ran off the picture");
1111 }
1112
1113 #[test]
1114 fn warp_keeps_ten_bit_codes() {
1115 let (w, h) = (16u32, 8u32);
1116 let y: Vec<u16> = (0..w * h).map(|i| 64 + (i % w * 50) as u16).collect();
1117 let c = vec![512u16; 8 * 4];
1118 let mut out = Default::default();
1119 warp_i420(&y, &c, &c, w, h, Sim::IDENTITY, &mut out);
1120 assert_eq!(out.0, y);
1121 warp_i420(&y, &c, &c, w, h, Sim { tx: 0.5, ..Sim::IDENTITY }, &mut out);
1122 assert_eq!(out.0[0], 89, "half way between 64 and 114, kept at 10 bits");
1123 }
1124}