forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

scenes.rs807 lines, 33.2 KiBHistoryRawDownload
1//! Shot-change detection on a source file: where the picture cuts, and where it
2//! fades through black. Headless; no UI, no export, no project.
3//!
4//! The pipeline is one decode pass over the file (or the range asked for):
5//!
6//! 1. Each analysed frame is reduced to a 64x36 luma thumbnail (point samples at
7//! cell centres, so the cost per frame is a few thousand reads, not a full
8//! pass over the picture) and a coarse chroma histogram (U and V each
9//! quantised to 8 levels, 64 bins, normalised to sum to 1).
10//! 2. Consecutive analysed frames are scored `0.5 * mad + 0.5 * hist`, where
11//! `mad` is the mean absolute luma difference over 255 and `hist` is the
12//! intersection distance `1 - sum(min(a, b))` between the two chroma
13//! histograms (equal to half their L1 distance). Both terms are in `0..=1`, so
14//! the score is too.
15//! 3. A pair is a hard cut when its score is at least the user threshold **and**
16//! at least [`ADAPT`] times the median of the previous [`WINDOW`] scores. The
17//! second test is the adaptive part: in a busy shot a large but ordinary
18//! change (a pan, a flash, a fast cut-in-motion) sits near its neighbours'
19//! median and is not a cut; a spike that stands out from the local activity
20//! is. The median is over raw scores, so one earlier cut does not raise the bar
21//! for the next one.
22//! 4. A run of at least [`BLACK_RUN`] consecutive analysed frames whose mean luma
23//! is below [`BLACK_LUMA`] (of 255) is a fade to and from black. It is reported
24//! once, at the first picture frame after the dark run, as a cut with score `1.0` and kind
25//! [`CutKind::FadeBlack`]. Hard cuts at its two edges are the same boundary
26//! seen again and are dropped. A dissolve that never gets dark is not a fade
27//! here; it is scored like any other change.
28//! 5. Candidates closer together than the minimum shot length collapse into the
29//! stronger one (a fade beats a hard cut at equal distance).
30//!
31//! `sample_fps` decimates the analysis, not the decode: a compressed stream has
32//! to be decoded frame by frame regardless, so the saving is in the reduction and
33//! scoring. With a cached proxy ([`crate::proxy::cached`]) the decode is the
34//! cheaper all-intra half-size copy, and the proxy is used when its frame count
35//! matches the source's, so its frame numbers are the source's.
36//!
37//! Positions are the first frame of the new shot. With `sample_fps: None` every
38//! frame is analysed, so that is exact. With a decimated analysis each candidate
39//! is refined by decoding the frames between its two samples and taking the one
40//! whose change is largest (or, for a fade, the first picture frame), so it is
41//! exact too, at the cost of a short extra decode per cut.
42
43use std::collections::VecDeque;
44use std::path::Path;
45use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
46use std::sync::mpsc::Receiver;
47use std::sync::Arc;
48
49use crate::decode::{DecodeSession, Frame};
50use crate::demux::{Demuxer, VideoMeta};
51
52/// Thumbnail grid the frames are reduced to.
53pub const THUMB_W: usize = 64;
54pub const THUMB_H: usize = 36;
55/// Coarse chroma histogram: 8 levels of U by 8 levels of V.
56const BINS: usize = 64;
57/// Rolling window of raw scores the adaptive threshold takes its median from.
58const WINDOW: usize = 8;
59/// A hard cut must stand this many times above the window's median.
60const ADAPT: f32 = 2.0;
61/// Mean luma (of 255) under which a frame counts as black.
62pub const BLACK_LUMA: f32 = 16.0;
63/// Consecutive black analysed frames that make a fade.
64pub const BLACK_RUN: usize = 3;
65/// Files longer than this get [`LONG_FILE_SAMPLE_FPS`] from [`SceneSettings::for_duration`].
66pub const LONG_FILE_SECS: f64 = 60.0;
67pub const LONG_FILE_SAMPLE_FPS: f64 = 10.0;
68pub const DEFAULT_THRESHOLD: f32 = 0.35;
69pub const DEFAULT_MIN_SHOT_SECS: f64 = 0.6;
70/// A dissolve step is a pair of frames whose luma barely moves (mean absolute difference
71/// at most this, over 255) while their colours do (chroma histogram distance at least
72/// [`DISSOLVE_HIST_MIN`]). A cut moves the luma a lot; a pan keeps the colours.
73const DISSOLVE_MAD_MAX: f32 = 0.05;
74const DISSOLVE_HIST_MIN: f32 = 0.03;
75/// Fewest consecutive dissolve steps that make a dissolve.
76const DISSOLVE_MIN_STEPS: usize = 4;
77
78/// How the detector is tuned. Every field is validated by [`detect`].
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct SceneSettings {
81 /// Score a change must reach to be a cut, `0..=1`. Default 0.35.
82 pub threshold: f32,
83 /// Shortest shot the result may contain, in seconds. Default 0.6.
84 pub min_shot_secs: f64,
85 /// Analysed frames per second; `None` analyses every frame.
86 pub sample_fps: Option<f64>,
87}
88
89impl Default for SceneSettings {
90 fn default() -> Self {
91 Self { threshold: DEFAULT_THRESHOLD, min_shot_secs: DEFAULT_MIN_SHOT_SECS, sample_fps: None }
92 }
93}
94
95impl SceneSettings {
96 /// The defaults for a file of `secs` seconds: every frame for a short file,
97 /// [`LONG_FILE_SAMPLE_FPS`] for a long one.
98 pub fn for_duration(secs: f64) -> Self {
99 let sample_fps = (secs > LONG_FILE_SECS).then_some(LONG_FILE_SAMPLE_FPS);
100 Self { sample_fps, ..Self::default() }
101 }
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub enum CutKind {
106 /// A change between two analysed frames.
107 Hard,
108 /// The first picture frame after a run of near-black frames.
109 FadeBlack,
110 /// A change spread over a run of frames: a cross-dissolve. The boundary runs from
111 /// the last frame of the old shot (`Cut::frame`) to the first of the new one (`end`).
112 Dissolve { end: u32 },
113}
114
115/// A shot boundary. `frame` is the first source frame of the new shot (for a dissolve,
116/// the last frame of the old one; see [`CutKind::Dissolve`]).
117#[derive(Clone, Copy, Debug, PartialEq)]
118pub struct Cut {
119 pub frame: u32,
120 pub score: f32,
121 pub kind: CutKind,
122}
123
124/// Detects the cuts in `path`, optionally only in `range` (source frames,
125/// half-open `[from, to)`; `None` is the whole file).
126///
127/// A range is analysed from a window of samples before its start, so the first
128/// changes inside it are judged against the same context a whole-file run has, and
129/// the sample grid is the whole file's. Cuts before `from` are not reported.
130///
131/// `progress`, when given, is set to the percentage of the range analysed
132/// (`0..=100`). `cancel`, when given and set, stops the walk and returns an
133/// error. Returns the cuts in frame order.
134pub fn detect(
135 path: &Path,
136 range: Option<(u32, u32)>,
137 s: &SceneSettings,
138 progress: Option<&AtomicU32>,
139 cancel: Option<&AtomicBool>,
140) -> crate::Result<Vec<Cut>> {
141 validate(s)?;
142 let (from, to) = range.unwrap_or((0, u32::MAX));
143 let (head, _) = Demuxer::open(path)?;
144 let fps = if head.frame_rate.is_finite() && head.frame_rate > 0.0 { head.frame_rate } else { 25.0 };
145 let step = s.sample_fps.map_or(1.0, |sf| (fps / sf).max(1.0));
146 let pre = (WINDOW as f64 * step).ceil() as u32 + 1;
147 let start = from.saturating_sub(pre);
148 let (meta, rx, decoder) = open_analysis(path, start, to)?;
149 let to = to.min(meta.frame_count);
150 if from >= to {
151 decoder.store(true, Ordering::Relaxed);
152 return Ok(Vec::new());
153 }
154 let span = f64::from(to - from);
155 let min_shot = (s.min_shot_secs * fps).ceil().max(0.0) as u32;
156
157 // The first due sample is the first grid point at or after `start`.
158 let mut due = (f64::from(start) / step).ceil() * step;
159 let mut prev: Option<(u32, Thumb)> = None;
160 let mut window: VecDeque<f32> = VecDeque::with_capacity(WINDOW);
161 // (frame, mean luma) of every analysed frame, for the black-run pass.
162 let mut means: Vec<(u32, f32)> = Vec::new();
163 // Each hard candidate with the analysed frame before it, for refinement.
164 let mut hard: Vec<(Cut, u32)> = Vec::new();
165 // The dissolve walked so far, and the dissolves found.
166 let mut run: Option<DissolveRun> = None;
167 let mut dissolves: Vec<Cut> = Vec::new();
168
169 for frame in rx.iter() {
170 if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
171 decoder.store(true, Ordering::Relaxed);
172 return Err("scene detection cancelled".into());
173 }
174 let idx = frame.index;
175 if idx >= to {
176 break;
177 }
178 if f64::from(idx) < due {
179 continue;
180 }
181 due += step;
182 while due <= f64::from(idx) {
183 due += step;
184 }
185 if let Some(p) = progress {
186 let done = (f64::from(idx.saturating_sub(from)) / span * 100.0).clamp(0.0, 100.0);
187 p.store(done as u32, Ordering::Relaxed);
188 }
189 let Some(thumb) = Thumb::of(&frame) else { continue };
190 means.push((idx, thumb.mean));
191 if let Some((prev_idx, before)) = &prev {
192 let raw = score(before, &thumb);
193 let median = median(&window);
194 if raw >= s.threshold && raw >= ADAPT * median && idx >= from {
195 hard.push((Cut { frame: idx, score: raw, kind: CutKind::Hard }, *prev_idx));
196 }
197 if window.len() == WINDOW {
198 window.pop_front();
199 }
200 window.push_back(raw);
201 let (mad, hist) = parts(before, &thumb);
202 if is_dissolve_step(mad, hist, before.mean.min(thumb.mean) < BLACK_LUMA) {
203 let r = run.get_or_insert_with(|| DissolveRun::start(*prev_idx, before));
204 r.push(idx, &thumb);
205 } else if let Some(r) = run.take() {
206 dissolves.extend(r.close(s.threshold));
207 }
208 }
209 prev = Some((idx, thumb));
210 }
211 decoder.store(true, Ordering::Relaxed);
212 if let Some(p) = progress {
213 p.store(100, Ordering::Relaxed);
214 }
215 if let Some(r) = run.take() {
216 dissolves.extend(r.close(s.threshold));
217 }
218
219 let fades = black_runs(&means);
220 // A hard cut on the edge of a black run is the fade itself, seen again.
221 hard.retain(|(c, _)| !fades.iter().any(|f| f.lo <= c.frame && c.frame <= f.hi));
222 // A dissolve inside a fade is the fade's own steps: the fade is the boundary.
223 let fade_win = fps.round().max(1.0) as u32;
224 dissolves.retain(|d| !fades.iter().any(|f| dissolve_in_fade(d, f, fade_win)));
225 // The steps of a dissolve are not cuts; the dissolve is the one boundary.
226 hard.retain(|(c, _)| !dissolves.iter().any(|d| inside_dissolve(d, c.frame)));
227 let mut all: Vec<Cut> = Vec::new();
228 for (c, before) in hard {
229 // A decimated candidate is the first analysed frame of the new shot; the
230 // exact frame is the one whose change from its predecessor is largest.
231 let frame = if step > 1.0 { refine_change(path, before, c.frame).unwrap_or(c.frame) } else { c.frame };
232 all.push(Cut { frame, ..c });
233 }
234 for f in &fades {
235 // A fade is placed at the first picture frame after its dark run.
236 let frame = if step > 1.0 { refine_fade(path, f.lo, f.cut.frame).unwrap_or(f.cut.frame) } else { f.cut.frame };
237 all.push(Cut { frame, ..f.cut });
238 }
239 all.extend(dissolves);
240 all.retain(|c| c.frame >= from && c.frame < to);
241 all.sort_by_key(|c| c.frame);
242 Ok(collapse(all, min_shot))
243}
244
245/// The decoded thumbnails of frames `lo..=hi` of the source, in order.
246fn thumbs(path: &Path, lo: u32, hi: u32) -> Option<Vec<(u32, Thumb)>> {
247 let (_, rx, cancel) = DecodeSession::open_range(path, lo, hi.saturating_add(1)).ok()?;
248 let mut out = Vec::new();
249 for frame in rx.iter() {
250 if frame.index > hi {
251 break;
252 }
253 if let Some(t) = Thumb::of(&frame) {
254 out.push((frame.index, t));
255 }
256 }
257 cancel.store(true, Ordering::Relaxed);
258 Some(out)
259}
260
261/// The frame in `(lo, hi]` where the picture changes most from the frame before it.
262fn refine_change(path: &Path, lo: u32, hi: u32) -> Option<u32> {
263 let frames = thumbs(path, lo, hi)?;
264 let mut best: Option<(f32, u32)> = None;
265 for pair in frames.windows(2) {
266 let sc = score(&pair[0].1, &pair[1].1);
267 if best.is_none_or(|(b, _)| sc > b) {
268 best = Some((sc, pair[1].0));
269 }
270 }
271 best.map(|(_, f)| f)
272}
273
274/// The first frame in `(lo, hi]` that is out of the dark run.
275fn refine_fade(path: &Path, lo: u32, hi: u32) -> Option<u32> {
276 thumbs(path, lo, hi)?
277 .into_iter()
278 .find(|(f, t)| *f > lo && t.mean >= BLACK_LUMA)
279 .map(|(f, _)| f)
280}
281
282fn validate(s: &SceneSettings) -> crate::Result<()> {
283 if !(s.threshold.is_finite() && (0.0..=1.0).contains(&s.threshold)) {
284 return Err(format!("threshold must be between 0 and 1, not {}", s.threshold).into());
285 }
286 if !(s.min_shot_secs.is_finite() && s.min_shot_secs >= 0.0) {
287 return Err(format!("min_shot_secs must be 0 or more, not {}", s.min_shot_secs).into());
288 }
289 if let Some(sf) = s.sample_fps && !(sf.is_finite() && sf > 0.0) {
290 return Err(format!("sample_fps must be above 0, not {sf}").into());
291 }
292 Ok(())
293}
294
295/// Opens the frames to analyse: the proxy when one is cached and has the source's
296/// frame count, the source otherwise. Returns the **source's** metadata either
297/// way, and the flag that stops whichever worker is not used.
298fn open_analysis(
299 path: &Path,
300 from: u32,
301 to: u32,
302) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
303 let (meta, rx, cancel) = DecodeSession::open_range(path, from, to)?;
304 if let Some(proxy) = crate::proxy::cached(path)
305 && let Ok((pmeta, prx, pcancel)) = DecodeSession::open_range(&proxy, from, to)
306 {
307 if pmeta.frame_count == meta.frame_count {
308 cancel.store(true, Ordering::Relaxed);
309 return Ok((meta, prx, pcancel));
310 }
311 pcancel.store(true, Ordering::Relaxed);
312 }
313 Ok((meta, rx, cancel))
314}
315
316/// One analysed frame, reduced.
317#[derive(Clone)]
318struct Thumb {
319 /// `THUMB_W * THUMB_H` luma samples, row-major.
320 luma: Vec<u8>,
321 /// Normalised U/V histogram.
322 hist: [f32; BINS],
323 /// Mean of `luma` as a 0..=255 value.
324 mean: f32,
325}
326
327impl Thumb {
328 fn of(f: &Frame) -> Option<Thumb> {
329 let (w, h) = (f.width as usize, f.height as usize);
330 if w == 0 || h == 0 || f.bgra.len() < w * h * 4 {
331 return None;
332 }
333 let mut luma = Vec::with_capacity(THUMB_W * THUMB_H);
334 let mut counts = [0u32; BINS];
335 let mut sum = 0u64;
336 for ty in 0..THUMB_H {
337 let sy = (ty * 2 + 1) * h / (2 * THUMB_H);
338 for tx in 0..THUMB_W {
339 let sx = (tx * 2 + 1) * w / (2 * THUMB_W);
340 let p = (sy * w + sx) * 4;
341 // BGRA in memory.
342 let b = i32::from(f.bgra[p]);
343 let g = i32::from(f.bgra[p + 1]);
344 let r = i32::from(f.bgra[p + 2]);
345 let y = ((77 * r + 150 * g + 29 * b) >> 8).clamp(0, 255);
346 let u = (((-43 * r - 85 * g + 128 * b) >> 8) + 128).clamp(0, 255);
347 let v = (((128 * r - 107 * g - 21 * b) >> 8) + 128).clamp(0, 255);
348 counts[((u >> 5) * 8 + (v >> 5)) as usize] += 1;
349 luma.push(y as u8);
350 sum += y as u64;
351 }
352 }
353 let n = (THUMB_W * THUMB_H) as f32;
354 let mut hist = [0f32; BINS];
355 for (dst, c) in hist.iter_mut().zip(counts) {
356 *dst = c as f32 / n;
357 }
358 Some(Thumb { luma, hist, mean: sum as f32 / n })
359 }
360}
361
362/// Blend of mean absolute luma difference and chroma histogram intersection
363/// distance, in `0..=1`.
364fn score(a: &Thumb, b: &Thumb) -> f32 {
365 let (mad, hist) = parts(a, b);
366 (0.5 * mad + 0.5 * hist).clamp(0.0, 1.0)
367}
368
369/// The two terms of [`score`]: mean absolute luma difference over 255, and the chroma
370/// histogram distance (both `0..=1`).
371fn parts(a: &Thumb, b: &Thumb) -> (f32, f32) {
372 let total: u64 = a
373 .luma
374 .iter()
375 .zip(&b.luma)
376 .map(|(x, y)| u64::from(x.abs_diff(*y)))
377 .sum();
378 let mad = total as f32 / (a.luma.len() as f32 * 255.0);
379 let hist: f32 = 1.0
380 - a.hist
381 .iter()
382 .zip(&b.hist)
383 .map(|(x, y)| x.min(*y))
384 .sum::<f32>();
385 (mad, hist.max(0.0))
386}
387
388/// Whether a pair of frames is one step of a dissolve: the luma barely moves while the
389/// colours do. A hard cut moves the luma a lot; a pan keeps the colours; a fade through black
390/// is dark, and is left to the black-run pass.
391fn is_dissolve_step(mad: f32, hist: f32, dark: bool) -> bool {
392 !dark && mad > 0.0 && mad <= DISSOLVE_MAD_MAX && hist >= DISSOLVE_HIST_MIN
393}
394
395/// A run of consecutive dissolve steps being walked: the frame and thumbnail before its
396/// first step, and the frame and thumbnail after its last one.
397struct DissolveRun {
398 anchor: u32,
399 anchor_thumb: Thumb,
400 last: u32,
401 last_thumb: Thumb,
402 steps: usize,
403}
404
405impl DissolveRun {
406 fn start(anchor: u32, before: &Thumb) -> Self {
407 Self { anchor, anchor_thumb: before.clone(), last: anchor, last_thumb: before.clone(), steps: 0 }
408 }
409
410 fn push(&mut self, idx: u32, thumb: &Thumb) {
411 self.last = idx;
412 self.last_thumb = thumb.clone();
413 self.steps += 1;
414 }
415
416 /// The dissolve this run makes, if it has enough steps and its two ends differ by at least
417 /// the threshold: one boundary from the anchor to the last frame.
418 fn close(self, threshold: f32) -> Option<Cut> {
419 if self.steps < DISSOLVE_MIN_STEPS {
420 return None;
421 }
422 let raw = score(&self.anchor_thumb, &self.last_thumb);
423 (raw >= threshold).then_some(Cut { frame: self.anchor, score: raw, kind: CutKind::Dissolve { end: self.last } })
424 }
425}
426
427/// Whether a dissolve boundary reaches into a fade's window: from its dark run to `win` frames
428/// after its first picture frame.
429fn dissolve_in_fade(d: &Cut, f: &Fade, win: u32) -> bool {
430 d.frame <= f.cut.frame + win && dissolve_end(d) >= f.lo
431}
432
433/// Whether `frame` is one of the steps inside a dissolve (after its first frame, up to its end).
434fn inside_dissolve(d: &Cut, frame: u32) -> bool {
435 frame > d.frame && frame <= dissolve_end(d)
436}
437
438/// The last frame of a dissolve, or its frame for any other kind of cut.
439fn dissolve_end(c: &Cut) -> u32 {
440 match c.kind {
441 CutKind::Dissolve { end } => end,
442 _ => c.frame,
443 }
444}
445
446/// Median of the window, or 0 when it is empty (the first cut of a file is
447/// judged on the threshold alone).
448fn median(window: &VecDeque<f32>) -> f32 {
449 if window.is_empty() {
450 return 0.0;
451 }
452 let mut v: Vec<f32> = window.iter().copied().collect();
453 v.sort_by(|a, b| a.total_cmp(b));
454 let mid = v.len() / 2;
455 if v.len().is_multiple_of(2) { (v[mid - 1] + v[mid]) / 2.0 } else { v[mid] }
456}
457
458/// A fade to black, with the analysed frames on either side of it.
459struct Fade {
460 cut: Cut,
461 /// Frame of the analysed sample before the dark run (or the first dark one).
462 lo: u32,
463 /// Frame of the analysed sample after the dark run (or the last dark one).
464 hi: u32,
465}
466
467/// Runs of at least [`BLACK_RUN`] consecutive dark analysed frames.
468fn black_runs(means: &[(u32, f32)]) -> Vec<Fade> {
469 let mut out = Vec::new();
470 let mut i = 0;
471 while i < means.len() {
472 if means[i].1 >= BLACK_LUMA {
473 i += 1;
474 continue;
475 }
476 let start = i;
477 while i < means.len() && means[i].1 < BLACK_LUMA {
478 i += 1;
479 }
480 let end = i; // exclusive
481 if end - start >= BLACK_RUN {
482 let lo = means[start.saturating_sub(1)].0;
483 let hi = means[end.min(means.len() - 1)].0;
484 out.push(Fade {
485 cut: Cut { frame: hi, score: 1.0, kind: CutKind::FadeBlack },
486 lo,
487 hi,
488 });
489 }
490 }
491 out
492}
493
494/// Keeps the stronger of any two cuts closer than `min_shot` frames.
495fn collapse(sorted: Vec<Cut>, min_shot: u32) -> Vec<Cut> {
496 let mut out: Vec<Cut> = Vec::with_capacity(sorted.len());
497 for c in sorted {
498 if let Some(last) = out.last_mut()
499 && c.frame.saturating_sub(last.frame) < min_shot
500 {
501 // A fade is the boundary itself; it beats a hard cut beside it.
502 let fade_wins = c.kind == CutKind::FadeBlack && last.kind == CutKind::Hard;
503 if c.score > last.score || fade_wins {
504 *last = c;
505 }
506 continue;
507 }
508 out.push(c);
509 }
510 out
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use std::path::PathBuf;
517 use crate::scratch::Scratch;
518 use std::process::Command;
519 use std::time::Instant;
520
521 fn asset(name: &str) -> PathBuf {
522 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
523 }
524
525 /// Three different generated sources back to back, re-encoded as one file.
526 /// Returns the file (which owns its directory, removed on drop) and the
527 /// frame numbers of the two joins.
528 fn three_shots(name: &str, seconds: u32) -> (Scratch, [u32; 2]) {
529 let joined = Scratch::file(name, "mp4");
530 let dir = joined.parent().unwrap().to_path_buf();
531 let parts = [
532 ("testsrc2", dir.join("a.mp4")),
533 ("mandelbrot", dir.join("b.mp4")),
534 ("smptebars", dir.join("c.mp4")),
535 ];
536 for (src, out) in &parts {
537 let lavfi = format!("{src}=size=640x360:rate=25");
538 let ok = Command::new("ffmpeg")
539 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &lavfi, "-t", &seconds.to_string()])
540 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
541 .arg(out)
542 .status()
543 .expect("ffmpeg runs")
544 .success();
545 assert!(ok, "ffmpeg made {src}");
546 }
547 let ok = Command::new("ffmpeg")
548 .args(["-v", "error", "-y"])
549 .args(["-i"]).arg(&parts[0].1)
550 .args(["-i"]).arg(&parts[1].1)
551 .args(["-i"]).arg(&parts[2].1)
552 .args(["-filter_complex", "[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]", "-map", "[v]"])
553 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
554 .arg(&*joined)
555 .status()
556 .expect("ffmpeg runs")
557 .success();
558 assert!(ok, "ffmpeg joined the shots");
559 let per = seconds * 25;
560 (joined, [per, 2 * per])
561 }
562
563 fn near(cuts: &[Cut], want: u32, slack: u32) -> bool {
564 cuts.iter().any(|c| c.frame.abs_diff(want) <= slack && c.kind == CutKind::Hard)
565 }
566
567 #[test]
568 fn finds_the_joins_of_three_sources() {
569 let (path, joins) = three_shots("joins", 2);
570 let cuts = detect(&path, None, &SceneSettings::default(), None, None).unwrap();
571 for j in joins {
572 assert!(near(&cuts, j, 2), "no cut within 2 frames of {j}: {cuts:?}");
573 }
574 assert_eq!(cuts.len(), 2, "exactly the two joins: {cuts:?}");
575 }
576
577 #[test]
578 fn a_range_only_sees_the_cuts_inside_it() {
579 let (path, joins) = three_shots("range", 2);
580 let cuts = detect(&path, Some((joins[0] - 10, joins[0] + 30)), &SceneSettings::default(), None, None).unwrap();
581 assert!(near(&cuts, joins[0], 2), "{cuts:?}");
582 assert!(cuts.iter().all(|c| c.frame < joins[1]), "{cuts:?}");
583 }
584
585 /// A range starting just after a cut sees the same cut as the whole file, at the
586 /// same frame, and nothing the whole file does not see: its first changes are
587 /// judged against the window before the range, not an empty one.
588 #[test]
589 fn a_range_agrees_with_the_whole_file() {
590 let (path, joins) = three_shots("agree", 2);
591 let whole = detect(&path, None, &SceneSettings::default(), None, None).unwrap();
592 for (from, to) in [(joins[0] - 3, joins[0] + 20), (joins[0] + 1, joins[1] + 5), (5, 3 * 50)] {
593 let part = detect(&path, Some((from, to)), &SceneSettings::default(), None, None).unwrap();
594 let want: Vec<u32> = whole.iter().map(|c| c.frame).filter(|&f| f >= from && f < to).collect();
595 let got: Vec<u32> = part.iter().map(|c| c.frame).collect();
596 assert_eq!(got, want, "range {from}..{to}");
597 }
598 }
599
600 #[test]
601 fn a_decimated_run_lands_on_the_first_frame_of_the_new_shot() {
602 let (path, joins) = three_shots("decimated", 2);
603 let s = SceneSettings { sample_fps: Some(4.0), ..SceneSettings::default() };
604 let cuts = detect(&path, None, &s, None, None).unwrap();
605 assert_eq!(cuts.iter().map(|c| c.frame).collect::<Vec<_>>(), joins.to_vec(), "{cuts:?}");
606 }
607
608 #[test]
609 fn a_continuous_shot_has_at_most_one_cut() {
610 let cuts = detect(&asset("test_av.mp4"), None, &SceneSettings::default(), None, None).unwrap();
611 assert!(cuts.len() <= 1, "a single shot should not cut: {cuts:?}");
612 }
613
614 #[test]
615 fn a_fade_through_black_is_one_cut_at_the_first_picture_frame() {
616 let path = Scratch::file("fade", "mp4");
617 // Two seconds of picture, a second of black between them, then picture.
618 let filter = "[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]";
619 let ok = Command::new("ffmpeg")
620 .args(["-v", "error", "-y", "-f", "lavfi", "-t", "2", "-i", "testsrc2=size=320x180:rate=25"])
621 .args(["-f", "lavfi", "-t", "1", "-i", "color=c=black:size=320x180:rate=25"])
622 .args(["-f", "lavfi", "-t", "2", "-i", "mandelbrot=size=320x180:rate=25"])
623 .args(["-filter_complex", filter, "-map", "[v]"])
624 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
625 .arg(&path)
626 .status()
627 .expect("ffmpeg runs")
628 .success();
629 assert!(ok);
630 let cuts = detect(&path, None, &SceneSettings::default(), None, None).unwrap();
631 let fades: Vec<_> = cuts.iter().filter(|c| c.kind == CutKind::FadeBlack).collect();
632 assert_eq!(fades.len(), 1, "{cuts:?}");
633 // The black second is frames 50..75; the picture is back at frame 75.
634 assert!(fades[0].frame.abs_diff(75) <= 1, "{cuts:?}");
635 assert_eq!(fades[0].score, 1.0);
636 }
637
638 /// A flat frame: every luma sample at `level`, and its chroma histogram all in one bin.
639 fn flat(level: f32, bin: usize) -> Thumb {
640 Thumb { luma: vec![level as u8; THUMB_W * THUMB_H], hist: one_bin(bin, 1.0), mean: level }
641 }
642
643 /// A chroma histogram with `w` of its weight in `bin` and the rest in `other`.
644 fn one_bin(bin: usize, w: f32) -> [f32; BINS] {
645 let mut hist = [0f32; BINS];
646 hist[bin] = w;
647 hist[(bin + 1) % BINS] += 1.0 - w;
648 hist
649 }
650
651 /// The dissolve walk of `detect` over a synthetic series of frames: the same steps, run
652 /// and close, with the threshold as given.
653 fn walk(series: &[Thumb], threshold: f32) -> Vec<Cut> {
654 let mut out = Vec::new();
655 let mut run: Option<DissolveRun> = None;
656 for i in 1..series.len() {
657 let (mad, hist) = parts(&series[i - 1], &series[i]);
658 let dark = series[i - 1].mean.min(series[i].mean) < BLACK_LUMA;
659 if is_dissolve_step(mad, hist, dark) {
660 run.get_or_insert_with(|| DissolveRun::start(i as u32 - 1, &series[i - 1])).push(i as u32, &series[i]);
661 } else if let Some(r) = run.take() {
662 out.extend(r.close(threshold));
663 }
664 }
665 if let Some(r) = run.take() {
666 out.extend(r.close(threshold));
667 }
668 out
669 }
670
671 /// Shot A (level 130, chroma bin 5) for 20 frames, then `n` dissolve frames: each one a
672 /// level lower and a little more of the chroma in bin 6, then shot B, which has the level and
673 /// chroma the last dissolve frame has, so the last step is a colour change with no luma change.
674 fn ramp_series(n: usize) -> Vec<Thumb> {
675 let mut s: Vec<Thumb> = (0..20).map(|_| flat(130.0, 5)).collect();
676 for k in 1..=n {
677 let level = 130.0 - k as f32;
678 let w = 1.0 - k as f32 / (n + 1) as f32;
679 s.push(Thumb { luma: vec![level as u8; THUMB_W * THUMB_H], hist: one_bin(5, w), mean: level });
680 }
681 let last = 130.0 - n as f32;
682 s.extend((0..20).map(|_| Thumb { luma: vec![last as u8; THUMB_W * THUMB_H], hist: one_bin(6, 1.0), mean: last }));
683 s
684 }
685
686 #[test]
687 fn a_dissolve_is_one_boundary_from_its_first_frame_to_its_last() {
688 let cuts = walk(&ramp_series(20), 0.35);
689 assert_eq!(cuts.len(), 1, "{cuts:?}");
690 assert_eq!(cuts[0].frame, 19, "{cuts:?}");
691 assert_eq!(cuts[0].kind, CutKind::Dissolve { end: 39 }, "{cuts:?}");
692 }
693
694 /// The same change read at a threshold the ends do not reach is not a dissolve.
695 #[test]
696 fn a_dissolve_below_the_threshold_is_not_reported() {
697 assert!(walk(&ramp_series(20), 0.9).is_empty());
698 }
699
700 /// Three steps are too few to be a dissolve; four are the least that are.
701 #[test]
702 fn a_dissolve_needs_four_steps() {
703 assert!(walk(&ramp_series(3), 0.35).is_empty());
704 assert_eq!(walk(&ramp_series(4), 0.35).len(), 1);
705 }
706
707 /// The luma moves steadily, the colours do not: a pan, not a dissolve.
708 #[test]
709 fn a_pan_is_not_a_dissolve() {
710 let s: Vec<Thumb> = (0..40).map(|i| flat(130.0 - 2.0 * i as f32, 5)).collect();
711 assert!(walk(&s, 0.05).is_empty());
712 }
713
714 /// A hard cut moves the luma a lot in one step: it is not a run of dissolve steps.
715 #[test]
716 fn a_hard_cut_is_not_a_dissolve() {
717 let mut s: Vec<Thumb> = (0..20).map(|_| flat(130.0, 5)).collect();
718 s.extend((0..20).map(|_| flat(40.0, 9)));
719 assert!(walk(&s, 0.05).is_empty());
720 }
721
722 #[test]
723 fn dissolve_steps_are_the_moving_pairs_that_are_not_dark() {
724 // mad 0.0118 (luma 60 over 20 steps), hist 0.05: a step. Dark on either side: not.
725 assert!(is_dissolve_step(0.0118, 0.05, false));
726 assert!(!is_dissolve_step(0.0118, 0.05, true));
727 // A cut (mad 0.4, hist 0.75), a pan (no colour change), and a still frame.
728 assert!(!is_dissolve_step(0.4, 0.75, false));
729 assert!(!is_dissolve_step(0.04, 0.0, false));
730 assert!(!is_dissolve_step(0.0, 0.0, false));
731 }
732
733 /// A dissolve is one boundary: its own steps are not cuts, the frame after it is.
734 #[test]
735 fn the_steps_of_a_dissolve_are_inside_it() {
736 let d = Cut { frame: 19, score: 0.6, kind: CutKind::Dissolve { end: 40 } };
737 assert!(!inside_dissolve(&d, 19));
738 assert!(inside_dissolve(&d, 20));
739 assert!(inside_dissolve(&d, 40));
740 assert!(!inside_dissolve(&d, 41));
741 }
742
743 /// A real two-second xfade dissolve (frames 25 to 50 at 25 fps) is one dissolve boundary at
744 /// the default threshold and at 0.1, where its steps used to read as four cuts.
745 #[test]
746 fn a_real_dissolve_is_one_boundary_at_any_threshold() {
747 let path = Scratch::file("xfade", "mp4");
748 let ok = Command::new("ffmpeg")
749 .args(["-v", "error", "-y", "-f", "lavfi", "-t", "2", "-i", "testsrc2=size=320x180:rate=25"])
750 .args(["-f", "lavfi", "-t", "2", "-i", "mandelbrot=size=320x180:rate=25"])
751 .args(["-filter_complex", "[0:v][1:v]xfade=transition=fade:duration=1:offset=1[v]", "-map", "[v]"])
752 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
753 .arg(&path)
754 .status()
755 .expect("ffmpeg runs")
756 .success();
757 assert!(ok);
758 for threshold in [DEFAULT_THRESHOLD, 0.1] {
759 let s = SceneSettings { threshold, ..SceneSettings::default() };
760 let cuts = detect(&path, None, &s, None, None).unwrap();
761 let dissolves: Vec<&Cut> = cuts.iter().filter(|c| matches!(c.kind, CutKind::Dissolve { .. })).collect();
762 assert_eq!(dissolves.len(), 1, "threshold {threshold}: {cuts:?}");
763 let d = dissolves[0];
764 let CutKind::Dissolve { end } = d.kind else { unreachable!() };
765 assert!(d.frame.abs_diff(25) <= 2 && end.abs_diff(50) <= 2, "threshold {threshold}: {cuts:?}");
766 assert!(cuts.iter().all(|c| !inside_dissolve(d, c.frame)), "threshold {threshold}: {cuts:?}");
767 }
768 }
769
770 #[test]
771 fn settings_out_of_range_are_refused() {
772 let s = SceneSettings { threshold: 1.5, ..SceneSettings::default() };
773 assert!(detect(&asset("test_av.mp4"), None, &s, None, None).is_err());
774 let s = SceneSettings { sample_fps: Some(0.0), ..SceneSettings::default() };
775 assert!(detect(&asset("test_av.mp4"), None, &s, None, None).is_err());
776 }
777
778 #[test]
779 fn cancel_stops_the_walk() {
780 let (path, _) = three_shots("cancel", 2);
781 let cancel = AtomicBool::new(true);
782 assert!(detect(&path, None, &SceneSettings::default(), None, Some(&cancel)).is_err());
783 }
784
785 /// Speed on a 5 s 720p file, in frames per second. Run with
786 /// `cargo test --release -p engine --lib scenes::tests::speed -- --ignored --nocapture`.
787 #[test]
788 #[ignore]
789 fn speed() {
790 let path = Scratch::file("speed", "mp4");
791 let ok = Command::new("ffmpeg")
792 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=25:duration=5"])
793 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
794 .arg(&path)
795 .status()
796 .expect("ffmpeg runs")
797 .success();
798 assert!(ok);
799 for sample in [None, Some(LONG_FILE_SAMPLE_FPS)] {
800 let s = SceneSettings { sample_fps: sample, ..SceneSettings::default() };
801 let t = Instant::now();
802 let cuts = detect(&path, None, &s, None, None).unwrap();
803 let secs = t.elapsed().as_secs_f64();
804 println!("sample {sample:?}: 125 frames in {secs:.3}s = {:.0} frames/s, {} cuts", 125.0 / secs, cuts.len());
805 }
806 }
807}