forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

scan.rs1013 lines, 43.8 KiBHistoryRawDownload
1//! Scan tool: shot boundaries of a source, found by `engine::scenes` (MCP.md section 4.4).
2//!
3//! The result is in the source's own frames, shaped the way `edit` `keep` takes
4//! ranges, so a scan can be handed straight back as a rough cut. Results are
5//! cached per file, modification time and settings under the user's cache
6//! directory, so a second scan of the same file is a file read.
7
8use std::path::{Path, PathBuf};
9use std::sync::atomic::Ordering;
10use std::time::UNIX_EPOCH;
11
12use serde_json::{json, Value};
13
14use engine::decode::{to_png_bytes, DecodeSession, Frame};
15use engine::demux::Demuxer;
16use engine::project::{Clip, Rate};
17use engine::scenes::{self, Cut, CutKind, SceneSettings};
18use engine::PlaybackSession;
19
20use crate::parse;
21use crate::server::{opt_str, tri, Reply, Server, Tool};
22use crate::tools::see::{base64, fit_height, frames_dir, picture_check, resize, save_png, tile_sheet};
23
24/// Tiles in a scan sheet, at most. More shots than this and the sheet is refused.
25const MAX_SHEET_TILES: usize = 96;
26const SHEET_COLS: usize = 4;
27const TILE_W: u32 = 320;
28
29const SCENES_DOC: &str = "Find the shots of a source file: where the picture cuts, and where it \
30fades through black. Returns the shots in SOURCE frames as {from, to} pairs in the form keep \
31takes, so the result can go straight into edit keep. A clip address (such as V1@450) scans that \
32clip's own source, limited to the clip's span, and adds each shot's timeline time. threshold \
33(0-1, default 0.35) sets how big a change must be; min_shot (seconds, default 0.6) merges closer \
34cuts. Each boundary is the first frame of the new shot, refined to the exact frame (in a range too); a fade through black is placed at the first picture frame after the dark run. A source with no picture (sound alone) is refused. sheet:true adds one contact-sheet image with each shot's middle frame, saved under the project's frame cache folder (~/.cache/edith/frames/<project>/) and named in the reply. Results are cached \
35per file.";
36
37pub fn tools() -> Vec<Tool> {
38 vec![Tool { name: "scenes", description: SCENES_DOC, schema: scenes_schema, run: scenes }]
39}
40
41fn scenes_schema() -> Value {
42 json!({
43 "type": "object",
44 "description": SCENES_DOC,
45 "properties": {
46 "source": {
47 "type": "string",
48 "description": "A source, such as src:2, or a clip address such as V1@450 to scan that clip's source within its span."
49 },
50 "range": {
51 "type": ["array", "object"],
52 "minItems": 2,
53 "maxItems": 2,
54 "items": {"type": ["string", "number"]},
55 "properties": {
56 "from": {"type": ["string", "number"]},
57 "to": {"type": ["string", "number"]}
58 },
59 "description": "Optional [from, to] or {from, to} in the source's time: 450f, 15.0s, or a number of seconds. To is exclusive. Intersected with a clip's span."
60 },
61 "threshold": {
62 "type": "number",
63 "minimum": 0,
64 "maximum": 1,
65 "description": "Cut sensitivity from 0 to 1. Default 0.35; lower finds more cuts."
66 },
67 "min_shot": {
68 "type": "number",
69 "minimum": 0,
70 "description": "Shortest shot in seconds; closer cuts merge into the stronger one. Default 0.6."
71 },
72 "sheet": {
73 "type": "boolean",
74 "description": "Also return one contact-sheet image with each shot's middle frame as a tile."
75 }
76 },
77 "required": ["source"]
78 })
79}
80
81/// What a scan reads: one source, and the clip it was addressed through, if any.
82struct Target {
83 src: usize,
84 clip: Option<Clip>,
85 /// The file's frames against the timeline's: how a clip's frame range, which
86 /// counts at the timeline's rate, becomes the file's own frames.
87 rate: Rate,
88 /// The timeline's own frame rate, for the clock of a timeline time.
89 timeline_fps: f64,
90}
91
92fn scenes(server: &mut Server, args: &Value) -> Reply {
93 let s = tri!(server.session_ref());
94 let Some(raw) = opt_str(args, "source") else {
95 return Reply::err("missing argument `source`: give src:<n>, such as src:0, or a clip address such as V1@450");
96 };
97 let mut target = tri!(target_of(s, raw));
98 let path = s.sources()[target.src].path.clone();
99 let name = file_name(&path);
100 if engine::is_image(&path) {
101 return Reply::err(format!("src:{} is a still image; scenes needs a moving picture", target.src));
102 }
103 if let Err(e) = picture_check(&path, target.src) {
104 return Reply::err(format!("{e}; scenes needs a moving picture"));
105 }
106 // The file's own frame count and rate: the source's frames, not the timeline's
107 // (`PlaybackSession::file_frames` counts in timeline frames).
108 let (meta, _demux) = match Demuxer::open(&path) {
109 Ok(v) => v,
110 Err(e) => return Reply::err(format!("cannot count the frames of src:{} {name}: {e}", target.src)),
111 };
112 let total = meta.frame_count;
113 if total == 0 {
114 return Reply::err(format!("cannot count the frames of src:{} {name}", target.src));
115 }
116 let fps = Some(meta.frame_rate)
117 .filter(|f| f.is_finite() && *f > 0.0)
118 .unwrap_or_else(|| parse::session_fps(s));
119 target.rate = match Rate::from_fps(fps, target.timeline_fps) {
120 Ok(r) => r,
121 Err(e) => return Reply::err(format!("cannot relate src:{} to the timeline's rate: {e}", target.src)),
122 };
123 let (from, to) = tri!(span_of(args, &target, fps, total));
124
125 let mut settings = SceneSettings::for_duration(f64::from(total) / fps);
126 if let Some(t) = args.get("threshold").filter(|v| !v.is_null()) {
127 let Some(t) = t.as_f64() else {
128 return Reply::err("argument `threshold` must be a number from 0 to 1");
129 };
130 settings.threshold = t as f32;
131 }
132 if let Some(m) = args.get("min_shot").filter(|v| !v.is_null()) {
133 let Some(m) = m.as_f64() else {
134 return Reply::err("argument `min_shot` must be a number of seconds");
135 };
136 settings.min_shot_secs = m;
137 }
138 let want_sheet = args.get("sheet").and_then(Value::as_bool).unwrap_or(false);
139 let sheet_dir = frames_dir(server.path.as_deref());
140
141 let Scan { cuts, flashes, cached } = match cuts_for(cache_dir().as_deref(), &path, (from, to), &settings) {
142 Ok(v) => v,
143 Err(e) => return Reply::err(e),
144 };
145 let flashes: Vec<(u32, u32)> = flashes.into_iter().filter(|&(a, b)| a < to && b > from).collect();
146 let shots = shots_of(from, to, &cuts);
147 if want_sheet && shots.len() > MAX_SHEET_TILES {
148 return Reply::err(format!(
149 "{} shots is more than one sheet holds ({MAX_SHEET_TILES}); raise min_shot or narrow range",
150 shots.len()
151 ));
152 }
153
154 let sheet = if want_sheet {
155 match sheet_of(&path, &shots, fps, &sheet_dir) {
156 Ok(v) => Some(v),
157 Err(r) => return r,
158 }
159 } else {
160 None
161 };
162
163 let lines = describe(&target, &name, &shots, &cuts, &flashes, from, to, fps);
164 let mut text = lines.join("\n");
165 let mut structured = structured_of(&target, &name, &shots, &cuts, &flashes, from, to, fps, cached);
166 if let Some((png, saved)) = &sheet {
167 text.push_str(&format!("\ncontact sheet: {} tiles, saved: {}", shots.len(), saved.display()));
168 structured["sheet"] = json!({"tiles": shots.len(), "path": saved.display().to_string()});
169 return Reply::ok(text).with(structured).image("image/png", base64(png));
170 }
171 Reply::ok(text).with(structured)
172}
173
174/// The source a target names, and the clip if it was a clip address.
175fn target_of(s: &PlaybackSession, raw: &str) -> Result<Target, Reply> {
176 let head = raw.split_whitespace().next().unwrap_or("");
177 if let Some(d) = head.strip_prefix("src:") {
178 let src = d
179 .parse::<usize>()
180 .map_err(|_| Reply::err(format!("`{raw}` is not src:<n> or a clip address")))?;
181 if src >= s.sources().len() {
182 return Err(Reply::err(format!(
183 "no source src:{src}; the project has {} source(s)",
184 s.sources().len()
185 )));
186 }
187 return Ok(Target { src, clip: None, rate: Rate::REAL_TIME, timeline_fps: parse::session_fps(s) });
188 }
189 let (lane, idx) = parse::clip(s, raw).map_err(Reply::err)?;
190 let clip = s
191 .lane_clips(lane)
192 .get(idx)
193 .cloned()
194 .ok_or_else(|| Reply::err(format!("no clip at `{raw}`")))?;
195 Ok(Target { src: clip.source, clip: Some(clip), rate: Rate::REAL_TIME, timeline_fps: parse::session_fps(s) })
196}
197
198/// The `[from, to)` span to scan, in source frames.
199fn span_of(args: &Value, target: &Target, fps: f64, total: u32) -> Result<(u32, u32), Reply> {
200 let (mut from, mut to) = (0, total);
201 if let Some(r) = args.get("range").filter(|v| !v.is_null()) {
202 // `[from, to]`, or `{from, to}` as the other tools take it; a missing end of the object is the source's.
203 let (a, b) = match r {
204 Value::Array(pair) if pair.len() == 2 => (pair[0].clone(), pair[1].clone()),
205 Value::Object(o) => (
206 o.get("from").filter(|v| !v.is_null()).cloned().unwrap_or_else(|| json!("0f")),
207 o.get("to").filter(|v| !v.is_null()).cloned().unwrap_or_else(|| json!(format!("{total}f"))),
208 ),
209 _ => return Err(Reply::err("argument `range` is [from, to] or {from, to}, two times in the source")),
210 };
211 from = parse::frame(&a, fps, total).map_err(Reply::err)?;
212 to = parse::frame(&b, fps, total).map_err(Reply::err)?;
213 }
214 if let Some(c) = &target.clip {
215 // The clip's range counts at the timeline's rate: its first and last frames
216 // as the file's own frames, the last one exclusive.
217 from = from.max(target.rate.source_at(c.in_frame));
218 to = to.min(target.rate.source_at(c.out_frame.saturating_sub(1)) + 1);
219 }
220 to = to.min(total);
221 if from >= to {
222 return Err(Reply::err(format!("the range is empty: {from}f to {to}f")));
223 }
224 Ok((from, to))
225}
226
227/// Shots of `[from, to)`: the spans between cuts, as `(from, to)` pairs.
228fn shots_of(from: u32, to: u32, cuts: &[Cut]) -> Vec<(u32, u32)> {
229 // A dissolve ends the old shot at its first frame and starts the new one at its last, so the
230 // frames of the dissolve itself belong to neither shot.
231 let mut shots = Vec::new();
232 let mut start = from;
233 for c in inner(from, to, cuts) {
234 shots.push((start, c.frame.max(start)));
235 start = match c.kind {
236 CutKind::Dissolve { end } => end.min(to),
237 _ => c.frame,
238 };
239 }
240 shots.push((start, to));
241 shots
242}
243
244/// The name of a cut's kind in the cache file and the JSON answer.
245fn kind_name(kind: CutKind) -> &'static str {
246 match kind {
247 CutKind::Hard => "hard",
248 CutKind::FadeBlack => "fade",
249 CutKind::Dissolve { .. } => "dissolve",
250 }
251}
252
253/// The cuts that fall strictly inside `(from, to)`.
254fn inner(from: u32, to: u32, cuts: &[Cut]) -> Vec<&Cut> {
255 cuts.iter().filter(|c| c.frame > from && c.frame < to).collect()
256}
257
258/// What a scan found: the shot boundaries, and the flashes that were dropped from them
259/// (each `[from, to)` in source frames, a run of frames that is not a shot of its own).
260struct Scan {
261 cuts: Vec<Cut>,
262 flashes: Vec<(u32, u32)>,
263 cached: bool,
264}
265
266/// Cuts from the cache when the same file and settings were scanned before,
267/// from the detector otherwise. `cached` says whether it was a cache hit.
268fn cuts_for(dir: Option<&Path>, path: &Path, range: (u32, u32), settings: &SceneSettings) -> Result<Scan, String> {
269 let file = dir.map(|d| d.join(format!("{}.json", cache_key(path, range, settings))));
270 if let Some(f) = &file
271 && let Some((cuts, flashes)) = read_cache(f)
272 {
273 return Ok(Scan { cuts, flashes, cached: true });
274 }
275 let mut cuts = scenes::detect(path, Some(range), settings, None, None)
276 .map_err(|e| format!("scene detection failed on {}: {e}", file_name(path)))?;
277 verify_fades(path, &mut cuts);
278 let flashes = find_flashes(path, &mut cuts);
279 if let Some(f) = &file {
280 write_cache(f, &cuts, &flashes);
281 }
282 Ok(Scan { cuts, flashes, cached: false })
283}
284
285/// Largest mean luma difference (over 255) a frame may have from the picture before a flash and
286/// still be that picture again.
287const FLASH_SAME: f64 = 0.02;
288/// Smallest mean luma difference (over 255) a flash frame must have from the picture before it.
289const FLASH_DIFF: f64 = 0.1;
290/// Longest flash, in frames. A 3-frame white flash is the case this is sized for.
291const FLASH_MAX: u32 = 4;
292
293/// The flash the boundary at `cut` belongs to, as `[from, to)`: one to [`FLASH_MAX`] frames that
294/// differ strongly from the picture before them, followed by that picture again. `cut` is either
295/// the first frame after the flash (the flash's end is the boundary) or its first frame. `dist(a, b)`
296/// is the mean absolute luma difference of frames `a` and `b`, over 255; NaN when unknown.
297fn flash_span(cut: u32, dist: &impl Fn(u32, u32) -> f64) -> Option<(u32, u32)> {
298 for n in 1..=FLASH_MAX {
299 let Some(before) = cut.checked_sub(n + 1) else { break };
300 if dist(before, cut) <= FLASH_SAME && (cut - n..cut).all(|k| dist(before, k) >= FLASH_DIFF) {
301 return Some((cut - n, cut));
302 }
303 }
304 let before = cut.checked_sub(1)?;
305 for n in 1..=FLASH_MAX {
306 let after = cut + n;
307 if dist(before, after) <= FLASH_SAME && (cut..after).all(|k| dist(before, k) >= FLASH_DIFF) {
308 return Some((cut, after));
309 }
310 }
311 None
312}
313
314/// Takes the flashes out of the hard cuts: a boundary that is only a flash (the picture leaves
315/// and comes straight back) is not a shot change, so it is dropped and reported as a flash.
316fn find_flashes(path: &Path, cuts: &mut Vec<Cut>) -> Vec<(u32, u32)> {
317 let total = Demuxer::open(path).map_or(0, |(m, _)| m.frame_count);
318 let mut flashes = Vec::new();
319 let mut keep = Vec::with_capacity(cuts.len());
320 for c in cuts.drain(..) {
321 if c.kind != CutKind::Hard {
322 keep.push(c);
323 continue;
324 }
325 let lo = c.frame.saturating_sub(FLASH_MAX + 1);
326 let hi = c.frame.saturating_add(FLASH_MAX).min(total.saturating_sub(1));
327 let window = frames_between(path, lo, hi).unwrap_or_default();
328 let dist = |a: u32, b: u32| -> f64 {
329 match (window.iter().find(|f| f.0 == a), window.iter().find(|f| f.0 == b)) {
330 (Some((_, fa)), Some((_, fb))) => luma_gap(fa, fb),
331 _ => f64::NAN,
332 }
333 };
334 match flash_span(c.frame, &dist) {
335 Some(span) => flashes.push(span),
336 None => keep.push(c),
337 }
338 }
339 *cuts = keep;
340 flashes
341}
342
343/// Mean absolute luma difference of two frames, over 255. NaN when their sizes differ.
344fn luma_gap(a: &Frame, b: &Frame) -> f64 {
345 if a.bgra.len() != b.bgra.len() || a.bgra.is_empty() {
346 return f64::NAN;
347 }
348 let luma = |p: &[u8]| ((77 * i32::from(p[2]) + 150 * i32::from(p[1]) + 29 * i32::from(p[0])) >> 8).clamp(0, 255);
349 let total: i64 = a
350 .bgra
351 .as_chunks::<4>()
352 .0
353 .iter()
354 .zip(b.bgra.as_chunks::<4>().0)
355 .map(|(p, q)| i64::from((luma(p) - luma(q)).abs()))
356 .sum();
357 total as f64 / (a.bgra.len() / 4) as f64 / 255.0
358}
359
360/// Share of the frame that must be near-black (luma 16 or below) for a dark run to be a fade.
361/// Grain around a mean of 18 has a dip below 16 now and then, which is a steady dark shot, not
362/// a fade: a fade's dark end is black nearly all over.
363const FADE_BLACK_SHARE: f64 = 0.8;
364/// How much brighter, in luma levels, the picture a second either side of a fade must be than its
365/// dark end. A dark shot that stays dark on both sides has no dip, so it is not a fade.
366const FADE_DIP: f64 = 32.0;
367
368/// Keeps a fade through black only when it is one: the frame before the cut is near-black on
369/// most of the frame, and the picture a second before and after (where the file has them) is
370/// clearly brighter. The engine finds a dark run by mean luma alone, which a steady dark shot
371/// can satisfy; this looks at the pixels, so it is checked here on the decoded frames.
372fn verify_fades(path: &Path, cuts: &mut Vec<Cut>) {
373 if !cuts.iter().any(|c| c.kind == CutKind::FadeBlack) {
374 return;
375 }
376 let Ok((meta, _demux)) = Demuxer::open(path) else {
377 cuts.retain(|c| c.kind != CutKind::FadeBlack);
378 return;
379 };
380 let fps = Some(meta.frame_rate).filter(|f| f.is_finite() && *f > 0.0).unwrap_or(25.0);
381 let win = fps.round().max(1.0) as u32;
382 cuts.retain(|c| c.kind != CutKind::FadeBlack || real_fade(path, c.frame, win, meta.frame_count));
383 drop_cuts_in_fades(cuts, win);
384}
385
386/// Drops the hard cuts that fall inside a fade in: within `win` frames after a fade's first picture
387/// frame. A fade that brightens in steps is many small changes, and the detector reads one of them
388/// as a cut; the fade is one shot boundary, so none of its steps is.
389fn drop_cuts_in_fades(cuts: &mut Vec<Cut>, win: u32) {
390 let fades: Vec<u32> = cuts.iter().filter(|c| c.kind == CutKind::FadeBlack).map(|c| c.frame).collect();
391 cuts.retain(|c| c.kind == CutKind::FadeBlack || !fades.iter().any(|&f| c.frame > f && c.frame <= f + win));
392}
393
394/// Whether the fade at `cut` (the first picture frame after its dark run) is a real one; see
395/// [`verify_fades`]. `win` is one second in frames.
396///
397/// The darkest frame before `cut` is the fade's black end. It must be near-black, and the run of
398/// near-black frames around it is the dark run. The picture a second before that run, and a second
399/// after it, must each be [`FADE_DIP`] levels brighter than the black, wherever the file has them.
400fn real_fade(path: &Path, cut: u32, win: u32, total: u32) -> bool {
401 let lo = cut.saturating_sub(4 * win);
402 let hi = cut.saturating_add(2 * win).min(total.saturating_sub(1));
403 let Some(frames) = frames_between(path, lo, hi) else { return false };
404 let stats: Vec<(u32, f64, f64)> = frames
405 .iter()
406 .map(|(i, f)| {
407 let (mean, share) = luma_stats(f);
408 (*i, mean, share)
409 })
410 .collect();
411 let at = |i: u32| stats.iter().find(|s| s.0 == i).copied();
412 // The first darkest frame before the cut; the cut itself is the first picture frame.
413 let Some(&(black, black_mean, black_share)) =
414 stats.iter().filter(|s| s.0 < cut).min_by(|a, b| a.1.total_cmp(&b.1))
415 else {
416 return false;
417 };
418 if black_share < FADE_BLACK_SHARE {
419 return false;
420 }
421 let mut run_lo = black;
422 while run_lo > lo && at(run_lo - 1).is_some_and(|s| s.2 >= FADE_BLACK_SHARE) {
423 run_lo -= 1;
424 }
425 let mut run_hi = black;
426 while run_hi < hi && at(run_hi + 1).is_some_and(|s| s.2 >= FADE_BLACK_SHARE) {
427 run_hi += 1;
428 }
429 let before = (run_lo.saturating_sub(win)..run_lo).filter_map(at).map(|s| s.1).reduce(f64::max);
430 let after = (run_hi + 1..=run_hi.saturating_add(win)).filter_map(at).map(|s| s.1).reduce(f64::max);
431 let sides: Vec<f64> = [before, after].into_iter().flatten().collect();
432 !sides.is_empty() && sides.iter().all(|&mean| mean >= black_mean + FADE_DIP)
433}
434
435/// Mean luma (of 255) of a frame, and the share of its pixels at luma 16 or below. Luma is
436/// the same weighting the engine's scene thumbnails use.
437fn luma_stats(f: &Frame) -> (f64, f64) {
438 let (mut sum, mut dark, mut n) = (0u64, 0u64, 0u64);
439 for p in f.bgra.as_chunks::<4>().0 {
440 let (b, g, r) = (i32::from(p[0]), i32::from(p[1]), i32::from(p[2]));
441 let y = ((77 * r + 150 * g + 29 * b) >> 8).clamp(0, 255) as u64;
442 sum += y;
443 dark += u64::from(y <= 16);
444 n += 1;
445 }
446 let n = n.max(1) as f64;
447 (sum as f64 / n, dark as f64 / n)
448}
449
450/// The frames `lo..=hi` of the source, by index. Empty when the decoder gives none.
451fn frames_between(path: &Path, lo: u32, hi: u32) -> Option<Vec<(u32, Frame)>> {
452 let (_, rx, cancel) = DecodeSession::open_range(path, lo, hi.saturating_add(1)).ok()?;
453 let out: Vec<(u32, Frame)> = rx.iter().take_while(|f| f.index <= hi).map(|f| (f.index, f)).collect();
454 cancel.store(true, Ordering::Relaxed);
455 Some(out)
456}
457
458/// The cache directory: `$XDG_CACHE_HOME/edith/scenes`, else `~/.cache/edith/scenes`.
459fn cache_dir() -> Option<PathBuf> {
460 let base = std::env::var_os("XDG_CACHE_HOME")
461 .filter(|v| !v.is_empty())
462 .map(PathBuf::from)
463 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))?;
464 Some(base.join("edith").join("scenes"))
465}
466
467/// A 64-bit FNV-1a over the file's path, modification time, range and settings,
468/// so an edited file or a changed setting misses the cache.
469fn cache_key(path: &Path, range: (u32, u32), st: &SceneSettings) -> String {
470 let mtime = std::fs::metadata(path)
471 .ok()
472 .and_then(|m| m.modified().ok())
473 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
474 .map_or(0, |d| d.as_nanos());
475 let text = format!(
476 "v5|{}|{mtime}|{}-{}|{:08x}|{:016x}|{:?}",
477 path.display(),
478 range.0,
479 range.1,
480 st.threshold.to_bits(),
481 st.min_shot_secs.to_bits(),
482 st.sample_fps.map(f64::to_bits),
483 );
484 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
485 for b in text.bytes() {
486 h ^= u64::from(b);
487 h = h.wrapping_mul(0x0000_0100_0000_01b3);
488 }
489 format!("{h:016x}")
490}
491
492/// The cuts and flashes a cache file holds, as `read_cache` returns them.
493type CachedScenes = (Vec<Cut>, Vec<(u32, u32)>);
494
495fn read_cache(file: &Path) -> Option<CachedScenes> {
496 let v: Value = serde_json::from_slice(&std::fs::read(file).ok()?).ok()?;
497 let cuts = v
498 .get("cuts")?
499 .as_array()?
500 .iter()
501 .map(|c| {
502 let kind = match c.get("kind")?.as_str()? {
503 "hard" => CutKind::Hard,
504 "fade" => CutKind::FadeBlack,
505 "dissolve" => CutKind::Dissolve { end: u32::try_from(c.get("end")?.as_u64()?).ok()? },
506 _ => return None,
507 };
508 Some(Cut {
509 frame: u32::try_from(c.get("frame")?.as_u64()?).ok()?,
510 score: c.get("score")?.as_f64()? as f32,
511 kind,
512 })
513 })
514 .collect::<Option<Vec<Cut>>>()?;
515 let flashes = v
516 .get("flashes")?
517 .as_array()?
518 .iter()
519 .map(|f| {
520 let at = |k: &str| u32::try_from(f.get(k)?.as_u64()?).ok();
521 Some((at("from")?, at("to")?))
522 })
523 .collect::<Option<Vec<(u32, u32)>>>()?;
524 Some((cuts, flashes))
525}
526
527/// Writes the cache file atomically (a temporary, then a rename). A cache that
528/// cannot be written costs the next scan its time and nothing else.
529fn write_cache(file: &Path, cuts: &[Cut], flashes: &[(u32, u32)]) {
530 let body = json!({
531 "cuts": cuts.iter().map(|c| json!({
532 "frame": c.frame,
533 "score": c.score,
534 "kind": kind_name(c.kind),
535 "end": match c.kind { CutKind::Dissolve { end } => Some(end), _ => None },
536 })).collect::<Vec<_>>(),
537 "flashes": flashes.iter().map(|&(from, to)| json!({"from": from, "to": to})).collect::<Vec<_>>(),
538 });
539 let Some(dir) = file.parent() else { return };
540 if std::fs::create_dir_all(dir).is_err() {
541 return;
542 }
543 let tmp = file.with_extension("json.tmp");
544 if std::fs::write(&tmp, body.to_string()).is_ok() {
545 let _ = std::fs::rename(&tmp, file);
546 }
547}
548
549/// One contact-sheet image: a tile per shot, at its middle frame. Returns the
550/// PNG bytes and the path it was saved to.
551/// The sheet is saved in the frame cache folder of the project (as `frame` and
552/// `contact_sheet` do), and its path is returned with the PNG bytes.
553fn sheet_of(path: &Path, shots: &[(u32, u32)], fps: f64, dir: &Path) -> Result<(Vec<u8>, PathBuf), Reply> {
554 let mids: Vec<u32> = shots.iter().map(|&(a, b)| a + (b - a) / 2).collect();
555 let (Some(&lo), Some(&last)) = (mids.first(), mids.last()) else {
556 return Err(Reply::err("no shots to draw"));
557 };
558 let (_, rx, cancel) = DecodeSession::open_range(path, lo, last + 1)
559 .map_err(|e| Reply::err(format!("cannot open {} for the sheet: {e}", file_name(path))))?;
560 let mut tiles: Vec<Frame> = Vec::with_capacity(mids.len());
561 for frame in rx.iter() {
562 let Some(&want) = mids.get(tiles.len()) else { break };
563 if frame.index < want {
564 continue;
565 }
566 if frame.index > want {
567 break;
568 }
569 let h = fit_height(&frame, TILE_W);
570 tiles.push(resize(&frame, TILE_W, h));
571 }
572 cancel.store(true, std::sync::atomic::Ordering::Relaxed);
573 if tiles.len() != mids.len() {
574 return Err(Reply::err(format!(
575 "could not decode the middle frame of every shot ({} of {})",
576 tiles.len(),
577 mids.len()
578 )));
579 }
580 let cols = SHEET_COLS.min(mids.len()) as u32;
581 let sheet = tile_sheet(&tiles, &mids, cols, TILE_W, fps);
582 let png = to_png_bytes(&sheet).map_err(|e| Reply::err(format!("cannot encode the sheet as PNG: {e}")))?;
583 let saved = save_png(&png, dir, &format!("scenes-{}-{lo}-{last}", file_name(path)), None)?;
584 Ok((png, saved))
585}
586
587/// The text answer: a header, then one line per shot in source time, with the
588/// timeline time of each shot when the target was a clip.
589#[allow(clippy::too_many_arguments)]
590fn describe(
591 target: &Target,
592 name: &str,
593 shots: &[(u32, u32)],
594 cuts: &[Cut],
595 flashes: &[(u32, u32)],
596 from: u32,
597 to: u32,
598 fps: f64,
599) -> Vec<String> {
600 let starts = inner(from, to, cuts);
601 let mut lines = vec![format!(
602 "{} shots · src:{} {name} · {from}f–{to}f ({}–{})",
603 shots.len(),
604 target.src,
605 parse::clock(from, fps),
606 parse::clock(to, fps),
607 )];
608 for (i, &(a, b)) in shots.iter().enumerate() {
609 let mut line = format!("{}. {}–{} ({}f)", i + 1, parse::clock(a, fps), parse::clock(b, fps), b - a);
610 if let Some(c) = i.checked_sub(1).and_then(|k| starts.get(k)) {
611 line.push_str(&match c.kind {
612 CutKind::Hard => format!(" · cut {:.2}", c.score),
613 CutKind::FadeBlack => " · fade through black".to_string(),
614 CutKind::Dissolve { end } => format!(" · dissolve {}–{}", parse::clock(c.frame, fps), parse::clock(end, fps)),
615 });
616 }
617 if let Some(clip) = &target.clip {
618 let (tl_a, tl_b) = (timeline_of(target.rate, clip, a), timeline_of(target.rate, clip, b));
619 line.push_str(&format!(
620 " · timeline {}–{}",
621 parse::clock(tl_a, target.timeline_fps),
622 parse::clock(tl_b, target.timeline_fps)
623 ));
624 }
625 lines.push(line);
626 }
627 for &(a, b) in flashes {
628 lines.push(format!(
629 "note: flash at {}–{} ({}f), not a cut",
630 parse::clock(a, fps),
631 parse::clock(b, fps),
632 b - a
633 ));
634 }
635 lines
636}
637
638/// The JSON answer: shots and cuts as `"Nf"` strings in source frames.
639#[allow(clippy::too_many_arguments)]
640fn structured_of(
641 target: &Target,
642 name: &str,
643 shots: &[(u32, u32)],
644 cuts: &[Cut],
645 flashes: &[(u32, u32)],
646 from: u32,
647 to: u32,
648 fps: f64,
649 cached: bool,
650) -> Value {
651 let frames = |f: u32| format!("{f}f");
652 let mut out = json!({
653 "source": format!("src:{}", target.src),
654 "file": name,
655 "fps": fps,
656 "cached": cached,
657 "range": {"from": frames(from), "to": frames(to)},
658 "shots": shots.iter().map(|&(a, b)| json!({"from": frames(a), "to": frames(b)})).collect::<Vec<_>>(),
659 "cuts": inner(from, to, cuts).iter().map(|c| json!({
660 "frame": frames(c.frame),
661 "score": c.score,
662 "kind": kind_name(c.kind),
663 "end": match c.kind { CutKind::Dissolve { end } => Some(frames(end)), _ => None },
664 })).collect::<Vec<_>>(),
665 "flashes": flashes.iter().map(|&(a, b)| json!({"from": frames(a), "to": frames(b)})).collect::<Vec<_>>(),
666 });
667 if let Some(clip) = &target.clip {
668 out["clip"] = json!({"start": clip.start, "lane_frames": clip.frames()});
669 out["timeline"] = json!(shots
670 .iter()
671 .map(|&(a, b)| json!({"from": timeline_of(target.rate, clip, a), "to": timeline_of(target.rate, clip, b)}))
672 .collect::<Vec<_>>());
673 }
674 out
675}
676
677/// The timeline frame a source frame of the file plays at, through the clip's
678/// speed. The clip's `in_frame` counts at the timeline's rate, so the file's
679/// frame is first put on that rate.
680fn timeline_of(rate: Rate, clip: &Clip, source: u32) -> u32 {
681 clip.start + clip.timeline_offset(rate.timeline_at(source).saturating_sub(clip.in_frame))
682}
683
684fn file_name(path: &Path) -> String {
685 path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned())
686}
687
688#[cfg(test)]
689mod tests {
690 use super::*;
691 use crate::testutil::TestDir;
692 use std::process::Command;
693 use std::sync::{Mutex, MutexGuard};
694
695 fn asset(name: &str) -> PathBuf {
696 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
697 }
698
699 fn server_on(path: &Path) -> Server {
700 let mut srv = Server::new();
701 srv.session = Some(PlaybackSession::open(path).expect("open test asset"));
702 srv
703 }
704
705 /// Scene sheets are saved under this process's temp root. The calls run one at a time
706 /// and clear that root afterwards, so no test leaves a `edith_mcp-<pid>` folder behind.
707 static SCRATCH: Mutex<()> = Mutex::new(());
708
709 fn call(srv: &mut Server, args: Value) -> Reply {
710 let _lock: MutexGuard<'_, ()> = SCRATCH.lock().unwrap_or_else(|e| e.into_inner());
711 let tool = crate::server::tools().into_iter().find(|t| t.name == "scenes").expect("tool exists");
712 let r = (tool.run)(srv, &args);
713 crate::tools::see::remove_scratch();
714 r
715 }
716
717 /// Two 1 s shots of different content, joined, in a fresh directory that is removed
718 /// when the returned guard drops.
719 fn two_shots(name: &str) -> (TestDir, PathBuf) {
720 let dir = TestDir::new(&format!("scan-{name}"));
721 let out = dir.join("two.mp4");
722 let ok = Command::new("ffmpeg")
723 .args(["-v", "error", "-y", "-f", "lavfi", "-t", "1", "-i", "testsrc2=size=320x180:rate=25"])
724 .args(["-f", "lavfi", "-t", "1", "-i", "mandelbrot=size=320x180:rate=25"])
725 .args(["-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0[v]", "-map", "[v]"])
726 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
727 .arg(&out)
728 .status()
729 .expect("ffmpeg runs")
730 .success();
731 assert!(ok);
732 (dir, out)
733 }
734
735 #[test]
736 fn scan_lists_the_shots_of_a_two_shot_file() {
737 let (_dir, path) = two_shots("lists");
738 let mut srv = server_on(&path);
739 let r = call(&mut srv, json!({"source": "src:0"}));
740 assert!(!r.is_error, "{}", r.text);
741 assert!(r.text.contains("1. 00:00.000–"), "{}", r.text);
742 assert!(r.text.contains("2. "), "{}", r.text);
743 let shots = r.structured.as_ref().unwrap()["shots"].as_array().unwrap().clone();
744 assert_eq!(shots.len(), 2, "{}", r.text);
745 assert_eq!(shots[0]["from"], "0f");
746 assert!(shots[0]["to"].as_str().unwrap().ends_with('f'));
747 assert_eq!(shots[1]["to"], "50f");
748 }
749
750 #[test]
751 fn scan_range_and_cache_round_trip() {
752 let (_dir, path) = two_shots("cache");
753 let mut srv = server_on(&path);
754 let dir = path.parent().unwrap().join("cache-dir");
755 let settings = SceneSettings::default();
756 let first = cuts_for(Some(&dir), &path, (0, 50), &settings).unwrap();
757 assert!(!first.cached);
758 let second = cuts_for(Some(&dir), &path, (0, 50), &settings).unwrap();
759 assert!(second.cached, "the second scan reads the cache");
760 assert_eq!(first.cuts, second.cuts);
761 assert_eq!(first.flashes, second.flashes);
762 assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
763 let r = call(&mut srv, json!({"source": "src:0", "range": ["10f", "40f"]}));
764 assert!(!r.is_error, "{}", r.text);
765 assert_eq!(r.structured.as_ref().unwrap()["range"]["from"], "10f");
766 }
767
768 #[test]
769 fn scan_accepts_a_range_object_as_the_other_tools_do() {
770 let (_dir, path) = two_shots("object-range");
771 let mut srv = server_on(&path);
772 let r = call(&mut srv, json!({"source": "src:0", "range": {"from": "10f", "to": "40f"}}));
773 assert!(!r.is_error, "{}", r.text);
774 assert_eq!(r.structured.as_ref().unwrap()["range"], json!({"from": "10f", "to": "40f"}));
775 let same = call(&mut srv, json!({"source": "src:0", "range": ["10f", "40f"]}));
776 assert_eq!(r.structured.as_ref().unwrap()["shots"], same.structured.as_ref().unwrap()["shots"]);
777 let bad = call(&mut srv, json!({"source": "src:0", "range": {"from": "30f", "to": "10f"}}));
778 assert!(bad.is_error && bad.text.contains("empty"), "{}", bad.text);
779 }
780
781 #[test]
782 fn scan_refuses_an_empty_or_bad_range() {
783 let (_dir, path) = two_shots("bad");
784 let mut srv = server_on(&path);
785 let r = call(&mut srv, json!({"source": "src:0", "range": ["30f", "10f"]}));
786 assert!(r.is_error && r.text.contains("empty"), "{}", r.text);
787 let r = call(&mut srv, json!({"source": "src:0", "range": "10f"}));
788 assert!(r.is_error, "{}", r.text);
789 let r = call(&mut srv, json!({"source": "src:9"}));
790 assert!(r.is_error && r.text.contains("no source"), "{}", r.text);
791 }
792
793 #[test]
794 fn scan_sheet_has_one_tile_per_shot() {
795 let (_dir, path) = two_shots("sheet");
796 let mut srv = server_on(&path);
797 let r = call(&mut srv, json!({"source": "src:0", "sheet": true}));
798 assert!(!r.is_error, "{}", r.text);
799 assert_eq!(r.images.len(), 1);
800 assert_eq!(r.structured.as_ref().unwrap()["sheet"]["tiles"], 2);
801 }
802
803 #[test]
804 fn scan_of_a_clip_adds_timeline_times() {
805 let mut srv = server_on(&asset("test_av.mp4"));
806 let edit = crate::server::tools().into_iter().find(|t| t.name == "edit").expect("edit exists");
807 let placed = (edit.run)(&mut srv, &json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "2s"]]}]}));
808 assert!(!placed.is_error, "{}", placed.text);
809 let r = call(&mut srv, json!({"source": "V1@0"}));
810 assert!(!r.is_error, "{}", r.text);
811 assert!(r.text.contains("timeline"), "{}", r.text);
812 assert!(r.structured.as_ref().unwrap()["timeline"].is_array());
813 }
814
815 /// A 30 fps timeline with the 25 fps test_25fps.mp4 imported as src:1. Its 50 frames
816 /// are 2.000 s at its own rate; in timeline frames at 30 fps they would be 60.
817 fn open_30_with_25() -> Server {
818 engine::ao::set_silent_output();
819 let mut sess = PlaybackSession::open(asset("test_av.mp4")).expect("open 30 fps asset");
820 sess.import(&asset("test_25fps.mp4")).expect("import 25 fps asset");
821 Server { session: Some(sess), ..Server::default() }
822 }
823
824 #[test]
825 fn scenes_of_a_clip_on_a_30_fps_timeline_reads_the_source_in_its_own_frames() {
826 let mut srv = open_30_with_25();
827 let edit = crate::server::tools().into_iter().find(|t| t.name == "edit").expect("edit exists");
828 let placed = (edit.run)(&mut srv, &json!({"ops": [{"op": "keep", "source": "src:1", "ranges": [["0s", "2s"]]}]}));
829 assert!(!placed.is_error, "{}", placed.text);
830 // The clip sits at V1@150 (5 s) and is 60 timeline frames (2 s at 30 fps), which are
831 // 50 frames of the 25 fps file.
832 let r = call(&mut srv, json!({"source": "V1@150"}));
833 assert!(!r.is_error, "{}", r.text);
834 assert!(r.text.contains("0f–50f (00:00.000–00:02.000)"), "{}", r.text);
835 assert!(r.text.contains("timeline 00:05.000–00:07.000"), "{}", r.text);
836 let st = r.structured.as_ref().unwrap();
837 assert_eq!(st["range"], json!({"from": "0f", "to": "50f"}));
838 let timeline = st["timeline"].as_array().unwrap();
839 assert_eq!(timeline.first().unwrap()["from"], 150);
840 assert_eq!(timeline.last().unwrap()["to"], 210);
841 }
842
843 #[test]
844 fn scenes_counts_a_25_fps_source_in_its_own_frames_on_a_30_fps_timeline() {
845 let mut srv = open_30_with_25();
846 let r = call(&mut srv, json!({"source": "src:1"}));
847 assert!(!r.is_error, "{}", r.text);
848 assert!(r.text.contains("0f–50f (00:00.000–00:02.000)"), "{}", r.text);
849 let st = r.structured.as_ref().unwrap();
850 assert_eq!(st["fps"].as_f64(), Some(25.0));
851 assert_eq!(st["range"], json!({"from": "0f", "to": "50f"}));
852 let shots = st["shots"].as_array().unwrap();
853 assert_eq!(shots.first().unwrap()["from"], "0f");
854 assert_eq!(shots.last().unwrap()["to"], "50f");
855 }
856
857 /// 14 s at 25 fps (350 frames): 6 s of steady dark grain (mean luma about 18, dipping below
858 /// 16 now and then), then 4 s of test pattern fading out to black, then 4 s fading in from
859 /// black. The real fade is the dark run around frames 225 to 275.
860 fn dark_then_fade(name: &str) -> (TestDir, PathBuf) {
861 let dir = TestDir::new(&format!("scan-{name}"));
862 let out = dir.join("darkfade.mp4");
863 let graph = "[0:v]noise=alls=40:allf=t[d];[1:v]fade=t=out:st=2:d=1[a];[2:v]fade=t=in:st=0:d=1[b];[d][a][b]concat=n=3:v=1:a=0[v]";
864 let ok = Command::new("ffmpeg")
865 .args(["-v", "error", "-y", "-f", "lavfi", "-t", "6", "-i", "color=c=0x121212:s=320x180:r=25"])
866 .args(["-f", "lavfi", "-t", "4", "-i", "testsrc2=s=320x180:r=25"])
867 .args(["-f", "lavfi", "-t", "4", "-i", "testsrc2=s=320x180:r=25"])
868 .args(["-filter_complex", graph, "-map", "[v]"])
869 .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
870 .arg(&out)
871 .status()
872 .expect("ffmpeg runs")
873 .success();
874 assert!(ok);
875 (dir, out)
876 }
877
878 #[test]
879 fn steady_dark_grain_is_not_a_fade_and_a_real_fade_is() {
880 let (_dir, path) = dark_then_fade("fade");
881 let cuts = cuts_for(None, &path, (0, 350), &SceneSettings::default()).unwrap().cuts;
882 let fades: Vec<u32> = cuts.iter().filter(|c| c.kind == CutKind::FadeBlack).map(|c| c.frame).collect();
883 assert!(!fades.is_empty(), "the real fade through black is not found: {cuts:?}");
884 assert!(fades.iter().all(|&f| (200..=290).contains(&f)), "a fade in the steady dark part: {fades:?}");
885 // The steady dark shot on its own, and a frame in the middle of it: near-black share and
886 // a dip are both judged on the decoded pixels.
887 assert!(!real_fade(&path, 100, 25, 350), "steady dark frame judged a fade");
888 assert!(real_fade(&path, fades[0], 25, 350), "the kept fade at {} is not confirmed", fades[0]);
889 }
890
891 /// Steady dark grain whose mean luma drifts across 16 (a slow flicker), so the engine's
892 /// mean-luma dark run fires on it twice. The pixels are not near-black, so neither is a fade.
893 #[test]
894 fn steady_dark_flicker_is_not_a_fade() {
895 let dir = TestDir::new("scan-flicker");
896 let path = dir.join("flicker.mp4");
897 let ok = Command::new("ffmpeg")
898 .args(["-v", "error", "-y", "-f", "lavfi", "-t", "6", "-i", "color=c=0x0a0a0a:s=320x180:r=25"])
899 .args(["-vf", "noise=alls=40:allf=t,eq=brightness='0.012*sin(2*PI*t/2)':eval=frame", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"])
900 .arg(&path)
901 .status()
902 .expect("ffmpeg runs")
903 .success();
904 assert!(ok);
905 let cuts = cuts_for(None, &path, (0, 150), &SceneSettings::default()).unwrap().cuts;
906 assert!(cuts.iter().all(|c| c.kind != CutKind::FadeBlack), "grain judged a fade: {cuts:?}");
907 }
908
909 #[test]
910 fn a_fade_needs_near_black_on_most_of_the_frame() {
911 let (_dir, path) = dark_then_fade("share");
912 // Frame 100 is steady dark grain: a share of its pixels at luma 16 or below is well under
913 // four in five, so it is refused whatever its mean does.
914 let frames = frames_between(&path, 100, 100).expect("frame 100 decodes");
915 let (mean, share) = luma_stats(&frames[0].1);
916 assert!(mean < 24.0 && mean > 10.0, "grain frame mean {mean}");
917 assert!(share < FADE_BLACK_SHARE, "grain frame has {share} near-black");
918 }
919
920 #[test]
921 fn luma_stats_averages_each_pixel_and_counts_the_near_black_ones() {
922 // Two pixels, BGRA: pure black (luma 0) and pure white (luma 255). Each is four bytes,
923 // so the mean is 127.5 and half the pixels are at luma 16 or below.
924 let f = Frame { index: 0, width: 2, height: 1, bgra: vec![0, 0, 0, 255, 255, 255, 255, 255] };
925 let (mean, share) = luma_stats(&f);
926 assert!((mean - 127.5).abs() < 1e-9, "mean {mean}");
927 assert!((share - 0.5).abs() < 1e-9, "near-black share {share}");
928 }
929
930 /// A dissolve from frame 100 to 130 splits the shots at its ends: the old shot stops at 100 and
931 /// the new one starts at 130, so the dissolve's own frames are in no shot.
932 #[test]
933 fn a_dissolve_leaves_its_frames_out_of_both_shots() {
934 let cuts = [
935 Cut { frame: 60, score: 0.5, kind: CutKind::Hard },
936 Cut { frame: 100, score: 0.6, kind: CutKind::Dissolve { end: 130 } },
937 ];
938 assert_eq!(shots_of(0, 200, &cuts), vec![(0, 60), (60, 100), (130, 200)]);
939 }
940
941 /// A synthetic frame-difference series: `series[i]` is the picture of frame i, as a luma level,
942 /// and the distance between two frames is their level gap over 255 (a flat picture per frame).
943 fn levels(series: &[f64]) -> impl Fn(u32, u32) -> f64 + '_ {
944 move |a, b| match (series.get(a as usize), series.get(b as usize)) {
945 (Some(x), Some(y)) => (x - y).abs() / 255.0,
946 _ => f64::NAN,
947 }
948 }
949
950 /// Shot A (level 130) for 10 frames, a 3-frame white flash (255) at frames 10 to 12, then shot A
951 /// again: a flash, not a cut, so `flash_span` at 13 (the first frame back) names [10, 13).
952 #[test]
953 fn a_three_frame_flash_is_found_from_its_end_and_its_start() {
954 let mut s = vec![130.0; 20];
955 s[10..13].fill(255.0);
956 let d = levels(&s);
957 assert_eq!(flash_span(13, &d), Some((10, 13)));
958 assert_eq!(flash_span(10, &d), Some((10, 13)));
959 }
960
961 /// A real hard cut from A to B (B stays): the picture never comes back, so no flash.
962 #[test]
963 fn a_hard_cut_to_a_new_shot_is_not_a_flash() {
964 let mut s = vec![130.0; 20];
965 s[10..].fill(60.0);
966 let d = levels(&s);
967 assert_eq!(flash_span(10, &d), None);
968 assert_eq!(flash_span(15, &d), None);
969 }
970
971 /// A flash of five frames is longer than the flash limit, so it is kept as a cut.
972 #[test]
973 fn a_flash_longer_than_the_limit_is_kept_as_a_cut() {
974 let mut s = vec![130.0; 20];
975 s[10..15].fill(255.0);
976 let d = levels(&s);
977 assert_eq!(flash_span(15, &d), None);
978 }
979
980 /// A flash whose frames are close to the picture before them differs too little to be one.
981 #[test]
982 fn a_dip_the_size_of_grain_is_not_a_flash() {
983 let mut s = vec![130.0; 20];
984 s[10..13].fill(136.0);
985 let d = levels(&s);
986 assert_eq!(flash_span(13, &d), None);
987 }
988
989 /// Unknown distances (a frame the decoder did not give) never make a flash.
990 #[test]
991 fn unknown_frames_never_make_a_flash() {
992 let d = |_: u32, _: u32| f64::NAN;
993 assert_eq!(flash_span(13, &d), None);
994 assert_eq!(flash_span(0, &d), None);
995 }
996
997 /// Hard cuts within a second after a fade in are its steps, and go; a hard cut well after the
998 /// fade, or before it, stays.
999 #[test]
1000 fn hard_cuts_inside_a_fade_in_are_dropped() {
1001 let cut = |frame, kind| Cut { frame, score: 0.1, kind };
1002 let mut cuts = vec![
1003 cut(100, CutKind::Hard),
1004 cut(304, CutKind::FadeBlack),
1005 cut(322, CutKind::Hard),
1006 cut(334, CutKind::Hard),
1007 cut(335, CutKind::Hard),
1008 ];
1009 drop_cuts_in_fades(&mut cuts, 30);
1010 let kept: Vec<u32> = cuts.iter().map(|c| c.frame).collect();
1011 assert_eq!(kept, vec![100, 304, 335]);
1012 }
1013}