forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

see.rs2854 lines, 129.3 KiBHistoryRawDownload
1//! See tools: one composed frame, and a contact sheet of many (MCP.md section 4.4).
2//!
3//! Both return PNG image blocks (`Reply::image`), a text line that says what is
4//! on screen, and a copy of the PNG in the persistent frame cache
5//! (`$XDG_CACHE_HOME/edith/frames/<project>/`) so the agent can re-open it later.
6//! Everything is headless: nothing here touches a window.
7
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicUsize, Ordering};
10
11use serde_json::{json, Value};
12
13use engine::decode::{to_png_bytes, DecodeSession, Frame};
14use engine::export::{fit_picture_clips, output_meta, ExportSettings, FitOutcome};
15use engine::project::{Clip, Lane, LaneKind, Title};
16use engine::scale::{crop_rect, fit_rect, nearest_90_steps, transformed_dst_rect, FitPolicy, Rect};
17use engine::text::overlay;
18use engine::{Project, PlaybackSession, VideoMeta};
19
20use crate::parse;
21use crate::server::{opt_str, tri, Reply, Server, Tool};
22use crate::tools::edit_fx::place_word;
23use crate::tools::export::{burn_schema, clash_note, parse_burn, parse_fit, parse_size, BURN_KEY};
24
25const FRAME_DEFAULT_W: u32 = 640;
26const FRAME_MAX_W: u32 = 1920;
27const SHEET_DEFAULT_COUNT: u32 = 12;
28const SHEET_MAX_COUNT: u32 = 48;
29const SHEET_DEFAULT_COLS: u32 = 4;
30const SHEET_DEFAULT_W: u32 = 1280;
31const SHEET_MAX_W: u32 = 2400;
32/// Dark gutter between tiles, in pixels.
33const GUTTER: u32 = 4;
34/// The band above each contact-sheet tile that holds its timecode: the 7-row glyphs at
35/// `SCALE` px, the outline, and a margin.
36const LABEL_H: u32 = (7 * SCALE) as u32 + 6;
37/// Fill colour of the sheet: BGRA, dark grey.
38const GUTTER_FILL: [u8; 4] = [24, 24, 24, 255];
39const WHITE: [u8; 4] = [255, 255, 255, 255];
40const BLACK: [u8; 4] = [0, 0, 0, 255];
41/// The fill and cross of a picture whose file is offline.
42const MISSING_FILL: [u8; 4] = [48, 48, 48, 255];
43const MISSING_MARK: [u8; 4] = [150, 150, 150, 255];
44/// Pixels per glyph pixel in the stamp.
45const SCALE: i64 = 2;
46/// Cut points listed in a contact sheet before "and N more".
47const CUTS_CAP: usize = 40;
48
49const FRAME_DOC: &str = "One frame of the composed timeline as a PNG image. Arguments: at (required: \
50a frame, a timecode or seconds; with source, a time in that source); source (src:<n>, takes the \
51frame from that source file instead of the timeline); width (pixels, default 640, max 1920); \
52save (a path you give: one more copy of the PNG is written there, parent folders are created); \
53burn_captions (true, or an object, to draw the timeline's captions onto the frame; not with source); \
54size (WIDTHxHEIGHT such as 1080x1920, or a height such as 1080p) and fit (keep, fit or fill) preview \
55the timeline as export_start would draw it at that picture size and fit: the reply says it is a \
56preview of that export size, and the project is not changed (not with source). \
57The PNG is always written to the frame cache, ~/.cache/edith/frames/<project>/ (or \
58$XDG_CACHE_HOME/edith/frames/<project>/), named <at>-<width>-<hash>.png; the cache keeps the newest \
59200 frames. The reply's `saved:` line gives the save path when you passed save, else the cache path. \
60The text says which clip is on each lane at that frame, and lists the layers (a picture over \
61another is named; a dissolve in progress shows its two clips and how far it has run). \
62Seconds round to the nearest frame, and the reply then shows both: `0.5s → 13f`.";
63
64const SHEET_DOC: &str = "A grid of frames, evenly spaced through a range (default the whole \
65timeline), each stamped with its timecode, as one PNG image. Arguments: range ({from, to}, default \
66the whole timeline, or the whole source with source); count (frames, default 12, max 48); cols \
67(tiles per row, default 4); width (whole sheet in pixels, default 1280, max 2400); source (src:<n>, \
68samples that source file; range is then in its time); save (a path you give: one more copy of the \
69PNG is written there, parent folders are created); burn_captions (as for frame; not with source). \
70The PNG is always written to the frame cache, ~/.cache/edith/frames/<project>/ (or \
71$XDG_CACHE_HOME/edith/frames/<project>/), and its path is in the reply's `saved:` line when you \
72pass no save. The text lists each tile's time and the clip under it, and the edit joins inside the \
73range (the joins between clips on the picture lanes: hard cuts, and dissolves with their length, \
74listed apart), so a tile can be related to a join. Picture cuts inside a clip are not joins: the \
75line points to scenes for them. With source there are no joins, and the line says so. \
76Each tile's timecode is stamped on it when it fits the tile; on narrow tiles (about 240 px wide with \
774 columns) the stamps are left off and the text lists the times.";
78
79const SCOPES_DOC: &str = "The video scopes of one frame of the composed timeline, as numbers: a luma \
80waveform, an RGB parade and a vectorscope, read from the graded picture at low resolution (what export \
81draws). Arguments: at (required: a frame, a timecode or seconds); bands (waveform bands left to right, \
82default 4, max 16). Levels are display percent, 0 black and 100 white (full-range R'G'B' of the Rec. 709 \
83picture). The reply gives: luma min / 5th percentile / median / 95th / max and mean, the share of the \
84frame crushed (luma at or under 2%) and clipped (at or over 98%); the waveform's p5 / median / p95 per \
85band, left to right; each of red, green and blue as the parade shows it, and which channel sits highest; \
86the mean saturation and the cast (how far, and toward which hue, the picture's average sits off grey on \
87the vectorscope). A LUT a clip names that cannot be used (missing or broken) is listed.";
88
89fn scopes_schema() -> Value {
90 json!({
91 "type": "object",
92 "description": SCOPES_DOC,
93 "properties": {
94 "at": {
95 "type": ["string", "number"],
96 "description": "The frame to read: 450f, 15.0s, 00:00:15:00, or a number of seconds."
97 },
98 "bands": {
99 "type": "integer",
100 "minimum": 1,
101 "maximum": 16,
102 "description": "Waveform bands, left to right. Default 4."
103 }
104 },
105 "required": ["at"]
106 })
107}
108
109/// Width the scopes read the frame at: plenty for a scope, and quick.
110const SCOPES_W: u32 = 320;
111
112fn scopes(server: &mut Server, args: &Value) -> Reply {
113 let bands = match args.get("bands") {
114 None | Some(Value::Null) => 4,
115 Some(v) => match v.as_u64().filter(|b| (1..=16).contains(b)) {
116 Some(b) => b as usize,
117 None => return Reply::err("bands is a whole number 1..16"),
118 },
119 };
120 let s = tri!(server.session_ref());
121 let fps = parse::session_fps(s);
122 let end = parse::session_end(s);
123 let at = tri!(parse::frame_arg(args, "at", fps, end));
124 let (project, meta) = s.export_snapshot();
125 let media = project.media_frames();
126 if at >= media {
127 return Reply::err(past_end_message(args, fps, at, media));
128 }
129 let f = match engine::export::compose_at_with(&project, &meta, at, SCOPES_W, SCOPES_W * 4, None) {
130 Ok(f) => f,
131 Err(e) => return Reply::err(format!("cannot compose frame {at}: {e}")),
132 };
133 let sc = engine::scopes::compute(&f.bgra, f.width as usize, f.height as usize, 64);
134 let sum = sc.summary(bands);
135 let r1 = |v: f32| (v * 10.0).round() / 10.0;
136 let sp = |x: &engine::scopes::Spread| {
137 format!("{:.0}/{:.0}/{:.0}/{:.0}/{:.0} (mean {:.1})", x.min, x.p5, x.median, x.p95, x.max, x.mean)
138 };
139 let names = ["red", "green", "blue"];
140 let means = [sum.spread[1].mean, sum.spread[2].mean, sum.spread[3].mean];
141 let hi = (0..3).max_by(|&a, &b| means[a].total_cmp(&means[b])).unwrap_or(0);
142 let lo = (0..3).min_by(|&a, &b| means[a].total_cmp(&means[b])).unwrap_or(0);
143 let balance = if means[hi] - means[lo] < 2.0 {
144 "channels balanced (means within 2%)".to_string()
145 } else {
146 format!("{} highest, {} lowest ({:.1}% apart)", names[hi], names[lo], means[hi] - means[lo])
147 };
148 let cast = if sum.cast < 1.0 {
149 "no cast (average within 1% of grey)".to_string()
150 } else {
151 format!("cast toward {} ({:.1}% off grey, {:.0}°)", engine::scopes::hue_word(sum.cast_angle), sum.cast, sum.cast_angle)
152 };
153 let bands_text: Vec<String> = sum.bands.iter().map(|b| format!("{:.0}/{:.0}/{:.0}", b[0], b[1], b[2])).collect();
154 let mut text = format!(
155 "scopes · {} ({}) · read at {}x{}\n\
156 waveform (luma %, min/p5/median/p95/max): {}; crushed {:.1}%, clipped {:.1}%\n\
157 waveform bands left→right (p5/median/p95): {}\n\
158 parade: red {}; green {}; blue {}; {balance}\n\
159 vectorscope: mean saturation {:.1}%; {cast}",
160 parse::clock(at, fps),
161 rounded_frame(args, fps, at),
162 f.width,
163 f.height,
164 sp(&sum.spread[0]),
165 sum.crushed,
166 sum.clipped,
167 bands_text.join(" | "),
168 sp(&sum.spread[1]),
169 sp(&sum.spread[2]),
170 sp(&sum.spread[3]),
171 sum.saturation,
172 );
173 let problems = s.lut_problems();
174 for (path, why) in &problems {
175 text.push_str(&format!("\nLUT not applied: {} ({why})", path.display()));
176 }
177 let spread_json = |x: &engine::scopes::Spread| {
178 json!({"min": r1(x.min), "p5": r1(x.p5), "median": r1(x.median), "p95": r1(x.p95), "max": r1(x.max), "mean": r1(x.mean)})
179 };
180 let structured = json!({
181 "frame": at,
182 "seconds": parse::secs(at, fps),
183 "luma": spread_json(&sum.spread[0]),
184 "crushed_pct": r1(sum.crushed),
185 "clipped_pct": r1(sum.clipped),
186 "waveform_bands": sum.bands.iter().map(|b| json!([r1(b[0]), r1(b[1]), r1(b[2])])).collect::<Vec<Value>>(),
187 "parade": {"red": spread_json(&sum.spread[1]), "green": spread_json(&sum.spread[2]), "blue": spread_json(&sum.spread[3])},
188 "saturation_pct": r1(sum.saturation),
189 "cast": {"pct": r1(sum.cast), "angle": r1(sum.cast_angle), "hue": engine::scopes::hue_word(sum.cast_angle)},
190 "lut_problems": problems.iter().map(|(p, e)| json!({"path": p.display().to_string(), "problem": e})).collect::<Vec<Value>>(),
191 });
192 Reply::ok(text).with(structured)
193}
194
195pub fn tools() -> Vec<Tool> {
196 vec![
197 Tool { name: "frame", description: FRAME_DOC, schema: frame_schema, run: frame },
198 Tool { name: "contact_sheet", description: SHEET_DOC, schema: sheet_schema, run: contact_sheet },
199 Tool { name: "scopes", description: SCOPES_DOC, schema: scopes_schema, run: scopes },
200 ]
201}
202
203// ---- schemas --------------------------------------------------------------
204
205fn frame_schema() -> Value {
206 json!({
207 "type": "object",
208 "description": FRAME_DOC,
209 "properties": {
210 "at": {
211 "type": ["string", "number"],
212 "description": "The frame to show: 450f, 15.0s, 00:00:15:00, 01:02.500, or a number of seconds. Seconds round to the nearest frame (0.5s at 25 fps is frame 13). On the timeline unless source is given; with source, a time in that source file."
213 },
214 "source": {
215 "type": "string",
216 "description": "A source to take the frame from instead of the timeline, such as src:2. Then `at` is a time in that source."
217 },
218 "width": {
219 "type": "integer",
220 "minimum": 1,
221 "maximum": FRAME_MAX_W,
222 "description": "Width of the image in pixels; the height follows the aspect. Default 640, max 1920."
223 },
224 "save": {
225 "type": "string",
226 "description": "Also write one more copy of the PNG to this path (parent folders are created). The frame cache copy is always written too; the reply's saved line gives this path."
227 },
228 "size": {
229 "type": "string",
230 "description": "Preview the timeline at this export picture size, as export_start takes it: WIDTHxHEIGHT such as 1080x1920, or a height with a p such as 1080p (16:9). Both sides even. The image is the export's frame scaled to width; the reply says it is a preview of that size."
231 },
232 "fit": {
233 "type": "string",
234 "enum": ["keep", "fit", "fill"],
235 "description": "Preview the export's fit of full-frame picture clips, as export_start takes it: keep (each clip's own fit, the default), fit, or fill. Overlays keep their own fit."
236 },
237 "burn_captions": burn_schema()
238 },
239 "required": ["at"]
240 })
241}
242
243fn sheet_schema() -> Value {
244 json!({
245 "type": "object",
246 "description": SHEET_DOC,
247 "properties": {
248 "range": {
249 "type": "object",
250 "description": "The stretch to sample. Omit for the whole timeline (or, with source, the whole source).",
251 "properties": {
252 "from": {
253 "type": ["string", "number"],
254 "description": "Start of the stretch, inclusive. Defaults to 0. Times as for `at` in frame."
255 },
256 "to": {
257 "type": ["string", "number"],
258 "description": "End of the stretch, exclusive. Defaults to the end."
259 }
260 }
261 },
262 "count": {
263 "type": "integer",
264 "minimum": 1,
265 "maximum": SHEET_MAX_COUNT,
266 "description": "How many frames to sample, evenly spaced, each at the centre of its interval. Default 12, max 48."
267 },
268 "cols": {
269 "type": "integer",
270 "minimum": 1,
271 "maximum": SHEET_MAX_COUNT,
272 "description": "Tiles per row. Default 4; at most count."
273 },
274 "width": {
275 "type": "integer",
276 "minimum": 1,
277 "maximum": SHEET_MAX_W,
278 "description": "Total width of the sheet in pixels. Default 1280, max 2400."
279 },
280 "source": {
281 "type": "string",
282 "description": "Sample a source file instead of the timeline, such as src:2. Then range is in that source's time."
283 },
284 "save": {
285 "type": "string",
286 "description": "Also write one more copy of the PNG to this path (parent folders are created). The frame cache copy is always written too; the reply's saved line gives this path."
287 },
288 "burn_captions": burn_schema()
289 }
290 })
291}
292
293// ---- frame ----------------------------------------------------------------
294
295fn frame(server: &mut Server, args: &Value) -> Reply {
296 let width = match width_arg(args, FRAME_DEFAULT_W, FRAME_MAX_W) {
297 Ok(w) => w,
298 Err(r) => return r,
299 };
300 let save = opt_str(args, "save").map(PathBuf::from);
301 match opt_str(args, "source") {
302 None => timeline_frame(server, args, width, save),
303 Some(_) if burn_asked(args) => {
304 Reply::err("burn_captions draws the timeline's captions: it cannot be used with source")
305 }
306 Some(_) if export_asked(args) => {
307 Reply::err("size and fit preview the timeline's export: they cannot be used with source")
308 }
309 Some(src) => source_frame(server, args, src, width, save),
310 }
311}
312
313/// Whether `size` or `fit` is given: the frame then previews the timeline as an export draws it.
314fn export_asked(args: &Value) -> bool {
315 [args.get("size"), args.get("fit")].into_iter().flatten().any(|v| !v.is_null())
316}
317
318/// The line a size or fit preview says: which export it stands for and what its fit reached.
319fn preview_words(meta: &VideoMeta, fit: Option<FitPolicy>, outcome: Option<&FitOutcome>) -> String {
320 // parse_fit only gives keep (no policy), fit or fill.
321 let word = match fit {
322 Some(FitPolicy::Fill) => "fill",
323 Some(FitPolicy::Fit) => "fit",
324 _ => "keep",
325 };
326 let on_fit = match outcome {
327 Some(o) => {
328 let clips: usize = o.lanes.iter().map(|(_, n)| n).sum();
329 format!(", {clips} full-frame clip(s) on it, {} overlay(s) keep their own", o.overlays)
330 }
331 None => String::new(),
332 };
333 format!("preview of the export at {}x{} (fit {word}{on_fit}); the project is unchanged", meta.width, meta.height)
334}
335
336/// The frame as the reply names it: `13f` when the `at` argument was exact, and
337/// `0.5s → 13f` when it was seconds that rounded to a frame (MCP.md 3.1).
338fn rounded_frame(args: &Value, fps: f64, at: u32) -> String {
339 let secs = match args.get("at") {
340 Some(Value::Number(n)) => n.as_f64(),
341 Some(Value::String(s)) if !s.trim_end().ends_with('f') && !s.contains(':') => {
342 s.trim().trim_end_matches('s').parse::<f64>().ok()
343 }
344 _ => None,
345 };
346 match secs {
347 Some(secs) if (secs * fps - at as f64).abs() > 1e-6 => format!("{secs}s → {at}f"),
348 _ => format!("{at}f"),
349 }
350}
351
352/// The refusal for a frame at or past the end of the timeline. It names the time
353/// the caller gave in seconds, the timeline length, and for an empty timeline
354/// the way out (media_import adds sources without placing them).
355fn past_end_message(args: &Value, fps: f64, at: u32, media: u32) -> String {
356 let asked = match args.get("at") {
357 Some(Value::Number(n)) => n.as_f64().map(|secs| format!("{secs:.1}s")),
358 Some(Value::String(s)) if !s.trim_end().ends_with('f') && !s.contains(':') => {
359 s.trim().trim_end_matches('s').parse::<f64>().ok().map(|secs| format!("{secs:.1}s"))
360 }
361 _ => None,
362 };
363 let asked = asked.unwrap_or_else(|| format!("frame {at}"));
364 if media == 0 {
365 return format!(
366 "{asked} is past the end: the timeline is empty. media_import adds sources without placing them; \
367 place or append them first, or use frame {{source:\"src:N\", at}} to look at a source"
368 );
369 }
370 let len = f64::from(media) / fps;
371 format!("{asked} is past the end (timeline {len:.1}s); pick a time before the end")
372}
373
374/// Whether the `at` argument is the word `end`.
375fn asks_end(args: &Value) -> bool {
376 matches!(args.get("at"), Some(Value::String(s)) if s.trim().eq_ignore_ascii_case("end"))
377}
378
379/// The warning for two titles on the same place that overlap in time, as a reply line that
380/// starts with a newline (empty when they do not). The window named is the part where both
381/// are on screen: `two titles overlap at top 1.0–3.0s`. Used by the frame and by title adds.
382pub(crate) fn overlap_line(a: &Title, b: &Title, fps: f64) -> String {
383 if a.style.place != b.style.place {
384 return String::new();
385 }
386 let from = a.start.max(b.start);
387 let to = a.end().min(b.end());
388 if from >= to {
389 return String::new();
390 }
391 let from = secs_text(parse::secs(from, fps));
392 let window = format!("{}–{}", from.trim_end_matches('s'), secs_text(parse::secs(to, fps)));
393 format!("\n warning: two titles overlap at {} {window}", place_word(a.style.place))
394}
395
396/// A frame's size as the reply gives it. A preview narrower than the thing it stands for says
397/// so and names that size: `preview 640x1137 (the export is 1080x1920)`.
398fn size_text(w: u32, h: u32, full: (u32, u32), whole: &str) -> String {
399 if (w, h) == full {
400 format!("{w}x{h}")
401 } else {
402 format!("preview {w}x{h} ({whole} is {}x{})", full.0, full.1)
403 }
404}
405
406/// A path as the reply names it: absolute, so the person can open it from anywhere.
407fn absolute_path(p: PathBuf) -> PathBuf {
408 std::path::absolute(&p).unwrap_or(p)
409}
410
411/// The warnings for a title on screen that covers part of a picture on an upper lane: every
412/// visible picture lane but the bottom one. The title's box is what `overlay` draws for it at the
413/// export size, and the picture's box is where the composite places its clip.
414fn title_cover_lines(s: &PlaybackSession, project: &Project, meta: &VideoMeta, at: u32) -> Vec<String> {
415 let visible: Vec<Lane> = s.lanes().into_iter().filter(|l| l.kind == LaneKind::Video && !s.lane_hidden(*l)).collect();
416 let upper: Vec<(Lane, usize)> = visible
417 .iter()
418 .skip(1)
419 .filter_map(|&l| s.lane_clips(l).iter().position(|c| c.start <= at && at < c.end()).map(|i| (l, i)))
420 .collect();
421 let mut out = Vec::new();
422 if upper.is_empty() {
423 return out;
424 }
425 let canvas = (meta.width, meta.height);
426 for (ti, t) in s.titles().iter().enumerate() {
427 if t.alpha_at(at) == 0 {
428 continue;
429 }
430 let Some(ink) = title_box(t, canvas) else {
431 continue;
432 };
433 for &(lane, idx) in &upper {
434 let clip = &s.lane_clips(lane)[idx];
435 let Some(src) = s.sources().get(clip.source) else {
436 continue;
437 };
438 let Some((w, h)) = picture_size(&src.path) else {
439 continue;
440 };
441 if !boxes_meet(ink, picture_box(project, lane, idx, at, (w, h), canvas)) {
442 continue;
443 }
444 let name = src.path.file_stem().map(|n| format!(" ({})", n.to_string_lossy())).unwrap_or_default();
445 out.push(format!(
446 "\n warning: title T{} covers part of {}{name}",
447 ti + 1,
448 parse::addr(lane, clip.start)
449 ));
450 }
451 }
452 out
453}
454
455/// The box a title draws on a `size` canvas, as `[x0, y0, x1, y1)`. It is found by blending the
456/// overlay over a white canvas and over a black one: a plate darkens the white, and the glyphs
457/// light the black, so the pixels that change are the ones the title covers.
458fn title_box(t: &Title, (w, h): (u32, u32)) -> Option<(u32, u32, u32, u32)> {
459 let lines: Vec<String> = t.text.split('\n').map(str::to_string).collect();
460 let ov = overlay(&t.style, w, h, &lines);
461 let mut hit: Option<(u32, u32, u32, u32)> = None;
462 for fill in [255u8, 0] {
463 let mut canvas = vec![fill; w as usize * h as usize * 4];
464 ov.blend_bgra(&mut canvas);
465 for (i, px) in canvas.as_chunks::<4>().0.iter().enumerate() {
466 if px[..3].iter().all(|&c| c == fill) {
467 continue;
468 }
469 let (x, y) = (i as u32 % w, i as u32 / w);
470 hit = Some(match hit {
471 None => (x, y, x + 1, y + 1),
472 Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)),
473 });
474 }
475 }
476 hit
477}
478
479/// The displayed size of a source's picture: a video's, or a still's. `None` for sound alone.
480fn picture_size(path: &Path) -> Option<(u32, u32)> {
481 match engine::probe_media(path).video {
482 Some(v) => Some((v.width, v.height)),
483 None if engine::is_image(path) => engine::decode::image_size(path).ok(),
484 None => None,
485 }
486}
487
488/// The box a clip covers on the `canvas` at `at`, with its fit policy and transform applied as the
489/// composite applies them (the crop first, then the quarter turn, then the placement).
490fn picture_box(project: &Project, lane: Lane, idx: usize, at: u32, (w, h): (u32, u32), canvas: (u32, u32)) -> Rect {
491 let t = project.transform_at(lane, idx, at).unwrap_or_default();
492 let crop = crop_rect(w, h, &t);
493 let (rw, rh) = if nearest_90_steps(t.rotate) % 2 == 1 { (crop.h, crop.w) } else { (crop.w, crop.h) };
494 let (dst, placed) = fit_rect(rw, rh, canvas.0, canvas.1, project.fit_of(lane, idx));
495 transformed_dst_rect(dst, placed, rw, rh, &t, canvas.0, canvas.1).0
496}
497
498/// Whether a title's box `[x0, y0, x1, y1)` shares a pixel with a picture's rect.
499fn boxes_meet((x0, y0, x1, y1): (u32, u32, u32, u32), r: Rect) -> bool {
500 !r.is_empty() && x0 < r.x + r.w && r.x < x1 && y0 < r.y + r.h && r.y < y1
501}
502
503/// The sources the picture lanes read at `at` whose files are not on disk, as (index, path),
504/// one entry per source. A hidden lane is not drawn, so a clip on one does not count.
505fn offline_under(s: &PlaybackSession, at: u32) -> Vec<(usize, PathBuf)> {
506 let mut out: Vec<(usize, PathBuf)> = Vec::new();
507 for lane in s.lanes().into_iter().filter(|l| l.kind == LaneKind::Video && !s.lane_hidden(*l)) {
508 let Some(c) = s.lane_clips(lane).iter().find(|c| c.start <= at && at < c.end()) else {
509 continue;
510 };
511 let Some(src) = s.sources().get(c.source) else {
512 continue;
513 };
514 if !engine::source_present(&src.path) && !out.iter().any(|(i, _)| *i == c.source) {
515 out.push((c.source, src.path.clone()));
516 }
517 }
518 out
519}
520
521/// The sentence that names an offline source and the fix, for a reply or a refusal.
522fn offline_line(idx: usize, path: &Path) -> String {
523 format!("src:{idx} {} is offline; its picture is missing here — relink with media_relink", path.display())
524}
525
526/// The picture drawn where a clip's file is offline: a grey tile with a cross, as tall as
527/// the composed frame would be at `width` for a picture of `src_w` by `src_h`.
528fn missing_tile(width: u32, src_w: u32, src_h: u32) -> Frame {
529 let height = (u64::from(width) * u64::from(src_h) / u64::from(src_w.max(1))).max(1) as u32;
530 let mut c = Canvas::new(width, height, MISSING_FILL);
531 let (w, h) = (i64::from(width), i64::from(height));
532 for x in 0..w {
533 let y = x * h / w;
534 for d in -1..=1 {
535 c.put(x, y + d, MISSING_MARK);
536 c.put(w - 1 - x, y + d, MISSING_MARK);
537 }
538 }
539 c.into_frame()
540}
541
542/// Whether `burn_captions` is switched on: `true` or an object. `false`, `null`
543/// and an absent key are off.
544fn burn_asked(args: &Value) -> bool {
545 !matches!(args.get(BURN_KEY), None | Some(Value::Null | Value::Bool(false)))
546}
547
548/// The `burn_captions` argument as [`parse_burn`] reads it. `true` means the
549/// defaults, `{}`; `false` means off, as an absent key does.
550fn burn_of(
551 args: &Value,
552 s: &PlaybackSession,
553) -> Result<Option<(usize, engine::text::TextStyle)>, String> {
554 match args.get(BURN_KEY) {
555 Some(Value::Bool(true)) => parse_burn(&json!({ BURN_KEY: {} }), s),
556 Some(Value::Bool(false)) => Ok(None),
557 _ => parse_burn(args, s),
558 }
559}
560
561fn timeline_frame(server: &mut Server, args: &Value, width: u32, save: Option<PathBuf>) -> Reply {
562 let s = tri!(server.session_ref());
563 let fps = parse::session_fps(s);
564 let end = parse::session_end(s);
565 let at = tri!(parse::frame_arg(args, "at", fps, end));
566 let burn = match burn_of(args, s) {
567 Ok(b) => b,
568 Err(e) => return Reply::err(e),
569 };
570 let (mut project, mut meta) = s.export_snapshot();
571 let media = project.media_frames();
572 // `end` is the timeline's last frame: the frame after it is the one that is past the end.
573 let at = if at >= media && asks_end(args) { media.saturating_sub(1) } else { at };
574 if at >= media {
575 return Reply::err(past_end_message(args, fps, at, media));
576 }
577 // size and fit preview the export as export_start draws it: the same per-export picture size
578 // and fit, on this copy of the timeline only, so the project keeps its own.
579 let (size, fit) = match (parse_size(args), parse_fit(args)) {
580 (Ok(sz), Ok(f)) => (sz, f),
581 (Err(e), _) | (_, Err(e)) => return Reply::err(e),
582 };
583 let fitted = fit.map(|f| (f, fit_picture_clips(&mut project, f)));
584 if let Some((w, h)) = size {
585 meta = output_meta(&meta, &ExportSettings { size: Some((w, h)), ..ExportSettings::default() });
586 }
587 let preview = (size.is_some() || fit.is_some())
588 .then(|| preview_words(&meta, fit, fitted.as_ref().map(|(_, o)| o)));
589 let captions = burn.as_ref().map(|(track, _)| *track);
590 let burn_place = burn.as_ref().map(|(_, style)| style.place);
591 // A box this tall never limits the width, so the picture comes back at `width`. A clip
592 // reading an offline file cannot compose: its frame is drawn missing, and named below.
593 let (f, missing) = match engine::export::compose_at_with(&project, &meta, at, width, width * 4, burn) {
594 Ok(f) => (f, Vec::new()),
595 Err(e) => {
596 let missing = offline_under(s, at);
597 if missing.is_empty() {
598 return Reply::err(format!("cannot compose frame {at}: {e}"));
599 }
600 (missing_tile(width, meta.width, meta.height), missing)
601 }
602 };
603 let png = match to_png_bytes(&f) {
604 Ok(p) => p,
605 Err(e) => return Reply::err(format!("cannot encode frame {at} as PNG: {e}")),
606 };
607 let dir = frames_dir(server.path.as_deref());
608 let cached = tri!(save_png(&png, &dir, &format!("{at}-{}.png", f.width), save.as_deref()));
609 let saved = save.map(absolute_path).unwrap_or_else(|| cached.clone());
610 let size = size_text(f.width, f.height, (meta.width, meta.height), "the export");
611 let under = describe_timeline(s, at);
612 let head = match (under.top_addr.as_deref(), hidden_only_text(&under.hidden_here)) {
613 (None, Some(hidden)) => format!(
614 "hidden lane only · black ({hidden}) · {} ({}) · {size}",
615 parse::clock(at, fps),
616 rounded_frame(args, fps, at),
617 ),
618 (top, _) => format!(
619 "{} · {} ({}) · {} · {size}",
620 top.unwrap_or("gap"),
621 parse::clock(at, fps),
622 rounded_frame(args, fps, at),
623 under.top_desc.as_deref().unwrap_or("black"),
624 ),
625 };
626 let mut text = head;
627 if let Some(p) = &preview {
628 text.push('\n');
629 text.push_str(p);
630 }
631 for line in &under.lines {
632 text.push_str("\n ");
633 text.push_str(line);
634 }
635 let (layer_lines, layer_json) = layer_notes(s, at);
636 for line in &layer_lines {
637 text.push_str("\n ");
638 text.push_str(line);
639 }
640 for (i, p) in &missing {
641 text.push('\n');
642 text.push_str(&offline_line(*i, p));
643 }
644 if let Some(line) = super::stabilise::pending_in(s, at, at) {
645 text.push('\n');
646 text.push_str(&line);
647 }
648 let titles: Vec<String> = s
649 .titles()
650 .iter()
651 .filter(|t| t.alpha_at(at) > 0)
652 .map(|t| t.text.replace('\n', " / "))
653 .collect();
654 for t in &titles {
655 text.push_str(&format!("\ntitle on screen: \"{t}\""));
656 }
657 // Two titles of one place on screen here draw over each other: each pair is named.
658 let on: Vec<&Title> = s.titles().iter().filter(|t| t.alpha_at(at) > 0).collect();
659 for (i, a) in on.iter().enumerate() {
660 for b in &on[i + 1..] {
661 text.push_str(&overlap_line(a, b, fps));
662 }
663 }
664 // A title on screen over a picture on an upper lane hides part of that picture: each is named.
665 for line in title_cover_lines(s, &project, &meta, at) {
666 text.push_str(&line);
667 }
668 // What the burn drew here, read from the same cues the picture was drawn from.
669 // The burn stacks every cue active at this frame, so each one is listed.
670 let drawn: Option<Vec<String>> = captions.map(|track| {
671 let cues = engine::export::burn_cues(&project, track, meta.frame_rate).unwrap_or_default();
672 let on_screen = engine::export::cues_on_screen(&cues, at, meta.frame_rate);
673 let shown: Vec<String> = on_screen.iter().map(|&i| cues[i].text.clone()).collect();
674 if shown.is_empty() {
675 text.push_str(&format!("\ncaptions burned (track {track}): no caption on screen at this frame"));
676 }
677 for words in &shown {
678 text.push_str(&format!("\ncaptions burned (track {track}): \"{}\"", words.replace('\n', " / ")));
679 }
680 // Mirrors export's no-glyph note, for the cues on screen here only: a character the
681 // caption face cannot draw in what this frame shows.
682 let lines: Vec<String> = on_screen
683 .iter()
684 .filter(|&&i| cues[i].image.is_none())
685 .map(|&i| cues[i].text.clone())
686 .collect();
687 let missing = engine::text::missing_glyphs(&lines);
688 if !missing.is_empty() {
689 let codes: Vec<String> = missing.iter().map(|c| format!("U+{:04X}", *c as u32)).collect();
690 text.push_str(&format!("\nno glyph for: {} (drawn as an empty box)", codes.join(" ")));
691 }
692 shown
693 });
694 // A caption drawn here and a title on screen here in the same place clash in the picture.
695 if let (Some(place), Some(shown)) = (burn_place, drawn.as_ref())
696 && !shown.is_empty()
697 {
698 for t in s.titles().iter().filter(|t| t.alpha_at(at) > 0 && t.style.place == place) {
699 text.push('\n');
700 text.push_str(&clash_note(parse::secs(at, fps), &t.text, place));
701 }
702 }
703 let picture = has_picture(s);
704 if !picture {
705 text.push_str("\nno picture here: the timeline is audio only, so the image is black");
706 }
707 text.push_str(&format!("\nsaved: {}", saved.display()));
708 let structured = json!({
709 "frame": at,
710 "seconds": parse::secs(at, fps),
711 "width": f.width,
712 "height": f.height,
713 "path": saved.display().to_string(),
714 "cache_path": cached.display().to_string(),
715 "lanes": under.structured,
716 "offline": missing.iter().map(|(i, p)| json!({"source": format!("src:{i}"), "path": p.display().to_string()})).collect::<Vec<Value>>(),
717 "layers": layer_json["layers"],
718 "dissolve": layer_json["dissolve"],
719 "titles": titles,
720 "picture": picture,
721 "captions_burned": captions,
722 "caption_drawn": drawn.as_ref().and_then(|d| d.first().cloned()),
723 "captions_drawn": drawn.unwrap_or_default(),
724 });
725 Reply::ok(text).with(structured).image("image/png", base64(&png))
726}
727
728fn source_frame(
729 server: &mut Server,
730 args: &Value,
731 src: &str,
732 width: u32,
733 save: Option<PathBuf>,
734) -> Reply {
735 let s = tri!(server.session_ref());
736 let idx = tri!(source_index(s, src));
737 let path = s.sources()[idx].path.clone();
738 let name = file_name(&path);
739 if !path.exists() {
740 return Reply::err(offline_line(idx, &path));
741 }
742 let fps = probe_fps(&path).unwrap_or_else(|| parse::session_fps(s));
743 let at = tri!(parse::frame_arg(args, "at", fps, u32::MAX));
744 // A still is a picture. Sound alone has none, so it is not decoded at all.
745 let facts = engine::probe_media(&path);
746 let picture = facts.video.is_some() || engine::is_image(&path);
747 if !picture && engine::is_audio(&path) {
748 return Reply::err(format!("no picture: {name} is audio only, so there is no frame to show"));
749 }
750 // A frame past the file's own length does not exist: say so with the length and the last time there is.
751 if let Some(secs) = probe_secs(&path) {
752 let len = (secs * fps).ceil() as u32;
753 if at >= len {
754 return Reply::err(past_length_text(&format!("src:{idx}"), secs, len, at, fps));
755 }
756 }
757 let f = match decode_source(&path, at, width) {
758 Ok(f) => f,
759 Err(e) => return Reply::err(e),
760 };
761 let png = match to_png_bytes(&f) {
762 Ok(p) => p,
763 Err(e) => return Reply::err(format!("cannot encode frame {at} as PNG: {e}")),
764 };
765 let dir = frames_dir(server.path.as_deref());
766 let cached = tri!(save_png(&png, &dir, &format!("src{idx}-{at}-{}.png", f.width), save.as_deref()));
767 let saved = save.map(absolute_path).unwrap_or(cached);
768 let size = match facts.video.as_ref() {
769 Some(v) => size_text(f.width, f.height, (v.width, v.height), "the source"),
770 None => format!("{}x{}", f.width, f.height),
771 };
772 let silent = if picture { "" } else { "\nno picture here: this source is audio only, so the image is black" };
773 let text = format!(
774 "src:{idx} {name} · {} ({}) · {size}{silent}\nsaved: {}",
775 parse::clock(at, fps),
776 rounded_frame(args, fps, at),
777 saved.display()
778 );
779 let structured = json!({
780 "source": format!("src:{idx}"),
781 "frame": at,
782 "seconds": parse::secs(at, fps),
783 "width": f.width,
784 "height": f.height,
785 "path": saved.display().to_string(),
786 });
787 Reply::ok(text).with(structured).image("image/png", base64(&png))
788}
789
790/// Seconds in plain words: at least one decimal, at most two (`0.53s`, `1.0s`, `0.5s`).
791fn secs_text(x: f64) -> String {
792 let s = format!("{x:.2}");
793 let t = s.trim_end_matches('0');
794 if t.ends_with('.') { format!("{t}0s") } else { format!("{t}s") }
795}
796
797/// The refusal for a frame past a source's known length of `len` frames (`secs` long). The last
798/// frame there is, `len - 1`, is the most a person can ask for.
799fn past_length_text(label: &str, secs: f64, len: u32, at: u32, fps: f64) -> String {
800 let last = len.saturating_sub(1);
801 format!(
802 "{label} is {} ({len}f) long; frame {at} ({}) is past its end — ask for at most {}",
803 secs_text(secs),
804 secs_text(f64::from(at) / fps),
805 secs_text(f64::from(last) / fps),
806 )
807}
808
809/// One source frame, scaled to `width` wide at its own aspect.
810fn decode_source(path: &Path, at: u32, width: u32) -> Result<Frame, String> {
811 let (_, rx, cancel) = DecodeSession::open_range(path, at, at.saturating_add(1))
812 .map_err(|e| format!("cannot open {} at frame {at}: {e}", file_name(path)))?;
813 let frame = rx
814 .recv()
815 .map_err(|_| {
816 format!(
817 "no picture at source frame {at} of {}: past its end, or the decoder gave none",
818 file_name(path)
819 )
820 });
821 cancel.store(true, Ordering::Relaxed);
822 let frame = frame?;
823 let h = fit_height(&frame, width);
824 Ok(resize(&frame, width, h))
825}
826
827// ---- contact sheet --------------------------------------------------------
828
829fn contact_sheet(server: &mut Server, args: &Value) -> Reply {
830 let count = match bounded(args, "count", SHEET_DEFAULT_COUNT, 1, SHEET_MAX_COUNT) {
831 Ok(v) => v,
832 Err(r) => return r,
833 };
834 let cols = match bounded(args, "cols", SHEET_DEFAULT_COLS.min(count), 1, count) {
835 Ok(v) => v,
836 Err(r) => return r,
837 };
838 let width = match bounded(args, "width", SHEET_DEFAULT_W, 1, SHEET_MAX_W) {
839 Ok(v) => v,
840 Err(r) => return r,
841 };
842 let tile_w = (width.saturating_sub((cols - 1) * GUTTER)) / cols;
843 let dir = frames_dir(server.path.as_deref());
844 let s = tri!(server.session_ref());
845 // A still sheets as one tile the whole width, so its columns never narrow it.
846 let still = opt_str(args, "source")
847 .and_then(|src| source_index(s, src).ok())
848 .is_some_and(|i| engine::is_image(&s.sources()[i].path));
849 if !still && tile_w < 16 {
850 return Reply::err(format!(
851 "width {width} is too narrow for {cols} columns; use a wider width or fewer cols"
852 ));
853 }
854 match opt_str(args, "source") {
855 None => sheet_of_timeline(s, args, &dir, count, cols, tile_w),
856 Some(_) if burn_asked(args) => {
857 Reply::err("burn_captions draws the timeline's captions: it cannot be used with source")
858 }
859 Some(src) => sheet_of_source(s, args, src, &dir, count, cols, tile_w, width),
860 }
861}
862
863fn sheet_of_timeline(
864 s: &PlaybackSession,
865 args: &Value,
866 dir: &Path,
867 count: u32,
868 cols: u32,
869 tile_w: u32,
870) -> Reply {
871 let fps = parse::session_fps(s);
872 let burn = match burn_of(args, s) {
873 Ok(b) => b,
874 Err(e) => return Reply::err(e),
875 };
876 let captions = burn.as_ref().map(|(track, _)| *track);
877 let (project, meta) = s.export_snapshot();
878 let total = project.media_frames();
879 if total == 0 {
880 return Reply::err(
881 "the timeline is empty, so there are no frames to sheet; media_import adds sources without placing them, so place a clip first",
882 );
883 }
884 let (from, to) = tri!(range_of(args, fps, total));
885 let samples = sample_frames(from, to, count);
886 // Which files are offline at each sample, read before the parallel composes. A tile whose
887 // clip is offline is drawn missing and named; the other tiles still compose.
888 let missing: Vec<Vec<(usize, PathBuf)>> = samples.iter().map(|&f| offline_under(s, f)).collect();
889 let (src_w, src_h) = (meta.width, meta.height);
890
891 let picked = parallel(samples.len(), |i| {
892 match engine::export::compose_at_with(&project, &meta, samples[i], tile_w, tile_w * 4, burn.clone()) {
893 Ok(f) => Ok((f, false)),
894 Err(_) if !missing[i].is_empty() => Ok((missing_tile(tile_w, src_w, src_h), true)),
895 Err(e) => Err(format!("cannot compose frame {}: {e}", samples[i])),
896 }
897 });
898 let picked = match picked.into_iter().collect::<Result<Vec<(Frame, bool)>, String>>() {
899 Ok(p) => p,
900 Err(e) => return Reply::err(e),
901 };
902 let mut gone: Vec<(usize, PathBuf)> = Vec::new();
903 for (i, (_, drawn_missing)) in picked.iter().enumerate() {
904 if *drawn_missing {
905 for (src, path) in &missing[i] {
906 if !gone.iter().any(|(j, _)| j == src) {
907 gone.push((*src, path.clone()));
908 }
909 }
910 }
911 }
912 let frames: Vec<Frame> = picked.into_iter().map(|(f, _)| f).collect();
913
914 let mut tiles = Vec::new();
915 for &f in &samples {
916 tiles.push(describe_timeline(s, f));
917 }
918 let cuts = cut_points(s, from, to);
919 let sheet = tile_sheet(&frames, &samples, cols, tile_w, fps);
920 let png = match to_png_bytes(&sheet) {
921 Ok(p) => p,
922 Err(e) => return Reply::err(format!("cannot encode the sheet as PNG: {e}")),
923 };
924 let name = format!("sheet-{from}-{count}-{}.png", sheet.width);
925 let extra = opt_str(args, "save").map(PathBuf::from);
926 let saved = match save_png(&png, dir, &name, extra.as_deref()) {
927 Ok(p) => extra.unwrap_or(p),
928 Err(r) => return r,
929 };
930
931 let header = format!(
932 "contact sheet · {count} tiles · {cols} cols · {}x{} · {}–{} ({from}f–{to}f)",
933 sheet.width,
934 sheet.height,
935 parse::clock(from, fps),
936 parse::clock(to, fps),
937 );
938 let mut lines = vec![header];
939 let mut tile_json = Vec::new();
940 for (i, (&f, t)) in samples.iter().zip(&tiles).enumerate() {
941 let desc = t.top_addr.clone().map_or_else(
942 || "gap".to_string(),
943 |a| format!("{a} {}", t.top_desc.clone().unwrap_or_default()),
944 );
945 lines.push(format!("{:>2} {} ({f}f) {desc}", i + 1, parse::clock(f, fps)));
946 tile_json.push(json!({"tile": i + 1, "frame": f, "seconds": parse::secs(f, fps), "clip": t.top_addr}));
947 }
948 if let Some(line) = super::stabilise::pending_in(s, from, to) {
949 lines.push(line);
950 }
951 // Picture joins are listed; audio joins (a music track every few seconds, say) are
952 // only counted, so a long range does not bury the picture joins.
953 let pictures: Vec<&Cut> = cuts.iter().filter(|c| c.picture).collect();
954 let audio_joins = cuts.len() - pictures.len();
955 let audio_tail = if audio_joins > 0 {
956 let noun = if audio_joins == 1 { "join" } else { "joins" };
957 format!(" · ({audio_joins} {noun} on audio lanes not shown)")
958 } else {
959 String::new()
960 };
961 // Picture cuts inside a clip are not joins between clips: scenes finds them, so the line points there.
962 let scenes_tail = tiles
963 .iter()
964 .find_map(|t| t.top_addr.clone())
965 .map_or_else(String::new, |a| format!(" · picture cuts inside a clip: scenes {a}"));
966 // Hard joins and dissolves are listed apart: `edit joins: 3.0s · dissolve 6.50s–7.00s`.
967 let hard: Vec<&Cut> = pictures.iter().copied().filter(|c| c.dissolve == 0).collect();
968 let dissolves: Vec<&Cut> = pictures.iter().copied().filter(|c| c.dissolve > 0).collect();
969 let cap_tail = |n: usize| {
970 let more = n.saturating_sub(CUTS_CAP);
971 if more > 0 { format!(" · and {more} more") } else { String::new() }
972 };
973 let joins_line = if pictures.is_empty() {
974 if audio_joins > 0 {
975 format!("edit joins: none on the picture lanes{audio_tail}")
976 } else {
977 "edit joins: none in range".to_string()
978 }
979 } else {
980 let cuts_part = if hard.is_empty() {
981 "edit joins: none".to_string()
982 } else {
983 let shown: Vec<String> = hard.iter().take(CUTS_CAP).map(|c| c.text.clone()).collect();
984 format!("edit joins: {}{}", shown.join(" · "), cap_tail(hard.len()))
985 };
986 let dissolve_part = if dissolves.is_empty() {
987 String::new()
988 } else {
989 // The cut is the frame the dissolve ends on, so the window starts a dissolve's length before it.
990 let shown: Vec<String> = dissolves
991 .iter()
992 .take(CUTS_CAP)
993 .map(|c| {
994 let from = c.frame.saturating_sub(c.dissolve);
995 format!("dissolve {:.2}s–{:.2}s", parse::secs(from, fps), parse::secs(c.frame, fps))
996 })
997 .collect();
998 format!(" · {}{}", shown.join(", "), cap_tail(dissolves.len()))
999 };
1000 format!("{cuts_part}{dissolve_part}{audio_tail}")
1001 };
1002 lines.push(format!("{joins_line}{scenes_tail}"));
1003 if let Some(track) = captions {
1004 lines.push(format!("captions burned (track {track})"));
1005 }
1006 for (i, p) in &gone {
1007 lines.push(offline_line(*i, p));
1008 }
1009 lines.push(format!("saved: {}", saved.display()));
1010 let cut_json: Vec<Value> = hard.iter().map(|c| json!({"frame": c.frame, "text": c.text})).collect();
1011 let dissolve_json: Vec<Value> = dissolves
1012 .iter()
1013 .map(|c| {
1014 json!({
1015 "frame": c.frame,
1016 "seconds": parse::secs(c.frame, fps),
1017 "frames": c.dissolve,
1018 "length_seconds": parse::secs(c.dissolve, fps),
1019 })
1020 })
1021 .collect();
1022 let offline_json: Vec<Value> =
1023 gone.iter().map(|(i, p)| json!({"source": format!("src:{i}"), "path": p.display().to_string()})).collect();
1024 let structured = json!({
1025 "width": sheet.width,
1026 "height": sheet.height,
1027 "tile": {"w": tile_w, "h": tile_height(&frames)},
1028 "path": saved.display().to_string(),
1029 "tiles": tile_json,
1030 "cuts": cut_json,
1031 "dissolves": dissolve_json,
1032 "audio_cuts": audio_joins,
1033 "captions_burned": captions,
1034 "offline": offline_json,
1035 });
1036 Reply::ok(lines.join("\n"))
1037 .with(structured)
1038 .image("image/png", base64(&png))
1039}
1040
1041/// Refuses a source with no picture (sound alone) before any frame is looked for, so
1042/// the reply names the source and the cause rather than a container error.
1043pub(crate) fn picture_check(path: &Path, idx: usize) -> Result<(), String> {
1044 let picture = engine::probe_media(path).video.is_some() || engine::is_image(path);
1045 if picture {
1046 Ok(())
1047 } else {
1048 Err(format!("src:{idx} ({}) has no picture", file_name(path)))
1049 }
1050}
1051
1052#[allow(clippy::too_many_arguments)]
1053fn sheet_of_source(
1054 s: &PlaybackSession,
1055 args: &Value,
1056 src: &str,
1057 dir: &Path,
1058 count: u32,
1059 cols: u32,
1060 tile_w: u32,
1061 width: u32,
1062) -> Reply {
1063 let idx = tri!(source_index(s, src));
1064 let path = s.sources()[idx].path.clone();
1065 let name = file_name(&path);
1066 if !path.exists() {
1067 return Reply::err(offline_line(idx, &path));
1068 }
1069 if let Err(e) = picture_check(&path, idx) {
1070 return Reply::err(e);
1071 }
1072 let fps = probe_fps(&path).unwrap_or_else(|| parse::session_fps(s));
1073 // A still is one picture, one frame long: it sheets as a single tile.
1074 let still = engine::is_image(&path);
1075 // Without a probed duration the range has to name its end.
1076 let total = match still {
1077 true => 1,
1078 false => probe_secs(&path).map_or(u32::MAX, |d| (d * fps).round() as u32),
1079 };
1080 let (from, to) = tri!(range_of(args, fps, total));
1081 if to == u32::MAX {
1082 return Reply::err(format!("{name} has no known duration; give range.to in frames"));
1083 }
1084 let save = opt_str(args, "save").map(PathBuf::from);
1085 // The one tile takes the whole width asked for, not a column's share of it.
1086 let (count, cols, tile_w) = match still {
1087 true => (1, 1, width),
1088 false => (count, cols, tile_w),
1089 };
1090 sheet_of_source_range(&path, idx, &name, from, to, fps, dir, count, cols, tile_w, save.as_deref())
1091}
1092
1093#[allow(clippy::too_many_arguments)]
1094fn sheet_of_source_range(
1095 path: &Path,
1096 idx: usize,
1097 name: &str,
1098 from: u32,
1099 to: u32,
1100 fps: f64,
1101 dir: &Path,
1102 count: u32,
1103 cols: u32,
1104 tile_w: u32,
1105 save: Option<&Path>,
1106) -> Reply {
1107 let samples = sample_frames(from, to, count);
1108 let frames = parallel(samples.len(), |i| decode_source(path, samples[i], tile_w));
1109 let frames = match frames.into_iter().collect::<Result<Vec<Frame>, String>>() {
1110 Ok(f) => f,
1111 Err(e) => return Reply::err(e),
1112 };
1113 let sheet = tile_sheet(&frames, &samples, cols, tile_w, fps);
1114 let png = match to_png_bytes(&sheet) {
1115 Ok(p) => p,
1116 Err(e) => return Reply::err(format!("cannot encode the sheet as PNG: {e}")),
1117 };
1118 let file = format!("sheet-src{idx}-{from}-{count}-{}.png", sheet.width);
1119 let saved = match save_png(&png, dir, &file, save) {
1120 Ok(p) => save.map_or(p, Path::to_path_buf),
1121 Err(r) => return r,
1122 };
1123 let header = format!(
1124 "contact sheet · src:{idx} {name} · {count} tiles · {cols} cols · {}x{} · {}–{} ({from}f–{to}f)",
1125 sheet.width,
1126 sheet.height,
1127 parse::clock(from, fps),
1128 parse::clock(to, fps),
1129 );
1130 let mut lines = vec![header];
1131 let mut tile_json = Vec::new();
1132 for (i, &f) in samples.iter().enumerate() {
1133 lines.push(format!("{:>2} {} ({f}f) src:{idx} {name}", i + 1, parse::clock(f, fps)));
1134 tile_json.push(json!({"tile": i + 1, "frame": f, "seconds": parse::secs(f, fps)}));
1135 }
1136 // Edit joins sit between clips on the timeline, so a source has none; scenes finds its picture cuts.
1137 lines.push(format!("edit joins: none (a source has no edit joins) · scenes src:{idx} finds its picture cuts"));
1138 lines.push(format!("saved: {}", saved.display()));
1139 let structured = json!({
1140 "width": sheet.width,
1141 "height": sheet.height,
1142 "tile": {"w": tile_w, "h": tile_height(&frames)},
1143 "path": saved.display().to_string(),
1144 "tiles": tile_json,
1145 });
1146 Reply::ok(lines.join("\n"))
1147 .with(structured)
1148 .image("image/png", base64(&png))
1149}
1150
1151/// `count` frame numbers in `[from, to)`, each at the centre of its interval.
1152fn sample_frames(from: u32, to: u32, count: u32) -> Vec<u32> {
1153 let len = u64::from(to - from);
1154 let n = u64::from(count);
1155 (0..n)
1156 .map(|i| {
1157 let off = (2 * i + 1) * len / (2 * n);
1158 (u64::from(from) + off).min(u64::from(to) - 1) as u32
1159 })
1160 .collect()
1161}
1162
1163/// Lays the frames out as a grid with a dark gutter. Each tile has its timecode in a
1164/// band above it, not drawn on the picture: a stamp over the picture hid the
1165/// lower-third titles on narrow tiles (MCP.md 4.4).
1166pub(crate) fn tile_sheet(frames: &[Frame], samples: &[u32], cols: u32, tile_w: u32, fps: f64) -> Frame {
1167 let th = tile_height(frames);
1168 let rows = (frames.len() as u32).div_ceil(cols);
1169 let cell_h = LABEL_H + th;
1170 let cw = cols * tile_w + (cols - 1) * GUTTER;
1171 let ch = rows * cell_h + (rows - 1) * GUTTER;
1172 let mut canvas = Canvas::new(cw, ch, GUTTER_FILL);
1173 for (i, (tile, &f)) in frames.iter().zip(samples).enumerate() {
1174 let i = i as u32;
1175 let x0 = (i % cols) * (tile_w + GUTTER);
1176 let y0 = (i / cols) * (cell_h + GUTTER);
1177 canvas.blit(tile, x0, y0 + LABEL_H);
1178 let label = parse::clock(f, fps);
1179 // A stamp that does not fit its tile at 2x is drawn at 1x, and dropped when
1180 // even that would run into the next tile; the text lists the times anyway.
1181 if let Some(scale) = stamp_scale(&label, tile_w) {
1182 draw_text_at(&mut canvas, i64::from(x0) + 4, i64::from(y0) + 3, &label, scale);
1183 }
1184 }
1185 canvas.into_frame()
1186}
1187
1188/// The largest stamp scale at which `label` fits inside a tile `tile_w` wide, with
1189/// a 4 px margin each side, or None when not even 1x fits.
1190fn stamp_scale(label: &str, tile_w: u32) -> Option<i64> {
1191 let chars = label.chars().count() as i64;
1192 [SCALE, 1].into_iter().find(|&k| chars * 6 * k + 8 <= i64::from(tile_w))
1193}
1194
1195fn tile_height(frames: &[Frame]) -> u32 {
1196 frames.iter().map(|f| f.height).max().unwrap_or(1)
1197}
1198
1199struct Cut {
1200 frame: u32,
1201 text: String,
1202 /// On a picture (V) lane; audio cuts are counted, not listed.
1203 picture: bool,
1204 /// Frames of the dissolve that joins the clips at `frame`; 0 for a hard cut.
1205 dissolve: u32,
1206}
1207
1208/// Clip boundaries on the media lanes that fall strictly inside `(from, to)`. A picture
1209/// boundary joined by a dissolve is one entry with its length, not a clip ending and
1210/// another starting, so a dissolve can be told from a hard cut.
1211fn cut_points(s: &PlaybackSession, from: u32, to: u32) -> Vec<Cut> {
1212 let mut cuts = Vec::new();
1213 for lane in s.lanes() {
1214 let picture = lane.kind == LaneKind::Video;
1215 let clips = s.lane_clips(lane);
1216 for (idx, c) in clips.iter().enumerate() {
1217 let end = c.end();
1218 let dissolve = if picture { s.transition_out_of(lane, idx) } else { 0 };
1219 let joined = clips.get(idx + 1).is_some_and(|b| b.start == end);
1220 if joined && dissolve > 0 {
1221 if from < end && end < to {
1222 let addr = parse::addr(lane, c.start);
1223 let text = format!("{end}f {addr} dissolves ({dissolve}f)");
1224 cuts.push(Cut { frame: end, text, picture, dissolve });
1225 }
1226 continue;
1227 }
1228 // A clip that a neighbour joins at its start was listed with that join: a dissolve
1229 // with its length, a hard cut as one `ends→starts` entry (see below).
1230 let joined_in = idx > 0 && clips[idx - 1].end() == c.start;
1231 if from < c.start && c.start < to && !joined_in {
1232 let addr = parse::addr(lane, c.start);
1233 cuts.push(Cut { frame: c.start, text: format!("{}f {addr} starts", c.start), picture, dissolve: 0 });
1234 }
1235 if from < end && end < to {
1236 let addr = parse::addr(lane, c.start);
1237 let text = match clips.get(idx + 1).filter(|b| b.start == end) {
1238 // A hard cut is one entry naming both sides, not an end and a start at one frame.
1239 Some(b) => format!("{end}f {addr}→{}", parse::addr(lane, b.start)),
1240 None => format!("{end}f {addr} ends"),
1241 };
1242 cuts.push(Cut { frame: end, text, picture, dissolve: 0 });
1243 }
1244 }
1245 }
1246 cuts.sort_by_key(|c| c.frame);
1247 cuts.dedup_by(|a, b| a.frame == b.frame && a.text == b.text);
1248 cuts
1249}
1250
1251// ---- describing what is on screen ----------------------------------------
1252
1253/// What is on each lane at one timeline frame.
1254struct Under {
1255 /// Address of the top (first) video clip at the frame, if any.
1256 top_addr: Option<String>,
1257 /// That clip's source description, `src:0 interview.mp4 @ 15.000s`.
1258 top_desc: Option<String>,
1259 /// One line per media lane: `A1 A1@0 src:0 ... `, or `V2 gap`.
1260 lines: Vec<String>,
1261 /// Names of the hidden picture lanes that have a clip at the frame: their clips are there
1262 /// but not drawn, so the frame is not a gap.
1263 hidden_here: Vec<String>,
1264 structured: Vec<Value>,
1265}
1266
1267fn describe_timeline(s: &PlaybackSession, at: u32) -> Under {
1268 let mut under = Under { top_addr: None, top_desc: None, lines: Vec::new(), hidden_here: Vec::new(), structured: Vec::new() };
1269 // Caption lanes are not picture or sound: what they draw is reported as its own line.
1270 for lane in s.lanes().into_iter().filter(|l| l.kind != LaneKind::Subtitle) {
1271 let name = parse::lane_name(lane);
1272 let clips = s.lane_clips(lane);
1273 // A hidden picture lane is not drawn, so it is marked and cannot be the picture on top.
1274 let hidden = lane.kind == LaneKind::Video && s.lane_hidden(lane);
1275 match clips.iter().find(|c| c.start <= at && at < c.end()) {
1276 Some(c) => {
1277 let addr = parse::addr(lane, c.start);
1278 let desc = clip_desc(s, c, at);
1279 if lane.kind == LaneKind::Video && !hidden && under.top_addr.is_none() {
1280 under.top_addr = Some(addr.clone());
1281 under.top_desc = Some(desc.clone());
1282 }
1283 let note = if hidden { " (hidden: not in the picture)" } else { "" };
1284 if hidden {
1285 under.hidden_here.push(name.clone());
1286 }
1287 under.lines.push(format!("{name:<3} {addr} {desc}{note}"));
1288 under.structured.push(json!({"lane": name, "clip": addr, "desc": desc, "hidden": hidden}));
1289 }
1290 None => {
1291 under.lines.push(format!("{name:<3} gap"));
1292 under.structured.push(json!({"lane": name, "clip": null}));
1293 }
1294 }
1295 }
1296 under
1297}
1298
1299/// What stacks at `at` on the picture lanes, read the way the composite reads it: the
1300/// visible video clips covering the frame, topmost first, and a dissolve in progress. A
1301/// dissolve blends only where one clip covers the frame (a layered picture is not blended),
1302/// and its window is the tail of the clip, as the export computes it: the frames from the
1303/// clip's end back, bounded by the transition, both clips' lengths and the span the frame
1304/// sits in, which starts where a higher lane last took over.
1305fn layer_notes(s: &PlaybackSession, at: u32) -> (Vec<String>, Value) {
1306 let visible: Vec<Lane> = s.lanes().into_iter().filter(|l| l.kind == LaneKind::Video && !s.lane_hidden(*l)).collect();
1307 let covering: Vec<(usize, usize)> = visible
1308 .iter()
1309 .enumerate()
1310 .filter_map(|(pos, &l)| s.lane_clips(l).iter().position(|c| c.start <= at && at < c.end()).map(|i| (pos, i)))
1311 .collect();
1312 let addr = |pos: usize, idx: usize| parse::addr(visible[pos], s.lane_clips(visible[pos])[idx].start);
1313 let mut lines = Vec::new();
1314 let layers: Vec<String> = covering.iter().rev().map(|&(pos, idx)| addr(pos, idx)).collect();
1315 let mut dissolve = Value::Null;
1316 if covering.len() >= 2 {
1317 lines.push(format!(
1318 "layered: {} (the topmost shows; the rest sit beneath it)",
1319 layers.join(" over ")
1320 ));
1321 } else if let Some(&(pos, idx)) = covering.first() {
1322 let lane = visible[pos];
1323 let clips = s.lane_clips(lane);
1324 let a = &clips[idx];
1325 let tout = s.transition_out_of(lane, idx);
1326 if let (true, Some(b)) = (tout > 0, clips.get(idx + 1).filter(|b| b.start == a.end())) {
1327 // The span the frame sits in starts where a higher lane last took over before it,
1328 // and ends where one takes over after it; a takeover before A's end means no tail.
1329 let higher = &visible[pos + 1..];
1330 let span_start = higher
1331 .iter()
1332 .flat_map(|&h| s.lane_clips(h).iter())
1333 .map(|c| c.end())
1334 .filter(|&e| a.start < e && e <= at)
1335 .fold(a.start, u32::max);
1336 let takes_over = higher
1337 .iter()
1338 .flat_map(|&h| s.lane_clips(h).iter())
1339 .any(|c| at < c.start && c.start < a.end());
1340 let window = tout.min(a.frames()).min(b.frames()).min(a.end() - span_start);
1341 let tail = a.end().saturating_sub(window);
1342 if !takes_over && window > 0 && at >= tail {
1343 let weight = f64::from(at - tail + 1) / f64::from(window + 1) * 100.0;
1344 let name = parse::lane_name(lane);
1345 let (from, to) = (addr(pos, idx), parse::addr(lane, b.start));
1346 let kind = a.transition_kind;
1347 let what = if kind == engine::transitions::TransitionKind::Dissolve {
1348 "dissolving".to_string()
1349 } else {
1350 format!("{} transition", kind.name())
1351 };
1352 lines.push(format!("{name} {what} {from}→{to}, {weight:.0}% (B's share of the blend)"));
1353 dissolve = json!({"from": from, "to": to, "window": window, "b_percent": weight.round(), "kind": kind.name()});
1354 }
1355 }
1356 }
1357 (lines, json!({"layers": layers, "dissolve": dissolve}))
1358}
1359
1360/// The note for a frame whose only clips are on hidden picture lanes: `V1 is hidden: not in
1361/// the picture`, or `V1 and V2 are hidden: not in the picture`. None when no hidden lane has one.
1362fn hidden_only_text(names: &[String]) -> Option<String> {
1363 match names {
1364 [] => None,
1365 [one] => Some(format!("{one} is hidden: not in the picture")),
1366 [init @ .., last] => Some(format!("{} and {last} are hidden: not in the picture", init.join(", "))),
1367 }
1368}
1369
1370/// Whether any video clip is placed on the timeline: without one the picture is black.
1371fn has_picture(s: &PlaybackSession) -> bool {
1372 s.lanes().into_iter().any(|l| l.kind == LaneKind::Video && !s.lane_clips(l).is_empty())
1373}
1374
1375/// `src:0 interview.mp4 @ 15.000s`: where in its source a clip shows `at`. A clip's
1376/// `in_frame` and the frame `at` lands on both count timeline frames of its source;
1377/// the decoder maps that to the file's own frame (`floor(frame * file / timeline)`,
1378/// as playback does), and the time is that source frame over the file's own rate.
1379fn clip_desc(s: &PlaybackSession, c: &Clip, at: u32) -> String {
1380 let src = s.sources().get(c.source);
1381 let name = src.map(|src| file_name(&src.path)).unwrap_or_else(|| "?".to_string());
1382 let timeline_frame = c.in_frame + c.source_offset(at - c.start);
1383 let secs = match src {
1384 Some(src) => {
1385 // Micro-frames per second, as the edit tools convert between the two rates.
1386 let micro = |fps: f64| (fps * 1e6).round().max(1.0) as u128;
1387 let file = micro(s.file_fps(&src.path));
1388 let tl = micro(parse::session_fps(s));
1389 let frame = (u128::from(timeline_frame) * file / tl) as u32;
1390 f64::from(frame) / (file as f64 / 1e6)
1391 }
1392 None => parse::secs(timeline_frame, parse::session_fps(s)),
1393 };
1394 format!("src:{} {name} @ {secs:.3}s", c.source)
1395}
1396
1397// ---- helpers --------------------------------------------------------------
1398
1399/// The timeline frame range from `range.from`/`range.to`, defaulting to the whole.
1400fn range_of(args: &Value, fps: f64, total: u32) -> Result<(u32, u32), Reply> {
1401 let range = args.get("range").filter(|v| !v.is_null());
1402 let from = match range.and_then(|r| r.get("from")).filter(|v| !v.is_null()) {
1403 Some(v) => parse::frame(v, fps, total).map_err(Reply::err)?,
1404 None => 0,
1405 };
1406 let to = match range.and_then(|r| r.get("to")).filter(|v| !v.is_null()) {
1407 Some(v) => parse::frame(v, fps, total).map_err(Reply::err)?,
1408 None => total,
1409 };
1410 if to <= from {
1411 return Err(Reply::err(format!("range {from}f–{to}f is empty; `to` must be after `from`")));
1412 }
1413 if to > total {
1414 return Err(Reply::err(format!("range ends at {to}f, past the end ({total} frames)")));
1415 }
1416 Ok((from, to))
1417}
1418
1419fn width_arg(args: &Value, default: u32, max: u32) -> Result<u32, Reply> {
1420 bounded(args, "width", default, 1, max)
1421}
1422
1423/// A whole-number argument in `min..=max`, or `default` when it is absent. A value
1424/// that is not a whole number, or is outside the range, is refused by name: never
1425/// taken as the default.
1426fn bounded(args: &Value, name: &str, default: u32, min: u32, max: u32) -> Result<u32, Reply> {
1427 let Some(raw) = args.get(name).filter(|v| !v.is_null()) else {
1428 return Ok(default);
1429 };
1430 let Some((v, shown)) = whole_number(raw) else {
1431 return Err(Reply::err(format!("argument `{name}` must be a whole number from {min} to {max}, not {raw}")));
1432 };
1433 if v < f64::from(min) {
1434 Err(Reply::err(format!("argument `{name}` {shown} is too small: {min} to {max}")))
1435 } else if v > f64::from(max) {
1436 Err(Reply::err(format!("argument `{name}` {shown} is too large: {min} to {max}")))
1437 } else {
1438 Ok(v as u32)
1439 }
1440}
1441
1442/// A whole-number JSON value as a float (for the range test) and as plain text. An
1443/// integral float such as `1000000000.0` counts, and prints without an exponent.
1444fn whole_number(raw: &Value) -> Option<(f64, String)> {
1445 if let Some(v) = raw.as_i64() {
1446 return Some((v as f64, v.to_string()));
1447 }
1448 if let Some(u) = raw.as_u64() {
1449 return Some((u as f64, u.to_string()));
1450 }
1451 let f = raw.as_f64().filter(|f| f.is_finite() && f.fract() == 0.0)?;
1452 Some((f, format!("{f:.0}")))
1453}
1454
1455/// `src:2` (or `src:2 interview.mp4`) to an index into the session's sources.
1456fn source_index(s: &PlaybackSession, raw: &str) -> Result<usize, Reply> {
1457 let head = raw.split_whitespace().next().unwrap_or("");
1458 let n = head
1459 .strip_prefix("src:")
1460 .and_then(|d| d.parse::<usize>().ok())
1461 .ok_or_else(|| Reply::err(format!("argument `source`: `{raw}` is not src:<n>, such as src:0")))?;
1462 if n >= s.sources().len() {
1463 return Err(Reply::err(format!(
1464 "no source src:{n}; the project has {} source(s)",
1465 s.sources().len()
1466 )));
1467 }
1468 Ok(n)
1469}
1470
1471fn file_name(path: &Path) -> String {
1472 path.file_name()
1473 .map(|n| n.to_string_lossy().into_owned())
1474 .unwrap_or_else(|| "?".to_string())
1475}
1476
1477fn probe_fps(path: &Path) -> Option<f64> {
1478 engine::probe_media(path).video.and_then(|v| v.frame_rate).filter(|f| *f > 0.0)
1479}
1480
1481fn probe_secs(path: &Path) -> Option<f64> {
1482 engine::probe_media(path).duration_secs.filter(|d| *d > 0.0)
1483}
1484
1485/// Most frame PNGs kept in the cache, across every project; the oldest are removed first.
1486const FRAME_CACHE_KEEP: usize = 200;
1487/// Most bytes of frame PNGs kept in the cache, across every project; the oldest go first.
1488const FRAME_CACHE_BYTES: u64 = 200 * 1024 * 1024;
1489const SCRATCH_PREFIX: &str = "edith_mcp-";
1490
1491/// `$XDG_CACHE_HOME/edith/frames`, or `~/.cache/edith/frames`. Saved frames live here
1492/// and outlive the process, so the path an agent is told stays valid.
1493fn frame_cache_root() -> PathBuf {
1494 frame_cache_base().join("edith").join("frames")
1495}
1496
1497#[cfg(not(test))]
1498fn frame_cache_base() -> PathBuf {
1499 std::env::var_os("XDG_CACHE_HOME")
1500 .map(PathBuf::from)
1501 .filter(|p| p.is_absolute())
1502 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
1503 .unwrap_or_else(|| std::env::temp_dir().join("edith-cache"))
1504}
1505
1506/// Tests never touch the real cache. Each test thread gets its own folder under the temp
1507/// dir, removed when the thread ends, so a panicking test leaves nothing behind either.
1508#[cfg(test)]
1509fn frame_cache_base() -> PathBuf {
1510 use std::sync::atomic::{AtomicUsize, Ordering};
1511 static NEXT: AtomicUsize = AtomicUsize::new(0);
1512 thread_local! {
1513 static BASE: crate::testutil::TestDir = crate::testutil::TestDir::new(&format!(
1514 "frame-cache-{}",
1515 NEXT.fetch_add(1, Ordering::Relaxed)
1516 ));
1517 }
1518 BASE.with(|b| b.path().to_path_buf())
1519}
1520
1521/// `<cache>/<project stem or 'untitled'>`: the folder one project's frames go in.
1522pub(crate) fn frames_dir(project: Option<&Path>) -> PathBuf {
1523 let stem = project
1524 .and_then(|p| p.file_stem())
1525 .map(|s| safe_component(&s.to_string_lossy()))
1526 .filter(|s| !s.is_empty())
1527 .unwrap_or_else(|| "untitled".to_string());
1528 frame_cache_root().join(stem)
1529}
1530
1531/// A name as one path component: anything but letters, digits, `-`, `_` and `.` becomes
1532/// `_`, and leading dots are dropped so it cannot climb out of the cache.
1533fn safe_component(s: &str) -> String {
1534 let mapped: String = s
1535 .chars()
1536 .map(|c| if c.is_alphanumeric() || "-_.".contains(c) { c } else { '_' })
1537 .collect();
1538 mapped.trim_start_matches('.').to_string()
1539}
1540
1541/// `<temp>/edith_mcp-<pid>`: this process's temp root for the scratch files that are not
1542/// frames (the scene sheets). Frames live in the persistent cache instead.
1543pub(crate) fn scratch_root() -> PathBuf {
1544 std::env::temp_dir().join(format!("{SCRATCH_PREFIX}{}", std::process::id()))
1545}
1546
1547/// The exit hook `main` calls. Removes only this process's temp root, which holds no
1548/// frames, so a frame path handed to the agent is never deleted here.
1549pub fn remove_scratch() {
1550 let _ = std::fs::remove_dir_all(scratch_root());
1551}
1552
1553/// Removes the scratch folders of processes that are no longer alive, so a crash does
1554/// not leave PNGs behind. Called once at startup. Does nothing without `/proc`, where
1555/// liveness cannot be told.
1556pub fn sweep_stale_scratch() {
1557 sweep_in(&std::env::temp_dir(), std::process::id());
1558}
1559
1560fn sweep_in(temp: &Path, own_pid: u32) {
1561 if !Path::new("/proc/self").exists() {
1562 return;
1563 }
1564 let Ok(entries) = std::fs::read_dir(temp) else { return };
1565 for entry in entries.flatten() {
1566 let name = entry.file_name();
1567 let Some(pid) = name
1568 .to_str()
1569 .and_then(|n| n.strip_prefix(SCRATCH_PREFIX))
1570 .and_then(|p| p.parse::<u32>().ok())
1571 else {
1572 continue;
1573 };
1574 let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
1575 if is_dir && pid != own_pid && !Path::new(&format!("/proc/{pid}")).exists() {
1576 let _ = std::fs::remove_dir_all(entry.path());
1577 }
1578 }
1579}
1580
1581/// Keeps the cache within its caps: removes the oldest PNGs under the project folders of
1582/// `root` until at most `keep` files and `max_bytes` bytes remain.
1583fn prune_cache(root: &Path, keep: usize, max_bytes: u64) {
1584 let Ok(projects) = std::fs::read_dir(root) else { return };
1585 let mut files: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new();
1586 for project in projects.flatten() {
1587 let Ok(inner) = std::fs::read_dir(project.path()) else { continue };
1588 for f in inner.flatten() {
1589 if let Ok(m) = f.metadata()
1590 && m.is_file()
1591 {
1592 files.push((m.modified().unwrap_or(std::time::UNIX_EPOCH), m.len(), f.path()));
1593 }
1594 }
1595 }
1596 // Newest first: keep while under both caps, remove everything older than the first miss.
1597 files.sort_by_key(|f| std::cmp::Reverse(f.0));
1598 let mut total: u64 = 0;
1599 for (i, (_, len, path)) in files.iter().enumerate() {
1600 total = total.saturating_add(*len);
1601 if i >= keep || total > max_bytes {
1602 let _ = std::fs::remove_file(path);
1603 }
1604 }
1605}
1606
1607/// A short tag of the PNG's bytes (FNV-1a, 12 hex digits). It goes in every cache name,
1608/// so the same moment of a different project state gets a new file instead of
1609/// overwriting the one an agent was already given.
1610fn content_tag(png: &[u8]) -> String {
1611 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1612 for b in png {
1613 h ^= u64::from(*b);
1614 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1615 }
1616 format!("{:012x}", h & 0xffff_ffff_ffff)
1617}
1618
1619/// Writes the PNG to `dir` (and to `extra` if given); returns the path written under `dir`.
1620/// The name gets the content tag before `.png`, so `12-960.png` is written as
1621/// `12-960-3fa9c0d2e1b7.png`.
1622pub(crate) fn save_png(png: &[u8], dir: &Path, name: &str, extra: Option<&Path>) -> Result<PathBuf, Reply> {
1623 std::fs::create_dir_all(dir)
1624 .map_err(|e| Reply::err(format!("cannot create {}: {e}", dir.display())))?;
1625 let stem = name.strip_suffix(".png").unwrap_or(name);
1626 let path = dir.join(format!("{stem}-{}.png", content_tag(png)));
1627 std::fs::write(&path, png)
1628 .map_err(|e| Reply::err(format!("cannot write {}: {e}", path.display())))?;
1629 prune_cache(&frame_cache_root(), FRAME_CACHE_KEEP, FRAME_CACHE_BYTES);
1630 if let Some(extra) = extra {
1631 if let Some(parent) = extra.parent().filter(|p| !p.as_os_str().is_empty()) {
1632 std::fs::create_dir_all(parent)
1633 .map_err(|e| Reply::err(format!("cannot create {}: {e}", parent.display())))?;
1634 }
1635 std::fs::write(extra, png)
1636 .map_err(|e| Reply::err(format!("cannot write {}: {e}", extra.display())))?;
1637 }
1638 Ok(path)
1639}
1640
1641/// Runs `f(0..n)` on up to the machine's parallelism, returning results in index order.
1642fn parallel<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
1643 let workers = std::thread::available_parallelism()
1644 .map(|p| p.get())
1645 .unwrap_or(4)
1646 .clamp(1, n.max(1));
1647 let next = AtomicUsize::new(0);
1648 let mut done: Vec<(usize, T)> = std::thread::scope(|sc| {
1649 let handles: Vec<_> = (0..workers)
1650 .map(|_| {
1651 sc.spawn(|| {
1652 let mut mine = Vec::new();
1653 loop {
1654 let i = next.fetch_add(1, Ordering::Relaxed);
1655 if i >= n {
1656 break;
1657 }
1658 mine.push((i, f(i)));
1659 }
1660 mine
1661 })
1662 })
1663 .collect();
1664 handles
1665 .into_iter()
1666 .flat_map(|h| h.join().expect("contact sheet worker panicked"))
1667 .collect()
1668 });
1669 done.sort_by_key(|(i, _)| *i);
1670 done.into_iter().map(|(_, t)| t).collect()
1671}
1672
1673pub(crate) fn fit_height(f: &Frame, width: u32) -> u32 {
1674 let h = (u64::from(f.height) * u64::from(width) + u64::from(f.width) / 2) / u64::from(f.width.max(1));
1675 (h as u32).max(1)
1676}
1677
1678/// Box-filter resize of a BGRA frame: each output pixel averages its source block.
1679pub(crate) fn resize(src: &Frame, w: u32, h: u32) -> Frame {
1680 let (sw, sh) = (u64::from(src.width), u64::from(src.height));
1681 let (dw, dh) = (u64::from(w), u64::from(h));
1682 let mut out = vec![0u8; (w * h * 4) as usize];
1683 for y in 0..dh {
1684 let y0 = y * sh / dh;
1685 let y1 = ((y + 1) * sh / dh).max(y0 + 1).min(sh);
1686 for x in 0..dw {
1687 let x0 = x * sw / dw;
1688 let x1 = ((x + 1) * sw / dw).max(x0 + 1).min(sw);
1689 let mut sum = [0u64; 4];
1690 for sy in y0..y1 {
1691 for sx in x0..x1 {
1692 let p = ((sy * sw + sx) * 4) as usize;
1693 for (acc, &b) in sum.iter_mut().zip(&src.bgra[p..p + 4]) {
1694 *acc += u64::from(b);
1695 }
1696 }
1697 }
1698 let n = (y1 - y0) * (x1 - x0);
1699 let o = ((y * dw + x) * 4) as usize;
1700 for c in 0..4 {
1701 out[o + c] = (sum[c] / n) as u8;
1702 }
1703 }
1704 }
1705 Frame { index: src.index, width: w, height: h, bgra: out }
1706}
1707
1708/// A BGRA canvas that tiles are blitted onto and text is stamped on.
1709struct Canvas {
1710 w: u32,
1711 h: u32,
1712 px: Vec<u8>,
1713}
1714
1715impl Canvas {
1716 fn new(w: u32, h: u32, fill: [u8; 4]) -> Self {
1717 let px = fill.iter().copied().cycle().take((w * h * 4) as usize).collect();
1718 Self { w, h, px }
1719 }
1720
1721 fn put(&mut self, x: i64, y: i64, c: [u8; 4]) {
1722 if x < 0 || y < 0 || x >= i64::from(self.w) || y >= i64::from(self.h) {
1723 return;
1724 }
1725 let o = ((y as usize) * self.w as usize + x as usize) * 4;
1726 self.px[o..o + 4].copy_from_slice(&c);
1727 }
1728
1729 /// Copies `f` with its top-left corner at (x0, y0), clipped to the canvas.
1730 fn blit(&mut self, f: &Frame, x0: u32, y0: u32) {
1731 let w = f.width.min(self.w.saturating_sub(x0));
1732 let h = f.height.min(self.h.saturating_sub(y0));
1733 for y in 0..h {
1734 let s = (y * f.width * 4) as usize;
1735 let d = (((y0 + y) * self.w + x0) * 4) as usize;
1736 let n = (w * 4) as usize;
1737 self.px[d..d + n].copy_from_slice(&f.bgra[s..s + n]);
1738 }
1739 }
1740
1741 fn into_frame(self) -> Frame {
1742 Frame { index: 0, width: self.w, height: self.h, bgra: self.px }
1743 }
1744}
1745
1746/// 5x7 glyphs for the timecode alphabet; `#` is a lit pixel.
1747const GLYPHS: [(char, [&str; 7]); 13] = [
1748 ('0', [".###.", "#...#", "#..##", "#.#.#", "##..#", "#...#", ".###."]),
1749 ('1', ["..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###."]),
1750 ('2', [".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####"]),
1751 ('3', ["#####", "...#.", "..#..", "...#.", "....#", "#...#", ".###."]),
1752 ('4', ["...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#."]),
1753 ('5', ["#####", "#....", "####.", "....#", "....#", "#...#", ".###."]),
1754 ('6', ["..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###."]),
1755 ('7', ["#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..."]),
1756 ('8', [".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###."]),
1757 ('9', [".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##.."]),
1758 (':', [".....", "..#..", "..#..", ".....", "..#..", "..#..", "....."]),
1759 ('.', [".....", ".....", ".....", ".....", ".....", ".##..", ".##.."]),
1760 ('f', ["..##.", ".#..#", ".#...", "###..", ".#...", ".#...", ".#..."]),
1761];
1762
1763/// Draws `text` at (x, y) in white with a 1-pixel black outline, at `scale` pixels per
1764/// glyph pixel. Characters outside the alphabet, spaces included, advance the pen blank.
1765fn draw_text_at(c: &mut Canvas, x: i64, y: i64, text: &str, scale: i64) {
1766 let mut lit: Vec<(i64, i64)> = Vec::new();
1767 let mut pen = x;
1768 for ch in text.chars() {
1769 if let Some((_, rows)) = GLYPHS.iter().find(|(g, _)| *g == ch) {
1770 for (ry, row) in rows.iter().enumerate() {
1771 for (rx, b) in row.bytes().enumerate() {
1772 if b != b'#' {
1773 continue;
1774 }
1775 for sy in 0..scale {
1776 for sx in 0..scale {
1777 lit.push((pen + rx as i64 * scale + sx, y + ry as i64 * scale + sy));
1778 }
1779 }
1780 }
1781 }
1782 }
1783 pen += 6 * scale;
1784 }
1785 for &(px, py) in &lit {
1786 for dy in -1..=1 {
1787 for dx in -1..=1 {
1788 c.put(px + dx, py + dy, BLACK);
1789 }
1790 }
1791 }
1792 for &(px, py) in &lit {
1793 c.put(px, py, WHITE);
1794 }
1795}
1796
1797/// Standard base64 (RFC 4648, padded). No dependency.
1798pub fn base64(bytes: &[u8]) -> String {
1799 const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1800 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
1801 for chunk in bytes.chunks(3) {
1802 let b0 = u32::from(chunk[0]);
1803 let b1 = u32::from(*chunk.get(1).unwrap_or(&0));
1804 let b2 = u32::from(*chunk.get(2).unwrap_or(&0));
1805 let n = (b0 << 16) | (b1 << 8) | b2;
1806 out.push(T[(n >> 18) as usize & 63] as char);
1807 out.push(T[(n >> 12) as usize & 63] as char);
1808 out.push(if chunk.len() > 1 { T[(n >> 6) as usize & 63] as char } else { '=' });
1809 out.push(if chunk.len() > 2 { T[n as usize & 63] as char } else { '=' });
1810 }
1811 out
1812}
1813
1814#[cfg(test)]
1815mod tests {
1816 use super::*;
1817 use crate::testutil::TestDir;
1818 use engine::project::Lane;
1819 use std::time::Instant;
1820
1821 fn server() -> Server {
1822 engine::ao::set_silent_output();
1823 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
1824 let mut srv = Server::new();
1825 srv.session = Some(PlaybackSession::open(p).expect("open test asset"));
1826 srv
1827 }
1828
1829 /// The source time a frame of a ramped clip names is the ramp's integral, not a single
1830 /// rate: 1x to 2x over 60 frames has played 90 source frames at frame 60.
1831 #[test]
1832 fn clip_desc_names_the_source_time_through_a_ramp() {
1833 let mut srv = server();
1834 let s = srv.session.as_mut().unwrap();
1835 let keys = [
1836 engine::project::SpeedKey { at: 0, speed: engine::project::Speed::NORMAL },
1837 engine::project::SpeedKey { at: 60, speed: engine::project::Speed::from_permille(2000) },
1838 ];
1839 s.set_speed_ramp(Lane::V1, 0, &keys).expect("the ramp sets");
1840 let c = s.lane_clips(Lane::V1)[0].clone();
1841 let fps = parse::session_fps(s);
1842 let want = format!("@ {:.3}s", f64::from(c.in_frame + 90) / fps);
1843 let got = clip_desc(s, &c, c.start + 60);
1844 assert!(got.ends_with(&want), "{got} should end with {want}");
1845 }
1846
1847 /// Calls any registered tool, so a test can set up a project with `edit`.
1848 fn call(srv: &mut Server, name: &str, args: Value) -> Reply {
1849 let tool = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool exists");
1850 (tool.run)(srv, &args)
1851 }
1852
1853 /// Decodes standard base64 (test only).
1854 fn unbase64(s: &str) -> Vec<u8> {
1855 let mut out = Vec::new();
1856 let mut acc = 0u32;
1857 let mut bits = 0;
1858 for ch in s.bytes().filter(|&b| b != b'=') {
1859 let v = match ch {
1860 b'A'..=b'Z' => ch - b'A',
1861 b'a'..=b'z' => ch - b'a' + 26,
1862 b'0'..=b'9' => ch - b'0' + 52,
1863 b'+' => 62,
1864 b'/' => 63,
1865 _ => panic!("bad base64 byte {ch}"),
1866 };
1867 acc = (acc << 6) | u32::from(v);
1868 bits += 6;
1869 if bits >= 8 {
1870 bits -= 8;
1871 out.push((acc >> bits) as u8);
1872 }
1873 }
1874 out
1875 }
1876
1877 /// (width, height) from a PNG's IHDR chunk.
1878 fn png_size(png: &[u8]) -> (u32, u32) {
1879 assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n", "not a PNG");
1880 let w = u32::from_be_bytes(png[16..20].try_into().unwrap());
1881 let h = u32::from_be_bytes(png[20..24].try_into().unwrap());
1882 (w, h)
1883 }
1884
1885 /// scopes reads the graded frame: a warm LUT puts red above blue in the parade
1886 /// and turns the cast toward red; a missing LUT is named and not applied.
1887 #[test]
1888 fn scopes_read_the_graded_frame_and_name_a_missing_lut() {
1889 let mut srv = server();
1890 let before = call(&mut srv, "scopes", json!({"at": "0.5s"}));
1891 assert!(!before.is_error, "{}", before.text);
1892 assert!(before.text.contains("waveform (luma %") && before.text.contains("parade: red") && before.text.contains("vectorscope:"), "{}", before.text);
1893 let b = before.structured.clone().expect("structured");
1894 let dir = std::env::temp_dir().join(format!("edith-scopes-{}", std::process::id()));
1895 std::fs::create_dir_all(&dir).unwrap();
1896 let cube = dir.join("warm.cube");
1897 // Red lifted hard, blue pulled down.
1898 std::fs::write(&cube, "LUT_3D_SIZE 2\n0.3 0 0\n1 0 0\n0.3 1 0\n1 1 0\n0.3 0 0.6\n1 0 0.6\n0.3 1 0.6\n1 1 0.6\n").unwrap();
1899 let r = call(&mut srv, "edit", json!({"ops": [{"op": "lut", "clip": "V1#0", "path": cube.display().to_string()}]}));
1900 assert!(!r.is_error, "{}", r.text);
1901 let after = call(&mut srv, "scopes", json!({"at": "0.5s", "bands": 2}));
1902 let a = after.structured.clone().expect("structured");
1903 let mean = |v: &Value, c: &str| v["parade"][c]["mean"].as_f64().unwrap();
1904 assert!(mean(&a, "red") - mean(&a, "blue") > mean(&b, "red") - mean(&b, "blue") + 10.0, "{}\n{}", before.text, after.text);
1905 assert_eq!(a["waveform_bands"].as_array().unwrap().len(), 2);
1906 std::fs::remove_file(&cube).unwrap();
1907 // Re-read from disk on the next open of the path: a missing file is named.
1908 engine::cube::LutRef::reload(&cube);
1909 let gone = call(&mut srv, "scopes", json!({"at": "0.5s"}));
1910 assert!(gone.text.contains("LUT not applied"), "{}", gone.text);
1911 let status = call(&mut srv, "project_status", json!({}));
1912 assert!(status.text.contains("LUT not applied") && status.text.contains("relink"), "{}", status.text);
1913 assert!(call(&mut srv, "scopes", json!({"at": "0.5s", "bands": 0})).is_error);
1914 std::fs::remove_dir_all(&dir).ok();
1915 }
1916
1917 #[test]
1918 fn base64_matches_rfc4648_vectors() {
1919 assert_eq!(base64(b""), "");
1920 assert_eq!(base64(b"f"), "Zg==");
1921 assert_eq!(base64(b"fo"), "Zm8=");
1922 assert_eq!(base64(b"foo"), "Zm9v");
1923 assert_eq!(base64(b"foob"), "Zm9vYg==");
1924 assert_eq!(base64(b"fooba"), "Zm9vYmE=");
1925 assert_eq!(base64(b"foobar"), "Zm9vYmFy");
1926 assert_eq!(base64(&[0xfb, 0xff]), "+/8=");
1927 assert_eq!(unbase64(&base64(&[0, 1, 2, 254, 255])), vec![0, 1, 2, 254, 255]);
1928 }
1929
1930 #[test]
1931 fn glyphs_draw_pixels() {
1932 let mut c = Canvas::new(120, 24, BLACK);
1933 draw_text_at(&mut c, 2, 2, "01:02.500", SCALE);
1934 let lit = c.px.chunks(4).filter(|p| p[0] == 255).count();
1935 assert!(lit > 100, "only {lit} white pixels");
1936 let mut one = Canvas::new(40, 24, BLACK);
1937 draw_text_at(&mut one, 2, 2, "0123456789:.f", SCALE);
1938 assert!(one.px.chunks(4).any(|p| p[0] == 255));
1939 }
1940
1941 /// A folder of a dead pid goes; this process's own, and a live one, stay.
1942 #[cfg(target_os = "linux")]
1943 #[test]
1944 fn sweep_removes_only_dead_processes_scratch() {
1945 let temp = TestDir::new("sweep");
1946 let dead = temp.join("edith_mcp-4294967290");
1947 let own = temp.join(format!("edith_mcp-{}", std::process::id()));
1948 let other = temp.join("edith_mcp-main-1");
1949 for d in [&dead, &own, &other] {
1950 std::fs::create_dir_all(d.join("frames")).unwrap();
1951 }
1952 sweep_in(&temp, std::process::id());
1953 assert!(!dead.exists(), "a dead process's scratch is removed");
1954 assert!(own.exists(), "our own scratch is kept");
1955 assert!(other.exists(), "names that are not a pid are left alone");
1956 }
1957
1958 #[test]
1959 fn same_moment_of_two_states_keeps_two_files() {
1960 // Two frames at one time with different pictures must not share a cache name.
1961 let dir = TestDir::new("same-moment");
1962 let a = save_png(b"state one", &dir, "150-640.png", None).ok().expect("saved");
1963 let b = save_png(b"state two", &dir, "150-640.png", None).ok().expect("saved");
1964 assert_ne!(a, b);
1965 assert_eq!(std::fs::read(&a).unwrap(), b"state one");
1966 assert_eq!(std::fs::read(&b).unwrap(), b"state two");
1967 let again = save_png(b"state one", &dir, "150-640.png", None).ok().expect("saved");
1968 assert_eq!(again, a, "the same bytes reuse the same file");
1969 }
1970
1971 #[test]
1972 fn prune_keeps_the_newest_files() {
1973 let root = TestDir::new("prune");
1974 let frames = root.join("frames");
1975 std::fs::create_dir_all(&frames).unwrap();
1976 for i in 0..12 {
1977 let p = frames.join(format!("{i}.png"));
1978 std::fs::write(&p, b"png").unwrap();
1979 // Older for smaller i, so the sort by modification time is the name order.
1980 let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000 + i);
1981 std::fs::File::options().write(true).open(&p).unwrap().set_modified(when).unwrap();
1982 }
1983 prune_cache(&root, 5, u64::MAX);
1984 let mut left: Vec<String> = std::fs::read_dir(&frames)
1985 .unwrap()
1986 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1987 .collect();
1988 left.sort();
1989 assert_eq!(left, ["10.png", "11.png", "7.png", "8.png", "9.png"]);
1990 }
1991
1992 #[test]
1993 fn prune_stops_at_the_byte_cap() {
1994 let root = TestDir::new("prune-bytes");
1995 let proj = root.join("proj");
1996 std::fs::create_dir_all(&proj).unwrap();
1997 for i in 0..4u64 {
1998 let p = proj.join(format!("{i}.png"));
1999 std::fs::write(&p, vec![0u8; 100]).unwrap();
2000 let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000 + i);
2001 std::fs::File::options().write(true).open(&p).unwrap().set_modified(when).unwrap();
2002 }
2003 // Room for two 100-byte files: the two newest stay.
2004 prune_cache(&root, 500, 250);
2005 let mut left: Vec<String> = std::fs::read_dir(&proj)
2006 .unwrap()
2007 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2008 .collect();
2009 left.sort();
2010 assert_eq!(left, ["2.png", "3.png"]);
2011 }
2012
2013 #[test]
2014 fn frames_dir_is_one_safe_folder_per_project() {
2015 let name = |p: Option<&Path>| frames_dir(p).file_name().unwrap().to_str().unwrap().to_string();
2016 assert_eq!(name(Some(Path::new("/x/My Edit (2).edith"))), "My_Edit__2_");
2017 assert_eq!(name(None), "untitled");
2018 assert_eq!(name(Some(Path::new("/x/..."))), "untitled");
2019 assert_eq!(safe_component("../../etc"), "_.._etc");
2020 }
2021
2022 #[test]
2023 fn a_frame_reply_names_the_frame_seconds_rounded_to() {
2024 // 0.5 s at 25 fps is 12.5 frames: the frame shown is 13, and the reply says so.
2025 assert_eq!(rounded_frame(&json!({"at": "0.5s"}), 25.0, 13), "0.5s → 13f");
2026 assert_eq!(rounded_frame(&json!({"at": 0.5}), 25.0, 13), "0.5s → 13f");
2027 assert_eq!(rounded_frame(&json!({"at": "1s"}), 25.0, 25), "25f");
2028 assert_eq!(rounded_frame(&json!({"at": "13f"}), 25.0, 13), "13f");
2029 assert_eq!(rounded_frame(&json!({"at": "00:00:00:13"}), 25.0, 13), "13f");
2030 }
2031
2032 /// A size preview draws the frame at the export's picture size, scaled to the width asked, and
2033 /// the reply says it is a preview of that export; the project keeps its own size.
2034 #[test]
2035 fn a_size_preview_is_the_export_size_and_says_so() {
2036 let mut srv = server();
2037 let r = call(&mut srv, "frame", json!({"at": "1.0s", "size": "1080x1920", "width": 270}));
2038 assert!(!r.is_error, "{}", r.text);
2039 assert_eq!(png_size(&unbase64(&r.images[0].1)), (270, 480), "{}", r.text);
2040 assert!(r.text.contains("preview of the export at 1080x1920 (fit keep)"), "{}", r.text);
2041 assert!(r.text.contains("the project is unchanged"), "{}", r.text);
2042 assert!(r.text.contains("preview 270x480 (the export is 1080x1920)"), "{}", r.text);
2043 let plain = call(&mut srv, "frame", json!({"at": "1.0s", "width": 270}));
2044 assert!(!plain.is_error, "{}", plain.text);
2045 assert!(!plain.text.contains("preview of the export"), "{}", plain.text);
2046 assert_eq!(png_size(&unbase64(&plain.images[0].1)).0, 270);
2047 }
2048
2049 /// `fit` on a size preview puts the full-frame clips on that policy and says how many; without
2050 /// a size the export is the project's own picture size.
2051 #[test]
2052 fn a_fit_preview_names_the_fit_and_the_clips_it_reached() {
2053 let mut srv = server();
2054 let r = call(&mut srv, "frame", json!({"at": "1.0s", "size": "720x1280", "fit": "fill", "width": 180}));
2055 assert!(!r.is_error, "{}", r.text);
2056 assert!(r.text.contains("(fit fill, 1 full-frame clip(s) on it"), "{}", r.text);
2057 assert_eq!(png_size(&unbase64(&r.images[0].1)), (180, 320), "{}", r.text);
2058 let fit_only = call(&mut srv, "frame", json!({"at": "1.0s", "fit": "fit", "width": 320}));
2059 assert!(!fit_only.is_error, "{}", fit_only.text);
2060 assert!(fit_only.text.contains("preview of the export at 1280x720 (fit fit"), "{}", fit_only.text);
2061 }
2062
2063 #[test]
2064 fn a_size_or_fit_refuses_a_source_and_a_bad_value() {
2065 let mut srv = server();
2066 let on_source = call(&mut srv, "frame", json!({"at": "0.5s", "source": "src:0", "size": "720p"}));
2067 assert!(on_source.is_error, "{}", on_source.text);
2068 assert!(on_source.text.contains("cannot be used with source"), "{}", on_source.text);
2069 let bad_fit = call(&mut srv, "frame", json!({"at": "0.5s", "fit": "stretch"}));
2070 assert!(bad_fit.is_error, "{}", bad_fit.text);
2071 let odd = call(&mut srv, "frame", json!({"at": "0.5s", "size": "161x120"}));
2072 assert!(odd.is_error, "{}", odd.text);
2073 }
2074
2075 #[test]
2076 fn frame_returns_one_png_block_at_the_width_asked() {
2077 let mut srv = server();
2078 let r = call(&mut srv, "frame", json!({"at": "1.0s"}));
2079 assert!(!r.is_error, "{}", r.text);
2080 assert_eq!(r.images.len(), 1);
2081 assert_eq!(r.images[0].0, "image/png");
2082 let png = unbase64(&r.images[0].1);
2083 assert_eq!(png_size(&png).0, 640);
2084 assert!(r.text.contains("V1@"), "{}", r.text);
2085 assert!(r.text.contains("src:0 test_av.mp4"), "{}", r.text);
2086 assert!(r.text.contains("640x"), "{}", r.text);
2087 let path = r.structured.as_ref().unwrap()["path"].as_str().unwrap().to_string();
2088 assert_eq!(std::fs::read(&path).unwrap(), png);
2089 }
2090
2091 #[test]
2092 fn frame_from_a_source_is_scaled_to_width() {
2093 let mut srv = server();
2094 let r = call(&mut srv, "frame", json!({"at": "1.0s", "source": "src:0", "width": 320}));
2095 assert!(!r.is_error, "{}", r.text);
2096 assert_eq!(png_size(&unbase64(&r.images[0].1)).0, 320);
2097 }
2098
2099 #[test]
2100 fn a_frame_past_a_sources_length_says_the_length_and_the_last_time() {
2101 engine::ao::set_silent_output();
2102 // A 2 s picture (60 frames at 30 fps) with 60 s of sound: the picture ends first.
2103 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_short_video_long_audio.mp4");
2104 let mut srv = Server::new();
2105 srv.session = Some(PlaybackSession::open(p).expect("open test asset"));
2106 let r = call(&mut srv, "frame", json!({"at": "2.5s", "source": "src:0"}));
2107 assert!(r.is_error, "{}", r.text);
2108 assert_eq!(
2109 r.text,
2110 "src:0 is 2.0s (60f) long; frame 75 (2.5s) is past its end — ask for at most 1.97s"
2111 );
2112 assert!(!r.text.contains("decoder"), "{}", r.text);
2113 // Inside the length the frame still comes back.
2114 let inside = call(&mut srv, "frame", json!({"at": "1.0s", "source": "src:0"}));
2115 assert!(!inside.is_error, "{}", inside.text);
2116 }
2117
2118 #[test]
2119 fn seconds_in_plain_words_keep_one_or_two_decimals() {
2120 assert_eq!(secs_text(1.0), "1.0s");
2121 assert_eq!(secs_text(0.5), "0.5s");
2122 assert_eq!(secs_text(0.533), "0.53s");
2123 assert_eq!(secs_text(2.0), "2.0s");
2124 }
2125
2126 #[test]
2127 fn frame_names_audio_only_sources_and_shows_stills() {
2128 let mut srv = server();
2129 let assets = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets");
2130 let s = srv.session.as_mut().unwrap();
2131 for name in ["test_tone.aac", "test_tone.opus", "test_tone_cover.mpeg"] {
2132 s.import(&assets.join(name)).expect("import the sound");
2133 }
2134 s.import(&assets.join("test_still.png")).expect("import the still");
2135 // src:0 is test_av.mp4; src:1 to src:3 are sound, src:4 the still.
2136 for n in 1..=4 {
2137 let r = call(&mut srv, "frame", json!({"at": "0s", "source": format!("src:{n}")}));
2138 if n < 4 {
2139 assert!(r.is_error, "{}", r.text);
2140 assert!(r.text.starts_with("no picture: test_tone"), "{}", r.text);
2141 assert!(r.text.contains("audio only"), "{}", r.text);
2142 assert!(!r.text.contains("box"), "no decode is attempted: {}", r.text);
2143 } else {
2144 assert!(!r.is_error, "{}", r.text);
2145 assert!(!r.text.contains("no picture"), "a still is a picture: {}", r.text);
2146 assert_eq!(r.images.len(), 1);
2147 }
2148 }
2149 }
2150
2151 /// A frame or contact sheet over an offline clip draws that picture missing and names the
2152 /// source with the fix, with no OS error; the other tiles still compose. A source frame of
2153 /// the offline file is refused by name.
2154 #[test]
2155 fn an_offline_clip_is_drawn_missing_and_named() {
2156 let td = TestDir::new("see-offline");
2157 let gone = td.path().join("gone.mp4");
2158 std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_25fps.mp4"), &gone)
2159 .expect("copy");
2160 let project = td.path().join("offline.edith");
2161 let mut server = Server::new();
2162 assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error);
2163 assert!(!call(&mut server, "media_import", json!({"paths": [gone]})).is_error);
2164 assert!(!call(
2165 &mut server,
2166 "edit",
2167 json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s"}]})
2168 )
2169 .is_error);
2170 assert!(!call(&mut server, "project_save", json!({})).is_error);
2171 std::fs::remove_file(&gone).expect("remove");
2172
2173 let mut opened = Server::new();
2174 assert!(!call(&mut opened, "project_open", json!({"path": project})).is_error);
2175 let note = "is offline; its picture is missing here — relink with media_relink";
2176
2177 let r = call(&mut opened, "frame", json!({"at": "1.0s", "width": 320}));
2178 assert!(!r.is_error, "{}", r.text);
2179 assert!(r.text.contains("src:0 ") && r.text.contains(note), "{}", r.text);
2180 assert!(!r.text.contains("No such file"), "{}", r.text);
2181 assert_eq!(r.images.len(), 1);
2182 assert_eq!(png_size(&unbase64(&r.images[0].1)).0, 320, "the missing picture is drawn at the width asked");
2183
2184 let sheet = call(&mut opened, "contact_sheet", json!({"count": 3, "cols": 3, "width": 480}));
2185 assert!(!sheet.is_error, "{}", sheet.text);
2186 assert!(sheet.text.contains(note), "{}", sheet.text);
2187 assert!(!sheet.text.contains("No such file"), "{}", sheet.text);
2188
2189 let src = call(&mut opened, "frame", json!({"source": "src:0", "at": 0}));
2190 assert!(src.is_error && src.text.starts_with("src:0 ") && src.text.contains(note), "{}", src.text);
2191 }
2192
2193 #[test]
2194 fn frame_refuses_bad_width_and_unknown_source() {
2195 let mut srv = server();
2196 let r = call(&mut srv, "frame", json!({"at": 10, "width": 4000}));
2197 assert!(r.is_error && r.text.contains("width"), "{}", r.text);
2198 let r = call(&mut srv, "frame", json!({"at": 10, "source": "src:9"}));
2199 assert!(r.is_error && r.text.contains("src:9"), "{}", r.text);
2200 }
2201
2202 /// A session on one asset, as `server` does, with the project at `fps`.
2203 fn server_at(asset: &str, fps: f64) -> Server {
2204 engine::ao::set_silent_output();
2205 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(asset);
2206 let mut srv = Server::new();
2207 let mut s = PlaybackSession::open(p).expect("open test asset");
2208 assert!(s.set_frame_rate(fps), "project set to {fps} fps");
2209 srv.session = Some(s);
2210 srv
2211 }
2212
2213 #[test]
2214 fn frame_names_the_source_time_in_seconds_across_a_rate_change() {
2215 // A 30 fps source in a 25 fps project: 4.96 s is timeline frame 124, and the
2216 // source plays it at 4.96 s, not at 124 frames of its own 30 fps (4.133 s).
2217 let mut srv = server_at("test_av.mp4", 25.0);
2218 let r = call(&mut srv, "frame", json!({"at": "4.96s"}));
2219 assert!(!r.is_error, "{}", r.text);
2220 // Timeline frame 124 shows source frame floor(124 * 30 / 25) = 148, at 4.933 s.
2221 assert!(r.text.contains("V1@0 src:0 test_av.mp4 @ 4.933s"), "{}", r.text);
2222
2223 // A 25 fps source in a 30 fps project: 1.96 s is timeline frame 59, which the
2224 // source shows at its own frame floor(59 * 25 / 30) = 49, at 1.960 s (not 59 of
2225 // its own 25 fps, 2.360 s, and not 59 / 30 = 1.967 s).
2226 let mut srv = server_at("test_25fps.mp4", 30.0);
2227 let r = call(&mut srv, "frame", json!({"at": "1.96s"}));
2228 assert!(!r.is_error, "{}", r.text);
2229 assert!(r.text.contains("V1@0 src:0 test_25fps.mp4 @ 1.960s"), "{}", r.text);
2230 }
2231
2232 #[test]
2233 fn source_frame_rounds_seconds_with_the_source_fps() {
2234 // 0.5 s at 25 fps is 12.5 frames: it rounds up to 13, which is 0.520 s, and the
2235 // reply says both. The project fps (25 here) plays no part in a source time.
2236 let mut srv = server_at("test_av.mp4", 25.0);
2237 let r = call(&mut srv, "frame", json!({"at": "0.5s", "source": "src:0"}));
2238 assert!(!r.is_error, "{}", r.text);
2239 assert!(r.text.contains("· 00:00.500 (15f)"), "{}", r.text);
2240
2241 let mut srv = server_at("test_25fps.mp4", 30.0);
2242 let r = call(&mut srv, "frame", json!({"at": "0.5s", "source": "src:0"}));
2243 assert!(!r.is_error, "{}", r.text);
2244 assert!(r.text.contains("· 00:00.520 (0.5s → 13f)"), "{}", r.text);
2245 assert_eq!(r.structured.as_ref().unwrap()["frame"], json!(13));
2246
2247 // An exact frame count names no rounding.
2248 let r = call(&mut srv, "frame", json!({"at": "13f", "source": "src:0"}));
2249 assert!(r.text.contains("· 00:00.520 (13f)"), "{}", r.text);
2250 }
2251
2252 #[test]
2253 fn timeline_frame_follows_the_project_fps_not_the_source() {
2254 // In a 30 fps project 0.5 s is timeline frame 15, whatever the 25 fps source is.
2255 let mut srv = server_at("test_25fps.mp4", 30.0);
2256 let placed = call(&mut srv, "edit", json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "2s"]]}]}));
2257 assert!(!placed.is_error, "{}", placed.text);
2258 let r = call(&mut srv, "frame", json!({"at": "0.5s"}));
2259 assert!(!r.is_error, "{}", r.text);
2260 assert!(r.text.contains("(15f)"), "{}", r.text);
2261 assert!(r.text.contains("src:0 test_25fps.mp4 @ 0.480s"), "{}", r.text);
2262 }
2263
2264 #[test]
2265 fn frame_with_save_names_the_path_it_wrote() {
2266 let dir = TestDir::new("frame-save");
2267 let want = dir.join("picked.png");
2268 let mut srv = server();
2269 let r = call(&mut srv, "frame", json!({"at": "1.0s", "save": want.display().to_string()}));
2270 assert!(!r.is_error, "{}", r.text);
2271 assert!(r.text.contains(&format!("saved: {}", want.display())), "{}", r.text);
2272 let structured = r.structured.as_ref().unwrap();
2273 assert_eq!(structured["path"].as_str().unwrap(), want.display().to_string());
2274 assert_ne!(structured["cache_path"].as_str().unwrap(), want.display().to_string());
2275 assert_eq!(std::fs::read(&want).unwrap(), unbase64(&r.images[0].1));
2276
2277 let src_want = dir.join("source.png");
2278 let r = call(&mut srv, "frame", json!({"at": "1.0s", "source": "src:0", "save": src_want.display().to_string()}));
2279 assert!(!r.is_error, "{}", r.text);
2280 assert!(r.text.contains(&format!("saved: {}", src_want.display())), "{}", r.text);
2281 assert!(src_want.exists());
2282 }
2283
2284 #[test]
2285 fn contact_sheet_save_names_the_path_it_wrote() {
2286 let dir = TestDir::new("sheet-save");
2287 let want = dir.join("sheet.png");
2288 let mut srv = server();
2289 let r = call(&mut srv, "contact_sheet", json!({"count": 4, "cols": 2, "save": want.display().to_string()}));
2290 assert!(!r.is_error, "{}", r.text);
2291 assert!(r.text.contains(&format!("saved: {}", want.display())), "{}", r.text);
2292 assert_eq!(std::fs::read(&want).unwrap(), unbase64(&r.images[0].1));
2293 }
2294
2295 #[test]
2296 fn contact_sheet_is_one_image_of_the_expected_size() {
2297 let mut srv = server();
2298 let r = call(&mut srv, "contact_sheet", json!({"count": 6, "cols": 3}));
2299 assert!(!r.is_error, "{}", r.text);
2300 assert_eq!(r.images.len(), 1);
2301 let (w, h) = png_size(&unbase64(&r.images[0].1));
2302 let st = r.structured.as_ref().unwrap();
2303 let th = st["tile"]["h"].as_u64().unwrap() as u32;
2304 assert_eq!(w, 1280);
2305 assert_eq!(h, 2 * (th + LABEL_H) + GUTTER, "rows of tiles, each with its label band, one gutter between");
2306 assert!(r.text.contains("edit joins:"), "{}", r.text);
2307 assert_eq!(st["tiles"].as_array().unwrap().len(), 6);
2308 }
2309
2310 /// `server`'s test_av on V1 at 0f, then test_25fps and test_av again on V1: a 12f
2311 /// dissolve (picture only) joins the first two, a hard cut the last two. Returns the
2312 /// frame where the dissolve's boundary falls.
2313 fn dissolve_then_cut() -> (Server, u32) {
2314 let mut srv = server();
2315 let second = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_25fps.mp4");
2316 assert!(!call(&mut srv, "media_import", json!({"paths": [second.display().to_string()]})).is_error);
2317 let at = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].end();
2318 let placed = call(
2319 &mut srv,
2320 "edit",
2321 json!({"ops": [{"op": "place", "source": "src:1", "lane": "V1", "at": format!("{at}f"), "audio": false}]}),
2322 );
2323 assert!(!placed.is_error, "{}", placed.text);
2324 let dissolved = call(
2325 &mut srv,
2326 "edit",
2327 json!({"ops": [{"op": "dissolve", "clip": "V1@0", "frames": 12, "linked": false}]}),
2328 );
2329 assert!(!dissolved.is_error, "{}", dissolved.text);
2330 let end = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].end();
2331 let cut = call(
2332 &mut srv,
2333 "edit",
2334 json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": format!("{end}f"), "audio": false}]}),
2335 );
2336 assert!(!cut.is_error, "{}", cut.text);
2337 (srv, at)
2338 }
2339
2340 #[test]
2341 fn contact_sheet_lists_a_dissolve_apart_from_the_hard_cut() {
2342 let (mut srv, at) = dissolve_then_cut();
2343 let s = srv.session.as_ref().unwrap();
2344 let fps = parse::session_fps(s);
2345 let hard_at = s.lane_clips(Lane::V1)[2].start;
2346 let r = call(&mut srv, "contact_sheet", json!({"count": 6, "cols": 3}));
2347 assert!(!r.is_error, "{}", r.text);
2348 let want = format!("dissolve {:.2}s–{:.2}s", parse::secs(at - 12, fps), parse::secs(at, fps));
2349 assert!(r.text.contains(&want), "{}", r.text);
2350 let cut_line = r.text.lines().find(|l| l.starts_with("edit joins:")).expect("cuts line");
2351 assert!(cut_line.contains(&format!("{hard_at}f V1@")), "{cut_line}");
2352 assert!(!cut_line.contains(&format!(" {at}f ")), "the dissolve is not also a cut: {cut_line}");
2353 let st = r.structured.as_ref().unwrap();
2354 assert_eq!(st["cuts"].as_array().unwrap().len(), 1, "the hard cut is one entry naming both sides");
2355 assert!(st["cuts"][0]["text"].as_str().unwrap().contains("→V1@"), "{}", st["cuts"][0]);
2356 let d = &st["dissolves"].as_array().unwrap()[0];
2357 assert_eq!(d["frame"].as_u64().unwrap(), u64::from(at));
2358 assert_eq!(d["frames"].as_u64().unwrap(), 12);
2359 }
2360
2361 #[test]
2362 fn contact_sheet_with_only_a_dissolve_in_range_says_no_cuts() {
2363 let (mut srv, at) = dissolve_then_cut();
2364 let fps = parse::session_fps(srv.session.as_ref().unwrap());
2365 let range = json!({"from": format!("{}f", at - 10), "to": format!("{}f", at + 30)});
2366 let r = call(&mut srv, "contact_sheet", json!({"count": 4, "cols": 2, "range": range}));
2367 assert!(!r.is_error, "{}", r.text);
2368 let want = format!("edit joins: none · dissolve {:.2}s–{:.2}s", parse::secs(at - 12, fps), parse::secs(at, fps));
2369 assert!(r.text.contains(&want), "{}", r.text);
2370 }
2371
2372 /// A hard cut between two clips on one lane is one `ends→starts` entry, and a gap's end and
2373 /// start stay two entries.
2374 #[test]
2375 fn contact_sheet_merges_a_hard_cut_and_keeps_gaps_apart() {
2376 let mut srv = server();
2377 let end = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].end();
2378 let cut = call(
2379 &mut srv,
2380 "edit",
2381 json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": format!("{end}f"), "audio": false}]}),
2382 );
2383 assert!(!cut.is_error, "{}", cut.text);
2384 let second = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start;
2385 assert_eq!(second, end, "the second clip starts where the first ends");
2386 // A one-second gap after it, so the next clip's end and start are not joined.
2387 let gap_at = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].end() + 30;
2388 let gapped = call(
2389 &mut srv,
2390 "edit",
2391 json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": format!("{gap_at}f"), "audio": false}]}),
2392 );
2393 assert!(!gapped.is_error, "{}", gapped.text);
2394 let r = call(&mut srv, "contact_sheet", json!({"count": 4, "cols": 2}));
2395 assert!(!r.is_error, "{}", r.text);
2396 let cut_line = r.text.lines().find(|l| l.starts_with("edit joins:")).expect("cuts line");
2397 let merged = format!("{end}f V1@0→V1@{end}");
2398 assert!(cut_line.contains(&merged), "{cut_line}");
2399 assert!(!cut_line.contains(&format!("{end}f V1@0 ends")), "no separate end at the cut: {cut_line}");
2400 assert!(!cut_line.contains(&format!("{end}f V1@{end} starts")), "no separate start at the cut: {cut_line}");
2401 let gap_end = gap_at - 30;
2402 assert!(cut_line.contains(&format!("{gap_end}f V1@{end} ends")), "a gap's end stays: {cut_line}");
2403 assert!(cut_line.contains(&format!("{gap_at}f V1@{gap_at} starts")), "a gap's start stays: {cut_line}");
2404 }
2405
2406 /// A clip with no joins in range: the line says so and points to scenes for the picture
2407 /// cuts inside the clip, which are not joins.
2408 #[test]
2409 fn contact_sheet_on_one_clip_points_to_scenes_for_its_picture_cuts() {
2410 let mut srv = server();
2411 let r = call(&mut srv, "contact_sheet", json!({"count": 4, "cols": 2}));
2412 assert!(!r.is_error, "{}", r.text);
2413 let join_line = r.text.lines().find(|l| l.starts_with("edit joins:")).expect("joins line");
2414 assert_eq!(join_line, "edit joins: none in range · picture cuts inside a clip: scenes V1@0", "{}", r.text);
2415 }
2416
2417 /// A join on an audio lane is counted, not listed, and the count says it is an audio join.
2418 #[test]
2419 fn contact_sheet_counts_an_audio_join_as_a_join_on_audio_lanes() {
2420 let mut srv = server();
2421 let end = srv.session.as_ref().unwrap().lane_clips(Lane::A1)[0].end();
2422 let joined = call(
2423 &mut srv,
2424 "edit",
2425 json!({"ops": [{"op": "place", "source": "src:0", "lane": "A1", "at": format!("{end}f")}]}),
2426 );
2427 assert!(!joined.is_error, "{}", joined.text);
2428 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::A1)[1].start, end, "the audio clip joins at {end}f");
2429 let r = call(&mut srv, "contact_sheet", json!({"count": 4, "cols": 2}));
2430 assert!(!r.is_error, "{}", r.text);
2431 let join_line = r.text.lines().find(|l| l.starts_with("edit joins:")).expect("joins line");
2432 assert!(join_line.contains(" · (1 join on audio lanes not shown) · "), "{join_line}");
2433 assert!(!r.text.contains("audio cuts"), "{}", r.text);
2434 }
2435
2436 /// A source has no edit joins: the line says so and names scenes for its picture cuts.
2437 #[test]
2438 fn contact_sheet_of_a_source_says_it_has_no_edit_joins() {
2439 let mut srv = server();
2440 let r = call(&mut srv, "contact_sheet", json!({"source": "src:0", "count": 4, "cols": 2}));
2441 assert!(!r.is_error, "{}", r.text);
2442 let want = "edit joins: none (a source has no edit joins) · scenes src:0 finds its picture cuts";
2443 assert!(r.text.lines().any(|l| l == want), "{}", r.text);
2444 }
2445
2446 /// An empty timeline says it is empty, not that the range runs past zero frames.
2447 #[test]
2448 fn contact_sheet_on_an_empty_timeline_says_the_timeline_is_empty() {
2449 let td = TestDir::new("r30-empty-sheet");
2450 let mut srv = Server::new();
2451 let made = call(&mut srv, "project_new", json!({"path": td.path().join("proj.edith"), "resolution": "1280x720"}));
2452 assert!(!made.is_error, "{}", made.text);
2453 let r = call(&mut srv, "contact_sheet", json!({"range": {"from": "12s", "to": "15s"}}));
2454 assert!(r.is_error, "{}", r.text);
2455 assert!(r.text.contains("the timeline is empty"), "{}", r.text);
2456 assert!(!r.text.contains("past the end"), "{}", r.text);
2457 }
2458
2459 #[test]
2460 fn contact_sheet_refuses_a_bad_count() {
2461 let mut srv = server();
2462 let r = call(&mut srv, "contact_sheet", json!({"count": 49}));
2463 assert!(r.is_error && r.text.contains("count"), "{}", r.text);
2464 }
2465
2466 #[test]
2467 fn gap_frame_is_black() {
2468 let mut srv = server();
2469 // Move the first clip (and its link group) to start at 500f, leaving a gap before it.
2470 let moved = call(
2471 &mut srv,
2472 "edit",
2473 json!({"ops": [{"op": "move", "clip": "V1@0", "at": "500f"}]}),
2474 );
2475 assert!(!moved.is_error, "{}", moved.text);
2476 let s = srv.session.as_ref().unwrap();
2477 assert!(s.gap_at(Lane::V1, 100).is_some(), "expected a gap at 100f");
2478 let r = call(&mut srv, "frame", json!({"at": "100f"}));
2479 assert!(!r.is_error, "{}", r.text);
2480 assert!(r.text.starts_with("gap ·"), "{}", r.text);
2481 let (project, meta) = srv.session.as_ref().unwrap().export_snapshot();
2482 let f = engine::export::compose_at(&project, &meta, 100, 64, 36).unwrap();
2483 let sum: u64 = f.bgra.chunks(4).map(|p| u64::from(p[0]) + u64::from(p[1]) + u64::from(p[2])).sum();
2484 let mean = sum / (f.bgra.len() as u64 / 4 * 3);
2485 assert!(mean < 16, "gap frame mean channel value {mean}");
2486 }
2487
2488 #[test]
2489 fn a_frame_whose_only_picture_is_hidden_is_not_called_a_gap() {
2490 let mut srv = server();
2491 // V1 holds the clip at 0; hiding the lane leaves the frame with a clip there but no picture.
2492 assert!(srv.session.as_mut().unwrap().set_lane_hidden(Lane::V1, true));
2493 let r = call(&mut srv, "frame", json!({"at": "100f"}));
2494 assert!(!r.is_error, "{}", r.text);
2495 assert!(
2496 r.text.starts_with("hidden lane only · black (V1 is hidden: not in the picture) · "),
2497 "{}",
2498 r.text
2499 );
2500 assert!(!r.text.contains("gap"), "{}", r.text);
2501 // The lane line still says the clip is there and not drawn.
2502 assert!(r.text.contains("V1 V1@0 src:0"), "{}", r.text);
2503 assert!(r.text.contains("(hidden: not in the picture)"), "{}", r.text);
2504 // A visible picture on another lane makes the frame a normal one again.
2505 assert!(srv.session.as_mut().unwrap().set_lane_hidden(Lane::V1, false));
2506 let shown = call(&mut srv, "frame", json!({"at": "100f"}));
2507 assert!(shown.text.starts_with("V1@0 "), "{}", shown.text);
2508 }
2509
2510 #[test]
2511 fn hidden_only_text_names_one_lane_or_several() {
2512 assert_eq!(hidden_only_text(&[]), None);
2513 assert_eq!(hidden_only_text(&["V1".to_string()]).unwrap(), "V1 is hidden: not in the picture");
2514 let two = ["V1".to_string(), "V2".to_string()];
2515 assert_eq!(hidden_only_text(&two).unwrap(), "V1 and V2 are hidden: not in the picture");
2516 let three = ["V1".to_string(), "V2".to_string(), "V3".to_string()];
2517 assert_eq!(hidden_only_text(&three).unwrap(), "V1, V2 and V3 are hidden: not in the picture");
2518 }
2519
2520 #[test]
2521 fn burn_captions_true_is_the_defaults_and_false_is_off() {
2522 let mut srv = server_with_subs();
2523 let plain = call(&mut srv, "frame", json!({"at": "1.0s", "width": 640}));
2524 let defaults = call(&mut srv, "frame", json!({"at": "1.0s", "width": 640, "burn_captions": {}}));
2525 let on = call(&mut srv, "frame", json!({"at": "1.0s", "width": 640, "burn_captions": true}));
2526 let off = call(&mut srv, "frame", json!({"at": "1.0s", "width": 640, "burn_captions": false}));
2527 assert!(!on.is_error, "{}", on.text);
2528 assert!(on.text.contains("captions burned (track 0)"), "{}", on.text);
2529 assert_eq!(unbase64(&on.images[0].1), unbase64(&defaults.images[0].1), "true is {{}}");
2530 assert!(!off.is_error, "{}", off.text);
2531 assert!(!off.text.contains("captions burned"), "{}", off.text);
2532 assert_eq!(unbase64(&off.images[0].1), unbase64(&plain.images[0].1), "false is no burn");
2533 }
2534
2535 #[test]
2536 fn contact_sheet_of_a_still_is_one_tile() {
2537 let mut srv = server();
2538 let still = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_still.png");
2539 srv.session.as_mut().expect("session").import(&still).expect("import the still");
2540 let r = call(&mut srv, "contact_sheet", json!({"source": "src:1", "count": 4}));
2541 assert!(!r.is_error, "{}", r.text);
2542 assert_eq!(r.images.len(), 1);
2543 assert_eq!(r.structured.as_ref().unwrap()["tiles"].as_array().unwrap().len(), 1, "{}", r.text);
2544 // The one tile takes the width asked for, even though a grid's columns would split it.
2545 let w = call(&mut srv, "contact_sheet", json!({"source": "src:1", "width": 640}));
2546 assert!(!w.is_error, "{}", w.text);
2547 assert_eq!(w.structured.as_ref().unwrap()["tile"]["w"], 640, "{}", w.text);
2548 assert_eq!(w.structured.as_ref().unwrap()["width"], 640, "{}", w.text);
2549 }
2550
2551 fn server_with_subs() -> Server {
2552 let mut srv = server();
2553 let srt = Path::new(env!("CARGO_MANIFEST_DIR")).join("../engine/tests/data/test_subs.srt");
2554 srv.session
2555 .as_mut()
2556 .expect("session")
2557 .import_subtitles(&srt)
2558 .expect("import test_subs.srt");
2559 srv
2560 }
2561
2562 #[test]
2563 fn burned_frame_differs_from_plain_inside_a_cue() {
2564 use engine::text::TextStyle;
2565 let mut srv = server_with_subs();
2566 let plain = call(&mut srv, "frame", json!({"at": "1.0s", "width": 640}));
2567 let burned = call(&mut srv, "frame", json!({"at": "1.0s", "width": 640, "burn_captions": {}}));
2568 assert!(!plain.is_error, "{}", plain.text);
2569 assert!(!burned.is_error, "{}", burned.text);
2570 assert!(burned.text.contains("captions burned (track 0)"), "{}", burned.text);
2571 assert_ne!(unbase64(&plain.images[0].1), unbase64(&burned.images[0].1), "burning must change the PNG");
2572
2573 // The same frame, straight from the compositor: the captions sit in the bottom
2574 // quarter and leave the top quarter alone.
2575 let s = srv.session.as_ref().expect("session");
2576 let fps = parse::session_fps(s);
2577 let at = parse::frame_arg(&json!({"at": "1.0s"}), "at", fps, parse::session_end(s))
2578 .unwrap_or_else(|r| panic!("{}", r.text));
2579 let (project, meta) = s.export_snapshot();
2580 let a = engine::export::compose_at_with(&project, &meta, at, 640, 2560, None).expect("plain");
2581 let b = engine::export::compose_at_with(&project, &meta, at, 640, 2560, Some((0, TextStyle::default())))
2582 .expect("burned");
2583 assert_eq!(a.bgra.len(), b.bgra.len());
2584 let row = (a.width * 4) as usize;
2585 let h = a.height as usize;
2586 let differs = |from: usize, to: usize| {
2587 (from..to).any(|y| a.bgra[y * row..(y + 1) * row] != b.bgra[y * row..(y + 1) * row])
2588 };
2589 assert!(differs(h * 3 / 4, h), "no caption pixels in the bottom quarter");
2590 assert!(!differs(0, h / 4), "captions changed the top quarter");
2591 }
2592
2593 #[test]
2594 fn burn_captions_refuses_source_and_bad_track() {
2595 let mut srv = server_with_subs();
2596 let r = call(&mut srv, "frame", json!({"at": "1.0s", "source": "src:0", "burn_captions": {}}));
2597 assert!(r.is_error && r.text.contains("source"), "{}", r.text);
2598 let r = call(&mut srv, "frame", json!({"at": "1.0s", "burn_captions": {"track": 4}}));
2599 assert!(r.is_error && r.text.contains("does not exist"), "{}", r.text);
2600 let r = call(&mut srv, "contact_sheet", json!({"count": 2, "burn_captions": {"track": 4}}));
2601 assert!(r.is_error && r.text.contains("does not exist"), "{}", r.text);
2602 let r = call(&mut srv, "contact_sheet", json!({"count": 2, "burn_captions": {"size": 60}}));
2603 assert!(!r.is_error, "{}", r.text);
2604 assert!(r.text.contains("captions burned (track 0)"), "{}", r.text);
2605 }
2606
2607 #[test]
2608 fn frame_refuses_a_width_that_is_not_a_size_before_anything_else() {
2609 let mut srv = server();
2610 for w in [json!(-3), json!(0), json!(5000), json!("wide"), json!(2.5)] {
2611 let r = call(&mut srv, "frame", json!({"at": "1.0s", "width": w}));
2612 assert!(r.is_error && r.text.contains("width"), "{w}: {}", r.text);
2613 }
2614 }
2615
2616 #[test]
2617 fn burned_frame_reports_the_caption_it_drew_after_an_edit_and_a_cut() {
2618 use crate::tools::edit::run_edit;
2619 let mut srv = server_with_subs();
2620 let ops = json!({"ops": [{"op": "captions_place", "track": 0}]});
2621 assert!(!run_edit(&mut srv, &ops).is_error);
2622 let ops = json!({"ops": [{"op": "cue_text", "track": 0, "index": 0, "text": "Hello there"}]});
2623 assert!(!run_edit(&mut srv, &ops).is_error);
2624
2625 let r = call(&mut srv, "frame", json!({"at": "1.0s", "burn_captions": {}}));
2626 assert!(!r.is_error, "{}", r.text);
2627 assert!(r.text.contains("captions burned (track 0): \"Hello there\""), "{}", r.text);
2628
2629 // Cut the second cue's time out of the captions, then burn at the spot it was.
2630 let s = srv.session.as_mut().expect("session");
2631 let fps = parse::session_fps(s);
2632 let lanes = s.subtitle_lanes();
2633 let (a, b, _, _) = s.sub_lane_cue_refs(lanes[0])[1];
2634 let cut_text = s.subtitles()[0].cues[1].text.clone();
2635 let from = (a as f64 * fps / 1e6).round() as u32;
2636 let len = ((b - a) as f64 * fps / 1e6).round().max(1.0) as u32;
2637 s.cut_regions(&[(from, len)], &lanes).expect("cut the second cue");
2638 let r = call(&mut srv, "frame", json!({"at": format!("{from}f"), "burn_captions": {}}));
2639 assert!(!r.is_error, "{}", r.text);
2640 assert!(!r.text.contains(&cut_text), "the cut caption is still reported: {}", r.text);
2641 }
2642
2643 #[test]
2644 fn burned_frame_lists_every_cue_on_screen_and_the_missing_glyph() {
2645 use crate::tools::edit::run_edit;
2646 let td = crate::testutil::TestDir::new("see_stacked_cues");
2647 let srt = td.path().join("stack.srt");
2648 // The two cues overlap at 2.5 s, and U+10FFFD is a noncharacter no face draws.
2649 std::fs::write(
2650 &srt,
2651 "1\n00:00:01,000 --> 00:00:04,000\nFirst \u{10FFFD}\n\n2\n00:00:02,000 --> 00:00:05,000\nSecond\n\n",
2652 )
2653 .expect("write the srt");
2654 let mut srv = server();
2655 srv.session.as_mut().expect("session").import_subtitles(&srt).expect("import");
2656 let ops = json!({"ops": [{"op": "captions_place", "track": 0}]});
2657 assert!(!run_edit(&mut srv, &ops).is_error);
2658
2659 let r = call(&mut srv, "frame", json!({"at": "2.5s", "burn_captions": {}}));
2660 assert!(!r.is_error, "{}", r.text);
2661 assert!(r.text.contains("captions burned (track 0): \"First"), "{}", r.text);
2662 assert!(r.text.contains("captions burned (track 0): \"Second\""), "{}", r.text);
2663 assert!(r.text.contains("no glyph for: U+10FFFD (drawn as an empty box)"), "{}", r.text);
2664 }
2665
2666 #[test]
2667 fn frame_text_lists_the_titles_on_screen() {
2668 use crate::tools::edit::run_edit;
2669 let mut srv = server();
2670 let ops = json!({"ops": [{"op": "title_add", "at": "0.5s", "duration": "1s", "text": "Opening"}]});
2671 let r = run_edit(&mut srv, &ops);
2672 assert!(!r.is_error, "{}", r.text);
2673 let r = call(&mut srv, "frame", json!({"at": "0.7s"}));
2674 assert!(!r.is_error, "{}", r.text);
2675 assert!(r.text.contains("title on screen: \"Opening\""), "{}", r.text);
2676 let r = call(&mut srv, "frame", json!({"at": "3.0s"}));
2677 assert!(!r.text.contains("title on screen"), "{}", r.text);
2678 }
2679
2680 #[test]
2681 #[ignore = "timing: run with --release --ignored -- --nocapture"]
2682 fn contact_sheet_12_timing() {
2683 let mut srv = server();
2684 let t = Instant::now();
2685 let r = call(&mut srv, "contact_sheet", json!({"count": 12}));
2686 let ms = t.elapsed().as_secs_f64() * 1000.0;
2687 assert!(!r.is_error, "{}", r.text);
2688 eprintln!("contact_sheet count 12: {ms:.1} ms");
2689 }
2690
2691 #[test]
2692 fn schemas_describe_every_property() {
2693 for tool in tools() {
2694 let schema = (tool.schema)();
2695 assert_eq!(schema["type"], "object", "{}", tool.name);
2696 for (key, p) in schema["properties"].as_object().expect("properties") {
2697 assert!(p["description"].as_str().is_some(), "{}.{key} has no description", tool.name);
2698 }
2699 }
2700 }
2701
2702 /// The `burn_captions` argument of frame and contact_sheet is the export's own schema: the
2703 /// boolean reading is said once, and its type takes a boolean as well as the object.
2704 #[test]
2705 fn burn_captions_schema_says_its_boolean_reading_once() {
2706 // `scopes` reads the picture's levels, never captions.
2707 for tool in tools().into_iter().filter(|t| t.name != "scopes") {
2708 let schema = (tool.schema)();
2709 let burn = &schema["properties"]["burn_captions"];
2710 assert_eq!(burn["type"], json!(["object", "boolean"]), "{}", tool.name);
2711 let doc = burn["description"].as_str().unwrap_or_default();
2712 assert_eq!(doc.matches("Pass true for the defaults").count(), 1, "{}: {doc}", tool.name);
2713 }
2714 }
2715
2716 #[test]
2717 fn integral_float_out_of_range_is_named_in_plain_words() {
2718 let err = bounded(&json!({"width": 1000000000.0}), "width", 640, 1, 1920).expect_err("refused");
2719 assert_eq!(err.text, "argument `width` 1000000000 is too large: 1 to 1920");
2720 let err = bounded(&json!({"width": 1e30}), "width", 640, 1, 1920).expect_err("refused");
2721 assert_eq!(err.text, "argument `width` 1000000000000000019884624838656 is too large: 1 to 1920");
2722 let err = bounded(&json!({"width": -5.0}), "width", 640, 1, 1920).expect_err("refused");
2723 assert_eq!(err.text, "argument `width` -5 is too small: 1 to 1920");
2724 let err = bounded(&json!({"width": 1000000000}), "width", 640, 1, 1920).expect_err("refused");
2725 assert_eq!(err.text, "argument `width` 1000000000 is too large: 1 to 1920");
2726 }
2727
2728 #[test]
2729 fn integral_float_in_range_is_accepted() {
2730 assert_eq!(bounded(&json!({"width": 1280.0}), "width", 640, 1, 1920).ok(), Some(1280));
2731 assert_eq!(bounded(&json!({}), "width", 640, 1, 1920).ok(), Some(640));
2732 }
2733
2734 #[test]
2735 fn fractional_width_still_says_whole_number() {
2736 let err = bounded(&json!({"width": 1.5}), "width", 640, 1, 1920).expect_err("refused");
2737 assert_eq!(err.text, "argument `width` must be a whole number from 1 to 1920, not 1.5");
2738 }
2739
2740 #[test]
2741 fn frame_at_end_shows_the_last_frame_not_refused() {
2742 let mut srv = server();
2743 let s = srv.session.as_ref().expect("session");
2744 let media = s.export_snapshot().0.media_frames();
2745 let r = call(&mut srv, "frame", json!({"at": "end"}));
2746 assert!(!r.is_error, "{}", r.text);
2747 assert!(r.text.contains(&format!("{}f", media - 1)), "{}", r.text);
2748 }
2749
2750 #[test]
2751 fn two_titles_on_one_place_that_overlap_warn_on_the_frame() {
2752 use crate::tools::edit::run_edit;
2753 let mut srv = server();
2754 let ops = json!({"ops": [
2755 {"op": "title_add", "at": "0s", "duration": "3s", "text": "Top one", "place": "top"},
2756 {"op": "title_add", "at": "1s", "duration": "2s", "text": "Top two", "place": "top"},
2757 ]});
2758 assert!(!run_edit(&mut srv, &ops).is_error);
2759 let r = call(&mut srv, "frame", json!({"at": "1.5s"}));
2760 assert!(!r.is_error, "{}", r.text);
2761 assert!(r.text.contains("warning: two titles overlap at top 1.0–3.0s"), "{}", r.text);
2762 let apart = call(&mut srv, "frame", json!({"at": "0.5s"}));
2763 assert!(!apart.text.contains("two titles overlap"), "{}", apart.text);
2764 }
2765
2766 #[test]
2767 fn caption_glyph_note_names_only_the_cue_on_screen() {
2768 use crate::tools::edit::run_edit;
2769 let td = crate::testutil::TestDir::new("see_glyph_on_screen");
2770 let srt = td.path().join("glyph.srt");
2771 // A Latin cue, then one with a character no face draws; the frame must only name the cue it shows.
2772 std::fs::write(&srt, "1\n00:00:00,200 --> 00:00:01,000\nHello\n\n2\n00:00:01,500 --> 00:00:02,200\n\u{10FFFD}\n\n")
2773 .expect("write the srt");
2774 let mut srv = server();
2775 srv.session.as_mut().expect("session").import_subtitles(&srt).expect("import");
2776 assert!(!run_edit(&mut srv, &json!({"ops": [{"op": "captions_place", "track": 0}]})).is_error);
2777
2778 let latin = call(&mut srv, "frame", json!({"at": "0.5s", "burn_captions": {}}));
2779 assert!(!latin.is_error, "{}", latin.text);
2780 assert!(!latin.text.contains("no glyph for"), "{}", latin.text);
2781 let cyrillic = call(&mut srv, "frame", json!({"at": "2.0s", "burn_captions": {}}));
2782 assert!(!cyrillic.is_error, "{}", cyrillic.text);
2783 assert!(cyrillic.text.contains("no glyph for: U+10FFFD"), "{}", cyrillic.text);
2784 }
2785
2786 #[test]
2787 fn a_preview_names_the_export_size_it_stands_for() {
2788 assert_eq!(size_text(640, 1137, (1080, 1920), "the export"), "preview 640x1137 (the export is 1080x1920)");
2789 assert_eq!(size_text(1080, 1920, (1080, 1920), "the export"), "1080x1920");
2790 let mut srv = server();
2791 let r = call(&mut srv, "frame", json!({"at": "1.0s", "width": 320}));
2792 assert!(!r.is_error, "{}", r.text);
2793 assert!(r.text.contains("preview 320x"), "{}", r.text);
2794 assert!(r.text.contains("(the export is "), "{}", r.text);
2795 }
2796
2797 #[test]
2798 fn a_relative_save_path_is_named_in_full() {
2799 let want = std::env::current_dir().unwrap().join("shots").join("one.png");
2800 assert_eq!(absolute_path(PathBuf::from("shots/one.png")), want);
2801 let mut srv = server();
2802 let td = TestDir::new("frame-save-rel");
2803 let abs = td.join("abs.png");
2804 let r = call(&mut srv, "frame", json!({"at": "1.0s", "save": abs.display().to_string()}));
2805 assert!(r.text.contains(&format!("saved: {}", abs.display())), "{}", r.text);
2806 }
2807
2808 #[test]
2809 fn a_title_over_an_upper_lane_picture_is_named_on_the_frame() {
2810 use crate::tools::edit::run_edit;
2811 let mut srv = server();
2812 let ops = json!({"ops": [
2813 {"op": "lane_add", "kind": "video"},
2814 {"op": "place", "source": 0, "at": "0f", "lane": "V2", "audio": false},
2815 {"op": "title_add", "at": "0.5s", "duration": "1s", "text": "Opening", "place": "top"},
2816 ]});
2817 assert!(!run_edit(&mut srv, &ops).is_error);
2818 let r = call(&mut srv, "frame", json!({"at": "0.7s"}));
2819 assert!(!r.is_error, "{}", r.text);
2820 assert!(r.text.contains("warning: title T1 covers part of V2@0 (test_av)"), "{}", r.text);
2821 let before = call(&mut srv, "frame", json!({"at": "0.1s"}));
2822 assert!(!before.text.contains("covers part of"), "{}", before.text);
2823 }
2824
2825 #[test]
2826 fn a_title_on_the_base_lane_alone_covers_no_upper_picture() {
2827 use crate::tools::edit::run_edit;
2828 let mut srv = server();
2829 let ops = json!({"ops": [{"op": "title_add", "at": "0.5s", "duration": "1s", "text": "Base", "place": "top"}]});
2830 assert!(!run_edit(&mut srv, &ops).is_error);
2831 let r = call(&mut srv, "frame", json!({"at": "0.7s"}));
2832 assert!(!r.text.contains("covers part of"), "{}", r.text);
2833 }
2834
2835 #[test]
2836 fn a_burned_caption_and_a_bottom_title_on_screen_together_are_named() {
2837 use crate::tools::edit::run_edit;
2838 let td = crate::testutil::TestDir::new("see_clash_on_frame");
2839 let srt = td.path().join("clash.srt");
2840 std::fs::write(&srt, "1\n00:00:01,000 --> 00:00:04,000\nA caption\n\n").expect("write the srt");
2841 let mut srv = server();
2842 srv.session.as_mut().expect("session").import_subtitles(&srt).expect("import");
2843 let ops = json!({"ops": [
2844 {"op": "captions_place", "track": 0},
2845 {"op": "title_add", "at": "1s", "duration": "3s", "text": "Lower", "place": "bottom"},
2846 ]});
2847 assert!(!run_edit(&mut srv, &ops).is_error);
2848 let both = call(&mut srv, "frame", json!({"at": "2.5s", "burn_captions": {}}));
2849 assert!(!both.is_error, "{}", both.text);
2850 assert!(both.text.contains("caption overlaps title 'Lower' (both at the bottom)"), "{}", both.text);
2851 let caption_only = call(&mut srv, "frame", json!({"at": "0.5s", "burn_captions": {}}));
2852 assert!(!caption_only.text.contains("overlaps title"), "{}", caption_only.text);
2853 }
2854}