programmatic video rendering framework that is actually fast
feat(cli): render the frames of multi-frame commands on several threads (#235)
Dmitriy Kovalenko50923ac08944
diff --git a/AGENTS.md b/AGENTS.mdindex d05ede98..5597b641 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -276,7 +276,7 @@ my-video/Cargo.toml # fframes with the `cli` and `compile-time-svgtree` featuresmedia/ # embedded by include_media_dir! (a DM Sans font to start with)src/lib.rs # the Video from the template- src/main.rs # fframes::cli (render, frame, strip, onion, svg, timeline, inspect, snapshot, audio)+ src/main.rs # fframes::cli (render, frame, strip, onion, svg, timeline, inspect, audio)```For the web editor copy `examples/hello-world/editor` next to it and adapt step 9; gate the@@ -639,7 +639,7 @@ The rest is optional and chains in any order:```rustcli::new(&video, options)- // Render with Skia. Frame previews (frame, strip, onion, snapshot) use the backend's own+ // Render with Skia. Frame previews (frame, strip, onion) use the backend's own// renderer, so they match the video; the CPU backend is the default..backend(SkiaFFramesRenderer::new_metal(&gpu, SkiaPipelineConfig::default())?)// The `preview` command: a real-time window with audio (fframes_native_player).@@ -677,7 +677,6 @@ See `examples/teej-podcast/src/main.rs`; `cargo fframes new` generates the same| `svg TIME` | the frame as SVG after conversion || `timeline` | size, fps, scenes with frame and second ranges, audio tracks || `inspect [RANGE] [--every 0.25s] [--pops]` | missing media/fonts/glyphs, text cut by the canvas edge, NaN transforms, panics; exit code 2 on errors. `--pops` also renders every frame small and warns about pops: parts that change in one frame between still frames (an element appearing, vanishing or jumping in front of another) |-| `snapshot TIMES [--update]` | compare frames with approved PNGs, writes `.actual.png` and `.diff.png` || `audio render/analyze/at` | WAV of the mix, loudness report and waveform, tracks playing at a time || `preview [TIME] [--paused] [--mute]` | real-time GPU window (`fframes_native_player`), blocks until closed |@@ -763,11 +762,6 @@ $R render # final filejust clippy && cargo fmt --all && just check-wasm my-video # if it has an editor bridge```-Snapshot the compile-time tree against the runtime parser with-`fframes_test_utils::assert_compile_time_svgr_eq_runtime(name, svgr)` (see-`examples/marketing/src/tests.rs`); the first run writes `_svgr_snapshots/`, later runs diff.-Pixel snapshots of frames: `fframes::snapshot::assert_frames(&mut previewer, &mut renderer, &["Intro@1s"], &Default::default())`.-## Important Notes- Run `just clippy` before committing - warnings are errorsdiff --git a/README.md b/README.mdindex 20fbd56f..6e2976da 100644--- a/README.md+++ b/README.md@@ -83,7 +83,6 @@ Every command runs as `cargo run --release -- <command>` inside the project:| `frame <scene>@end,<scene>@50%` | full-size PNGs in `frames/` || `onion "<scene>@0..<scene>@1s" -n 6` | `onion.png`, the blended movement || `audio analyze --waveform w.png` | the loudness report and a waveform with scene lines and cue ticks |-| `snapshot` | a comparison with approved PNGs, `.diff.png` marks what changed || `preview` | the real-time window, for a human || `render [--draft]` | the video, or a part of it |diff --git a/cargo-fframes/templates/gitignore.tmpl b/cargo-fframes/templates/gitignore.tmplindex b5dc1103..f7b44229 100644--- a/cargo-fframes/templates/gitignore.tmpl+++ b/cargo-fframes/templates/gitignore.tmpl@@ -8,5 +8,3 @@ onion.png*.wav!media/*.wavtest_render/-_frame_snapshots/*.actual.png-_frame_snapshots/*.diff.pngdiff --git a/cargo-fframes/templates/main_skia.rs.tmpl b/cargo-fframes/templates/main_skia.rs.tmplindex ef0b5095..d3b93e78 100644--- a/cargo-fframes/templates/main_skia.rs.tmpl+++ b/cargo-fframes/templates/main_skia.rs.tmpl@@ -35,7 +35,7 @@ fn main() -> ExitCode {},).args(args)- // Frame previews (frame, strip, onion, snapshot) render with the same Skia backend.+ // Frame previews (frame, strip, onion) render with the same Skia backend..backend(SkiaFFramesRenderer::{{skia_constructor}}(&gpu,diff --git a/examples/signal-lab/.gitignore b/examples/signal-lab/.gitignoreindex b5dc1103..f7b44229 100644--- a/examples/signal-lab/.gitignore+++ b/examples/signal-lab/.gitignore@@ -8,5 +8,3 @@ onion.png*.wav!media/*.wavtest_render/-_frame_snapshots/*.actual.png-_frame_snapshots/*.diff.pngdiff --git a/examples/signal-lab/_frame_snapshots/datascene_3s.png b/examples/signal-lab/_frame_snapshots/datascene_3s.pngdeleted file mode 100644index d36fa553..00000000Binary files a/examples/signal-lab/_frame_snapshots/datascene_3s.png and /dev/null differdiff --git a/examples/signal-lab/_frame_snapshots/finalscene_3s.png b/examples/signal-lab/_frame_snapshots/finalscene_3s.pngdeleted file mode 100644index 32bd25ec..00000000Binary files a/examples/signal-lab/_frame_snapshots/finalscene_3s.png and /dev/null differdiff --git a/examples/signal-lab/_frame_snapshots/productscene_3s.png b/examples/signal-lab/_frame_snapshots/productscene_3s.pngdeleted file mode 100644index e683d6ce..00000000Binary files a/examples/signal-lab/_frame_snapshots/productscene_3s.png and /dev/null differdiff --git a/examples/signal-lab/_frame_snapshots/systemscene_3s.png b/examples/signal-lab/_frame_snapshots/systemscene_3s.pngdeleted file mode 100644index ba9fcb0a..00000000Binary files a/examples/signal-lab/_frame_snapshots/systemscene_3s.png and /dev/null differdiff --git a/examples/signal-lab/tests/frames.rs b/examples/signal-lab/tests/frames.rsdeleted file mode 100644index d84327d6..00000000--- a/examples/signal-lab/tests/frames.rs+++ /dev/null@@ -1,56 +0,0 @@-//! Visual regression: renders a few frames and compares them with the approved PNGs in-//! `_frame_snapshots/`. The first run creates them; `FFRAMES_UPDATE_SNAPSHOTS=1 cargo test`-//! accepts intentional changes. Failing frames leave `.actual.png` and `.diff.png` files.-use fframes::{CpuFrameRenderer, Previewer, RenderOptions, StaticMediaProvider, snapshot};-use signal_lab::{SignalLabMedia, SignalLabVideo};--#[test]-fn key_frames_match_snapshots() {- let media = SignalLabMedia::prepare().unwrap();- let video = SignalLabVideo;- let options = RenderOptions {- media: Some(&media),- scale_resolution: 0.5,- ..Default::default()- };- let mut previewer = Previewer::new(&video, &options).unwrap();-- snapshot::assert_frames(- &mut previewer,- &mut CpuFrameRenderer::default(),- &[- "ProductScene@3s",- "DataScene@3s",- "SystemScene@3s",- "FinalScene@3s",- ],- &snapshot::SnapshotOptions::default(),- );-}--#[test]-fn no_problems_in_any_frame() {- let media = SignalLabMedia::prepare().unwrap();- let video = SignalLabVideo;- let options = RenderOptions {- media: Some(&media),- ..Default::default()- };- let mut previewer = Previewer::new(&video, &options).unwrap();-- let duration = previewer.timeline().duration_in_frames;- for frame in 0..duration {- let report = previewer.inspect(frame).unwrap();- let problems: Vec<_> = report- .diagnostics- .iter()- .filter(|d| d.severity >= fframes::diagnostics::Severity::Warning)- .map(|d| d.message.as_str())- .collect();- assert!(- problems.is_empty(),- "frame {frame} ({:.2}s): {problems:?}",- report.seconds- );- }-}diff --git a/fframes/src/lib.rs b/fframes/src/lib.rsindex 071bf8df..ba47882b 100644--- a/fframes/src/lib.rs+++ b/fframes/src/lib.rs@@ -68,7 +68,7 @@//! fn main() -> std::process::ExitCode {//! let media = Media::prepare().expect("embedded media");//! let video = Hello { media: &media, title: "world" };-//! // `render`, `frame`, `strip`, `inspect`, `snapshot`, `audio` and more (feature `cli`).+//! // `render`, `frame`, `strip`, `inspect`, `audio` and more (feature `cli`).//! fframes::cli::new(&video, RenderOptions { media: Some(&media), ..Default::default() }).run()//! }//! ```diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rsindex fa980e48..b95627cf 100644--- a/fframes/src/renderer/cli.rs+++ b/fframes/src/renderer/cli.rs@@ -15,11 +15,12 @@//! into a `#[derive(clap::Args)]` struct: `let args = cli::parse::<MyArgs>();`, build the video//! from `args.app`, then `cli::new(&video, options).args(args).run()`.use super::{- CpuFrameRenderer, FFramesRenderBackend, FrameRenderer, FrameReport, Previewer, RgbaFrame,+ CpuFrameRenderer, FFramesRenderBackend, FFramesRendererError, FrameRenderer, FrameReport,+ Previewer, RgbaFrame,continuity::{PopDetector, PopKind},element_labels::{self, LabelledElement},fframes_logger::FFramesLoggerVariant,- sheet, snapshot,+ sheet,};use crate::diagnostics::Severity;use crate::{AudioMixer, AudioTimelineSamples, AudioTimelineUnit, RenderOptions, Video};@@ -109,8 +110,6 @@ pub enum Command {Timeline,/// Check frames for missing media and fonts, clipped text and panics without rendering.Inspect(InspectArgs),- /// Compare frames with approved PNG snapshots (visual regression).- Snapshot(SnapshotArgs),/// Render, measure and query the audio mix.#[command(subcommand)]Audio(AudioCommand),@@ -284,6 +283,19 @@ fn check_render_size<V: Video>(scale: f64) -> CliResult<()> {}/// The pixels of `region` (video pixels) in a frame rendered at any scale.+/// The file name of a time spec: `[email protected]` -> `intro_1.5s`.+fn file_name(spec: &str) -> String {+ let name: String = spec+ .chars()+ .map(|c| match c {+ 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' | '-' => c.to_ascii_lowercase(),+ '%' => 'p',+ _ => '_',+ })+ .collect();+ name.trim_matches('_').to_owned()+}+fn crop_frame<V: Video>(frame: &RgbaFrame, region: Region) -> RgbaFrame {let scale = f64::from(frame.width) / V::WIDTH as f64;frame.crop(@@ -294,24 +306,6 @@ fn crop_frame<V: Video>(frame: &RgbaFrame, region: Region) -> RgbaFrame {)}-#[derive(Debug, Clone, Args)]-pub struct SnapshotArgs {- /// Frames to compare.- #[arg(required = true, value_delimiter = ',', num_args = 1..)]- pub at: Vec<String>,- #[arg(long, default_value = "_frame_snapshots")]- pub dir: PathBuf,- /// Accept the current frames as the new snapshots.- #[arg(long)]- pub update: bool,- /// Per channel difference (0-255) that still counts as equal.- #[arg(long, default_value_t = 16)]- pub threshold: u8,- /// Fraction of pixels allowed to differ.- #[arg(long, default_value_t = 0.001)]- pub max_diff: f64,-}-#[derive(Debug, Clone, Subcommand)]pub enum AudioCommand {/// Mix the audio (or a range of it) to a stereo WAV file.@@ -579,9 +573,6 @@ impl<'r, 'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend, A: ArgCommand::Inspect(args) => {inspect(json, &mut previewer, frame_renderer, args)}- Command::Snapshot(args) => {- snapshots(json, &mut previewer, frame_renderer, args)- }Command::Audio(args) => audio(json, &previewer, args),Command::Preview(args) => {let Some(play) = player else {@@ -852,9 +843,26 @@ fn frame<'a, 'm: 'a, V: Video>(check_render_size::<V>(scale)?;previewer.set_scale(scale);+ let specs = resolve_frames(previewer, &args.at)?;+ let frames: Vec<usize> = specs.iter().map(|(_, frame)| *frame).collect();+ let mut rendered = Vec::with_capacity(frames.len());+ previewer+ .render_inspected_each(&frames, renderer, |mut pixels, report| {+ // The labels of `--ids` need the whole frame. Without them only the crop stays in+ // memory until all frames are done, which is small also at a large zoom.+ if !args.ids+ && let Some(crop) = args.crop+ {+ pixels = crop_frame::<V>(&pixels, crop);+ }+ rendered.push((pixels, report));+ Ok(())+ })+ .map_err(err)?;+let mut results = Vec::new();- for (spec, frame) in resolve_frames(previewer, &args.at)? {- let (mut pixels, report) = previewer.render_inspected(frame, renderer).map_err(err)?;+ let mut images = Vec::new();+ for ((spec, frame), (mut pixels, report)) in specs.into_iter().zip(rendered) {let elements = if args.ids {let tree = previewer.svg_tree(frame).map_err(err)?;let mut elements = element_labels::labelled_elements(&tree);@@ -878,12 +886,13 @@ fn frame<'a, 'm: 'a, V: Video>(} else {None};- if let Some(crop) = args.crop {+ if args.ids+ && let Some(crop) = args.crop+ {pixels = crop_frame::<V>(&pixels, crop);}- let name = snapshot::snapshot_name(&spec);+ let name = file_name(&spec);let path = args.output.join(format!("{name}.png"));- pixels.save_png(&path).map_err(err)?;let svg = if args.svg {let svg_path = args.output.join(format!("{name}.svg"));std::fs::write(&svg_path, previewer.svg(frame).map_err(err)?).map_err(err)?;@@ -891,6 +900,7 @@ fn frame<'a, 'm: 'a, V: Video>(} else {None};+ images.push(pixels);results.push(FrameResult {spec,path,@@ -899,6 +909,15 @@ fn frame<'a, 'm: 'a, V: Video>(report,});}+ // The PNGs encode on several threads.+ {+ use rayon::prelude::*;+ images+ .par_iter()+ .zip(&results)+ .try_for_each(|(pixels, result)| pixels.save_png(&result.path))+ .map_err(err)?;+ }print(json, &results, || {results@@ -940,28 +959,30 @@ fn render_cells<'a, 'm: 'a, V: Video>() -> CliResult<(Vec<sheet::SheetCell>, Vec<FrameReport>)> {let mut cells = Vec::new();let mut reports = Vec::new();- for &frame in frames {- let (mut pixels, report) = previewer.render_inspected(frame, renderer).map_err(err)?;- if let Some(crop) = crop {- pixels = crop_frame::<V>(&pixels, crop);- }- cells.push(sheet::SheetCell {- frame: pixels,- label: format!(- "{:.2}s f{}{}",- report.seconds,- frame,- scenes_label(&report.scenes)- ),- });- if report- .diagnostics- .iter()- .any(|d| d.severity > Severity::Info)- {- reports.push(report);- }- }+ previewer+ .render_inspected_each(frames, renderer, |mut pixels, report| {+ if let Some(crop) = crop {+ pixels = crop_frame::<V>(&pixels, crop);+ }+ cells.push(sheet::SheetCell {+ frame: pixels,+ label: format!(+ "{:.2}s f{}{}",+ report.seconds,+ report.frame,+ scenes_label(&report.scenes)+ ),+ });+ if report+ .diagnostics+ .iter()+ .any(|d| d.severity > Severity::Info)+ {+ reports.push(report);+ }+ Ok(())+ })+ .map_err(err)?;Ok((cells, reports))}@@ -1188,19 +1209,23 @@ fn scan_pops<'a, 'm: 'a, V: Video>(let mut detector = PopDetector::new(width, height);let progress = !json && std::io::stderr().is_terminal();let total = range.len();- for (i, frame) in range.clone().enumerate() {- let pixels = previewer.render(frame, renderer).map_err(err)?;- if (pixels.width, pixels.height) != (width, height) {- return Err(format!(- "the renderer returned a {}x{} frame instead of {width}x{height}",- pixels.width, pixels.height- ));- }- detector.push(pixels);- if progress && i % 30 == 0 {- eprint!("\rscanning for pops: frame {i}/{total}");- }- }+ let frames: Vec<usize> = range.clone().collect();+ previewer+ .render_each(&frames, renderer, |frame, pixels| {+ if (pixels.width, pixels.height) != (width, height) {+ return Err(FFramesRendererError::Custom(format!(+ "the renderer returned a {}x{} frame instead of {width}x{height}",+ pixels.width, pixels.height+ )));+ }+ detector.push(pixels);+ let i = frame - range.start;+ if progress && i.is_multiple_of(30) {+ eprint!("\rscanning for pops: frame {i}/{total}");+ }+ Ok(())+ })+ .map_err(err)?;if progress {eprint!("\r{}\r", " ".repeat(48));}@@ -1326,37 +1351,40 @@ fn inspect<'a, 'm: 'a, V: Video>(frames.dedup();let mut findings: Vec<Finding> = Vec::new();- for &frame in &frames {- let report = previewer.inspect(frame).map_err(err)?;- for diagnostic in report.diagnostics {- if diagnostic.severity == Severity::Info && !args.info {- continue;- }- match findings.iter_mut().find(|f| f.key == diagnostic.key) {- Some(finding) => {- finding.last_frame = frame;- finding.last_seconds = report.seconds;- finding.frames += 1;- for scene in &report.scenes {- if !finding.scenes.contains(scene) {- finding.scenes.push(scene.clone());+ previewer+ .inspect_each(&frames, |report| {+ let frame = report.frame;+ for diagnostic in report.diagnostics {+ if diagnostic.severity == Severity::Info && !args.info {+ continue;+ }+ match findings.iter_mut().find(|f| f.key == diagnostic.key) {+ Some(finding) => {+ finding.last_frame = frame;+ finding.last_seconds = report.seconds;+ finding.frames += 1;+ for scene in &report.scenes {+ if !finding.scenes.contains(scene) {+ finding.scenes.push(scene.clone());+ }}}+ None => findings.push(Finding {+ severity: diagnostic.severity,+ key: diagnostic.key,+ message: diagnostic.message,+ first_frame: frame,+ last_frame: frame,+ first_seconds: report.seconds,+ last_seconds: report.seconds,+ frames: 1,+ scenes: report.scenes.clone(),+ }),}- None => findings.push(Finding {- severity: diagnostic.severity,- key: diagnostic.key,- message: diagnostic.message,- first_frame: frame,- last_frame: frame,- first_seconds: report.seconds,- last_seconds: report.seconds,- frames: 1,- scenes: report.scenes.clone(),- }),}- }- }+ Ok(())+ })+ .map_err(err)?;let pop_scanned_frames = if args.pops {findings.extend(scan_pops(json, previewer, renderer, range.clone())?);Some(range.len())@@ -1415,52 +1443,6 @@ fn inspect<'a, 'm: 'a, V: Video>(})}-fn snapshots<'a, 'm: 'a, V: Video>(- json: bool,- previewer: &mut Previewer<'a, 'm, V>,- renderer: &mut dyn FrameRenderer,- args: SnapshotArgs,-) -> CliResult {- let options = snapshot::SnapshotOptions {- directory: args.dir,- channel_threshold: args.threshold,- max_diff_ratio: args.max_diff,- update: args.update || snapshot::SnapshotOptions::default().update,- };- let mut results = Vec::new();- for spec in args.at.iter().flat_map(|s| s.split_whitespace()) {- results.push(snapshot::check_frame(previewer, renderer, spec, &options).map_err(err)?);- }- let failed = results- .iter()- .any(|r| r.status == snapshot::SnapshotStatus::Failed);-- print(json, &results, || {- results- .iter()- .map(|r| {- let mut line = format!("{:?} {} (frame {})", r.status, r.spec, r.frame);- if r.status == snapshot::SnapshotStatus::Failed {- let _ = write!(- line,- ": {:.3}% of pixels differ, actual {}, diff {}",- r.diff_ratio * 100.,- r.actual.as_deref().unwrap_or(Path::new("-")).display(),- r.diff.as_deref().unwrap_or(Path::new("-")).display()- );- }- line- })- .collect::<Vec<_>>()- .join("\n")- });- Ok(if failed {- ExitCode::from(2)- } else {- ExitCode::SUCCESS- })-}-/// One time of `audio at`.#[derive(Serialize)]struct AudioAt {@@ -1825,6 +1807,13 @@ fn waveform_image<'a, 'm: 'a, V: Video>(mod tests {use super::*;+ #[test]+ fn file_names_are_safe() {+ assert_eq!(file_name("[email protected]"), "intro_1.5s");+ assert_eq!(file_name("50%"), "50p");+ assert_eq!(file_name("#3"), "3");+ }+#[test]fn spread_includes_both_ends() {assert_eq!(spread(0..101, 5), vec![0, 25, 50, 75, 100]);diff --git a/fframes/src/renderer/mod.rs b/fframes/src/renderer/mod.rsindex 5acd0c95..3d2b24ad 100644--- a/fframes/src/renderer/mod.rs+++ b/fframes/src/renderer/mod.rs@@ -49,7 +49,6 @@ pub mod continuity;pub mod element_labels;#[cfg(feature = "cpu_renderer")]pub mod sheet;-pub mod snapshot;#[cfg(feature = "cli")]pub mod cli;diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rsindex 3a1d2562..fd1f5634 100644--- a/fframes/src/renderer/preview.rs+++ b/fframes/src/renderer/preview.rs@@ -292,10 +292,8 @@ pub struct Previewer<'a, 'media, TVideo: Video> {image_source: HashMap<String, Arc<usvgr::PreloadedImageData>>,size: VideoSize,timeline_index: TimelineIndex,- converter_cache: usvgr::Cache,+ worker: Worker,converter_text_cache_capacity: usize,- text_cache: Option<TextCache>,- decoders: VideoDecodersWorker,}impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {@@ -336,10 +334,8 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {runtime,image_source,timeline_index,- converter_cache: usvgr::Cache::new_with_text_cache(10),+ worker: Worker::new(10),converter_text_cache_capacity: 10,- text_cache: TextCache::new(10),- decoders: VideoDecodersWorker::new(2),})}@@ -418,16 +414,6 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {self.size = VideoSize::new_scaled(TVideo::WIDTH, TVideo::HEIGHT, scale);}- fn check_frame(&self, frame: usize) -> FFramesRendererResult<()> {- if frame >= self.timeline_index.duration_in_frames {- return Err(FFramesRendererError::Custom(format!(- "frame {frame} is outside the video (0..{})",- self.timeline_index.duration_in_frames- )));- }- Ok(())- }-/// Calls `Video::render_frame` and converts the result.pub fn svg_tree(&mut self, frame: usize) -> FFramesRendererResult<usvgr::Tree> {self.convert_frame(frame, false)@@ -439,43 +425,78 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {frame: usize,fast_shapes: bool,) -> FFramesRendererResult<usvgr::Tree> {- self.check_frame(frame)?;-- let ctx = FFramesContext {- time_base: self.runtime.time_base,- mode: crate::FFramesMode::Renderer,- media_source: self.options.media,- duration_in_frames: self.runtime.timeline.duration_in_frames,- scenes: self.runtime.timeline.scenes.as_ref(),- font_source: Some(&self.runtime.font_source),- abort_signal: None,- current_video_size: self.size.clone(),- };-- let svgr = super::render_frame_guarded(+ Conversion::new(self.video,- Frame::__internal_make_for_renderer(- frame,- frame,- TVideo::FPS,- self.text_cache.clone(),- self.decoders.clone(),- ),- &ctx,- )?;-- let usvg_options = usvgr::Options {- image_data: Some(&self.image_source),- font_family: self.options.default_font.to_string(),+ &self.runtime,+ &self.options,+ &self.image_source,+ &self.size,fast_shapes,- ..Default::default()+ )+ .convert(&mut self.worker, frame)+ }++ /// Converts `frames` and calls `each` with what `keep` keeps of every tree and the+ /// problems found in it, in the order of `frames`. Stops at the first error of `each`.+ ///+ /// With more than one thread, the threads call `Video::render_frame` and convert the+ /// frames while `each` works on this thread, see [`Schedule`].+ fn convert_each<T: Send>(+ &mut self,+ frames: &[usize],+ batch: Batch,+ keep: impl Fn(usvgr::Tree) -> T + Sync,+ mut each: impl FnMut(+ usize,+ FFramesRendererResult<T>,+ Vec<Diagnostic>,+ ) -> FFramesRendererResult<()>,+ ) -> FFramesRendererResult<()> {+ let conversion = Conversion::new(+ self.video,+ &self.runtime,+ &self.options,+ &self.image_source,+ &self.size,+ batch.fast_shapes,+ );+ let convert = |worker: &mut Worker, frame: usize| {+ if !batch.inspect {+ return (conversion.convert(worker, frame).map(&keep), Vec::new());+ }+ let (tree, mut found) = diagnostics::collect(|| conversion.convert(worker, frame));+ if let Ok(tree) = &tree {+ found.extend(diagnostics::inspect_tree(+ tree,+ tree.size().width(),+ tree.size().height(),+ ));+ }+ (tree.map(&keep), found)};- Ok(svgr.into_svg_tree(- &usvg_options,- &mut self.converter_cache,- self.runtime.font_source.as_db_ref(),- )?)+ let threads = batch.threads.min(frames.len());+ if threads <= 1 {+ for &frame in frames {+ let (kept, found) = convert(&mut self.worker, frame);+ each(frame, kept, found)?;+ }+ return Ok(());+ }+ let (run, window) = match batch.schedule {+ Schedule::Ahead => (1, threads * AHEAD_PER_THREAD),+ Schedule::Parts => (frames.len().div_ceil(threads), frames.len()),+ };+ let capacity = self.converter_text_cache_capacity;+ in_order(+ frames.len(),+ threads,+ run,+ window,+ || Worker::new(capacity),+ |worker, index| convert(worker, frames[index]),+ |index, (kept, found)| each(frames[index], kept, found),+ )}/// The frame as an SVG document, as the renderer sees it after conversion (text is@@ -502,7 +523,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {if let Some(capacity) = renderer.svg_text_cache_capacity()&& capacity != self.converter_text_cache_capacity{- self.converter_cache = usvgr::Cache::new_with_text_cache(capacity);+ self.worker.converter_cache = usvgr::Cache::new_with_text_cache(capacity);self.converter_text_cache_capacity = capacity;}}@@ -513,53 +534,679 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {frame: usize,renderer: &mut dyn FrameRenderer,) -> FFramesRendererResult<(RgbaFrame, FrameReport)> {- self.check_frame(frame)?;+ let mut rendered = None;+ self.render_inspected_on(&[frame], renderer, 1, |pixels, report| {+ rendered = Some((pixels, report));+ Ok(())+ })?;+ Ok(rendered.expect("the frame is rendered or an error is returned"))+ }++ /// [`Self::render`] for several frames: `each` gets the pixels in the order of `frames`.+ /// Stops at the first error.+ ///+ /// Several threads call `Video::render_frame` and convert the next frames while+ /// `renderer` draws on this thread: a quarter of [`super::get_thread_count`]+ /// (`FFRAMES_NUM_THREADS`), at most four. With fewer than eight, the frames convert on+ /// this thread.+ pub fn render_each(+ &mut self,+ frames: &[usize],+ renderer: &mut dyn FrameRenderer,+ mut each: impl FnMut(usize, RgbaFrame) -> FFramesRendererResult<()>,+ ) -> FFramesRendererResult<()> {self.configure_renderer_cache(renderer);let (width, height) = self.size();- let fast_shapes = renderer.fast_shapes();- let (tree, mut found) = diagnostics::collect(|| self.convert_frame(frame, fast_shapes));- let tree = tree?;- found.extend(diagnostics::inspect_tree(- &tree,- tree.size().width(),- tree.size().height(),- ));- let pixels = renderer.render_tree(&tree, TVideo::BACKGROUND_COLOR, width, height)?;+ let batch = Batch {+ fast_shapes: renderer.fast_shapes(),+ inspect: false,+ threads: convert_threads(),+ schedule: Schedule::Ahead,+ };+ self.convert_each(+ frames,+ batch,+ |tree| tree,+ |frame, tree, _| {+ let pixels =+ renderer.render_tree(&tree?, TVideo::BACKGROUND_COLOR, width, height)?;+ each(frame, pixels)+ },+ )+ }- Ok((pixels, self.report(frame, found)))+ /// [`Self::render_inspected`] for several frames, on several threads like+ /// [`Self::render_each`]. `each` gets the frames in the order of `frames`.+ pub fn render_inspected_each(+ &mut self,+ frames: &[usize],+ renderer: &mut dyn FrameRenderer,+ each: impl FnMut(RgbaFrame, FrameReport) -> FFramesRendererResult<()>,+ ) -> FFramesRendererResult<()> {+ self.render_inspected_on(frames, renderer, convert_threads(), each)}- fn report(&self, frame: usize, found: Vec<Diagnostic>) -> FrameReport {- FrameReport {- frame,- seconds: self.timeline_index.frame_to_seconds(frame),- scenes: self- .timeline_index- .scenes_at(frame)- .map(|s| s.name.clone())- .collect(),- diagnostics: found.into_iter().map(ReportedDiagnostic::from).collect(),- }+ fn render_inspected_on(+ &mut self,+ frames: &[usize],+ renderer: &mut dyn FrameRenderer,+ threads: usize,+ mut each: impl FnMut(RgbaFrame, FrameReport) -> FFramesRendererResult<()>,+ ) -> FFramesRendererResult<()> {+ self.configure_renderer_cache(renderer);+ let (width, height) = self.size();+ let batch = Batch {+ fast_shapes: renderer.fast_shapes(),+ inspect: true,+ threads,+ schedule: Schedule::Ahead,+ };+ let index = self.timeline_index.clone();+ self.convert_each(+ frames,+ batch,+ |tree| tree,+ |frame, tree, found| {+ let pixels =+ renderer.render_tree(&tree?, TVideo::BACKGROUND_COLOR, width, height)?;+ each(pixels, report(&index, frame, found))+ },+ )}/// Converts a frame and reports problems in it (missing media or fonts, clipped text,/// panics) without rasterizing it.pub fn inspect(&mut self, frame: usize) -> FFramesRendererResult<FrameReport> {- self.check_frame(frame)?;- let (tree, mut found) = diagnostics::collect(|| self.svg_tree(frame));+ let mut inspected = None;+ self.inspect_on(&[frame], 1, |report| {+ inspected = Some(report);+ Ok(())+ })?;+ Ok(inspected.expect("the frame is inspected or an error is returned"))+ }++ /// [`Self::inspect`] for several frames, on several threads like [`Self::render_each`].+ /// `each` gets the reports in the order of `frames`.+ pub fn inspect_each(+ &mut self,+ frames: &[usize],+ each: impl FnMut(FrameReport) -> FFramesRendererResult<()>,+ ) -> FFramesRendererResult<()> {+ self.inspect_on(frames, convert_threads(), each)+ }++ fn inspect_on(+ &mut self,+ frames: &[usize],+ threads: usize,+ mut each: impl FnMut(FrameReport) -> FFramesRendererResult<()>,+ ) -> FFramesRendererResult<()> {+ let batch = Batch {+ fast_shapes: false,+ inspect: true,+ threads,+ schedule: Schedule::Parts,+ };+ let index = self.timeline_index.clone();+ // Only the problems are needed, so the trees are dropped on the threads.+ self.convert_each(frames, batch, drop, |frame, tree, found| {+ match tree {+ // The panic is already reported as a diagnostic.+ Ok(()) | Err(FFramesRendererError::FramePanicked(_)) => {}+ Err(err) => return Err(err),+ }+ each(report(&index, frame, found))+ })+ }+}++fn report(index: &TimelineIndex, frame: usize, found: Vec<Diagnostic>) -> FrameReport {+ FrameReport {+ frame,+ seconds: index.frame_to_seconds(frame),+ scenes: index.scenes_at(frame).map(|s| s.name.clone()).collect(),+ diagnostics: found.into_iter().map(ReportedDiagnostic::from).collect(),+ }+}++/// The caches of a thread that converts frames.+struct Worker {+ text_cache: Option<TextCache>,+ decoders: VideoDecodersWorker,+ converter_cache: usvgr::Cache,+}++impl Worker {+ fn new(converter_text_cache_capacity: usize) -> Self {+ Self {+ text_cache: TextCache::new(10),+ decoders: VideoDecodersWorker::new(2),+ converter_cache: usvgr::Cache::new_with_text_cache(converter_text_cache_capacity),+ }+ }+}++/// What converting a frame needs besides the caches. The threads that convert frames share it.+struct Conversion<'p, 'media, TVideo> {+ video: &'p TVideo,+ ctx: FFramesContext<'p, 'media>,+ options: usvgr::Options<'p>,+ font_db: &'p usvgr::fontdb::Database,+}++impl<'p, 'media: 'p, TVideo: Video> Conversion<'p, 'media, TVideo> {+ fn new(+ video: &'p TVideo,+ runtime: &'p FFramesRendererRuntime<'_>,+ options: &RenderOptions<'_, 'media>,+ image_source: &'p HashMap<String, Arc<usvgr::PreloadedImageData>>,+ size: &VideoSize,+ fast_shapes: bool,+ ) -> Self {+ Self {+ video,+ ctx: FFramesContext {+ time_base: runtime.time_base,+ mode: crate::FFramesMode::Renderer,+ media_source: options.media,+ duration_in_frames: runtime.timeline.duration_in_frames,+ scenes: runtime.timeline.scenes.as_ref(),+ font_source: Some(&runtime.font_source),+ abort_signal: None,+ current_video_size: size.clone(),+ },+ options: usvgr::Options {+ image_data: Some(image_source),+ font_family: options.default_font.to_string(),+ fast_shapes,+ ..Default::default()+ },+ font_db: runtime.font_source.as_db_ref(),+ }+ }++ /// Calls `Video::render_frame` for `frame` and converts the result.+ fn convert(&self, worker: &mut Worker, frame: usize) -> FFramesRendererResult<usvgr::Tree> {+ if frame >= self.ctx.duration_in_frames {+ return Err(FFramesRendererError::Custom(format!(+ "frame {frame} is outside the video (0..{})",+ self.ctx.duration_in_frames+ )));+ }+ let svgr = super::render_frame_guarded(+ self.video,+ Frame::__internal_make_for_renderer(+ frame,+ frame,+ TVideo::FPS,+ worker.text_cache.clone(),+ worker.decoders.clone(),+ ),+ &self.ctx,+ )?;+ Ok(svgr.into_svg_tree(&self.options, &mut worker.converter_cache, self.font_db)?)+ }+}++/// How [`Previewer::convert_each`] converts frames.+#[derive(Clone, Copy)]+struct Batch {+ /// See [`FrameRenderer::fast_shapes`].+ fast_shapes: bool,+ /// Report the problems found while converting and those of [`diagnostics::inspect_tree`].+ inspect: bool,+ threads: usize,+ schedule: Schedule,+}- match tree {- Ok(tree) => found.extend(diagnostics::inspect_tree(- &tree,- tree.size().width(),- tree.size().height(),- )),- // The panic is already reported as a diagnostic.- Err(FFramesRendererError::FramePanicked(_)) => {}- Err(err) => return Err(err),+/// How the threads of [`Previewer::convert_each`] share the frames.+#[derive(Clone, Copy)]+enum Schedule {+ /// A thread converts the next frame, at most [`AHEAD_PER_THREAD`] frames for each thread+ /// ahead of the frame that `each` needs next. The trees wait in memory until then.+ Ahead,+ /// Each thread converts one contiguous part of the frames. So the video decoders of a+ /// thread read forward, instead of decoding the frames of the other threads too. All+ /// results can wait until `each` gets them, so they must be small.+ Parts,+}++/// How many frames each thread of [`Schedule::Ahead`] may convert ahead of the frame that+/// the renderer needs next.+const AHEAD_PER_THREAD: usize = 2;++/// The threads that convert frames for [`Previewer::render_each`] and the other methods for+/// several frames: a quarter of [`super::get_thread_count`], from one to four.+///+/// The renderer draws one frame at a time, and two to four threads keep it busy. More+/// threads only decode the video sources again: each thread has its own decoders, and with+/// [`Schedule::Ahead`] they decode the frames of the other threads too.+fn convert_threads() -> usize {+ (super::get_thread_count() / 4).clamp(1, 4)+}++/// Runs `work` for the items `0..count` on `threads` new threads and calls `done` on this+/// thread with the results in the order of the items. A thread takes `run` items that follow+/// each other at a time. It takes them only when `done` got all items but the last `window`+/// before them, so at most `window + run - 1` results wait in memory. `worker` makes the+/// state of a thread on that thread. Stops at the first error of `done` and returns it.+fn in_order<W, R: Send, E>(+ count: usize,+ threads: usize,+ run: usize,+ window: usize,+ worker: impl Fn() -> W + Sync,+ work: impl Fn(&mut W, usize) -> R + Sync,+ mut done: impl FnMut(usize, R) -> Result<(), E>,+) -> Result<(), E> {+ use std::sync::{Condvar, Mutex, MutexGuard, PoisonError, mpsc};++ struct Progress {+ /// The next item that a thread starts.+ next: usize,+ /// The number of items that `done` got.+ done: usize,+ stop: bool,+ }++ struct Shared {+ progress: Mutex<Progress>,+ moved: Condvar,+ }++ impl Shared {+ fn lock(&self) -> MutexGuard<'_, Progress> {+ self.progress.lock().unwrap_or_else(PoisonError::into_inner)+ }++ fn stop(&self) {+ self.lock().stop = true;+ self.moved.notify_all();+ }+ }++ /// Stops all threads when the thread that holds it panics, so that no thread waits for+ /// an item that never comes. The scope then panics too.+ struct StopOnPanic<'s>(&'s Shared);++ impl Drop for StopOnPanic<'_> {+ fn drop(&mut self) {+ if std::thread::panicking() {+ self.0.stop();+ }+ }+ }++ let (run, window) = (run.max(1), window.max(1));+ let shared = Shared {+ progress: Mutex::new(Progress {+ next: 0,+ done: 0,+ stop: false,+ }),+ moved: Condvar::new(),+ };+ let (sender, receiver) = mpsc::channel();+ std::thread::scope(|scope| {+ let _stop = StopOnPanic(&shared);+ for _ in 0..threads.max(1) {+ let sender = sender.clone();+ let (shared, worker, work) = (&shared, &worker, &work);+ scope.spawn(move || {+ let _stop = StopOnPanic(shared);+ let mut state = worker();+ 'runs: loop {+ let items = {+ let mut progress = shared.lock();+ while !progress.stop+ && progress.next < count+ && progress.next >= progress.done + window+ {+ progress = shared+ .moved+ .wait(progress)+ .unwrap_or_else(PoisonError::into_inner);+ }+ if progress.stop || progress.next >= count {+ break;+ }+ let start = progress.next;+ progress.next = (start + run).min(count);+ start..progress.next+ };+ for index in items {+ if shared.lock().stop+ || sender.send((index, work(&mut state, index))).is_err()+ {+ break 'runs;+ }+ }+ }+ });+ }+ drop(sender);++ // The results arrive in any order and wait until `done` got the items before them.+ let mut waiting: HashMap<usize, R> = HashMap::new();+ let mut next = 0;+ for (index, result) in &receiver {+ waiting.insert(index, result);+ while let Some(result) = waiting.remove(&next) {+ if let Err(err) = done(next, result) {+ shared.stop();+ return Err(err);+ }+ next += 1;+ shared.lock().done = next;+ shared.moved.notify_all();+ }+ }+ Ok(())+ })+}++#[cfg(test)]+mod batch_tests {+ use super::*;+ use crate::{AudioMap, Duration, Svgr};+ use std::sync::Mutex;+ use std::sync::atomic::{AtomicUsize, Ordering};++ /// Frames that differ, with a text in a missing font, a missing image from frame 20 and+ /// a panic at `panic_at`.+ struct Changing {+ panic_at: Option<usize>,+ }++ impl Video for Changing {+ const FPS: usize = 10;+ const WIDTH: usize = 64;+ const HEIGHT: usize = 32;++ fn duration(&self) -> Duration<'_> {+ Duration::Frames(24)+ }++ fn audio(&self) -> AudioMap<'_> {+ AudioMap::none()+ }++ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ assert!(Some(frame.index) != self.panic_at, "boom");+ if frame.index >= 20 {+ let _ = ctx.get_image("missing.png");+ }+ let width = frame.index * 2 + 1;+ crate::svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="32">+ <rect x="0" y="4" width={width} height="20" fill="#ff8800" />+ <text x="2" y="30" font-family="No Such Font" font-size="8">"fframes"</text>+ </svg>+ )+ }+ }++ /// Out of order, with a repeated frame.+ const FRAMES: [usize; 9] = [23, 5, 0, 12, 12, 19, 20, 3, 8];++ /// The frames, with their reports without the missing font warnings.+ type Rendered = (Vec<(RgbaFrame, (String, bool))>, Option<String>);++ /// A report without its missing font warnings, and whether it had one. The converter+ /// warns about a font when it lays out a text. With `compile-time-svgtree` it lays out+ /// the same text once per cache, and each thread has its own cache.+ fn without_fonts(mut report: FrameReport) -> (String, bool) {+ let all = report.diagnostics.len();+ report+ .diagnostics+ .retain(|d| !matches!(d.diagnostic, Diagnostic::MissingFont { .. }));+ let font = report.diagnostics.len() != all;+ (format!("{report:?}"), font)+ }++ /// Without the cache the threads warn about the font where one previewer does. With it+ /// the first frame warns, and the threads warn at least where one previewer does.+ fn assert_fonts(expected: &[bool], actual: &[bool]) {+ assert_eq!(actual.len(), expected.len());+ if cfg!(feature = "compile-time-svgtree") {+ assert!(expected[0] && actual[0]);+ assert!(+ expected+ .iter()+ .zip(actual)+ .all(|(&one, &threads)| !one || threads)+ );+ } else {+ assert_eq!(actual, expected);+ }+ }++ fn one_by_one(video: &Changing, frames: &[usize]) -> Rendered {+ let mut previewer = Previewer::new(video, &RenderOptions::default()).unwrap();+ let mut renderer = CpuFrameRenderer::default();+ let mut rendered = Vec::new();+ for &frame in frames {+ match previewer.render_inspected(frame, &mut renderer) {+ Ok((pixels, report)) => rendered.push((pixels, without_fonts(report))),+ Err(err) => return (rendered, Some(err.to_string())),+ }+ }+ (rendered, None)+ }++ fn batch(video: &Changing, frames: &[usize]) -> Rendered {+ let mut previewer = Previewer::new(video, &RenderOptions::default()).unwrap();+ let mut rendered = Vec::new();+ let result = previewer.render_inspected_on(+ frames,+ &mut CpuFrameRenderer::default(),+ 4,+ |pixels, report| {+ rendered.push((pixels, without_fonts(report)));+ Ok(())+ },+ );+ (rendered, result.err().map(|err| err.to_string()))+ }++ fn assert_same((expected, expected_err): Rendered, (actual, actual_err): Rendered) {+ assert_eq!(actual.len(), expected.len());+ for ((pixels, (report, _)), (expected_pixels, (expected_report, _))) in+ actual.iter().zip(&expected)+ {+ assert_eq!(report, expected_report);+ assert_eq!(pixels.pixels, expected_pixels.pixels, "{report}");+ }+ let fonts = |rendered: &[(RgbaFrame, (String, bool))]| {+ rendered+ .iter()+ .map(|(_, (_, font))| *font)+ .collect::<Vec<_>>()+ };+ assert_fonts(&fonts(&expected), &fonts(&actual));+ assert_eq!(actual_err, expected_err);+ }++ #[test]+ fn several_threads_render_and_report_like_one_by_one() {+ let video = Changing { panic_at: None };+ let expected = one_by_one(&video, &FRAMES);+ assert_eq!(expected.0.len(), FRAMES.len());+ assert!(expected.0[0].1.0.contains("MissingMedia"));+ // A warning of the converter, which goes through the logger of the thread.+ assert!(expected.0[0].1.1);+ assert_same(expected, batch(&video, &FRAMES));++ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();+ let mut renderer = CpuFrameRenderer::default();+ let mut rendered = Vec::new();+ previewer+ .render_each(&FRAMES, &mut renderer, |frame, pixels| {+ rendered.push((frame, pixels.pixels));+ Ok(())+ })+ .unwrap();+ for (&frame, (rendered_frame, pixels)) in FRAMES.iter().zip(rendered) {+ assert_eq!(rendered_frame, frame);+ assert_eq!(+ pixels,+ previewer.render(frame, &mut renderer).unwrap().pixels+ );+ }+ }++ #[test]+ fn several_threads_stop_at_the_first_error_like_one_by_one() {+ let video = Changing { panic_at: Some(12) };+ let expected = one_by_one(&video, &FRAMES);+ assert_eq!(expected.0.len(), 3);+ assert!(expected.1.as_ref().unwrap().contains("boom"));+ assert_same(expected, batch(&video, &FRAMES));++ let outside = [1, 2, 99, 3];+ let expected = one_by_one(&video, &outside);+ assert_eq!(expected.0.len(), 2);+ assert_same(expected, batch(&video, &outside));+ }++ #[test]+ fn several_threads_inspect_like_one_by_one() {+ let video = Changing { panic_at: Some(12) };+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();+ let (expected, expected_fonts): (Vec<String>, Vec<bool>) = FRAMES+ .iter()+ .map(|&frame| without_fonts(previewer.inspect(frame).unwrap()))+ .unzip();+ assert!(expected[3].contains("Panic"));++ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();+ let mut reports = Vec::new();+ previewer+ .inspect_on(&FRAMES, 4, |report| {+ reports.push(without_fonts(report));+ Ok(())+ })+ .unwrap();+ let (reports, fonts): (Vec<String>, Vec<bool>) = reports.into_iter().unzip();+ assert_eq!(reports, expected);+ assert_fonts(&expected_fonts, &fonts);+ }++ #[test]+ fn results_come_in_order_and_at_most_a_window_ahead() {+ let done = AtomicUsize::new(0);+ let ahead = AtomicUsize::new(0);+ let mut next = 0;+ in_order(+ 300,+ 6,+ 1,+ 8,+ || (),+ |(), index| {+ // `done` is at most the count of `in_order`, so this is at most how far ahead+ // the item started.+ ahead.fetch_max(index + 1 - done.load(Ordering::SeqCst), Ordering::SeqCst);+ std::thread::sleep(std::time::Duration::from_micros((index % 7) as u64 * 30));+ index * 2+ },+ |index, result| {+ assert_eq!((index, result), (next, next * 2));+ next += 1;+ std::thread::sleep(std::time::Duration::from_micros(100));+ done.store(next, Ordering::SeqCst);+ Ok::<_, ()>(())+ },+ )+ .unwrap();+ assert_eq!(next, 300);+ let ahead = ahead.load(Ordering::SeqCst);+ assert!((2..=8).contains(&ahead), "{ahead} items ahead");+ }++ #[test]+ fn runs_of_items_come_in_order() {+ let threads = Mutex::new(vec![None; 100]);+ let mut next = 0;+ in_order(+ 100,+ 4,+ 25,+ 100,+ || (),+ |(), index| {+ threads.lock().unwrap()[index] = Some(std::thread::current().id());+ index+ },+ |index, result| {+ assert_eq!((index, result), (next, next));+ next += 1;+ Ok::<_, ()>(())+ },+ )+ .unwrap();+ assert_eq!(next, 100);+ // Each thread converted one part that follows each other.+ let threads = threads.into_inner().unwrap();+ for part in threads.chunks(25) {+ assert!(part.iter().all(|thread| *thread == part[0]));}+ }- Ok(self.report(frame, found))+ #[test]+ fn an_error_stops_the_threads() {+ let started = Mutex::new(Vec::new());+ let mut delivered = Vec::new();+ let result = in_order(+ 100,+ 4,+ 1,+ 8,+ || (),+ |(), index| started.lock().unwrap().push(index),+ |index, ()| {+ if index == 10 {+ return Err(index);+ }+ delivered.push(index);+ Ok(())+ },+ );+ assert_eq!(result, Err(10));+ assert_eq!(delivered, (0..10).collect::<Vec<_>>());+ let started = started.into_inner().unwrap();+ assert!(started.iter().all(|&index| index < 11 + 8), "{started:?}");+ }++ #[test]+ #[should_panic(expected = "a scoped thread panicked")]+ fn a_panic_of_a_thread_does_not_hang() {+ let _ = in_order(+ 100,+ 4,+ 1,+ 2,+ || (),+ |(), index| assert!(index != 7, "boom"),+ |_, ()| Ok::<_, ()>(()),+ );+ }++ #[test]+ #[should_panic(expected = "done panics")]+ fn a_panic_of_done_does_not_hang() {+ let _ = in_order(+ 100,+ 4,+ 1,+ 2,+ || (),+ |(), _| std::thread::sleep(std::time::Duration::from_millis(1)),+ |index, ()| {+ assert!(index != 3, "done panics");+ Ok::<_, ()>(())+ },+ );}}@@ -610,16 +1257,16 @@ mod cache_tests {preview.configure_renderer_cache(&Renderer(Some(100_000)));assert_eq!(preview.converter_text_cache_capacity, 100_000);// A value carried by the converter must survive another frame's configuration.- preview.converter_cache.paint.insert(+ preview.worker.converter_cache.paint.insert("warm".into(),usvgr::Paint::Color(usvgr::Color::new_rgb(1, 2, 3)),);preview.configure_renderer_cache(&Renderer(Some(100_000)));- assert!(preview.converter_cache.paint.contains_key("warm"));+ assert!(preview.worker.converter_cache.paint.contains_key("warm"));preview.configure_renderer_cache(&Renderer(None));assert_eq!(preview.converter_text_cache_capacity, 100_000);preview.configure_renderer_cache(&Renderer(Some(0)));assert_eq!(preview.converter_text_cache_capacity, 0);- assert!(preview.converter_cache.usvgr_text_cache.is_none());+ assert!(preview.worker.converter_cache.usvgr_text_cache.is_none());}}diff --git a/fframes/src/renderer/render_backend.rs b/fframes/src/renderer/render_backend.rsindex 812c99d0..8a7ee068 100644--- a/fframes/src/renderer/render_backend.rs+++ b/fframes/src/renderer/render_backend.rs@@ -18,8 +18,8 @@ pub trait FFramesRenderBackend {false}- /// Renders single frames (`fframes::Previewer`, the CLI's `frame`, `strip`, `onion` and- /// `snapshot`) the way this backend renders the video, so previews match the output.+ /// Renders single frames (`fframes::Previewer`, the CLI's `frame`, `strip` and `onion`)+ /// the way this backend renders the video, so previews match the output./// `None` uses the built-in CPU renderer.fn frame_renderer(&self) -> Option<impl super::FrameRenderer + '_> {None::<std::convert::Infallible>diff --git a/fframes/src/renderer/snapshot.rs b/fframes/src/renderer/snapshot.rsdeleted file mode 100644index fda20654..00000000--- a/fframes/src/renderer/snapshot.rs+++ /dev/null@@ -1,275 +0,0 @@-//! Visual regression of individual frames: render frames addressed by time specs, compare-//! them with approved PNGs and write the actual frame and a diff image when they differ.-//!-//! ```ignore-//! #[test]-//! fn intro_looks_right() {-//! let video = MyVideo::new();-//! let mut previewer = fframes::Previewer::new(&video, &options).unwrap();-//! fframes::snapshot::assert_frames(-//! &mut previewer,-//! &mut fframes::CpuFrameRenderer::default(),-//! &["[email protected]", "Intro@end", "50%"],-//! &fframes::snapshot::SnapshotOptions::default(),-//! );-//! }-//! ```-//!-//! Missing snapshots are written on the first run. Set `FFRAMES_UPDATE_SNAPSHOTS=1` to accept-//! changed frames.-use super::{FFramesRendererError, FFramesRendererResult, FrameRenderer, Previewer, RgbaFrame};-use crate::Video;-use serde::Serialize;-use std::path::{Path, PathBuf};--#[derive(Debug, Clone)]-pub struct SnapshotOptions {- pub directory: PathBuf,- /// A pixel differs when any channel differs by more than this (0-255). Absorbs- /// anti-aliasing differences between machines.- pub channel_threshold: u8,- /// The snapshot fails when more than this fraction of pixels differ.- pub max_diff_ratio: f64,- /// Overwrite snapshots that differ. Defaults to `FFRAMES_UPDATE_SNAPSHOTS` being set.- pub update: bool,-}--impl Default for SnapshotOptions {- fn default() -> Self {- Self {- directory: PathBuf::from("_frame_snapshots"),- channel_threshold: 16,- max_diff_ratio: 0.001,- update: std::env::var("FFRAMES_UPDATE_SNAPSHOTS")- .is_ok_and(|v| v != "0" && !v.is_empty()),- }- }-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]-#[serde(rename_all = "snake_case")]-pub enum SnapshotStatus {- Matched,- Created,- Updated,- Failed,-}--#[derive(Debug, Clone, Serialize)]-pub struct SnapshotResult {- pub spec: String,- pub frame: usize,- pub status: SnapshotStatus,- pub snapshot: PathBuf,- /// Fraction of differing pixels (0 when created).- pub diff_ratio: f64,- /// Written when the frame differs.- pub actual: Option<PathBuf>,- pub diff: Option<PathBuf>,-}--/// `[email protected]` -> `intro_1.5s`-pub fn snapshot_name(spec: &str) -> String {- let name: String = spec- .chars()- .map(|c| match c {- 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' | '-' => c.to_ascii_lowercase(),- '%' => 'p',- _ => '_',- })- .collect();- name.trim_matches('_').to_owned()-}--/// Compares two frames. Returns the fraction of differing pixels and a diff image (the-/// expected frame dimmed, differing pixels red), or `None` for the image when sizes differ.-pub fn diff_frames(- expected: &RgbaFrame,- actual: &RgbaFrame,- channel_threshold: u8,-) -> (f64, Option<RgbaFrame>) {- if expected.width != actual.width || expected.height != actual.height {- return (1., None);- }-- let mut differing = 0usize;- let mut diff = Vec::with_capacity(expected.pixels.len());- for (e, a) in expected- .pixels- .as_chunks::<4>()- .0- .iter()- .zip(actual.pixels.as_chunks::<4>().0)- {- let differs = e- .iter()- .zip(a)- .any(|(e, a)| e.abs_diff(*a) > channel_threshold);- if differs {- differing += 1;- diff.extend_from_slice(&[255, 0, 0, 255]);- } else {- let gray = ((u32::from(e[0]) + u32::from(e[1]) + u32::from(e[2])) / 3 / 4) as u8;- diff.extend_from_slice(&[gray, gray, gray, 255]);- }- }-- let total = f64::from((expected.width * expected.height).max(1));- (- differing as f64 / total,- Some(RgbaFrame {- width: expected.width,- height: expected.height,- pixels: diff,- }),- )-}--fn load_png(path: &Path) -> FFramesRendererResult<RgbaFrame> {- let image = image::open(path)- .map_err(|err| FFramesRendererError::ImageError((path.display().to_string(), err)))?- .into_rgba8();- Ok(RgbaFrame {- width: image.width(),- height: image.height(),- pixels: image.into_raw(),- })-}--/// Renders the frame at `spec` and compares it with its snapshot.-pub fn check_frame<'a, 'media: 'a, TVideo: Video>(- previewer: &mut Previewer<'a, 'media, TVideo>,- renderer: &mut dyn FrameRenderer,- spec: &str,- options: &SnapshotOptions,-) -> FFramesRendererResult<SnapshotResult> {- let frame = previewer- .timeline()- .resolve_frame(spec)- .map_err(|err| FFramesRendererError::Custom(err.to_string()))?;- let actual = previewer.render(frame, renderer)?;-- std::fs::create_dir_all(&options.directory)?;- let name = snapshot_name(spec);- let snapshot = options.directory.join(format!("{name}.png"));- let actual_path = options.directory.join(format!("{name}.actual.png"));- let diff_path = options.directory.join(format!("{name}.diff.png"));- let _ = std::fs::remove_file(&actual_path);- let _ = std::fs::remove_file(&diff_path);-- let mut result = SnapshotResult {- spec: spec.to_owned(),- frame,- status: SnapshotStatus::Matched,- snapshot: snapshot.clone(),- diff_ratio: 0.,- actual: None,- diff: None,- };-- if !snapshot.exists() {- actual.save_png(&snapshot)?;- result.status = SnapshotStatus::Created;- return Ok(result);- }-- let expected = load_png(&snapshot)?;- let (ratio, diff) = diff_frames(&expected, &actual, options.channel_threshold);- result.diff_ratio = ratio;-- if ratio <= options.max_diff_ratio {- return Ok(result);- }-- if options.update {- actual.save_png(&snapshot)?;- result.status = SnapshotStatus::Updated;- return Ok(result);- }-- actual.save_png(&actual_path)?;- result.actual = Some(actual_path);- if let Some(diff) = diff {- diff.save_png(&diff_path)?;- result.diff = Some(diff_path);- }- result.status = SnapshotStatus::Failed;- Ok(result)-}--/// Checks every spec and panics with a readable report if any frame differs.-pub fn assert_frames<'a, 'media: 'a, TVideo: Video>(- previewer: &mut Previewer<'a, 'media, TVideo>,- renderer: &mut dyn FrameRenderer,- specs: &[&str],- options: &SnapshotOptions,-) -> Vec<SnapshotResult> {- let results: Vec<SnapshotResult> = specs- .iter()- .map(|spec| {- check_frame(previewer, renderer, spec, options)- .unwrap_or_else(|err| panic!("snapshot {spec}: {err}"))- })- .collect();-- let failed: Vec<String> = results- .iter()- .filter(|r| r.status == SnapshotStatus::Failed)- .map(|r| {- format!(- " {} (frame {}): {:.3}% of pixels differ, see {} and {}",- r.spec,- r.frame,- r.diff_ratio * 100.,- r.actual.as_deref().unwrap_or(Path::new("-")).display(),- r.diff.as_deref().unwrap_or(Path::new("-")).display(),- )- })- .collect();-- assert!(- failed.is_empty(),- "{} frame snapshot(s) differ (FFRAMES_UPDATE_SNAPSHOTS=1 accepts them):\n{}",- failed.len(),- failed.join("\n")- );-- results-}--#[cfg(test)]-mod tests {- use super::*;-- fn solid(color: [u8; 4]) -> RgbaFrame {- RgbaFrame {- width: 4,- height: 4,- pixels: color.repeat(16),- }- }-- #[test]- fn diff_ignores_small_differences() {- let (ratio, _) = diff_frames(- &solid([100, 100, 100, 255]),- &solid([110, 100, 100, 255]),- 16,- );- assert_eq!(ratio, 0.);- let (ratio, diff) = diff_frames(- &solid([100, 100, 100, 255]),- &solid([200, 100, 100, 255]),- 16,- );- assert_eq!(ratio, 1.);- assert_eq!(&diff.unwrap().pixels[..4], &[255, 0, 0, 255]);- }-- #[test]- fn names_are_file_safe() {- assert_eq!(snapshot_name("[email protected]"), "intro_1.5s");- assert_eq!(snapshot_name("50%"), "50p");- assert_eq!(snapshot_name("#3"), "3");- }-}diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.mdindex 6a2e5b9d..69964886 100644--- a/skills/fframes-video/SKILL.md+++ b/skills/fframes-video/SKILL.md@@ -220,7 +220,6 @@ times with commas.| `svg TIME` | read a frame's final SVG as text (positions, text, colors) || `preview [TIME] [--paused] [--mute]` | real-time window with sound, for the user || `render [RANGE] [-o out.mp4] [--draft]` | encode the video or a part of it (audio cut to match) |-| `snapshot TIMES [--update]` | compare frames with approved PNGs, `.diff.png` marks changes || `audio analyze [RANGE] [--waveform w.png]` | loudness (LUFS), true peak, clipping, silence, per scene || `audio at TIMES` | which sounds play at a moment, where in their file and how loud || `audio render [RANGE] -o a.wav` | the mix as a WAV file |