Skip to content

programmatic video rendering framework that is actually fast

feat(cli): add frame crops, element labels, time strips, pop detection and stereo media (#227)

Dmitriy Kovalenko87837373f056
diff --git a/AGENTS.md b/AGENTS.md
index 364f6990..5e823458 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -288,7 +288,9 @@ the editor bridge builds the library with `default-features = false`.
Embed static assets with `include_media_dir!`. The path is relative to the **workspace root**
and every file in the folder becomes a field of the generated struct; fonts are registered by
their family name. Audio (`mp3`, `wav`, `flac`, `aac`, `ogg`, `m4a`) is decoded to mono at
-compile time; files loaded with `MediaDirectory` keep stereo.
+compile time unless the macro gets the `stereo` option
+(`include_media_dir!(pub struct MyVideoMedia, "examples/my-video/media", stereo)`, twice the
+embedded size); files loaded with `MediaDirectory` keep stereo.
```rust
use fframes::include_media_dir;
@@ -629,12 +631,12 @@ See `examples/teej-podcast/src/main.rs`; `cargo fframes new` generates the same
| command | what |
| --- | --- |
| `render [RANGE] [-o out.mp4] [--draft]` | the video or a range of it (default command); `--draft` = half size + fastest preset |
-| `frame 1s,50%,Intro@end [-o dir] [--svg]` | PNGs of single frames plus the problems found in them |
-| `strip [RANGE] -n 12` | labelled contact sheet of evenly spaced frames, one image to review motion |
+| `frame 1s,50%,Intro@end [-o dir] [--svg] [--crop x,y,w,h] [--zoom N] [--ids]` | PNGs of single frames plus the problems found in them; `--crop` renders one rectangle sharply (zoomed to about 960 px wide), `--ids` outlines and labels every element with an `id` |
+| `strip [RANGE \| TIMES] -n 12 [--crop x,y,w,h]` | labelled contact sheet of evenly spaced frames (or of comma separated times), one image to review motion |
| `onion RANGE -n 6` | frames blended into one image, shows the path of a movement |
| `svg TIME` | the frame as SVG after conversion |
| `timeline` | size, fps, scenes with frame and second ranges, audio tracks |
-| `inspect [RANGE] [--every 0.25s]` | missing media/fonts/glyphs, text cut by the canvas edge, NaN transforms, panics; exit code 2 on errors |
+| `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 |
diff --git a/fframes-editor-controller/src/wasm_audio.rs b/fframes-editor-controller/src/wasm_audio.rs
index 07ec0266..e980a1a4 100644
--- a/fframes-editor-controller/src/wasm_audio.rs
+++ b/fframes-editor-controller/src/wasm_audio.rs
@@ -27,9 +27,23 @@ impl AudioData {
fframes::AudioData::Lazy => panic!("Lazy audio is not supported in wasm"),
};
+ // The editor plays one channel: mix stereo files down instead of dropping the right.
+ let fltp_data = match &preloaded_data.right {
+ Some(right) => {
+ let mixed: Vec<f32> = preloaded_data
+ .samples
+ .iter()
+ .zip(right.iter())
+ .map(|(left, right)| (left + right) * 0.5)
+ .collect();
+ js_sys::Float32Array::from(mixed.as_slice())
+ }
+ None => js_sys::Float32Array::from(preloaded_data.samples.as_ref()),
+ };
+
Self {
name,
- fltp_data: js_sys::Float32Array::from(preloaded_data.samples.as_ref()),
+ fltp_data,
sample_rate: preloaded_data.sample_rate,
}
}
diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rs
index a0f7cdd7..fa980e48 100644
--- a/fframes/src/renderer/cli.rs
+++ b/fframes/src/renderer/cli.rs
@@ -16,7 +16,10 @@
//! from `args.app`, then `cli::new(&video, options).args(args).run()`.
use super::{
CpuFrameRenderer, FFramesRenderBackend, FrameRenderer, FrameReport, Previewer, RgbaFrame,
- fframes_logger::FFramesLoggerVariant, sheet, snapshot,
+ continuity::{PopDetector, PopKind},
+ element_labels::{self, LabelledElement},
+ fframes_logger::FFramesLoggerVariant,
+ sheet, snapshot,
};
use crate::diagnostics::Severity;
use crate::{AudioMixer, AudioTimelineSamples, AudioTimelineUnit, RenderOptions, Video};
@@ -156,11 +159,21 @@ pub struct FrameArgs {
/// Also write the converted SVG next to every PNG.
#[arg(long)]
pub svg: bool,
+ /// Only this rectangle, `x,y,width,height` in the video's pixels, e.g. `1100,520,240,120`.
+ #[arg(long, value_parser = parse_region)]
+ pub crop: Option<Region>,
+ /// Render this many times larger. Defaults to enough to show a `--crop` about 960 pixels
+ /// wide (at most 8).
+ #[arg(long)]
+ pub zoom: Option<f64>,
+ /// Outline every element that has an `id` and label it with its id (listed in --json).
+ #[arg(long)]
+ pub ids: bool,
}
#[derive(Debug, Clone, Args)]
pub struct StripArgs {
- /// Range to sample.
+ /// Range to sample, or comma separated times to show side by side, e.g. `1s,Intro@end,50%`.
#[arg(default_value = "all")]
pub range: String,
/// Number of frames.
@@ -173,6 +186,10 @@ pub struct StripArgs {
pub width: u32,
#[arg(short, long, default_value = "strip.png")]
pub output: PathBuf,
+ /// Show only this rectangle of every frame, `x,y,width,height` in the video's pixels,
+ /// rendered sharply at `--width`.
+ #[arg(long, value_parser = parse_region)]
+ pub crop: Option<Region>,
}
#[derive(Debug, Clone, Args)]
@@ -216,6 +233,65 @@ pub struct InspectArgs {
/// Exit with code 2 when a finding of this severity is found.
#[arg(long, value_enum, default_value = "error")]
pub fail_on: FailOn,
+ /// Also render every frame of the range small and report pops (warnings): parts of the
+ /// picture that change in a single frame between still frames, like an element that
+ /// appears, vanishes or jumps in front of another one instead of moving there.
+ #[arg(long)]
+ pub pops: bool,
+}
+
+/// A rectangle in the video's pixels.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
+pub struct Region {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+fn parse_region(value: &str) -> Result<Region, String> {
+ let parts = value
+ .split(',')
+ .map(|part| part.trim().parse::<f64>())
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|_| format!("`{value}` is not `x,y,width,height`"))?;
+ match parts[..] {
+ [x, y, width, height] if width > 0. && height > 0. => Ok(Region {
+ x,
+ y,
+ width,
+ height,
+ }),
+ _ => Err(format!(
+ "`{value}`: expected `x,y,width,height` with a positive width and height"
+ )),
+ }
+}
+
+/// Larger frames do not fit into the GPU surfaces of the Skia backend.
+const MAX_RENDER_SIDE: f64 = 16_384.;
+
+/// Fails when the whole frame at `scale` would exceed [`MAX_RENDER_SIDE`].
+fn check_render_size<V: Video>(scale: f64) -> CliResult<()> {
+ let (width, height) = (V::WIDTH as f64 * scale, V::HEIGHT as f64 * scale);
+ if width > MAX_RENDER_SIDE || height > MAX_RENDER_SIDE {
+ return Err(format!(
+ "the whole frame would be rendered at {width:.0}x{height:.0}, more than \
+ {MAX_RENDER_SIDE} pixels per side; use a smaller --zoom or a wider --crop"
+ ));
+ }
+ Ok(())
+}
+
+/// The pixels of `region` (video pixels) in a frame rendered at any scale.
+fn crop_frame<V: Video>(frame: &RgbaFrame, region: Region) -> RgbaFrame {
+ let scale = f64::from(frame.width) / V::WIDTH as f64;
+ frame.crop(
+ (region.x * scale).round().max(0.) as u32,
+ (region.y * scale).round().max(0.) as u32,
+ (region.width * scale).round().max(1.) as u32,
+ (region.height * scale).round().max(1.) as u32,
+ )
}
#[derive(Debug, Clone, Args)]
@@ -500,7 +576,9 @@ impl<'r, 'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend, A: Arg
}
Command::Svg(args) => svg(json, &mut previewer, args),
Command::Timeline => timeline(json, &previewer),
- Command::Inspect(args) => inspect(json, &mut previewer, args),
+ Command::Inspect(args) => {
+ inspect(json, &mut previewer, frame_renderer, args)
+ }
Command::Snapshot(args) => {
snapshots(json, &mut previewer, frame_renderer, args)
}
@@ -724,10 +802,38 @@ struct FrameResult {
spec: String,
path: PathBuf,
svg: Option<PathBuf>,
+ /// Elements with an `id` in the frame (or the crop), with `--ids`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ elements: Option<Vec<LabelledElement>>,
#[serde(flatten)]
report: FrameReport,
}
+/// How many labelled elements the text output lists; --json has all of them.
+const LISTED_ELEMENTS: usize = 40;
+
+fn elements_text(elements: &[LabelledElement]) -> String {
+ let mut text = String::new();
+ for element in elements.iter().take(LISTED_ELEMENTS) {
+ let _ = writeln!(
+ text,
+ " #{} {} {:.0},{:.0} {:.0}x{:.0}",
+ element.id, element.kind, element.x, element.y, element.width, element.height
+ );
+ }
+ if elements.len() > LISTED_ELEMENTS {
+ let _ = writeln!(
+ text,
+ " ... {} more, see --json",
+ elements.len() - LISTED_ELEMENTS
+ );
+ }
+ if elements.is_empty() {
+ text.push_str(" no elements with an `id`\n");
+ }
+ text
+}
+
fn frame<'a, 'm: 'a, V: Video>(
json: bool,
previewer: &mut Previewer<'a, 'm, V>,
@@ -735,9 +841,46 @@ fn frame<'a, 'm: 'a, V: Video>(
args: FrameArgs,
) -> CliResult {
std::fs::create_dir_all(&args.output).map_err(err)?;
+ let zoom = args.zoom.unwrap_or_else(|| {
+ args.crop
+ .map_or(1., |crop| (960. / crop.width).clamp(1., 8.))
+ });
+ if !(zoom > 0. && zoom.is_finite()) {
+ return Err(format!("--zoom {zoom} must be a positive number"));
+ }
+ let scale = previewer.options().scale_resolution * zoom;
+ check_render_size::<V>(scale)?;
+ previewer.set_scale(scale);
+
let mut results = Vec::new();
for (spec, frame) in resolve_frames(previewer, &args.at)? {
- let (pixels, report) = previewer.render_inspected(frame, renderer).map_err(err)?;
+ let (mut pixels, report) = previewer.render_inspected(frame, renderer).map_err(err)?;
+ let elements = if args.ids {
+ let tree = previewer.svg_tree(frame).map_err(err)?;
+ let mut elements = element_labels::labelled_elements(&tree);
+ if let Some(crop) = args.crop {
+ elements.retain(|e| {
+ f64::from(e.x) < crop.x + crop.width
+ && f64::from(e.x + e.width) > crop.x
+ && f64::from(e.y) < crop.y + crop.height
+ && f64::from(e.y + e.height) > crop.y
+ });
+ }
+ pixels = element_labels::draw_labels(
+ &pixels,
+ &tree,
+ &elements,
+ previewer.font_db(),
+ previewer.options().default_font,
+ )
+ .map_err(err)?;
+ Some(elements)
+ } else {
+ None
+ };
+ if let Some(crop) = args.crop {
+ pixels = crop_frame::<V>(&pixels, crop);
+ }
let name = snapshot::snapshot_name(&spec);
let path = args.output.join(format!("{name}.png"));
pixels.save_png(&path).map_err(err)?;
@@ -752,6 +895,7 @@ fn frame<'a, 'm: 'a, V: Video>(
spec,
path,
svg,
+ elements,
report,
});
}
@@ -770,6 +914,9 @@ fn frame<'a, 'm: 'a, V: Video>(
r.path.display(),
diagnostics_text(&r.report, " ")
);
+ if let Some(elements) = &r.elements {
+ text.push_str(&elements_text(elements));
+ }
text
})
.trim_end()
@@ -789,11 +936,15 @@ fn render_cells<'a, 'm: 'a, V: Video>(
previewer: &mut Previewer<'a, 'm, V>,
renderer: &mut dyn FrameRenderer,
frames: &[usize],
+ crop: Option<Region>,
) -> CliResult<(Vec<sheet::SheetCell>, Vec<FrameReport>)> {
let mut cells = Vec::new();
let mut reports = Vec::new();
for &frame in frames {
- let (pixels, report) = previewer.render_inspected(frame, renderer).map_err(err)?;
+ 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!(
@@ -839,13 +990,24 @@ fn strip<'a, 'm: 'a, V: Video>(
renderer: &mut dyn FrameRenderer,
args: StripArgs,
) -> CliResult {
- let range = previewer
- .timeline()
- .resolve_range(&args.range)
- .map_err(err)?;
- let frames = spread(range, args.count);
- previewer.set_scale(f64::from(args.width) / V::WIDTH as f64);
- let (cells, diagnostics) = render_cells(previewer, renderer, &frames)?;
+ let frames = if args.range.contains(',') {
+ let specs: Vec<String> = args.range.split(',').map(str::to_owned).collect();
+ resolve_frames(previewer, &specs)?
+ .into_iter()
+ .map(|(_, frame)| frame)
+ .collect()
+ } else {
+ let range = previewer
+ .timeline()
+ .resolve_range(&args.range)
+ .map_err(err)?;
+ spread(range, args.count)
+ };
+ let visible_width = args.crop.map_or(V::WIDTH as f64, |crop| crop.width);
+ let scale = f64::from(args.width) / visible_width;
+ check_render_size::<V>(scale)?;
+ previewer.set_scale(scale);
+ let (cells, diagnostics) = render_cells(previewer, renderer, &frames, args.crop)?;
let image = sheet::contact_sheet(
&cells,
args.columns,
@@ -880,7 +1042,7 @@ fn onion<'a, 'm: 'a, V: Video>(
if scale.is_none() {
previewer.set_scale(0.5);
}
- let (cells, diagnostics) = render_cells(previewer, renderer, &frames)?;
+ let (cells, diagnostics) = render_cells(previewer, renderer, &frames, None)?;
let pixels: Vec<RgbaFrame> = cells.into_iter().map(|c| c.frame).collect();
let image = sheet::onion_skin(&pixels).map_err(err)?;
ensure_parent(&args.output)?;
@@ -1005,12 +1167,137 @@ struct Finding {
#[derive(Serialize)]
struct InspectResult {
checked_frames: usize,
+ /// Frames rendered and compared with `--pops`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pop_scanned_frames: Option<usize>,
findings: Vec<Finding>,
}
+/// Width in pixels of the frames `inspect --pops` compares.
+const POP_SCAN_WIDTH: f64 = 480.;
+
+/// Renders every frame of `range` small and reports pops, see [`super::continuity`].
+fn scan_pops<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &mut Previewer<'a, 'm, V>,
+ renderer: &mut dyn FrameRenderer,
+ range: std::ops::Range<usize>,
+) -> CliResult<Vec<Finding>> {
+ previewer.set_scale((POP_SCAN_WIDTH / V::WIDTH as f64).min(1.));
+ let (width, height) = previewer.size();
+ 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}");
+ }
+ }
+ if progress {
+ eprint!("\r{}\r", " ".repeat(48));
+ }
+
+ // The same region popping again and again is one finding (a counter, a blinking light),
+ // so that a single pop elsewhere stands out.
+ let mut groups: Vec<(crate::renderer::continuity::Pop, Vec<usize>)> = Vec::new();
+ for pop in detector.finish() {
+ let overlapping = groups.iter_mut().find(|(group, _)| {
+ group.kind == pop.kind
+ && pop.x < group.x + group.width
+ && group.x < pop.x + pop.width
+ && pop.y < group.y + group.height
+ && group.y < pop.y + pop.height
+ });
+ if let Some((group, frames)) = overlapping {
+ let (right, bottom) = (
+ (group.x + group.width).max(pop.x + pop.width),
+ (group.y + group.height).max(pop.y + pop.height),
+ );
+ group.x = group.x.min(pop.x);
+ group.y = group.y.min(pop.y);
+ group.width = right - group.x;
+ group.height = bottom - group.y;
+ group.strength = group.strength.max(pop.strength);
+ frames.push(pop.frame);
+ } else {
+ let frame = pop.frame;
+ groups.push((pop, vec![frame]));
+ }
+ }
+
+ let to_video = V::WIDTH as f32 / width as f32;
+ let timeline = previewer.timeline();
+ Ok(groups
+ .into_iter()
+ .map(|(pop, frames)| {
+ let frames: Vec<usize> = frames.into_iter().map(|f| range.start + f).collect();
+ let (first, last) = (frames[0], frames[frames.len() - 1]);
+ let margin = 16.;
+ let x = (pop.x as f32 * to_video - margin).max(0.);
+ let y = (pop.y as f32 * to_video - margin).max(0.);
+ let w = pop.width as f32 * to_video + 2. * margin;
+ let h = pop.height as f32 * to_video + 2. * margin;
+ let (what, compare) = match pop.kind {
+ PopKind::Step => (
+ "changes in one frame between still frames: something appears, vanishes \
+ or jumps in front of something else",
+ format!("{},{first}", first.saturating_sub(1)),
+ ),
+ PopKind::Flash => (
+ "differs in a single frame from the frames before and after it",
+ format!("{},{first},{}", first.saturating_sub(1), first + 1),
+ ),
+ };
+ let (first_seconds, last_seconds) = (
+ timeline.frame_to_seconds(first),
+ timeline.frame_to_seconds(last),
+ );
+ let repeats = if frames.len() > 1 {
+ format!(
+ " ({} times until {last_seconds:.2}s, like a counter or a blinking element)",
+ frames.len()
+ )
+ } else {
+ String::new()
+ };
+ let mut scenes: Vec<String> = Vec::new();
+ for &frame in &frames {
+ for scene in timeline.scenes_at(frame) {
+ if !scenes.contains(&scene.name) {
+ scenes.push(scene.name.clone());
+ }
+ }
+ }
+ Finding {
+ severity: Severity::Warning,
+ key: format!("pop:{first}:{}:{}", pop.x, pop.y),
+ message: format!(
+ "pop at {x:.0},{y:.0} {w:.0}x{h:.0}{repeats}: the picture {what}; compare \
+ `frame {compare} --crop {x:.0},{y:.0},{w:.0},{h:.0}`"
+ ),
+ first_frame: first,
+ last_frame: last,
+ first_seconds,
+ last_seconds,
+ frames: frames.len(),
+ scenes,
+ }
+ })
+ .collect())
+}
+
fn inspect<'a, 'm: 'a, V: Video>(
json: bool,
previewer: &mut Previewer<'a, 'm, V>,
+ renderer: &mut dyn FrameRenderer,
args: InspectArgs,
) -> CliResult {
let timeline = previewer.timeline().clone();
@@ -1070,6 +1357,12 @@ fn inspect<'a, 'm: 'a, V: Video>(
}
}
}
+ let pop_scanned_frames = if args.pops {
+ findings.extend(scan_pops(json, previewer, renderer, range.clone())?);
+ Some(range.len())
+ } else {
+ None
+ };
findings.sort_by(|a, b| {
b.severity
.cmp(&a.severity)
@@ -1084,10 +1377,15 @@ fn inspect<'a, 'm: 'a, V: Video>(
let result = InspectResult {
checked_frames: frames.len(),
+ pop_scanned_frames,
findings,
};
print(json, &result, || {
- let mut text = format!("checked {} frames: ", result.checked_frames);
+ let mut text = format!("checked {} frames", result.checked_frames);
+ if let Some(scanned) = result.pop_scanned_frames {
+ let _ = write!(text, ", compared {scanned} frames for pops");
+ }
+ text.push_str(": ");
if result.findings.is_empty() {
text.push_str("no problems found");
} else {
@@ -1564,5 +1862,59 @@ mod tests {
cli.command,
Some(Command::Audio(AudioCommand::Analyze { .. }))
));
+
+ let cli = Cli::<NoArgs>::try_parse_from([
+ "video",
+ "frame",
+ "1s,2s",
+ "--crop",
+ "100,50.5,240,120",
+ "--zoom",
+ "3",
+ "--ids",
+ ])
+ .unwrap();
+ let Some(Command::Frame(args)) = cli.command else {
+ panic!("frame expected");
+ };
+ assert_eq!(args.at, ["1s", "2s"]);
+ assert_eq!(
+ args.crop,
+ Some(Region {
+ x: 100.,
+ y: 50.5,
+ width: 240.,
+ height: 120.
+ })
+ );
+ assert_eq!(args.zoom, Some(3.));
+ assert!(args.ids);
+
+ let cli = Cli::<NoArgs>::try_parse_from([
+ "video",
+ "strip",
+ "1s,Intro@end,50%",
+ "--crop",
+ "0,0,960,540",
+ ])
+ .unwrap();
+ assert!(
+ matches!(cli.command, Some(Command::Strip(StripArgs { ref range, crop: Some(_), .. })) if range == "1s,Intro@end,50%")
+ );
+
+ let cli = Cli::<NoArgs>::try_parse_from(["video", "inspect", "Intro", "--pops"]).unwrap();
+ assert!(matches!(
+ cli.command,
+ Some(Command::Inspect(InspectArgs { pops: true, .. }))
+ ));
+ }
+
+ #[test]
+ fn parses_regions() {
+ assert!(parse_region("1,2,3,4").is_ok());
+ assert!(parse_region("1, 2, 3.5, 4").is_ok());
+ assert!(parse_region("1,2,3").is_err());
+ assert!(parse_region("1,2,0,4").is_err());
+ assert!(parse_region("a,2,3,4").is_err());
}
}
diff --git a/fframes/src/renderer/continuity.rs b/fframes/src/renderer/continuity.rs
new file mode 100644
index 00000000..787044b6
--- /dev/null
+++ b/fframes/src/renderer/continuity.rs
@@ -0,0 +1,326 @@
+//! Finds pops: parts of a picture that change in a single frame between frames in which they
+//! stand still. An element that appears, vanishes or jumps in front of another element without
+//! moving there is easy to miss in a contact sheet but obvious when the video plays.
+//!
+//! Frames are compared in square blocks. A block pops when it changes a lot from one frame to
+//! the next while it, and the blocks around it, are still in the comparison before and after.
+//! A single frame that differs from the frames on both sides (a flash) is reported too. Motion
+//! changes the same area in consecutive frames and is therefore not reported; neither are cuts
+//! that change most of the picture at once.
+use super::RgbaFrame;
+use serde::Serialize;
+
+/// Block edge in pixels of the compared frames.
+const BLOCK: u32 = 8;
+/// Mean difference per channel (0-255) of a block that counts as a sudden change.
+const SUDDEN: f32 = 20.;
+/// Mean difference per channel below which a block counts as standing still.
+const STILL: f32 = 3.;
+/// Share of the picture above which a change is a cut, not a pop.
+const CUT: f32 = 0.3;
+
+/// What changed abruptly.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PopKind {
+ /// Changed between two frames and then stayed: something appeared, vanished or swapped
+ /// places with another element.
+ Step,
+ /// One frame differs from the frames before and after it.
+ Flash,
+}
+
+/// A region that popped, in the pixels of the compared frames.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Pop {
+ /// The first frame (index in the sequence fed to [`PopDetector::push`]) that shows the
+ /// change.
+ pub frame: usize,
+ pub kind: PopKind,
+ pub x: u32,
+ pub y: u32,
+ pub width: u32,
+ pub height: u32,
+ /// Largest mean difference per channel (0-255) of a block in the region.
+ pub strength: f32,
+}
+
+/// Mean absolute difference per block between two frames of the same size.
+fn block_differences(a: &RgbaFrame, b: &RgbaFrame, columns: usize, rows: usize) -> Vec<f32> {
+ let mut sums = vec![0f32; columns * rows];
+ let mut counts = vec![0u32; columns * rows];
+ let width = a.width as usize;
+ for (i, (pa, pb)) in a
+ .pixels
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .zip(b.pixels.as_chunks::<4>().0)
+ .enumerate()
+ {
+ let (x, y) = (i % width, i / width);
+ let block =
+ (y / BLOCK as usize).min(rows - 1) * columns + (x / BLOCK as usize).min(columns - 1);
+ let difference: u32 = (0..3).map(|c| u32::from(pa[c].abs_diff(pb[c]))).sum();
+ sums[block] += difference as f32 / 3.;
+ counts[block] += 1;
+ }
+ sums.iter()
+ .zip(counts)
+ .map(|(sum, count)| sum / count.max(1) as f32)
+ .collect()
+}
+
+/// Feeds consecutive frames one at a time and collects the pops between them. Keeps only the
+/// last three frames and comparisons, so it scans long videos in constant memory.
+pub struct PopDetector {
+ columns: usize,
+ rows: usize,
+ size: (u32, u32),
+ frames: Vec<RgbaFrame>,
+ /// `differences[i]` compares `frames[i]` with `frames[i + 1]`.
+ differences: Vec<Vec<f32>>,
+ pushed: usize,
+ pops: Vec<Pop>,
+}
+
+impl PopDetector {
+ pub fn new(width: u32, height: u32) -> Self {
+ Self {
+ columns: width.div_ceil(BLOCK).max(1) as usize,
+ rows: height.div_ceil(BLOCK).max(1) as usize,
+ size: (width, height),
+ frames: Vec::new(),
+ differences: Vec::new(),
+ pushed: 0,
+ pops: Vec::new(),
+ }
+ }
+
+ /// Adds the next frame of the sequence. Frames must all have the size given to `new`.
+ pub fn push(&mut self, frame: RgbaFrame) {
+ debug_assert_eq!((frame.width, frame.height), self.size);
+ if let Some(previous) = self.frames.last() {
+ let difference = block_differences(previous, &frame, self.columns, self.rows);
+ self.differences.push(difference);
+ }
+ self.frames.push(frame);
+ self.pushed += 1;
+ // `frames` holds the last four frames; `differences` the three comparisons between them.
+ if self.frames.len() > 4 {
+ self.frames.remove(0);
+ self.differences.remove(0);
+ }
+ self.detect();
+ }
+
+ /// All pops found, in the order of their frames.
+ pub fn finish(self) -> Vec<Pop> {
+ self.pops
+ }
+
+ /// Largest value in the block's neighbourhood (itself and the eight blocks around it).
+ fn around(&self, values: &[f32], block: usize) -> f32 {
+ let (column, row) = (
+ (block % self.columns) as isize,
+ (block / self.columns) as isize,
+ );
+ let mut largest = 0f32;
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let (c, r) = (column + dx, row + dy);
+ if c >= 0 && r >= 0 && (c as usize) < self.columns && (r as usize) < self.rows {
+ largest = largest.max(values[r as usize * self.columns + c as usize]);
+ }
+ }
+ }
+ largest
+ }
+
+ fn detect(&mut self) {
+ let blocks = self.columns * self.rows;
+ let n = self.differences.len();
+ // A step between frames k and k + 1 is decided once the comparison after it is known:
+ // differences [before, change, after].
+ if n >= 3 {
+ let (before, change, after) = (
+ &self.differences[n - 3],
+ &self.differences[n - 2],
+ &self.differences[n - 1],
+ );
+ let flagged: Vec<(usize, f32)> = (0..blocks)
+ .filter(|&b| {
+ change[b] >= SUDDEN
+ && self.around(before, b) < STILL
+ && self.around(after, b) < STILL
+ })
+ .map(|b| (b, change[b]))
+ .collect();
+ self.report(&flagged, PopKind::Step, self.pushed - 2);
+ }
+ // A flash: frames [k, k + 1, k + 2, k + 3] with k + 1 different from k and k + 2 while
+ // k and k + 2 are alike, and everything around still before and after.
+ if n >= 3 && self.frames.len() >= 4 {
+ let (before, into, out_of) = (
+ &self.differences[n - 3],
+ &self.differences[n - 2],
+ &self.differences[n - 1],
+ );
+ let returned = block_differences(
+ &self.frames[self.frames.len() - 3],
+ &self.frames[self.frames.len() - 1],
+ self.columns,
+ self.rows,
+ );
+ let flagged: Vec<(usize, f32)> = (0..blocks)
+ .filter(|&b| {
+ into[b] >= SUDDEN
+ && out_of[b] >= SUDDEN
+ && returned[b] < STILL
+ && self.around(before, b) < STILL
+ })
+ .map(|b| (b, into[b]))
+ .collect();
+ self.report(&flagged, PopKind::Flash, self.pushed - 2);
+ }
+ }
+
+ /// Groups flagged `(block, strength)` pairs into connected regions; a change of most of the
+ /// picture is a cut.
+ fn report(&mut self, flagged: &[(usize, f32)], kind: PopKind, frame: usize) {
+ if flagged.is_empty() || flagged.len() as f32 > CUT * (self.columns * self.rows) as f32 {
+ return;
+ }
+ let columns_count = self.columns;
+ let mut unvisited: Vec<(usize, f32)> = flagged.to_vec();
+ while let Some(start) = unvisited.pop() {
+ let mut region = vec![start];
+ let mut i = 0;
+ while i < region.len() {
+ let block = region[i].0;
+ let (column, row) = (block % columns_count, block / columns_count);
+ unvisited.retain(|&(other, strength)| {
+ let (c, r) = (other % columns_count, other / columns_count);
+ let touches = c.abs_diff(column) <= 1 && r.abs_diff(row) <= 1;
+ if touches {
+ region.push((other, strength));
+ }
+ !touches
+ });
+ i += 1;
+ }
+ let columns = region.iter().map(|(b, _)| b % columns_count);
+ let rows = region.iter().map(|(b, _)| b / columns_count);
+ let (left, right) = (
+ columns.clone().min().unwrap_or(0),
+ columns.max().unwrap_or(0),
+ );
+ let (top, bottom) = (rows.clone().min().unwrap_or(0), rows.max().unwrap_or(0));
+ let x = left as u32 * BLOCK;
+ let y = top as u32 * BLOCK;
+ self.pops.push(Pop {
+ frame,
+ kind,
+ x,
+ y,
+ width: ((right + 1) as u32 * BLOCK).min(self.size.0) - x,
+ height: ((bottom + 1) as u32 * BLOCK).min(self.size.1) - y,
+ strength: region
+ .iter()
+ .map(|&(_, strength)| strength)
+ .fold(0., f32::max),
+ });
+ }
+ self.pops.sort_by_key(|pop| (pop.frame, pop.y, pop.x));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const W: u32 = 64;
+ const H: u32 = 48;
+
+ /// A grey frame with a white square at `square` (x, y, size), if any.
+ fn frame(square: Option<(u32, u32, u32)>) -> RgbaFrame {
+ let mut pixels = vec![80u8; (W * H * 4) as usize];
+ if let Some((sx, sy, size)) = square {
+ for y in sy..(sy + size).min(H) {
+ for x in sx..(sx + size).min(W) {
+ let i = ((y * W + x) * 4) as usize;
+ pixels[i..i + 3].copy_from_slice(&[255, 255, 255]);
+ }
+ }
+ }
+ RgbaFrame {
+ width: W,
+ height: H,
+ pixels,
+ }
+ }
+
+ fn scan(frames: Vec<RgbaFrame>) -> Vec<Pop> {
+ let mut detector = PopDetector::new(W, H);
+ for frame in frames {
+ detector.push(frame);
+ }
+ detector.finish()
+ }
+
+ #[test]
+ fn element_appearing_between_still_frames_is_a_step() {
+ let pops = scan(vec![
+ frame(None),
+ frame(None),
+ frame(Some((16, 16, 8))),
+ frame(Some((16, 16, 8))),
+ frame(Some((16, 16, 8))),
+ ]);
+ assert_eq!(pops.len(), 1, "{pops:?}");
+ let pop = &pops[0];
+ assert_eq!(pop.kind, PopKind::Step);
+ assert_eq!(pop.frame, 2);
+ assert_eq!((pop.x, pop.y, pop.width, pop.height), (16, 16, 8, 8));
+ }
+
+ #[test]
+ fn single_frame_glitch_is_a_flash() {
+ let pops = scan(vec![
+ frame(None),
+ frame(None),
+ frame(Some((40, 8, 8))),
+ frame(None),
+ frame(None),
+ ]);
+ assert!(
+ pops.iter()
+ .any(|p| p.kind == PopKind::Flash && p.frame == 2 && p.x == 40),
+ "{pops:?}"
+ );
+ }
+
+ #[test]
+ fn continuous_motion_is_not_a_pop() {
+ let pops = scan((0..8).map(|i| frame(Some((4 + i * 6, 16, 8)))).collect());
+ assert!(pops.is_empty(), "{pops:?}");
+ }
+
+ #[test]
+ fn cut_of_the_whole_picture_is_not_a_pop() {
+ let full = Some((0, 0, W.max(H)));
+ let pops = scan(vec![
+ frame(None),
+ frame(None),
+ frame(full),
+ frame(full),
+ frame(full),
+ ]);
+ assert!(pops.is_empty(), "{pops:?}");
+ }
+
+ #[test]
+ fn still_video_has_no_pops() {
+ assert_eq!(scan(vec![frame(None); 6]), Vec::new());
+ }
+}
diff --git a/fframes/src/renderer/element_labels.rs b/fframes/src/renderer/element_labels.rs
new file mode 100644
index 00000000..a54cc87d
--- /dev/null
+++ b/fframes/src/renderer/element_labels.rs
@@ -0,0 +1,207 @@
+//! Outlines and labels the elements of a frame that have an `id`, to tell which shape is which
+//! in a rendered PNG (`frame --ids`).
+use super::{FFramesRendererError, FFramesRendererResult, RgbaFrame, sheet};
+use crate::usvgr;
+use serde::Serialize;
+use std::fmt::Write as _;
+use usvgr::tiny_skia_path::PathSegment;
+
+/// More labels than this make the picture unreadable; the rest are listed, not drawn.
+const MAX_LABELS: usize = 400;
+
+/// An element with an `id` and its bounding box in the video's coordinates.
+#[derive(Debug, Clone, Serialize)]
+pub struct LabelledElement {
+ pub id: String,
+ /// `path`, `group`, `image` or `text`.
+ pub kind: &'static str,
+ pub x: f32,
+ pub y: f32,
+ pub width: f32,
+ pub height: f32,
+ /// The outline as SVG path data in the video's coordinates (paths only).
+ #[serde(skip)]
+ outline: Option<String>,
+}
+
+fn path_data(path: &usvgr::tiny_skia_path::Path, transform: usvgr::Transform) -> Option<String> {
+ let path = path.clone().transform(transform)?;
+ let mut data = String::new();
+ for segment in path.segments() {
+ let _ = match segment {
+ PathSegment::MoveTo(p) => write!(data, "M{} {} ", p.x, p.y),
+ PathSegment::LineTo(p) => write!(data, "L{} {} ", p.x, p.y),
+ PathSegment::QuadTo(a, p) => write!(data, "Q{} {} {} {} ", a.x, a.y, p.x, p.y),
+ PathSegment::CubicTo(a, b, p) => {
+ write!(data, "C{} {} {} {} {} {} ", a.x, a.y, b.x, b.y, p.x, p.y)
+ }
+ PathSegment::Close => write!(data, "Z "),
+ };
+ }
+ Some(data)
+}
+
+fn collect(group: &usvgr::Group, out: &mut Vec<LabelledElement>) {
+ for node in group.children() {
+ if let usvgr::Node::Group(child) = node
+ && child.opacity().get() == 0.
+ {
+ continue;
+ }
+ let id = node.id();
+ if !id.is_empty() {
+ let bbox = node.abs_bounding_box();
+ if bbox.width().is_finite() && bbox.height().is_finite() {
+ let (kind, outline) = match node {
+ usvgr::Node::Path(path) => {
+ ("path", path_data(path.data(), path.abs_transform()))
+ }
+ usvgr::Node::FastShape(shape) => (
+ "path",
+ shape
+ .to_path()
+ .and_then(|path| path_data(path.data(), path.abs_transform())),
+ ),
+ usvgr::Node::Group(_) => ("group", None),
+ usvgr::Node::Image(_) => ("image", None),
+ usvgr::Node::Text(_) => ("text", None),
+ };
+ out.push(LabelledElement {
+ id: id.to_owned(),
+ kind,
+ x: bbox.x(),
+ y: bbox.y(),
+ width: bbox.width(),
+ height: bbox.height(),
+ outline,
+ });
+ }
+ }
+ if let usvgr::Node::Group(child) = node {
+ collect(child, out);
+ }
+ }
+}
+
+/// Every element of `tree` with a non-empty `id`, in drawing order.
+pub fn labelled_elements(tree: &usvgr::Tree) -> Vec<LabelledElement> {
+ let mut elements = Vec::new();
+ collect(tree.root(), &mut elements);
+ elements
+}
+
+fn escape_xml(text: &str) -> String {
+ text.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
+}
+
+/// Draws `elements` of `tree` over `frame` (a render of the same tree): path outlines, boxes
+/// around groups, images and text, and the `id` of each.
+pub fn draw_labels(
+ frame: &RgbaFrame,
+ tree: &usvgr::Tree,
+ elements: &[LabelledElement],
+ fontdb: &usvgr::fontdb::Database,
+ font_family: &str,
+) -> FFramesRendererResult<RgbaFrame> {
+ // Labels need a font even when the video brings none.
+ let system;
+ let fontdb = if fontdb.faces().next().is_some() {
+ fontdb
+ } else {
+ let mut db = usvgr::fontdb::Database::new();
+ db.load_system_fonts();
+ system = db;
+ &system
+ };
+ let size = tree.size();
+ // Lines and type keep the same size in pixels however large the frame is rendered.
+ let unit = size.width() / frame.width as f32;
+ let font_size = 12. * unit;
+ let family = escape_xml(&sheet::label_font_family(fontdb, font_family));
+
+ let mut shapes = String::new();
+ let mut labels = String::new();
+ for element in elements.iter().take(MAX_LABELS) {
+ let colour = if element.kind == "path" {
+ "#ff2bd6"
+ } else {
+ "#ffd400"
+ };
+ match &element.outline {
+ Some(outline) => {
+ let _ = write!(
+ shapes,
+ r#"<path d="{outline}" fill="none" stroke="{colour}" stroke-width="{}" />"#,
+ 1.2 * unit
+ );
+ }
+ None => {
+ let _ = write!(
+ shapes,
+ r#"<rect x="{}" y="{}" width="{}" height="{}" fill="none" stroke="{colour}" stroke-width="{}" stroke-dasharray="{} {}" />"#,
+ element.x,
+ element.y,
+ element.width,
+ element.height,
+ 1.2 * unit,
+ 6. * unit,
+ 4. * unit
+ );
+ }
+ }
+ // Paths are labelled at their centre, containers at their top left corner.
+ let (x, y) = if element.kind == "path" {
+ (
+ element.x + element.width / 2.,
+ element.y + element.height / 2.,
+ )
+ } else {
+ (element.x + 2. * unit, element.y + font_size)
+ };
+ let text = escape_xml(&element.id);
+ let width = text.chars().count() as f32 * font_size * 0.6 + 6. * unit;
+ let anchor_x = if element.kind == "path" {
+ x - width / 2.
+ } else {
+ x
+ };
+ let _ = write!(
+ labels,
+ r##"<rect x="{}" y="{}" width="{width}" height="{}" rx="{}" fill="#000000" fill-opacity="0.7" /><text x="{}" y="{}" font-size="{font_size}" font-family="{family}" fill="#ffffff">{text}</text>"##,
+ anchor_x,
+ y - font_size * 0.95,
+ font_size * 1.3,
+ 2. * unit,
+ anchor_x + 3. * unit,
+ y,
+ );
+ }
+
+ let svg = format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" viewBox="0 0 {} {}">{shapes}{labels}</svg>"#,
+ frame.width,
+ frame.height,
+ size.width(),
+ size.height()
+ );
+ let overlay = usvgr::Tree::from_str(&svg, &usvgr::Options::default(), fontdb)
+ .map_err(|err| FFramesRendererError::Internal(format!("element labels: {err}")))?;
+ let mut pixmap = sheet::to_pixmap(frame)?;
+ let ctx = svgr::Context::new_from_pixmap_unsafe(&pixmap);
+ svgr::render(
+ &overlay,
+ super::fit_transform(&overlay, frame.width, frame.height),
+ &mut pixmap.as_mut(),
+ &mut svgr::SvgrCache::none(),
+ &svgr::PixmapPool::new(),
+ &ctx,
+ );
+ Ok(RgbaFrame::from_premultiplied(
+ frame.width,
+ frame.height,
+ pixmap.take(),
+ ))
+}
diff --git a/fframes/src/renderer/mod.rs b/fframes/src/renderer/mod.rs
index 11d222a2..5acd0c95 100644
--- a/fframes/src/renderer/mod.rs
+++ b/fframes/src/renderer/mod.rs
@@ -44,6 +44,9 @@ pub use frame_guard::*;
mod preview;
pub use preview::*;
+pub mod continuity;
+#[cfg(feature = "cpu_renderer")]
+pub mod element_labels;
#[cfg(feature = "cpu_renderer")]
pub mod sheet;
pub mod snapshot;
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index 01004734..3a1d2562 100644
--- a/fframes/src/renderer/preview.rs
+++ b/fframes/src/renderer/preview.rs
@@ -51,6 +51,24 @@ impl RgbaFrame {
.expect("RgbaFrame pixel buffer matches its size")
}
+ /// The pixels of a rectangle of the frame, clamped to the frame.
+ pub fn crop(&self, x: u32, y: u32, width: u32, height: u32) -> RgbaFrame {
+ let x = x.min(self.width.saturating_sub(1));
+ let y = y.min(self.height.saturating_sub(1));
+ let width = width.clamp(1, self.width - x);
+ let height = height.clamp(1, self.height - y);
+ let mut pixels = Vec::with_capacity((width * height * 4) as usize);
+ for row in y..y + height {
+ let start = ((row * self.width + x) * 4) as usize;
+ pixels.extend_from_slice(&self.pixels[start..start + (width * 4) as usize]);
+ }
+ RgbaFrame {
+ width,
+ height,
+ pixels,
+ }
+ }
+
pub fn save_png(&self, path: impl AsRef<Path>) -> FFramesRendererResult<()> {
let path = path.as_ref();
image::save_buffer(
diff --git a/fframes/src/renderer/sheet.rs b/fframes/src/renderer/sheet.rs
index 30e00723..2cbdbbad 100644
--- a/fframes/src/renderer/sheet.rs
+++ b/fframes/src/renderer/sheet.rs
@@ -11,7 +11,7 @@ pub struct SheetCell {
pub label: String,
}
-fn to_pixmap(frame: &RgbaFrame) -> FFramesRendererResult<tiny_skia::Pixmap> {
+pub(crate) fn to_pixmap(frame: &RgbaFrame) -> FFramesRendererResult<tiny_skia::Pixmap> {
let mut data = frame.pixels.clone();
for px in data.as_chunks_mut::<4>().0 {
let a = u32::from(px[3]);
@@ -38,7 +38,7 @@ fn escape_xml(text: &str) -> String {
}
/// Font families for labels: the requested one, then whatever the database has.
-fn label_font_family(fontdb: &usvgr::fontdb::Database, preferred: &str) -> String {
+pub(crate) fn label_font_family(fontdb: &usvgr::fontdb::Database, preferred: &str) -> String {
let mut families = vec![format!("'{}'", preferred)];
if let Some(face) = fontdb.faces().next()
&& let Some((family, _)) = face.families.first()
diff --git a/fframes/src/renderer/tests/preview_tests.rs b/fframes/src/renderer/tests/preview_tests.rs
index a088e1ca..f2a767fd 100644
--- a/fframes/src/renderer/tests/preview_tests.rs
+++ b/fframes/src/renderer/tests/preview_tests.rs
@@ -120,3 +120,84 @@ fn inspect_reports_missing_media_and_empty_frames() {
);
assert!(kinds.iter().any(|d| matches!(d, Diagnostic::EmptyFrame)));
}
+
+struct Labelled;
+
+impl Video for Labelled {
+ const FPS: usize = 10;
+ const WIDTH: usize = 200;
+ const HEIGHT: usize = 100;
+ const BACKGROUND_COLOR: Color = Color::rgb(255, 255, 255);
+
+ fn duration(&self) -> crate::Duration<'_> {
+ crate::Duration::Frames(1)
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+
+ fn render_frame<'a>(&'a self, _: Frame, _: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ crate::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">
+ <g id="group" transform="translate(100 0)">
+ <rect id="box" x="10" y="20" width="30" height="40" fill="#336699" />
+ </g>
+ <path id="triangle" d="M10 90 L50 50 L60 90 Z" fill="#cc3300" />
+ <rect x="0" y="0" width="5" height="5" fill="#000000" />
+ </svg>
+ )
+ }
+}
+
+#[test]
+fn elements_with_ids_are_listed_and_labelled() {
+ use crate::renderer::element_labels::{draw_labels, labelled_elements};
+
+ let video = Labelled;
+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();
+ let mut renderer = CpuFrameRenderer::default();
+ let tree = previewer.svg_tree(0).unwrap();
+ let elements = labelled_elements(&tree);
+
+ let ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect();
+ assert_eq!(ids, ["group", "box", "triangle"]);
+ let rect = &elements[1];
+ assert_eq!(rect.kind, "path");
+ // Bounding boxes are in the video's coordinates, transforms applied.
+ assert_eq!(
+ (rect.x, rect.y, rect.width, rect.height),
+ (110., 20., 30., 40.)
+ );
+ assert_eq!(elements[0].kind, "group");
+
+ let frame = previewer.render(0, &mut renderer).unwrap();
+ let labelled =
+ draw_labels(&frame, &tree, &elements, previewer.font_db(), "sans-serif").unwrap();
+ assert_eq!(
+ (labelled.width, labelled.height),
+ (frame.width, frame.height)
+ );
+ assert_ne!(labelled.pixels, frame.pixels);
+}
+
+#[test]
+fn frames_crop_to_a_clamped_rectangle() {
+ let video = Labelled;
+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();
+ let frame = previewer
+ .render(0, &mut CpuFrameRenderer::default())
+ .unwrap();
+
+ let crop = frame.crop(110, 20, 30, 40);
+ assert_eq!((crop.width, crop.height), (30, 40));
+ // The crop is exactly the blue rect.
+ assert!(
+ crop.pixels
+ .chunks(4)
+ .all(|px| px == [0x33, 0x66, 0x99, 255])
+ );
+
+ let corner = frame.crop(190, 90, 50, 50);
+ assert_eq!((corner.width, corner.height), (10, 10));
+}
diff --git a/fframes/src/tests.rs b/fframes/src/tests.rs
index 367f5828..bb9968f6 100644
--- a/fframes/src/tests.rs
+++ b/fframes/src/tests.rs
@@ -113,3 +113,44 @@ fn test_audio_map_resolve() {
]
);
}
+
+/// `include_media_dir!` mixes audio down to mono unless it gets the `stereo` option.
+mod embedded_audio_channels {
+ use crate::StaticMediaProvider;
+
+ mod stereo {
+ fframes_media_dir_macro::include_media_dir!(pub struct Media, "fframes/test-media/stereo", stereo);
+ }
+ mod mono {
+ fframes_media_dir_macro::include_media_dir!(pub struct Media, "fframes/test-media/stereo");
+ }
+
+ fn channels(audio: &crate::AudioData) -> (Vec<f32>, Option<Vec<f32>>) {
+ let crate::AudioData::Preloaded(data) = audio else {
+ panic!("embedded audio is preloaded");
+ };
+ (
+ data.samples.to_vec(),
+ data.right.as_ref().map(|r| r.to_vec()),
+ )
+ }
+
+ #[test]
+ fn stereo_option_keeps_both_channels() {
+ let media = stereo::Media::prepare().unwrap();
+ let (left, right) = channels(&media.tone_wav);
+ let right = right.expect("the right channel is embedded");
+ assert_eq!(left.len(), right.len());
+ // The fixture has a tone on the left and silence on the right.
+ assert!(left.iter().any(|s| s.abs() > 0.1));
+ assert!(right.iter().all(|s| s.abs() < 1e-3));
+ }
+
+ #[test]
+ fn audio_is_mono_by_default() {
+ let media = mono::Media::prepare().unwrap();
+ let (mixed, right) = channels(&media.tone_wav);
+ assert!(right.is_none());
+ assert!(mixed.iter().any(|s| s.abs() > 0.05));
+ }
+}
diff --git a/fframes/test-media/stereo/tone.wav b/fframes/test-media/stereo/tone.wav
new file mode 100644
index 00000000..31a4b138
Binary files /dev/null and b/fframes/test-media/stereo/tone.wav differ
diff --git a/media-dir-macro/src/lib.rs b/media-dir-macro/src/lib.rs
index 5f472f3b..181b5e2e 100644
--- a/media-dir-macro/src/lib.rs
+++ b/media-dir-macro/src/lib.rs
@@ -11,6 +11,16 @@ use std::{
use syn::{Ident, parse_macro_input};
/// Embed the contents of a directory in your crate.
+///
+/// ```ignore
+/// include_media_dir!(pub struct Media, "examples/my-video/media");
+/// // Keep both channels of stereo audio files (twice the embedded size):
+/// include_media_dir!(pub struct Media, "examples/my-video/media", stereo);
+/// ```
+///
+/// Every file becomes a field of the struct. Fonts are embedded as they are; images,
+/// subtitles and audio are decoded at compile time. Audio is mixed down to mono unless the
+/// `stereo` option is given; mono files stay mono either way.
#[proc_macro]
pub fn include_media_dir(input: TokenStream) -> TokenStream {
let fframes_crate_ident = resolve_fframes_crate_ident();
@@ -19,9 +29,10 @@ pub fn include_media_dir(input: TokenStream) -> TokenStream {
visibility,
ident,
path,
+ stereo,
} = parse_macro_input!(input as parser::IncludeMediaDirInput);
- let media_files = read_media_files_dir(&path);
+ let media_files = read_media_files_dir(&path, stereo);
let fields = media_files
.iter()
.map(|field| MediaFile::to_type_tokens(field, &fframes_crate_ident));
@@ -242,7 +253,8 @@ enum MediaVariant {
impl MediaVariant {
fn from_extension(file_name: &str, path: &Path) -> Option<Self> {
match path.extension()?.to_str()? {
- // Decoded to mono samples at compile time, every format ffmpeg reads works.
+ // Decoded to samples at compile time (mono unless `stereo`), every format ffmpeg
+ // reads works.
"mp3" | "wav" | "flac" | "aac" | "ogg" | "m4a" => Some(MediaVariant::Audio),
"ttf" | "ttc" | "otf" | "otc" => Some(MediaVariant::Font),
"jpeg" | "png" | "jpg" => Some(MediaVariant::Image),
@@ -262,6 +274,25 @@ struct MediaFile {
filename: String,
ident: syn::Ident,
variant: MediaVariant,
+ /// Audio only: keep the right channel of stereo files.
+ stereo: bool,
+}
+
+/// A `&'static [f32]` expression for samples embedded as an aligned byte literal.
+fn samples_tokens(samples: &[f32], fframes_crate_ident: &syn::Ident) -> proc_macro2::TokenStream {
+ let literal = Literal::byte_string(bytemuck::cast_slice::<f32, u8>(samples));
+ quote! {
+ {
+ static ALIGNED_LITERAL: &FFramesForceAlignTo<f32, [u8]> = &FFramesForceAlignTo {
+ _align: [],
+ bytes: *#literal
+ };
+
+ std::borrow::Cow::Borrowed(
+ #fframes_crate_ident::bytemuck::cast_slice::<u8, f32>(&ALIGNED_LITERAL.bytes)
+ )
+ }
+ }
}
impl MediaFile {
@@ -295,30 +326,36 @@ impl MediaFile {
fn inline_file(&self, fframes_crate_ident: &syn::Ident) -> proc_macro2::TokenStream {
match self.variant {
MediaVariant::Audio => {
+ let decoded = if self.stereo {
+ fframes_media::PreloadedAudioData::decode_raw_file_stereo(None, &self.path)
+ } else {
+ fframes_media::PreloadedAudioData::decode_raw_file(None, &self.path)
+ };
let fframes_media::PreloadedAudioData {
samples,
sample_rate,
- ..
- } = fframes_media::PreloadedAudioData::decode_raw_file(None, &self.path).unwrap();
+ right,
+ } = decoded.unwrap_or_else(|err| {
+ panic!(
+ "Unable to decode the audio file {}: {err:?}",
+ self.path.display()
+ )
+ });
- let bytes = bytemuck::cast_slice::<f32, u8>(&samples);
- let literal = Literal::byte_string(bytes);
+ let samples = samples_tokens(&samples, fframes_crate_ident);
+ let right = if let Some(right) = right {
+ let right = samples_tokens(&right, fframes_crate_ident);
+ quote! { Some(#right) }
+ } else {
+ quote! { None }
+ };
quote! {
#fframes_crate_ident::AudioData::Preloaded(
#fframes_crate_ident::media::PreloadedAudioData {
- samples: {
- static ALIGNED_LITERAL: &FFramesForceAlignTo<f32, [u8]> = &FFramesForceAlignTo {
- _align: [],
- bytes: *#literal
- };
-
- std::borrow::Cow::Borrowed(
- #fframes_crate_ident::bytemuck::cast_slice::<u8, f32>(&ALIGNED_LITERAL.bytes)
- )
- },
+ samples: #samples,
sample_rate: #sample_rate,
- right: None,
+ right: #right,
}
)
}
@@ -475,7 +512,7 @@ fn create_image_identifier_for_platform_wasm(
}
}
-fn read_media_files_dir(path: &Path) -> Vec<MediaFile> {
+fn read_media_files_dir(path: &Path, stereo: bool) -> Vec<MediaFile> {
let children = read_dir(path).unwrap_or_else(|e| {
panic!(
"Unable to read the entries in \"{}\": {}",
@@ -501,6 +538,7 @@ fn read_media_files_dir(path: &Path) -> Vec<MediaFile> {
variant,
filename: file_name.to_owned(),
path: child,
+ stereo,
});
}
} else {
diff --git a/media-dir-macro/src/parser.rs b/media-dir-macro/src/parser.rs
index ac7dbcdb..6bd245b1 100644
--- a/media-dir-macro/src/parser.rs
+++ b/media-dir-macro/src/parser.rs
@@ -10,6 +10,8 @@ pub struct IncludeMediaDirInput {
pub path: PathBuf,
pub ident: syn::Ident,
pub visibility: syn::Visibility,
+ /// Keep both channels of stereo audio files instead of mixing them down to mono.
+ pub stereo: bool,
}
impl Parse for IncludeMediaDirInput {
@@ -23,10 +25,24 @@ impl Parse for IncludeMediaDirInput {
let path = std::fs::canonicalize(path_literal.value())
.map_err(|err| syn::Error::new(path_literal.span(), format!("{err}\nMedia dir should be relative cargo project root (the project or workspace Cargo.toml directory)")))?;
+ let mut stereo = false;
+ if input.parse::<Option<Comma>>()?.is_some() && !input.is_empty() {
+ let option = input.parse::<syn::Ident>()?;
+ if option != "stereo" {
+ return Err(syn::Error::new(
+ option.span(),
+ "unknown option, the only one is `stereo` (keep both channels of stereo audio)",
+ ));
+ }
+ stereo = true;
+ input.parse::<Option<Comma>>()?;
+ }
+
Ok(Self {
path,
ident,
visibility,
+ stereo,
})
}
}
diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.md
index e56d7398..6a2e5b9d 100644
--- a/skills/fframes-video/SKILL.md
+++ b/skills/fframes-video/SKILL.md
@@ -171,9 +171,13 @@ After every change:
appears on a scene's first frames is usually an entrance; check it with a strip.
3. `$R strip <scene or range> -n 12` writes a contact sheet (`strip.png`): evenly spaced frames
in one labelled image. Open it with your image tool. It is the fastest way to judge layout,
- rhythm and motion.
+ rhythm and motion. `$R strip 2s,5s,9s` puts chosen times side by side.
4. `$R frame Intro@end,Outro@50%` writes full-size PNGs into `frames/` for detail checks
- (typography, alignment, contrast) and prints problems found in those frames.
+ (typography, alignment, contrast) and prints problems found in those frames. Judge small
+ details (contact between elements, edges, small shapes) on a sharp zoomed crop, never on a
+ scaled-down frame: `$R frame 3s --crop 1100,520,240,120` (video pixels, zoomed to about
+ 960 px wide). `--ids` outlines and names every element that has an `id`, to find which
+ shape is which.
5. `$R onion "[email protected]@1s" -n 6` blends frames into one image (`onion.png`) to show the
path and spacing of a movement: easing, overshoot, stagger.
6. `$R preview Intro` opens a real-time window with sound for the user to watch (space
@@ -184,6 +188,12 @@ After every change:
When an encoded sample is needed, `$R render Intro --draft` encodes one scene at half
resolution. `$R render` writes the full video for a requested final export.
+Before showing a finished video, run `$R inspect --pops`: it renders every frame small and
+warns about pops, parts of the picture that change in one frame between still frames, like an
+element that appears, vanishes or jumps in front of another one instead of moving there. Each
+warning gives the `frame ... --crop ...` command to look at it; repeats of the same region
+(counters, blinking lights) are grouped into one warning.
+
Rules:
- Look at the PNGs before saying anything looks good.
- Prefer `strip` to many `frame` calls; add `--scale 0.5` when composition is all you need.
@@ -203,9 +213,9 @@ times with commas.
| command | use it to |
| --- | --- |
| `timeline` | see scenes, durations, audio tracks and their mix settings |
-| `inspect [RANGE] [--every 0.1s \| --all-frames] [--fail-on warning]` | find problems without rendering pixels |
-| `strip [RANGE] -n N [--columns 4] [--width 480]` | review flow and motion in one image |
-| `frame TIMES [-o dir] [--svg]` | full-size PNGs (and the laid-out SVG) of chosen frames |
+| `inspect [RANGE] [--every 0.1s \| --all-frames] [--fail-on warning] [--pops]` | find problems without rendering pixels; `--pops` also finds elements that pop in or out |
+| `strip [RANGE \| TIMES] -n N [--columns 4] [--width 480] [--crop x,y,w,h]` | review flow and motion in one image |
+| `frame TIMES [-o dir] [--svg] [--crop x,y,w,h] [--zoom N] [--ids]` | full-size PNGs (and the laid-out SVG) of chosen frames, sharp crops, labelled elements |
| `onion RANGE -n N` | see a movement's trajectory and easing |
| `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 |
@@ -284,8 +294,8 @@ The short version of `references/design.md`:
## 6. Sound
-Put audio files in `media/` (compiled in, mono) or load a folder at runtime with
-`MediaDirectory` for stereo, then place them:
+Put audio files in `media/` (compiled in, mono unless `include_media_dir!(.., "media", stereo)`)
+or load a folder at runtime with `MediaDirectory`, then place them:
```rust
AudioMap::from([
diff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.md
index bc0bb4cf..9ca552c8 100644
--- a/skills/fframes-video/references/api.md
+++ b/skills/fframes-video/references/api.md
@@ -168,7 +168,8 @@ family, size and weight in the `<text>` attributes. `text-anchor="middle"` cente
- `include_media_dir!(pub struct MyMedia, "media")` embeds a folder; the path is relative to
the Cargo workspace root, which in a generated project is the project folder. Call
- `MyMedia::prepare()` in `main.rs`. Fonts register by family name, audio decodes to mono.
+ `MyMedia::prepare()` in `main.rs`. Fonts register by family name, audio decodes to mono;
+ `include_media_dir!(pub struct MyMedia, "media", stereo)` keeps stereo files stereo.
- Large or stereo files: `let dir = MediaDirectory::read_folder("assets")?; let media = dir.process_media_source()?;`
and combine providers with `CombinedMediaProvider::from([&static_media as &dyn MediaProvider, &media])`.
- Video frames: `frame.get_synced_video_frame(ctx, "clip.mp4", &SyncVideoFrameInput { start_from, looping, editor_fallback_image })`
diff --git a/skills/fframes-video/references/audio.md b/skills/fframes-video/references/audio.md
index 2a77cb2e..4ea90482 100644
--- a/skills/fframes-video/references/audio.md
+++ b/skills/fframes-video/references/audio.md
@@ -5,8 +5,9 @@ and ask the user to listen in `cargo run --release -- preview`.
## Files
-- Short SFX and music can live in `media/` (embedded, decoded to mono at compile time; mp3,
- wav, flac, aac, ogg, m4a).
+- Short SFX and music can live in `media/` (embedded, decoded at compile time; mp3, wav, flac,
+ aac, ogg, m4a). Embedded audio is mono unless the macro gets the `stereo` option:
+ `include_media_dir!(pub struct Media, "media", stereo)` keeps both channels (twice the size).
- Stereo music, voice-overs and anything large: a folder loaded at runtime keeps stereo:
```rust