Skip to content

programmatic video rendering framework that is actually fast

feat: Agent-friendly CLI, stereo audio mixer and project scaffolding (#139)

Dmitriy Kovalenko410b4be4ca2b
diff --git a/AGENTS.md b/AGENTS.md
index 30b932ff..be622175 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -234,6 +234,8 @@ cargo test -- --nocapture
/svgr-macro # The svgr! procedural macro (SVG DSL + static-subtree hashing)
/media-dir-macro # include_media_dir! (embeds a media folder into the binary)
/webvtt-parser # Subtitle format parser
+/cargo-fframes # `cargo fframes new`: project scaffolding (templates/)
+/scripts/new-video.sh # curl | bash bootstrap for cargo-fframes
/e2e # End-to-end visual regression test
/examples # Example video projects (each is a lib + bin + editor bridge)
```
@@ -249,61 +251,41 @@ plugs it into the web editor for live preview. `examples/hello-world` is the min
### 1. Scaffold the crate
```bash
-cp -r examples/hello-world examples/my-video
-rm -rf examples/my-video/{out.mp4,test_render,editor/node_modules,Cargo.lock}
+just new my-video # = cargo run -p cargo-fframes -- fframes new my-video --dir examples/my-video --yes
+cargo fframes new my-video --template multi-scene --fps 60 --backend skia-metal --yes # anywhere
+curl -fsSL https://raw.githubusercontent.com/dmtrKovalenko/fframes/main/scripts/new-video.sh | bash -s -- my-video
```
-Then rename every occurrence of `hello-world` / `hello_world` / `HelloWorld` in:
+`cargo-fframes new` asks for anything not passed when run in a terminal; `--yes` (or no
+terminal) never asks. Flags: `--template single-scene|multi-scene` (one scene in any format, or
+two scenes on a 16:9 grid), `--title`, `--format landscape|portrait|square|uhd`, `--fps`,
+`--backend cpu|skia-metal|skia-vulkan`, `--dir`, `--fframes-path <checkout>`. Inside this
+repository it uses workspace dependencies and registers the crate in the workspace members;
+elsewhere it pins the crates.io release matching its own version (`--git` for `main`,
+`--fframes-path` for a checkout) and makes the crate its own workspace. `release.sh` publishes
+`cargo-fframes` and `fframes_native_player` with the other crates on every push to main.
-- `examples/my-video/Cargo.toml` (package name, `[lib] name`, `[[bin]] name`)
-- `examples/my-video/src/{lib.rs,main.rs}` and the video module
-- `examples/my-video/editor/editor-bridge/{Cargo.toml,lib.rs}` and `editor/package.json`
-
-Register both crates in the workspace `Cargo.toml` `members` list:
-
-```toml
-"examples/my-video",
-"examples/my-video/editor/editor-bridge",
-```
-
-and add `just check-wasm my-video` to the `check-examples` recipe in the `justfile`. Run
-`yarn install` at the repository root once so the editor package picks up the new workspace.
-
-The crate layout that the tooling expects:
+The generated crate compiles and renders as is:
```
-examples/my-video/
- Cargo.toml # lib (cdylib + rlib) + bin gated by the `renderer` feature
- media/ # fonts, images, audio, subtitles embedded via include_media_dir!
- dynamic_media/ # optional: large files read at runtime (renderer only)
- src/lib.rs # `pub mod my_video; pub use my_video::*;`
- src/my_video.rs # the Video impl
- src/main.rs # CLI that calls fframes::render
- editor/editor-bridge/ # WASM crate, see step 9
- editor/{index.html,main.tsx,package.json,vite.config.ts}
+my-video/
+ Cargo.toml # fframes with the `cli` and `compile-time-svgtree` features
+ media/ # 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)
+ tests/frames.rs # frame snapshots + "no warnings in any frame"
```
-`Cargo.toml` essentials (feature names are ffmpeg codecs; keep `libav-agree-gpl` when using
-x264/x265):
-
-```toml
-[dependencies]
-fframes = { workspace = true, features = ["h264", "h265", "libav-agree-gpl"] }
-clap = { version = "4.3.4", features = ["derive"] }
-
-[features]
-default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"] # the editor bridge builds with default-features = false
-
-[lib]
-crate-type = ["cdylib", "rlib"]
-```
+For the web editor copy `examples/hello-world/editor` next to it and adapt step 9; gate the
+`cli` and `compile-time-svgtree` features behind a `renderer` feature like hello-world does,
+the editor bridge builds the library with `default-features = false`.
### 2. Media
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.
+their family name. Audio (`mp3`, `wav`, `flac`, `aac`, `ogg`, `m4a`) is decoded to mono at
+compile time; files loaded with `MediaDirectory` keep stereo.
```rust
use fframes::include_media_dir;
@@ -535,30 +517,100 @@ fframes::svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080"
draws nothing in their place, and the editor shows a placeholder.
- Requires the `compile-time-svgtree` feature (the default `renderer` feature of the examples).
-### 8. Render it
+### 7c. Audio mix
+
+`fn audio` places files on the timeline. Tuples still work; `AudioTrack` adds mix settings:
+
+```rust
+use fframes::{AudioMap, AudioTrack, AudioTimestamp::*, FadeCurve};
+
+AudioMap::from([
+ AudioTrack::new("music.mp3", Second(0.)..Eof).gain_db(-16.).fade_in(1.).fade_out(2.).duck_under_voice(),
+ AudioTrack::new("voice.wav", Second(0.5)..Eof).voice(),
+ AudioTrack::new("whoosh.wav", Second(4.25)..Eof).gain_db(-6.).pan(-0.4),
+ AudioTrack::new("take.wav", Second(10.)..Second(14.)).offset(3.2), // plays 3.2s..7.2s of the file
+])
+```
+
+- Tracks start at their exact sample (`Second(4.25)` is not rounded to a frame), overlapping
+ tracks are summed linearly and the master bus has a -1 dBFS lookahead limiter
+ (`RenderOptions::audio_mix`), output is stereo. Other sample rates are resampled with a
+ windowed sinc.
+- `duck_under_voice()` lowers a track by 12 dB while any `.voice()` track plays, ramping down
+ before the voice starts (`Ducking { depth_db, attack, hold, release, merge_gap }` to tune).
+- Fade curves: `EqualPower` (default), `Linear`, `SCurve`, `Exponential`. Cuts (offsets,
+ range renders) get 5 ms de-click fades.
+- Verify without listening: `audio analyze` (integrated/short-term loudness in LUFS, true
+ peak, clipping, silent ranges, loudness per scene, `--waveform` PNG with scenes and cues)
+ and `audio at 4.2s` (which files play, where in the file, at what level, ducked or not).
+ Aim for about -14 LUFS integrated for web video and a true peak below -1 dBTP.
+
+### 8. Render it: `fframes::cli`
-`main.rs` calls `fframes::render(output, &video, backend, &options)`; keep the CLI flags of the
-hello-world example (`--output`, `--video-codec`, `--concurrency`, `--verbose`).
+`main.rs` hands the video to `fframes::cli` (feature `cli`), which gives every video the same
+command line:
```rust
-let media = MyVideoMedia::prepare()?;
-fframes::render(
- "out.mp4",
- &MyVideo { media: &media, title: "World" },
- fframes::cpu::CpuRenderingBackend { cache_capacity: 20, ..Default::default() },
- &RenderOptions {
- media: Some(&media),
- logger: fframes_logger::FFramesLoggerVariant::Compact,
- video_encoder_options: EncoderOptions {
- preferred_encoder: Some("libx264"),
- codec_params: Some(&[("crf", "23"), ("preset", "slow")]),
- ..Default::default()
- },
- ..Default::default()
- },
-)?;
+use fframes::cli;
+
+fn main() -> std::process::ExitCode {
+ let media = MyVideoMedia::prepare().expect("media");
+ let video = MyVideo { media: &media, title: "World" };
+ cli::new(&video, RenderOptions { media: Some(&media), ..Default::default() }).run()
+}
+```
+
+The rest is optional and chains in any order:
+
+```rust
+cli::new(&video, options)
+ // Render with Skia. Frame previews (frame, strip, onion, snapshot) 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).
+ .preview(fframes_native_player::cli_preview)
+ // What `render` writes without `-o`.
+ .default_output("out.webm")
+ .run()
```
+Flags of your own go into a `#[derive(clap::Args)]` struct. Parse first when the video is built
+from them:
+
+```rust
+use fframes::cli::{self, clap};
+
+#[derive(Debug, clap::Args)]
+struct Args {
+ #[arg(long, default_value = "World", global = true)]
+ title: String,
+}
+
+let args = cli::parse::<Args>();
+let video = MyVideo { media: &media, title: &args.app.title.clone() };
+cli::new(&video, options).args(args).run()
+```
+
+See `examples/teej-podcast/src/main.rs`; `cargo fframes new` generates the same setup.
+
+| 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 |
+| `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 |
+| `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 |
+
+Global flags: `--json` (one JSON document on stdout, JSON progress events on stderr),
+`--scale 0.5`. Times: frames `120`, `3.2s`, `1:05`, `50%`, `start`/`end`, scenes `Intro`
+(`IntroScene` also matches), `#3`, `Intro[1]`, `[email protected]`/`@50%`/`@end`; ranges `a..b`,
+`a..`, `..b`, `all` or a scene name.
+
- Backends: `fframes::cpu::CpuRenderingBackend` (default, tiny-skia, multi-threaded) or the
Skia backend from `fframes_skia_renderer` with `SkiaFFramesRenderer::new_vulkan(&SkiaVulkanCtx::new(W, H)?, SkiaPipelineConfig { .. })`
(`features = ["vulkan"]`; `new_metal` with `metal`). The Skia backend walks the `svgr!` tree
@@ -566,8 +618,10 @@ fframes::render(
backend on 1080p (see `cargo run --release -p fframes_skia_renderer --features vulkan --example svgr_vs_skia`).
- macOS: request `hevc_videotoolbox` only with `fframes = { features = ["videotoolbox"] }`
(see `examples/teej-podcast/Cargo.toml`), otherwise the encoder silently falls back.
-- One frame to a PNG (fast iteration): `fframes::render_frame(index, &video, backend, &options)`
- returns RGBA bytes; `examples/teej-podcast` exposes it as `--preview --preview-frame N`.
+- In code: `fframes::Previewer::new(&video, &options)` keeps fonts, images and caches between
+ frames (`render`, `render_inspected`, `svg`, `inspect`, `timeline()`, `timeline_report()`);
+ `RenderOptions::frame_range` renders part of a video with matching audio.
+- A panic in `render_frame` fails the render with the frame, second and scene it happened in.
- `just render my-video` renders and opens the result; `just bench my-video` times it.
### 9. Editor preview
@@ -601,18 +655,23 @@ pub fn create_wasm_bridge() -> WasmBridge {
### 10. Verify before you finish
+Look at the video without playing it (`R` = `cargo run --release -p my-video --`):
+
```bash
-just clippy # -D warnings
-cargo fmt --all
-just check-wasm my-video
-cd examples/my-video && cargo run --release # render, then look at frames:
-ffmpeg -ss 5 -i out.mp4 -frames:v 1 frame5.png
+$R timeline # the structure is what you intended
+$R inspect # no errors or warnings in any frame
+$R strip -n 12 # overall flow; `strip Intro -n 8` for one scene
+$R frame Intro@end,Outro@50% # full size details, check text stays inside its boxes
+$R audio analyze --waveform w.png # levels, silence, cue positions
+$R render # final file
+cargo test -p my-video # frame snapshots
+just 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.
-Inspect at least one rendered frame per distinct layout and confirm text stays inside its boxes.
+Pixel snapshots of frames: `fframes::snapshot::assert_frames(&mut previewer, &mut renderer, &["Intro@1s"], &Default::default())`.
## Important Notes
diff --git a/Cargo.lock b/Cargo.lock
index fdee1103..d0be3049 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -241,6 +241,7 @@ version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"clap",
"fframes",
+ "fframes_native_player",
"fframes_skia_renderer",
]
@@ -303,6 +304,7 @@ name = "beta-example"
version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"fframes",
+ "fframes_native_player",
"fframes_skia_renderer",
"hello-world-example",
"lazy_static",
@@ -458,6 +460,14 @@ dependencies = [
"wayland-client",
]
+[[package]]
+name = "cargo-fframes"
+version = "1.0.0-beta.6.rc-3.2"
+dependencies = [
+ "clap",
+ "dialoguer",
+]
+
[[package]]
name = "cast"
version = "0.3.0"
@@ -656,9 +666,22 @@ dependencies = [
"encode_unicode",
"libc",
"once_cell",
+ "unicode-width",
"windows-sys 0.59.0",
]
+[[package]]
+name = "console"
+version = "0.16.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3"
+dependencies = [
+ "encode_unicode",
+ "libc",
+ "unicode-width",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
@@ -883,6 +906,17 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a"
+[[package]]
+name = "dialoguer"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "658bce805d770f407bc62102fca7c2c64ceef2fbcb2b8bd19d2765ce093980de"
+dependencies = [
+ "console 0.15.11",
+ "shell-words",
+ "thiserror 1.0.69",
+]
+
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -1067,6 +1101,7 @@ name = "fframes"
version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"approx",
+ "clap",
"colored",
"criterion",
"fframes-media",
@@ -1078,6 +1113,7 @@ dependencies = [
"konst",
"lazy_static",
"libm",
+ "log",
"lru",
"memmap",
"microfft",
@@ -1088,6 +1124,7 @@ dependencies = [
"rangemap",
"rayon",
"serde",
+ "serde_json",
"svgr",
"svgr-macro",
"ttf-parser 0.25.1",
@@ -1557,14 +1594,15 @@ dependencies = [
[[package]]
name = "indicatif"
-version = "0.16.2"
+version = "0.18.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d207dc617c7a380ab07ff572a6e52fa202a2a8f355860ac9c38e23f8196be1b"
+checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c"
dependencies = [
- "console",
- "lazy_static",
- "number_prefix",
- "regex",
+ "console 0.16.6",
+ "portable-atomic",
+ "unicode-width",
+ "unit-prefix",
+ "web-time",
]
[[package]]
@@ -2057,6 +2095,7 @@ version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"clap",
"fframes",
+ "fframes_native_player",
"fframes_skia_renderer",
"image",
]
@@ -2210,12 +2249,6 @@ dependencies = [
"syn 2.0.100",
]
-[[package]]
-name = "number_prefix"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
-
[[package]]
name = "objc"
version = "0.2.7"
@@ -2667,6 +2700,7 @@ version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"clap",
"fframes",
+ "fframes_native_player",
"fframes_skia_renderer",
"getrandom 0.2.15",
"image",
@@ -2752,6 +2786,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -3298,10 +3338,17 @@ version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"clap",
"fframes",
+ "fframes_native_player",
"fframes_skia_renderer",
"image",
]
+[[package]]
+name = "shell-words"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
+
[[package]]
name = "shlex"
version = "1.3.0"
@@ -3314,6 +3361,15 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+[[package]]
+name = "signal-lab"
+version = "0.1.0"
+dependencies = [
+ "fframes",
+ "fframes_native_player",
+ "fframes_skia_renderer",
+]
+
[[package]]
name = "simd-adler32"
version = "0.3.7"
@@ -3610,8 +3666,8 @@ version = "1.0.0-beta.6.rc-3.2"
dependencies = [
"clap",
"fframes",
+ "fframes_native_player",
"fframes_skia_renderer",
- "image",
]
[[package]]
@@ -3928,6 +3984,18 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
+[[package]]
+name = "unicode-width"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+
+[[package]]
+name = "unit-prefix"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
+
[[package]]
name = "usvgr"
version = "0.46.0"
diff --git a/Cargo.toml b/Cargo.toml
index 222039e1..b4819c1d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,7 @@ members = [
"fframes-native-player",
"media-dir-macro",
"render-bench",
+ "cargo-fframes",
# Examples
"examples/podcast",
"examples/podcast/editor/editor-bridge",
@@ -44,6 +45,7 @@ members = [
# maybe clean this up?
# "fframes-lyon-renderer",
+ "examples/signal-lab",
]
[workspace.dependencies]
diff --git a/cargo-fframes/Cargo.toml b/cargo-fframes/Cargo.toml
new file mode 100644
index 00000000..0188071c
--- /dev/null
+++ b/cargo-fframes/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "cargo-fframes"
+version = "1.0.0-beta.6.rc-3.2"
+edition = "2024"
+license = "MIT"
+repository = "https://github.com/dmtrKovalenko/fframes"
+homepage = "https://fframes.studio"
+description = "Creates new fframes video projects: `cargo fframes new my-video`"
+
+[dependencies]
+clap = { version = "4.5", features = ["derive"] }
+dialoguer = { version = "0.11", default-features = false }
+
+[[bin]]
+name = "cargo-fframes"
+path = "src/main.rs"
diff --git a/cargo-fframes/src/main.rs b/cargo-fframes/src/main.rs
new file mode 100644
index 00000000..044d2a33
--- /dev/null
+++ b/cargo-fframes/src/main.rs
@@ -0,0 +1,658 @@
+//! `cargo fframes new <name>`: creates a video project that renders, previews and tests
+//! out of the box.
+//!
+//! Interactive in a terminal (asks for everything that was not passed as a flag); with
+//! `--yes` or without a terminal it never asks and uses defaults, so scripts and AI agents
+//! can run it in one command.
+use clap::{Parser, Subcommand, ValueEnum};
+use std::io::IsTerminal;
+use std::path::{Path, PathBuf};
+use std::process::ExitCode;
+
+const FFRAMES_GIT: &str = "https://github.com/dmtrKovalenko/fframes";
+
+const LIB_SINGLE_SCENE: &str = include_str!("../templates/lib_single_scene.rs.tmpl");
+const LIB_MULTI_SCENE: &str = include_str!("../templates/lib_multi_scene.rs.tmpl");
+const MAIN_CPU: &str = include_str!("../templates/main_cpu.rs.tmpl");
+const MAIN_SKIA: &str = include_str!("../templates/main_skia.rs.tmpl");
+const FRAMES_TEST: &str = include_str!("../templates/frames_test.rs.tmpl");
+const CARGO_TOML: &str = include_str!("../templates/Cargo.toml.tmpl");
+const README: &str = include_str!("../templates/README.md.tmpl");
+const GITIGNORE: &str = include_str!("../templates/gitignore.tmpl");
+const FONT: &[u8] = include_bytes!("../templates/DMSans-Medium.ttf");
+
+#[derive(Debug, Parser)]
+#[command(name = "cargo-fframes", about = "fframes project tools")]
+struct Cli {
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Debug, Subcommand)]
+enum Command {
+ /// Create a new video project.
+ New(NewArgs),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum Backend {
+ /// Built-in tiny-skia renderer: no GPU and no Skia build, but ~10x slower and no preview window.
+ Cpu,
+ /// Skia on the GPU through Metal (macOS, default there). The first build compiles Skia (~20 min).
+ SkiaMetal,
+ /// Skia on the GPU through Vulkan (default on Linux and Windows).
+ SkiaVulkan,
+}
+
+impl Backend {
+ /// Skia on the platform's native GPU API: fast renders and the real-time `preview` window.
+ fn platform_default() -> Self {
+ if cfg!(target_os = "macos") {
+ Backend::SkiaMetal
+ } else {
+ Backend::SkiaVulkan
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum Template {
+ /// One scene that adapts to any format: a greeting that springs in over a moving glow.
+ SingleScene,
+ /// Two scenes on a 16:9 grid: a product announcement and an animated chart.
+ MultiScene,
+}
+
+impl Template {
+ fn lib(self) -> &'static str {
+ match self {
+ Template::SingleScene => LIB_SINGLE_SCENE,
+ Template::MultiScene => LIB_MULTI_SCENE,
+ }
+ }
+
+ /// Settled frames for the snapshot test.
+ fn snapshot_specs(self) -> &'static str {
+ match self {
+ Template::SingleScene => r#""2s", "4s""#,
+ Template::MultiScene => r#""ProductScene@3s", "DataScene@3s""#,
+ }
+ }
+
+ /// A range worth a contact sheet or a draft render in the README.
+ fn strip_range(self) -> &'static str {
+ match self {
+ Template::SingleScene => "0..2s",
+ Template::MultiScene => "DataScene",
+ }
+ }
+
+ fn entrance_range(self) -> &'static str {
+ match self {
+ Template::SingleScene => "0..1.5s",
+ Template::MultiScene => "[email protected]@1.5s",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum Format {
+ /// 1920x1080
+ Landscape,
+ /// 1080x1920 (reels, shorts, tiktok)
+ Portrait,
+ /// 1080x1080
+ Square,
+ /// 3840x2160
+ Uhd,
+}
+
+impl Format {
+ fn size(self) -> (usize, usize) {
+ match self {
+ Format::Landscape => (1920, 1080),
+ Format::Portrait => (1080, 1920),
+ Format::Square => (1080, 1080),
+ Format::Uhd => (3840, 2160),
+ }
+ }
+}
+
+#[derive(Debug, clap::Args)]
+struct NewArgs {
+ /// Crate name, e.g. `launch-video`. Also the directory name.
+ name: Option<String>,
+ /// Title shown in the video.
+ #[arg(long)]
+ title: Option<String>,
+ /// `single-scene` (any format) or `multi-scene` (two scenes, 16:9).
+ #[arg(long, value_enum)]
+ template: Option<Template>,
+ #[arg(long, value_enum)]
+ backend: Option<Backend>,
+ #[arg(long, value_enum)]
+ format: Option<Format>,
+ #[arg(long)]
+ fps: Option<usize>,
+ /// Where to create the project (default: ./<name>).
+ #[arg(long)]
+ dir: Option<PathBuf>,
+ /// Use a local fframes checkout instead of crates.io.
+ #[arg(long, conflicts_with = "git")]
+ fframes_path: Option<PathBuf>,
+ /// Depend on the `main` branch of the fframes repository instead of the crates.io release
+ /// matching this version of cargo-fframes.
+ #[arg(long)]
+ git: bool,
+ /// Never ask, use defaults for everything not passed.
+ #[arg(short, long)]
+ yes: bool,
+}
+
+struct Project {
+ name: String,
+ template: Template,
+ title: String,
+ backend: Backend,
+ width: usize,
+ height: usize,
+ fps: usize,
+ dir: PathBuf,
+}
+
+fn main() -> ExitCode {
+ // `cargo fframes new` runs `cargo-fframes fframes new`.
+ let args = std::env::args()
+ .enumerate()
+ .filter_map(|(i, arg)| (i != 1 || arg != "fframes").then_some(arg));
+ let cli = Cli::parse_from(args);
+
+ let result = match cli.command {
+ Command::New(args) => new(args),
+ };
+
+ match result {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(message) => {
+ eprintln!("error: {message}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn valid_name(name: &str) -> Result<(), String> {
+ let mut chars = name.chars();
+ match chars.next() {
+ Some(c) if c.is_ascii_lowercase() => {}
+ _ => return Err(format!("\"{name}\" must start with a lowercase letter")),
+ }
+ if !name
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
+ {
+ return Err(format!("\"{name}\" may only contain a-z, 0-9, - and _"));
+ }
+ Ok(())
+}
+
+fn pascal_case(name: &str) -> String {
+ name.split(['-', '_'])
+ .filter(|part| !part.is_empty())
+ .map(|part| {
+ let mut chars = part.chars();
+ chars
+ .next()
+ .map(|first| first.to_ascii_uppercase().to_string() + chars.as_str())
+ .unwrap_or_default()
+ })
+ .collect()
+}
+
+fn title_case(name: &str) -> String {
+ name.split(['-', '_'])
+ .filter(|part| !part.is_empty())
+ .map(|part| {
+ let mut chars = part.chars();
+ chars
+ .next()
+ .map(|first| first.to_ascii_uppercase().to_string() + chars.as_str())
+ .unwrap_or_default()
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+fn ask(args: NewArgs) -> Result<Project, String> {
+ let interactive =
+ !args.yes && std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
+ let theme = dialoguer::theme::SimpleTheme;
+ let prompt_err = |e: dialoguer::Error| e.to_string();
+
+ let name = match args.name {
+ Some(name) => name,
+ None if interactive => dialoguer::Input::<String>::with_theme(&theme)
+ .with_prompt("Project name")
+ .default("my-video".into())
+ .validate_with(|name: &String| valid_name(name))
+ .interact_text()
+ .map_err(prompt_err)?,
+ None => return Err("pass a project name: cargo fframes new <name>".into()),
+ };
+ valid_name(&name)?;
+
+ let title = match args.title {
+ Some(title) => title,
+ None if interactive => dialoguer::Input::<String>::with_theme(&theme)
+ .with_prompt("Title shown in the video")
+ .default(title_case(&name))
+ .interact_text()
+ .map_err(prompt_err)?,
+ None => title_case(&name),
+ };
+
+ let template = match args.template {
+ Some(template) => template,
+ None if interactive => {
+ let items = [
+ "single-scene - one scene that adapts to any format",
+ "multi-scene - two scenes: product announcement and animated chart (16:9)",
+ ];
+ let choice = dialoguer::Select::with_theme(&theme)
+ .with_prompt("Template")
+ .items(&items)
+ .default(0)
+ .interact()
+ .map_err(prompt_err)?;
+ [Template::SingleScene, Template::MultiScene][choice]
+ }
+ None => Template::SingleScene,
+ };
+
+ let backend = match args.backend {
+ Some(backend) => backend,
+ None if interactive => {
+ let items = [
+ "skia-metal - GPU on macOS: fast renders + preview window, first build ~20 min",
+ "skia-vulkan - GPU on Linux/Windows (macOS via MoltenVK)",
+ "cpu - no Skia build, slower renders, no preview window",
+ ];
+ let default = match Backend::platform_default() {
+ Backend::SkiaMetal => 0,
+ _ => 1,
+ };
+ let choice = dialoguer::Select::with_theme(&theme)
+ .with_prompt("Rendering backend")
+ .items(&items)
+ .default(default)
+ .interact()
+ .map_err(prompt_err)?;
+ [Backend::SkiaMetal, Backend::SkiaVulkan, Backend::Cpu][choice]
+ }
+ None => Backend::platform_default(),
+ };
+
+ let format = match args.format {
+ Some(format) => format,
+ None if interactive => {
+ let items = [
+ "landscape 1920x1080",
+ "portrait 1080x1920 (reels, shorts)",
+ "square 1080x1080",
+ "uhd 3840x2160",
+ ];
+ let choice = dialoguer::Select::with_theme(&theme)
+ .with_prompt("Format")
+ .items(&items)
+ .default(0)
+ .interact()
+ .map_err(prompt_err)?;
+ [
+ Format::Landscape,
+ Format::Portrait,
+ Format::Square,
+ Format::Uhd,
+ ][choice]
+ }
+ None => Format::Landscape,
+ };
+
+ let fps = match args.fps {
+ Some(fps) => fps,
+ None if interactive => {
+ let items = ["30", "60", "24", "25"];
+ let choice = dialoguer::Select::with_theme(&theme)
+ .with_prompt("Frames per second")
+ .items(&items)
+ .default(0)
+ .interact()
+ .map_err(prompt_err)?;
+ items[choice].parse().expect("fps choices are numbers")
+ }
+ None => 30,
+ };
+
+ let (width, height) = format.size();
+ if template == Template::MultiScene && width * 9 != height * 16 {
+ return Err(format!(
+ "the multi-scene template is laid out for 16:9 (landscape or uhd), not {width}x{height}; \
+ use --template single-scene for other formats"
+ ));
+ }
+ let dir = args.dir.unwrap_or_else(|| PathBuf::from(&name));
+ Ok(Project {
+ name,
+ template,
+ title,
+ backend,
+ width,
+ height,
+ fps,
+ dir,
+ })
+}
+
+/// The fframes repository containing `dir`, if any (its root `Cargo.toml` is a workspace
+/// and it has the `fframes` crate).
+fn find_fframes_workspace(dir: &Path) -> Option<PathBuf> {
+ let absolute = std::path::absolute(dir).ok()?;
+ absolute.ancestors().skip(1).find_map(|candidate| {
+ let manifest = std::fs::read_to_string(candidate.join("Cargo.toml")).ok()?;
+ (manifest.contains("[workspace]") && candidate.join("fframes/Cargo.toml").exists())
+ .then(|| candidate.to_path_buf())
+ })
+}
+
+fn render(template: &str, vars: &[(&str, String)]) -> String {
+ vars.iter().fold(template.to_owned(), |text, (key, value)| {
+ text.replace(&format!("{{{{{key}}}}}"), value)
+ })
+}
+
+fn register_workspace_member(root: &Path, member: &str) -> Result<(), String> {
+ let manifest_path = root.join("Cargo.toml");
+ let manifest = std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?;
+ if manifest.contains(&format!("\"{member}\"")) {
+ return Ok(());
+ }
+ let members = manifest
+ .find("members = [")
+ .ok_or("the workspace Cargo.toml has no `members = [` list")?;
+ let close = members
+ + manifest[members..]
+ .find("\n]")
+ .ok_or("can not find the end of the workspace members list")?;
+ let updated = format!(
+ "{}\n \"{member}\",{}",
+ &manifest[..close],
+ &manifest[close..]
+ );
+ std::fs::write(&manifest_path, updated).map_err(|e| e.to_string())
+}
+
+fn new(args: NewArgs) -> Result<(), String> {
+ let fframes_path = args.fframes_path.clone();
+ let from_git = args.git;
+ let project = ask(args)?;
+ let dir = &project.dir;
+
+ if dir.exists()
+ && std::fs::read_dir(dir)
+ .map_err(|e| e.to_string())?
+ .next()
+ .is_some()
+ {
+ return Err(format!("{} already exists and is not empty", dir.display()));
+ }
+
+ let workspace = find_fframes_workspace(dir);
+ let fframes_features = r#"features = ["compile-time-svgtree", "cli"]"#;
+ let skia_feature = match project.backend {
+ Backend::Cpu => None,
+ Backend::SkiaMetal => Some("metal"),
+ Backend::SkiaVulkan => Some("vulkan"),
+ };
+
+ // Skia renderer and the real-time player (the `preview` command) for GPU backends.
+ let skia_deps = |renderer_source: &str, player_source: &str| {
+ skia_feature
+ .map(|f| {
+ // Workspace dependencies can not turn default features off.
+ let player_features = if player_source == "workspace = true" {
+ format!("features = [\"{f}\"]")
+ } else {
+ format!("default-features = false, features = [\"{f}\", \"audio\"]")
+ };
+ format!(
+ "fframes_skia_renderer = {{ {renderer_source}, features = [\"{f}\"] }}\n\
+ fframes_native_player = {{ {player_source}, {player_features} }}\n"
+ )
+ })
+ .unwrap_or_default()
+ };
+
+ let (fframes_dep, skia_dep, media_path, standalone_tables, run) = match (
+ &workspace,
+ &fframes_path,
+ ) {
+ (Some(root), _) => {
+ let relative = std::path::absolute(dir)
+ .map_err(|e| e.to_string())?
+ .strip_prefix(root)
+ .map_err(|e| e.to_string())?
+ .to_string_lossy()
+ .replace('\\', "/");
+ (
+ format!("fframes = {{ workspace = true, {fframes_features} }}"),
+ skia_deps("workspace = true", "workspace = true"),
+ format!("{relative}/media"),
+ String::new(),
+ format!("cargo run --release -p {} --", project.name),
+ )
+ }
+ (None, source) => {
+ let [fframes_source, skia_source, player_source] = match source {
+ Some(path) => {
+ let path = std::path::absolute(path).map_err(|e| e.to_string())?;
+ ["fframes", "fframes-skia-renderer", "fframes-native-player"]
+ .map(|crate_dir| format!("path = \"{}\"", path.join(crate_dir).display()))
+ }
+ None if from_git => {
+ std::array::from_fn(|_| format!("git = \"{FFRAMES_GIT}\", branch = \"main\""))
+ }
+ // fframes and cargo-fframes are released together with the same version, so
+ // the generated project uses exactly the fframes this template was written for.
+ None => {
+ std::array::from_fn(|_| format!("version = \"={}\"", env!("CARGO_PKG_VERSION")))
+ }
+ };
+ (
+ format!("fframes = {{ {fframes_source}, {fframes_features} }}"),
+ skia_deps(&skia_source, &player_source),
+ "media".to_owned(),
+ // Its own workspace, and dependencies optimized in dev builds so that
+ // `cargo run` without --release still renders quickly.
+ "\n[workspace]\n\n[profile.dev]\nopt-level = 1\n\n[profile.dev.package.\"*\"]\nopt-level = 3\n"
+ .to_owned(),
+ "cargo run --release --".to_owned(),
+ )
+ }
+ };
+
+ let (skia_module, skia_ctx, skia_constructor, skia_hint, backend_label) = match project.backend
+ {
+ Backend::Cpu => ("", "", "", "", "built-in CPU"),
+ Backend::SkiaMetal => ("metal", "SkiaMetalCtx", "new_metal", "", "Skia (Metal)"),
+ Backend::SkiaVulkan => ("vulkan", "SkiaVulkanCtx", "new_vulkan", "", "Skia (Vulkan)"),
+ };
+
+ let lib_name = project.name.replace('-', "_");
+ let vars: Vec<(&str, String)> = vec![
+ ("crate_name", project.name.clone()),
+ ("lib_name", lib_name.clone()),
+ ("Struct", pascal_case(&project.name)),
+ ("title", project.title.replace('"', "\\\"")),
+ ("width", project.width.to_string()),
+ ("height", project.height.to_string()),
+ ("fps", project.fps.to_string()),
+ ("media_path", media_path),
+ // Codec features build ffmpeg from source; Windows links a prebuilt ffmpeg instead.
+ (
+ "codecs",
+ format!(
+ "\n[target.'cfg(not(windows))'.dependencies]\n{}\n",
+ fframes_dep.replace(
+ fframes_features,
+ r#"features = ["h264", "libav-agree-gpl"]"#
+ )
+ ),
+ ),
+ ("fframes_dep", fframes_dep),
+ ("skia_dep", skia_dep),
+ ("standalone_tables", standalone_tables),
+ ("skia_module", skia_module.to_owned()),
+ ("skia_ctx", skia_ctx.to_owned()),
+ ("skia_constructor", skia_constructor.to_owned()),
+ ("skia_hint", skia_hint.to_owned()),
+ ("backend_label", backend_label.to_owned()),
+ ("run", run.clone()),
+ (
+ "snapshot_specs",
+ project.template.snapshot_specs().to_owned(),
+ ),
+ ("strip_range", project.template.strip_range().to_owned()),
+ (
+ "entrance_range",
+ project.template.entrance_range().to_owned(),
+ ),
+ // The real-time player only exists in Skia projects.
+ (
+ "preview_line",
+ if project.backend == Backend::Cpu {
+ String::new()
+ } else {
+ format!(
+ "{run} preview # real-time GPU window with sound (space, h/l, j/k, q)\n"
+ )
+ },
+ ),
+ ];
+
+ let main = if project.backend == Backend::Cpu {
+ MAIN_CPU
+ } else {
+ MAIN_SKIA
+ };
+ let files: [(&str, String); 6] = [
+ ("Cargo.toml", render(CARGO_TOML, &vars)),
+ ("src/lib.rs", render(project.template.lib(), &vars)),
+ ("src/main.rs", render(main, &vars)),
+ ("tests/frames.rs", render(FRAMES_TEST, &vars)),
+ ("README.md", render(README, &vars)),
+ (".gitignore", render(GITIGNORE, &vars)),
+ ];
+
+ for (path, content) in &files {
+ let path = dir.join(path);
+ std::fs::create_dir_all(path.parent().expect("files are in the project"))
+ .map_err(|e| e.to_string())?;
+ std::fs::write(&path, content).map_err(|e| e.to_string())?;
+ }
+ std::fs::create_dir_all(dir.join("media")).map_err(|e| e.to_string())?;
+ std::fs::write(dir.join("media/DMSans-Medium.ttf"), FONT).map_err(|e| e.to_string())?;
+
+ if let Some(root) = &workspace {
+ let member = std::path::absolute(dir)
+ .map_err(|e| e.to_string())?
+ .strip_prefix(root)
+ .map_err(|e| e.to_string())?
+ .to_string_lossy()
+ .replace('\\', "/");
+ register_workspace_member(root, &member)?;
+ }
+
+ let cd = format!("cd {}", dir.display());
+ println!(
+ "Created {} ({}x{} @ {} fps, {backend_label})",
+ dir.display(),
+ project.width,
+ project.height,
+ project.fps
+ );
+ if workspace.is_some() {
+ println!("Added it to the fframes workspace members.");
+ }
+ if project.backend != Backend::Cpu {
+ println!("The first build compiles Skia from source, which takes a while.");
+ }
+ println!(
+ "\nNext:\n {cd}\n {run} timeline\n {run} frame 1s,50%,end # writes frames/*.png\n {run} strip -n 12 # writes strip.png{preview}\n {run} render # writes out.mp4\n cargo test # frame snapshots",
+ preview = if project.backend == Backend::Cpu {
+ String::new()
+ } else {
+ format!("\n {run} preview # real-time GPU window with sound")
+ }
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn names() {
+ assert_eq!(pascal_case("launch-video_2"), "LaunchVideo2");
+ assert_eq!(title_case("launch-video"), "Launch Video");
+ assert!(valid_name("launch-video").is_ok());
+ assert!(valid_name("Launch").is_err());
+ assert!(valid_name("1video").is_err());
+ assert!(valid_name("my video").is_err());
+ }
+
+ #[test]
+ fn templates_have_no_unknown_placeholders() {
+ let vars: Vec<(&str, String)> = [
+ "crate_name",
+ "lib_name",
+ "Struct",
+ "title",
+ "width",
+ "height",
+ "fps",
+ "media_path",
+ "fframes_dep",
+ "codecs",
+ "skia_dep",
+ "standalone_tables",
+ "skia_module",
+ "skia_ctx",
+ "skia_constructor",
+ "skia_hint",
+ "backend_label",
+ "run",
+ "preview_line",
+ "snapshot_specs",
+ "strip_range",
+ "entrance_range",
+ ]
+ .into_iter()
+ .map(|k| (k, "x".to_owned()))
+ .collect();
+ for template in [
+ LIB_SINGLE_SCENE,
+ LIB_MULTI_SCENE,
+ MAIN_CPU,
+ MAIN_SKIA,
+ FRAMES_TEST,
+ CARGO_TOML,
+ README,
+ GITIGNORE,
+ ] {
+ let rendered = render(template, &vars);
+ assert!(
+ !rendered.contains("{{"),
+ "unreplaced placeholder in:\n{rendered}"
+ );
+ }
+ }
+}
diff --git a/cargo-fframes/templates/Cargo.toml.tmpl b/cargo-fframes/templates/Cargo.toml.tmpl
new file mode 100644
index 00000000..2e35bf3c
--- /dev/null
+++ b/cargo-fframes/templates/Cargo.toml.tmpl
@@ -0,0 +1,18 @@
+[package]
+name = "{{crate_name}}"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+{{fframes_dep}}
+{{skia_dep}}{{codecs}}
+[lib]
+name = "{{lib_name}}"
+path = "src/lib.rs"
+doctest = false
+
+[[bin]]
+name = "{{crate_name}}"
+path = "src/main.rs"
+{{standalone_tables}}
diff --git a/cargo-fframes/templates/DMSans-Medium.ttf b/cargo-fframes/templates/DMSans-Medium.ttf
new file mode 100644
index 00000000..fc8a5ebd
Binary files /dev/null and b/cargo-fframes/templates/DMSans-Medium.ttf differ
diff --git a/cargo-fframes/templates/README.md.tmpl b/cargo-fframes/templates/README.md.tmpl
new file mode 100644
index 00000000..41bfd39f
--- /dev/null
+++ b/cargo-fframes/templates/README.md.tmpl
@@ -0,0 +1,29 @@
+# {{title}}
+
+A {{width}}x{{height}} @ {{fps}} fps video made with [fframes](https://github.com/dmtrKovalenko/fframes),
+rendered with the {{backend_label}} backend.
+
+| file | what |
+| --- | --- |
+| `src/lib.rs` | the video: scenes, animation, audio map |
+| `src/main.rs` | the command line (`fframes::cli`) |
+| `media/` | fonts, images and audio embedded into the binary |
+| `tests/frames.rs` | frame snapshots and a check of every frame for problems |
+
+## Work on it
+
+```sh
+{{run}} timeline # scenes, duration, audio tracks
+{{run}} frame 1s,50%,end # PNGs into frames/ and the problems found in them
+{{run}} strip {{strip_range}} -n 8 # contact sheet, writes strip.png
+{{run}} onion "{{entrance_range}}" # motion trail of an entrance, writes onion.png
+{{run}} inspect # missing media/fonts, clipped text, panics in any frame
+{{run}} render {{strip_range}} --draft # a part of the video, half resolution, fast preset
+{{run}} audio analyze --waveform w.png # loudness (LUFS), peaks, silence per scene
+{{run}} render # the final video, writes out.mp4
+{{preview_line}}cargo test # frame snapshots (FFRAMES_UPDATE_SNAPSHOTS=1 to accept)
+```
+
+Times accept frames (`120`), seconds (`3.2s`), `m:ss`, percentages (`50%`), scenes (`DataScene`,
+`#1`) and offsets inside scenes (`[email protected]`, `@50%`, `@end`). Add `--json` to any
+command for machine-readable output.
diff --git a/cargo-fframes/templates/frames_test.rs.tmpl b/cargo-fframes/templates/frames_test.rs.tmpl
new file mode 100644
index 00000000..2d295b14
--- /dev/null
+++ b/cargo-fframes/templates/frames_test.rs.tmpl
@@ -0,0 +1,50 @@
+//! Visual regression: renders a few frames and compares them with the approved PNGs in
+//! `_frame_snapshots/`. The first run only creates them, so look at the PNGs before you
+//! commit 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 {{lib_name}}::{ {{Struct}}Media, {{Struct}}Video };
+
+#[test]
+fn key_frames_match_snapshots() {
+ let media = {{Struct}}Media::prepare().unwrap();
+ let video = {{Struct}}Video::new(&media, "{{title}}");
+ 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(),
+ // Settled frames: the middle of a scene, not the end of it where it fades out.
+ &[{{snapshot_specs}}],
+ &snapshot::SnapshotOptions::default(),
+ );
+}
+
+#[test]
+fn no_problems_in_any_frame() {
+ // Converting a frame without rasterizing it is fast, so every frame is checked.
+ let media = {{Struct}}Media::prepare().unwrap();
+ let video = {{Struct}}Video::new(&media, "{{title}}");
+ 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/cargo-fframes/templates/gitignore.tmpl b/cargo-fframes/templates/gitignore.tmpl
new file mode 100644
index 00000000..b5dc1103
--- /dev/null
+++ b/cargo-fframes/templates/gitignore.tmpl
@@ -0,0 +1,12 @@
+/target
+out.mp4
+*.mp4
+!media/*.mp4
+frames/
+strip.png
+onion.png
+*.wav
+!media/*.wav
+test_render/
+_frame_snapshots/*.actual.png
+_frame_snapshots/*.diff.png
diff --git a/cargo-fframes/templates/lib_multi_scene.rs.tmpl b/cargo-fframes/templates/lib_multi_scene.rs.tmpl
new file mode 100644
index 00000000..3ce631d9
--- /dev/null
+++ b/cargo-fframes/templates/lib_multi_scene.rs.tmpl
@@ -0,0 +1,238 @@
+//! {{title}}: a two-scene fframes video, a product announcement and a data story.
+//!
+//! The video is a list of scenes. Each scene is a Rust struct that returns an SVG tree for
+//! every frame; `svgr!` is SVG with `{rust expressions}` in attributes and text. The layout
+//! is drawn on a 1920x1080 grid and scaled to the output size.
+//! Check your work with the CLI in `main.rs` (`cargo run --release -- --help`).
+use fframes::{
+ AnimateRuntimeInput, AudioMap, Color, Duration, FFramesContext, FontQuery, Frame, Scene,
+ Scenes, Svgr, TextOverflow, Transform, Video,
+ animation::{AnimationRuntime, Easing},
+ include_media_dir,
+};
+use std::sync::LazyLock;
+
+// Every file of `media/` is embedded into the binary. Fonts are used by family name.
+include_media_dir!(pub struct {{Struct}}Media, "{{media_path}}");
+
+pub const WIDTH: usize = {{width}};
+pub const HEIGHT: usize = {{height}};
+pub const SCENE_SECONDS: f32 = 6.0;
+const TOTAL_SECONDS: f32 = SCENE_SECONDS * 2.0;
+
+const PAPER: &str = "#eeeae2";
+const INK: &str = "#152c2b";
+const MUTED: &str = "#53645e";
+const GREEN: &str = "#709542";
+const LIME: &str = "#d2f87a";
+const FONT: &str = "DM Sans";
+/// The only weight in `media/`; add font files for more.
+const WEIGHT: u16 = 500;
+
+/// Fast start, long settle: good for things sliding into place.
+static EASE: LazyLock<AnimationRuntime> =
+ LazyLock::new(|| AnimationRuntime::new(0.8, &Easing::CubicBezier(0.16, 1.0, 0.3, 1.0)));
+/// Springs stop at their own settle time, 3 s is only the upper bound.
+static SPRING: LazyLock<AnimationRuntime> = LazyLock::new(|| {
+ AnimationRuntime::new(3.0, &Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 })
+});
+
+pub struct {{Struct}}Video<'a> {
+ pub media: &'a {{Struct}}Media,
+ product: ProductScene<'a>,
+ data: DataScene,
+}
+
+impl<'a> {{Struct}}Video<'a> {
+ pub fn new(media: &'a {{Struct}}Media, title: &'a str) -> Self {
+ Self {
+ media,
+ product: ProductScene { title },
+ data: DataScene,
+ }
+ }
+}
+
+impl std::fmt::Debug for {{Struct}}Video<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("{{Struct}}Video").finish()
+ }
+}
+
+impl Video for {{Struct}}Video<'_> {
+ const FPS: usize = {{fps}};
+ const WIDTH: usize = WIDTH;
+ const HEIGHT: usize = HEIGHT;
+ const BACKGROUND_COLOR: Color = Color::WHITE;
+
+ fn duration(&self) -> Duration<'_> {
+ // The sum of the scene durations.
+ Duration::Auto
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ // Put audio files into `media/` and place them on the timeline, e.g.:
+ //
+ // use fframes::{AudioTrack, AudioTimestamp::*};
+ // AudioMap::from([
+ // AudioTrack::new("music.mp3", Second(0.)..Eof).gain_db(-16.).fade_out(1.).duck_under_voice(),
+ // AudioTrack::new("voice.wav", Second(0.5)..Eof).voice(),
+ // AudioTrack::new("pop.wav", Second(SCENE_SECONDS + 0.25)..Eof).gain_db(-8.),
+ // ])
+ AudioMap::none()
+ }
+
+ fn define_scenes(&self) -> Scenes<'_> {
+ Scenes::from(vec![&self.product as &dyn Scene, &self.data])
+ }
+
+ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ // SVG skips zero-width rects, so the progress bar starts as a hairline.
+ let progress = (frame.seconds() / TOTAL_SECONDS * 1536.0).max(0.5);
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width={WIDTH} height={HEIGHT} viewBox="0 0 1920 1080">
+ <rect width="1920" height="1080" fill={PAPER} />
+ {ctx.render_scenes(&frame)}
+ <path d="M192 946 H1728" stroke="#b4bdb1" stroke-width="2" />
+ <rect x="192" y="945" width={progress} height="3" fill={GREEN} />
+ <text x="192" y="1002" font-family={FONT} font-weight={WEIGHT} font-size="28" fill={MUTED}>"MADE WITH FFRAMES"</text>
+ <text x="1728" y="1002" text-anchor="end" font-family={FONT} font-weight={WEIGHT} font-size="28" fill={MUTED}>"SVG + RUST"</text>
+ </svg>
+ )
+ }
+}
+
+/// 0 to 1 over 0.8 s from `start` (seconds into the scene).
+fn ramp(frame: &Frame, start: f32) -> f32 {
+ frame.animate_runtime(AnimateRuntimeInput { on_second: start, from: 0.0, to: 1.0, animation_runtime: &EASE })
+}
+
+/// Vertical offset that springs from 56 px to 0 at `start`.
+fn rise(frame: &Frame, start: f32) -> f32 {
+ frame.animate_runtime(AnimateRuntimeInput { on_second: start, from: 56.0, to: 0.0, animation_runtime: &SPRING })
+}
+
+/// The scene label at the top.
+fn label<'a>(number: &'a str, title: &'a str) -> Svgr<'a> {
+ fframes::svgr!(<g font-family={FONT} font-size="30" font-weight={WEIGHT} fill={INK}>
+ <circle cx="209" cy="147" r="17" fill={GREEN} />
+ <text x="252" y="158">{title}</text>
+ <text x="1728" y="158" text-anchor="end">{number}</text>
+ </g>)
+}
+
+/// Largest size up to `preferred` at which `text` fits `max_width`, measured with the real font.
+fn fit_size<'a>(frame: &mut Frame, ctx: &FFramesContext<'a, '_>, text: &'a str, preferred: usize, max_width: usize) -> usize {
+ let mut size = preferred;
+ loop {
+ let font = FontQuery { family: FONT, size, weight: WEIGHT, ..Default::default() };
+ match frame.text_width(ctx, font, text) {
+ Some(width) if width > max_width && size > 24 => size -= 4,
+ _ => return size,
+ }
+ }
+}
+
+#[derive(Debug)]
+struct ProductScene<'a> {
+ title: &'a str,
+}
+
+impl Scene for ProductScene<'_> {
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(SCENE_SECONDS)
+ }
+
+ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ // The title shrinks to fit the left column.
+ let title_size = fit_size(&mut frame, ctx, self.title, 208, 760);
+
+ // Status rows enter one after another, 0.12 s apart.
+ let rows: Vec<Svgr> = [("Build", "Ready"), ("Review", "Ready"), ("Publish", "Ready")]
+ .into_iter()
+ .enumerate()
+ .map(|(i, (name, status))| {
+ let y = 470 + i * 105;
+ let start = 0.7 + i as f32 * 0.12;
+ fframes::svgr!(<g opacity={ramp(&frame, start)} transform={Transform::translate(0, rise(&frame, start))}>
+ <rect x="1088" y={y - 46} width="540" height="82" rx="14" fill="#29403d" />
+ <text x="1124" y={y + 8} font-size="38" fill={PAPER}>{name}</text>
+ <text x="1586" y={y + 8} text-anchor="end" font-size="30" fill={LIME}>{status}</text>
+ </g>)
+ })
+ .collect();
+ let angle = frame.seconds() * 8.0;
+
+ fframes::svgr!(<g font-family={FONT} font-weight={WEIGHT}>
+ {label("01 / 02", "PRODUCT ANNOUNCEMENT")}
+ <text x="183" y="445" font-size={title_size} letter-spacing="-6" fill={INK}>{self.title}</text>
+ <text x="192" y="543" font-size="52" fill={INK}>"Your next release,"</text>
+ <text x="192" y="610" font-size="52" fill={INK}>"in motion."</text>
+ <g opacity={ramp(&frame, 0.4)}>
+ <rect x="192" y="703" width="380" height="76" rx="38" fill={INK} />
+ <text x="382" y="753" text-anchor="middle" font-size="32" fill={LIME}>"A FICTIONAL PRODUCT"</text>
+ </g>
+ <g transform={Transform::translate(0, rise(&frame, 0.0))}>
+ <rect x="1000" y="262" width="728" height="576" rx="32" fill={INK} />
+ <circle cx="1095" cy="352" r="14" fill={LIME} />
+ <text x="1138" y="365" font-size="38" fill={PAPER}>"Release / 01"</text>
+ {rows}
+ <g transform={format!("translate(1650 278) rotate({angle})")}>
+ <circle r="73" fill={LIME} />
+ <path d="M-34 0 H34 M0 -34 V34 M-24 -24 L24 24 M-24 24 L24 -24" stroke={INK} stroke-width="7" />
+ </g>
+ </g>
+ </g>)
+ }
+}
+
+#[derive(Debug)]
+struct DataScene;
+
+impl Scene for DataScene {
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(SCENE_SECONDS)
+ }
+
+ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ // Bars grow one after another; the counter lands on the last bar's value.
+ let bars: Vec<Svgr> = [("01", 24.0), ("02", 41.0), ("03", 58.0), ("04", 76.0)]
+ .into_iter()
+ .enumerate()
+ .map(|(i, (name, value))| {
+ let p = ramp(&frame, 0.25 + i as f32 * 0.1);
+ let height = (value * 4.3 * p).max(0.5);
+ let x = 982 + i * 188;
+ let fill = if i == 3 { GREEN } else { "#b4bdb1" };
+ fframes::svgr!(<g>
+ <rect x={x} y={798.0 - height} width="126" height={height} rx="8" fill={fill} />
+ <text x={x + 63} y={775.0 - height} text-anchor="middle" font-size="36" fill={INK}>{format!("{:.0}", value * p)}</text>
+ <text x={x + 63} y="851" text-anchor="middle" font-size="30" fill={MUTED}>{name}</text>
+ </g>)
+ })
+ .collect();
+ let count = 76.0 * ramp(&frame, 0.55);
+
+ // `text_fit` cuts a line that is too long and returns a `Cow<str>`; `svgr!` needs
+ // an owned `String` or a `&str`.
+ let heading = frame
+ .text_fit(
+ ctx,
+ FontQuery { family: FONT, size: 108, weight: WEIGHT, ..Default::default() },
+ "Give numbers a rhythm.",
+ 1536,
+ TextOverflow::Ellipsis,
+ )
+ .map(|text| text.into_owned())
+ .unwrap_or_else(|| "Give numbers a rhythm.".to_owned());
+
+ fframes::svgr!(<g font-family={FONT} font-weight={WEIGHT}>
+ {label("02 / 02", "DATA STORY")}
+ <text x="192" y="314" font-size="108" letter-spacing="-4" fill={INK}>{heading}</text>
+ <text x="180" y="646" font-size="248" letter-spacing="-12" fill={INK}>{format!("{count:.0}")}</text>
+ <text x="192" y="734" font-size="46" fill={INK}>"Weekly activations"</text>
+ <text x="192" y="802" font-size="30" fill={MUTED}>"ILLUSTRATIVE DATA / WEEKS 01-04"</text>
+ {bars}
+ </g>)
+ }
+}
diff --git a/cargo-fframes/templates/lib_single_scene.rs.tmpl b/cargo-fframes/templates/lib_single_scene.rs.tmpl
new file mode 100644
index 00000000..5116af36
--- /dev/null
+++ b/cargo-fframes/templates/lib_single_scene.rs.tmpl
@@ -0,0 +1,129 @@
+//! {{title}}: a single-scene fframes video.
+//!
+//! `render_frame` returns an SVG tree for every frame; `svgr!` is SVG with `{rust
+//! expressions}` in attributes and text. Check your work with the CLI in `main.rs`
+//! (`cargo run --release -- --help`).
+use fframes::{
+ AudioMap, Color, Duration, FFramesContext, FontQuery, Frame, Svgr, Transform, Video,
+ animation::Easing, include_media_dir,
+};
+use std::sync::OnceLock;
+
+// Every file of `media/` is embedded into the binary. Fonts are used by family name.
+include_media_dir!(pub struct {{Struct}}Media, "{{media_path}}");
+
+pub const WIDTH: usize = {{width}};
+pub const HEIGHT: usize = {{height}};
+/// 1.0 at 1080p, landscape or portrait: multiply sizes and distances by it.
+const UNIT: f32 = (if WIDTH < HEIGHT { WIDTH } else { HEIGHT }) as f32 / 1080.0;
+
+const FONT: &str = "DM Sans";
+/// The only weight in `media/`; add font files for more.
+const WEIGHT: u16 = 500;
+const INK: &str = "#0f172a";
+const MUTED: &str = "#475569";
+const ACCENT: &str = "#6366f1";
+
+pub struct {{Struct}}Video<'a> {
+ pub media: &'a {{Struct}}Media,
+ greeting: String,
+ /// Font size of the greeting, measured once so it fits the width.
+ greeting_size: OnceLock<usize>,
+}
+
+impl<'a> {{Struct}}Video<'a> {
+ pub fn new(media: &'a {{Struct}}Media, title: &str) -> Self {
+ Self {
+ media,
+ greeting: format!("Hello, {title}"),
+ greeting_size: OnceLock::new(),
+ }
+ }
+
+ /// Largest size up to 150 px (at 1080p) at which the greeting fits 80% of the width.
+ fn greeting_size<'b>(&'b self, frame: &mut Frame, ctx: &FFramesContext<'b, '_>) -> usize {
+ if let Some(size) = self.greeting_size.get() {
+ return *size;
+ }
+ let max_width = WIDTH as f32 * 0.8;
+ let mut size = (150. * UNIT) as usize;
+ loop {
+ let font = FontQuery { family: FONT, size, weight: WEIGHT, ..Default::default() };
+ match frame.text_width(ctx, font, &self.greeting) {
+ Some(width) if width as f32 > max_width && size > 24 => size -= 4,
+ // Only remember real measurements (fonts can be missing in the web editor).
+ Some(_) => return *self.greeting_size.get_or_init(|| size),
+ None => return size,
+ }
+ }
+ }
+}
+
+impl std::fmt::Debug for {{Struct}}Video<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("{{Struct}}Video").field("greeting", &self.greeting).finish()
+ }
+}
+
+impl Video for {{Struct}}Video<'_> {
+ const FPS: usize = {{fps}};
+ const WIDTH: usize = WIDTH;
+ const HEIGHT: usize = HEIGHT;
+ const BACKGROUND_COLOR: Color = Color::WHITE;
+
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(6.0)
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ // Put audio files into `media/` and place them on the timeline, e.g.:
+ //
+ // use fframes::{AudioTrack, AudioTimestamp::*};
+ // AudioMap::from([AudioTrack::new("music.mp3", Second(0.)..Eof).gain_db(-12.).fade_out(1.5)])
+ AudioMap::none()
+ }
+
+ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let spring = Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 };
+ let size = self.greeting_size(&mut frame, ctx);
+
+ // The greeting springs up and fades in, the subtitle follows, everything fades out.
+ let rise = frame.animate(&fframes::timeline!(at 0.2, animate 80.0_f32 => 0.0, spring));
+ let fade_in = frame.animate(&fframes::timeline!(at 0.2 => 0.6, animate 0.0_f32 => 1.0, Easing::EaseOut));
+ let subtitle = frame.animate(&fframes::timeline!(at 0.9 => 1.4, animate 0.0_f32 => 1.0, Easing::EaseOut));
+ let fade_out = frame.animate(&fframes::timeline!(at 5.4 => 5.9, animate 1.0_f32 => 0.0, Easing::EaseIn));
+ // SVG skips zero-sized rects, so the underline grows from a hairline.
+ let underline = frame.animate(&fframes::timeline!(at 0.6 => 1.3, animate 0.5_f32 => 360.0, Easing::EaseInOut)) * UNIT;
+ // A slow drift keeps the background alive while the text holds.
+ let drift = frame.animate(&fframes::timeline!(at 0.0 => 6.0, animate 0.0_f32 => 160.0, Easing::EaseInOut)) * UNIT;
+
+ let (cx, cy) = (WIDTH as f32 / 2., HEIGHT as f32 / 2.);
+
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox={format!("0 0 {WIDTH} {HEIGHT}")} width={WIDTH} height={HEIGHT}>
+ <defs>
+ <radialGradient id="glow" cx="0.5" cy="0.5" r="0.5">
+ <stop offset="0" stop-color="#c7d2fe" stop-opacity="0.9" />
+ <stop offset="1" stop-color="#c7d2fe" stop-opacity="0" />
+ </radialGradient>
+ </defs>
+ <rect width={WIDTH} height={HEIGHT} fill="#f8fafc" />
+ <circle cx={WIDTH as f32 * 0.78 - drift} cy={HEIGHT as f32 * 0.25 + drift * 0.5} r={620. * UNIT} fill="url(#glow)" />
+
+ <g opacity={fade_in * fade_out} transform={Transform::translate(0, rise * UNIT)}>
+ <text x={cx} y={cy} font-family={FONT} font-size={size} font-weight={WEIGHT} fill={INK} text-anchor="middle">
+ {self.greeting.as_str()}
+ </text>
+ <rect x={cx - underline / 2.} y={cy + 36. * UNIT} width={underline} height={10. * UNIT} rx={5. * UNIT} fill={ACCENT} />
+ <text x={cx} y={cy + 120. * UNIT} font-family={FONT} font-size={44. * UNIT} font-weight={WEIGHT} fill={MUTED} text-anchor="middle" opacity={subtitle}>
+ "made with fframes"
+ </text>
+ </g>
+
+ <text x={48. * UNIT} y={HEIGHT as f32 - 48. * UNIT} font-family={FONT} font-size={26. * UNIT} font-weight={WEIGHT} fill={MUTED}>
+ {format!("frame {} / {:.2}s", frame.index, frame.seconds())}
+ </text>
+ </svg>
+ )
+ }
+}
diff --git a/cargo-fframes/templates/main_cpu.rs.tmpl b/cargo-fframes/templates/main_cpu.rs.tmpl
new file mode 100644
index 00000000..dcbdd302
--- /dev/null
+++ b/cargo-fframes/templates/main_cpu.rs.tmpl
@@ -0,0 +1,34 @@
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, cli};
+use {{lib_name}}::{ {{Struct}}Media, {{Struct}}Video };
+use fframes::cli::clap; // the derive below expands to `clap::...`
+use std::process::ExitCode;
+
+/// Flags of this video next to the standard ones of `fframes::cli` (render, frame, strip,
+/// inspect, audio, ...). Run `cargo run --release -- --help`.
+#[derive(Debug, clap::Args)]
+struct VideoArgs {
+ #[arg(long, default_value = "{{title}}", global = true)]
+ title: String,
+}
+
+fn main() -> ExitCode {
+ let args = cli::parse::<VideoArgs>();
+ let media = {{Struct}}Media::prepare().expect("media");
+ let title = args.app.title.clone();
+ let video = {{Struct}}Video::new(&media, &title);
+
+ cli::new(
+ &video,
+ RenderOptions {
+ media: Some(&media),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ codec_params: Some(&[("crf", "20"), ("preset", "medium"), ("tune", "animation")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ )
+ .args(args)
+ .run()
+}
diff --git a/cargo-fframes/templates/main_skia.rs.tmpl b/cargo-fframes/templates/main_skia.rs.tmpl
new file mode 100644
index 00000000..ef0b5095
--- /dev/null
+++ b/cargo-fframes/templates/main_skia.rs.tmpl
@@ -0,0 +1,52 @@
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, cli};
+use fframes_skia_renderer::{
+ SkiaFFramesRenderer, SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig,
+ {{skia_module}}::{{skia_ctx}},
+};
+use {{lib_name}}::{ {{Struct}}Media, {{Struct}}Video, HEIGHT, WIDTH };
+use fframes::cli::clap; // the derive below expands to `clap::...`
+use std::process::ExitCode;
+
+/// Flags of this video next to the standard ones of `fframes::cli` (render, frame, strip,
+/// inspect, audio, ...). Run `cargo run --release -- --help`.
+#[derive(Debug, clap::Args)]
+struct VideoArgs {
+ #[arg(long, default_value = "{{title}}", global = true)]
+ title: String,
+}
+
+fn main() -> ExitCode {
+ let args = cli::parse::<VideoArgs>();
+ let media = {{Struct}}Media::prepare().expect("media");
+ let title = args.app.title.clone();
+ let video = {{Struct}}Video::new(&media, &title);
+ let gpu = {{skia_ctx}}::new(WIDTH, HEIGHT).expect("GPU context{{skia_hint}}");
+
+ cli::new(
+ &video,
+ RenderOptions {
+ media: Some(&media),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ codec_params: Some(&[("crf", "20"), ("preset", "medium"), ("tune", "animation")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ )
+ .args(args)
+ // Frame previews (frame, strip, onion, snapshot) render with the same Skia backend.
+ .backend(
+ SkiaFFramesRenderer::{{skia_constructor}}(
+ &gpu,
+ SkiaPipelineConfig {
+ concurrency_policy: SkiaPipelineConcurrencyPolicy::MaxPerformance,
+ ..Default::default()
+ },
+ )
+ .expect("skia renderer"),
+ )
+ // `preview` opens the real-time GPU player.
+ .preview(fframes_native_player::cli_preview)
+ .run()
+}
diff --git a/examples/audio-announce/Cargo.toml b/examples/audio-announce/Cargo.toml
index c998417a..1def9c87 100644
--- a/examples/audio-announce/Cargo.toml
+++ b/examples/audio-announce/Cargo.toml
@@ -9,10 +9,15 @@ fframes = { workspace = true, features = ["h264", "libav-agree-gpl"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fframes_skia_renderer = { workspace = true, features = ["vulkan"] }
+# `preview`: real-time GPU window
+fframes_native_player.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_native_player = { workspace = true, features = ["metal"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
videotoolbox = ["fframes/videotoolbox"]
[lib]
diff --git a/examples/audio-announce/src/main.rs b/examples/audio-announce/src/main.rs
index 69e38858..e9d2dbfd 100644
--- a/examples/audio-announce/src/main.rs
+++ b/examples/audio-announce/src/main.rs
@@ -1,62 +1,40 @@
use audio_announce_example::{AudioAnnounce, AudioAnnounceMedia};
-use clap::Parser;
+use fframes::cli::{self, clap};
use fframes::{
- CombinedMediaProvider, EncoderOptions, MediaProvider, RenderOptions, StaticMediaProvider,
- Video, fframes_logger,
+ CombinedMediaProvider, EncoderOptions, MediaProvider, RenderOptions, StaticMediaProvider, Video,
};
use fframes_skia_renderer::vulkan::SkiaVulkanCtx;
use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig};
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
+#[derive(Debug, clap::Args)]
struct Args {
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long)]
- video_codec: Option<String>,
- #[clap(long)]
- audio_codec: Option<String>,
- #[clap(short, long)]
- concurrency: Option<usize>,
- #[clap(short, long)]
- pub font: Option<String>,
+ /// Font family of the text.
+ #[arg(short, long, global = true)]
+ font: Option<String>,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = AudioAnnounceMedia::prepare().unwrap();
let media_folder = fframes::MediaDirectory::read_folder("./dynamic_media").unwrap();
let dynamic_media = media_folder.process_media_source().unwrap();
+ let all_media = CombinedMediaProvider::from([
+ &media as &dyn MediaProvider,
+ &dynamic_media as &dyn MediaProvider,
+ ]);
+ let font = args.app.font.clone();
let vulkan_ctx = SkiaVulkanCtx::new(AudioAnnounce::WIDTH, AudioAnnounce::HEIGHT).unwrap();
- fframes::render(
- args.output.as_str(),
+ cli::new(
&AudioAnnounce {
media: &media,
- font: args.font.as_deref(),
+ font: font.as_deref(),
},
- // Render it with CPU to see the difference
- // fframes::cpu::CpuRenderingBackend {
- // ..Default::default()
- // },
- SkiaFFramesRenderer::new_vulkan(
- &vulkan_ctx,
- SkiaPipelineConfig {
- buffer_queue_size: AudioAnnounce::FPS,
- concurrency_policy:
- // this works perfectly on my machine but you should test different options
- fframes_skia_renderer::SkiaPipelineConcurrencyPolicy::Concurrency(4),
- ..Default::default()
- },
- )
- .expect("Failed to create metal renderer"),
- &RenderOptions {
- media: Some(&CombinedMediaProvider::from([
- &media as &dyn MediaProvider,
- &dynamic_media as &dyn MediaProvider,
- ])),
+ RenderOptions {
+ media: Some(&all_media),
load_system_fonts: true,
- logger: fframes_logger::FFramesLoggerVariant::Compact,
video_encoder_options: EncoderOptions {
preferred_encoder: Some("libx264"),
qmin: 0,
@@ -75,5 +53,21 @@ fn main() {
..Default::default()
},
)
- .unwrap();
+ .args(args)
+ .backend(
+ // Swap in `fframes::cpu::CpuRenderingBackend::default()` to compare with the CPU.
+ SkiaFFramesRenderer::new_vulkan(
+ &vulkan_ctx,
+ SkiaPipelineConfig {
+ buffer_queue_size: AudioAnnounce::FPS,
+ // this works well on the author's machine, test other values on yours
+ concurrency_policy:
+ fframes_skia_renderer::SkiaPipelineConcurrencyPolicy::Concurrency(4),
+ ..Default::default()
+ },
+ )
+ .expect("Failed to create the skia renderer"),
+ )
+ .preview(fframes_native_player::cli_preview)
+ .run()
}
diff --git a/examples/beta/Cargo.toml b/examples/beta/Cargo.toml
index ebdf7d45..773ec5f1 100644
--- a/examples/beta/Cargo.toml
+++ b/examples/beta/Cargo.toml
@@ -16,11 +16,17 @@ fframes = { workspace = true, features = ["h264", "libav-agree-gpl"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fframes_skia_renderer = { workspace = true, features = ["vulkan"] }
+# `preview`: real-time GPU window
+fframes_native_player.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_native_player = { workspace = true, features = ["metal"] }
[features]
default = ["renderer"]
renderer = [
"fframes/compile-time-svgtree",
+ "fframes/cli",
"hello-world-example/renderer",
"marketing-example/renderer",
"podcast-example/renderer",
diff --git a/examples/beta/src/main.rs b/examples/beta/src/main.rs
index bd00f657..40cf9830 100644
--- a/examples/beta/src/main.rs
+++ b/examples/beta/src/main.rs
@@ -1,12 +1,12 @@
use beta_example::{BetaExamples, BetaVideo};
use fframes::{
CombinedMediaProvider, EncoderOptions, MediaDirectory, MediaProvider, RenderOptions,
- StaticMediaProvider, cpu::CpuRenderingBackend, fframes_logger, lazy_static::lazy_static,
+ StaticMediaProvider, cli, cpu::CpuRenderingBackend, lazy_static::lazy_static,
};
use hello_world_example::{HelloWorldMedia, HelloWorldVideo};
use marketing_example::{MarketingMedia, MarketingVideo};
use podcast_example::PodcastVideo;
-use std::{path::Path, sync::Arc};
+use std::{path::Path, process::ExitCode, sync::Arc};
use tiktok_example::{GooseMedia, GooseVideo};
lazy_static! {
@@ -15,7 +15,7 @@ lazy_static! {
static ref HELLO_WORLD_MEDIA: HelloWorldMedia = HelloWorldMedia::prepare().unwrap();
}
-fn main() {
+fn main() -> ExitCode {
let media_folder = MediaDirectory::read_folder(Path::new("./media")).unwrap();
let fs_media = media_folder.process_media_source().unwrap();
@@ -26,8 +26,7 @@ fn main() {
&fs_media as &dyn MediaProvider,
]);
- fframes::render(
- "out.mp4",
+ cli::new(
&BetaVideo {
iphone_scene: beta_example::IphoneScene {
hours: 12,
@@ -52,14 +51,9 @@ fn main() {
}),
},
},
- CpuRenderingBackend {
- cache_capacity: 200,
- ..Default::default()
- },
- &RenderOptions {
+ RenderOptions {
media: Some(&media),
load_system_fonts: true,
- logger: fframes_logger::FFramesLoggerVariant::Compact,
video_encoder_options: EncoderOptions {
preferred_encoder: Some("libx264"),
..Default::default()
@@ -68,5 +62,10 @@ fn main() {
..Default::default()
},
)
- .unwrap();
+ .backend(CpuRenderingBackend {
+ cache_capacity: 200,
+ ..Default::default()
+ })
+ .preview(fframes_native_player::cli_preview)
+ .run()
}
diff --git a/examples/conference-splash-screen/Cargo.toml b/examples/conference-splash-screen/Cargo.toml
index b30a6f81..90bac824 100644
--- a/examples/conference-splash-screen/Cargo.toml
+++ b/examples/conference-splash-screen/Cargo.toml
@@ -13,7 +13,7 @@ image = "0.25.4"
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
crate-type = ["cdylib", "rlib"]
@@ -25,3 +25,8 @@ doctest = false
name = "conference_splash_screen_bin"
path = "src/main.rs"
required-features = ["renderer"]
+
+[[bin]]
+name = "render_all"
+path = "src/bin/render_all.rs"
+required-features = ["renderer"]
diff --git a/examples/conference-splash-screen/src/bin/render_all.rs b/examples/conference-splash-screen/src/bin/render_all.rs
new file mode 100644
index 00000000..32806113
--- /dev/null
+++ b/examples/conference-splash-screen/src/bin/render_all.rs
@@ -0,0 +1,66 @@
+//! Renders the splash screen, a preview image and a description of every talk into `output/`.
+use conference_splash_screen::ConferenceMedia;
+use fframes::{
+ CombinedMediaProvider, CpuFrameRenderer, MediaProvider, Previewer, StaticMediaProvider,
+};
+use std::{fs, path::PathBuf};
+
+#[path = "../talks.rs"]
+mod talks;
+
+/// The frame used as the preview image.
+const PREVIEW_FRAME: usize = 145;
+
+fn generate_description(talk: &talks::Talk) -> String {
+ format!(
+ "{}'s FunOCaml 2024 talk recording!\n\nOverview by {}:\n{}\n{}\n\nConnect with us\nWebsite: https://fun-ocaml.com/\nTwitter: https://x.com/FunOCaml",
+ talk.speaker_name,
+ talk.speaker_name.split(' ').next().unwrap_or("speaker"),
+ talk.description,
+ talk.social_links
+ .as_deref()
+ .map(|links| format!("Find speaker: {links}"))
+ .unwrap_or_default()
+ )
+}
+
+fn main() {
+ let media = ConferenceMedia::prepare().unwrap();
+ let media_folder = talks::dynamic_media();
+ let dynamic_media = media_folder.process_media_source().unwrap();
+ let media_provider = CombinedMediaProvider::from([
+ &media as &dyn MediaProvider,
+ &dynamic_media as &dyn MediaProvider,
+ ]);
+ let options = talks::render_options(&media_provider);
+
+ let _ = fs::remove_dir_all("output");
+ fs::create_dir_all("output").unwrap();
+
+ println!("Rendering {} talks...", talks::TALKS.len());
+ for (index, talk) in talks::TALKS.iter().enumerate() {
+ let filename = format!("{}_{index}", talk.speaker_name.replace(' ', "_"));
+ let video = talks::video(&media, talk);
+
+ fframes::render(
+ format!("output/{filename}.mp4"),
+ &video,
+ talks::backend(),
+ &options,
+ )
+ .expect("Failed to render video");
+
+ Previewer::new(&video, &options)
+ .and_then(|mut previewer| {
+ previewer.render(PREVIEW_FRAME, &mut CpuFrameRenderer::default())
+ })
+ .and_then(|frame| frame.save_png(format!("output/{filename}_preview.png")))
+ .expect("Failed to save the preview image");
+
+ fs::write(
+ PathBuf::from(format!("output/{filename}_description.txt")),
+ generate_description(talk),
+ )
+ .expect("Failed to save description");
+ }
+}
diff --git a/examples/conference-splash-screen/src/main.rs b/examples/conference-splash-screen/src/main.rs
index 5b0d9866..4fbf3160 100644
--- a/examples/conference-splash-screen/src/main.rs
+++ b/examples/conference-splash-screen/src/main.rs
@@ -1,142 +1,58 @@
-use conference_splash_screen::{ConferenceMedia, ConferenceVideo, SpeakerScene, SponsorScene};
-use fframes::{
- CombinedMediaProvider, EncoderOptions, MediaDirectory, MediaProvider, RenderOptions,
- StaticMediaProvider, Video, fframes_logger, lazy_static::lazy_static,
-};
-use image::{ImageBuffer, Rgba};
-use serde::{Deserialize, Serialize};
-use std::{
- fs, io,
- path::{Path, PathBuf},
-};
-
-#[derive(Debug, Serialize, Deserialize)]
-struct Talk {
- #[serde(rename = "abstract")]
- description: String,
- proposal_title: String,
- speaker_name: String,
- social_links: Option<String>,
- avatar: Option<String>,
-}
-
-lazy_static! {
- static ref TALKS: Vec<Talk> = serde_json::from_str(include_str!("../sessions.json")).unwrap();
+//! One talk's splash screen through `fframes::cli`. `render_all` renders every talk.
+use conference_splash_screen::ConferenceMedia;
+use fframes::cli::{self, clap};
+use fframes::{CombinedMediaProvider, MediaProvider, StaticMediaProvider};
+use std::process::ExitCode;
+
+mod talks;
+
+#[derive(Debug, clap::Args)]
+struct Args {
+ /// The talk: an index into sessions.json or part of the speaker's name.
+ #[arg(long, default_value = "0", global = true)]
+ talk: String,
}
-fn clean_dir(dir_path: &str) -> io::Result<()> {
- let path = Path::new(dir_path);
-
- if path.is_dir() {
- for entry in fs::read_dir(path)? {
- let entry = entry?;
- let file_path = entry.path();
-
- if file_path.is_file() {
- fs::remove_file(file_path)?;
- }
- }
- Ok(())
- } else {
- Err(io::Error::new(
- io::ErrorKind::NotFound,
- "Directory not found",
- ))
+/// A talk by index (`3`) or by a case-insensitive part of the speaker's name.
+fn find_talk(query: &str) -> Result<&'static talks::Talk, String> {
+ if let Ok(index) = query.parse::<usize>() {
+ return talks::TALKS.get(index).ok_or_else(|| {
+ format!(
+ "there are {} talks, index {index} is out of range",
+ talks::TALKS.len()
+ )
+ });
}
+ let query = query.to_lowercase();
+ talks::TALKS
+ .iter()
+ .find(|talk| talk.speaker_name.to_lowercase().contains(&query))
+ .ok_or_else(|| format!("no talk by a speaker matching \"{query}\""))
}
-fn generate_description(talk: &Talk) -> String {
- format!(
- "{}'s FunOCaml 2024 talk recording!\n\nOverview by {}:\n{}\n{}\n\nConnect with us\nWebsite: https://fun-ocaml.com/\nTwitter: https://x.com/FunOCaml",
- talk.speaker_name,
- talk.speaker_name.split(' ').next().unwrap_or("speaker"),
- talk.description,
- talk.social_links
- .as_deref()
- .map(|links| format!("Find speaker: {links}"))
- .unwrap_or("".to_string())
- )
-}
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
+ let talk = match find_talk(&args.app.talk) {
+ Ok(talk) => talk,
+ Err(message) => {
+ eprintln!("error: {message}");
+ return ExitCode::FAILURE;
+ }
+ };
-fn main() {
let media = ConferenceMedia::prepare().unwrap();
- let media_folder = MediaDirectory::read_folder(Path::new("./dynamic_media")).unwrap();
+ let media_folder = talks::dynamic_media();
let dynamic_media = media_folder.process_media_source().unwrap();
-
- clean_dir("output").unwrap();
-
let media_provider = CombinedMediaProvider::from([
&media as &dyn MediaProvider,
&dynamic_media as &dyn MediaProvider,
]);
- let options = RenderOptions {
- media: Some(&media_provider),
- load_system_fonts: true,
- tmp_files_directory: Some(&PathBuf::from("./test_video")),
- logger: fframes_logger::FFramesLoggerVariant::Compact,
- video_encoder_options: EncoderOptions {
- preferred_encoder: Some("libx265"),
- qmin: 0,
- qmax: 69,
- qcompress: 0.6,
- max_qdiff: 4,
- gop_size: 250,
- // codec_params: Some(&[
- // ("x265-params", "log-level=none"), // ✅ Correct syntax
- // ("crf", "18"), // Constant Rate Factor: 18 for high quality
- // ("preset", "slow"), // Slow preset for better compression
- // ("profile:v", "high"), // High profile as specified in the example
- // ("level:v", "5.1"), // Level 5.1 as specified
- // ("b:v", "6000k"), // Set video bitrate to 6000 kb/s
- // ("maxrate", "6600k"), // Set max bitrate (10% higher than target)
- // ("bufsize", "12000k"), // Set buffer size (2 * bitrate)
- // ]),
- ..Default::default()
- },
- ..Default::default()
- };
-
- let backend = fframes::cpu::CpuRenderingBackend {
- concurrency: 1,
- cache_capacity: 200,
- ..Default::default()
- };
-
- println!("Rendering {} talks...", TALKS.len());
- TALKS.iter().enumerate().for_each(|(index, talk)| {
- let filename = format!("{}_{index}", talk.speaker_name.replace(" ", "_"));
- let video = ConferenceVideo {
- media: &media,
- sponsor_scene: SponsorScene { media: &media },
- speaker_scene: SpeakerScene {
- avatar: talk.avatar.as_deref(),
- media: &media,
- speaker_name: &talk.speaker_name,
- talk_title: &talk.proposal_title,
- talk_description: &talk.description,
- },
- };
-
- fframes::render(format!("output/{filename}.mp4"), &video, backend, &options)
- .expect("Failed to render video");
-
- // 330 is a frame that we want to use as a preview
- let preview_image = fframes::render_frame(145, &video, backend, &options).unwrap();
- let img_buffer = ImageBuffer::<Rgba<u8>, Vec<u8>>::from_raw(
- ConferenceVideo::WIDTH as u32,
- ConferenceVideo::HEIGHT as u32,
- preview_image,
- )
- .expect("Failed to parse the preview image buffer");
- img_buffer
- .save(format!("output/{filename}_preview.png"))
- .expect("Failed to save preview image");
-
- fs::write(
- PathBuf::from(format!("output/{filename}_description.txt")),
- generate_description(talk),
- )
- .expect("Failed to save description");
- });
+ cli::new(
+ &talks::video(&media, talk),
+ talks::render_options(&media_provider),
+ )
+ .args(args)
+ .backend(talks::backend())
+ .run()
}
diff --git a/examples/conference-splash-screen/src/talks.rs b/examples/conference-splash-screen/src/talks.rs
new file mode 100644
index 00000000..6881b366
--- /dev/null
+++ b/examples/conference-splash-screen/src/talks.rs
@@ -0,0 +1,68 @@
+//! Loads the talks of `sessions.json` and builds the video, media and render options that
+//! both binaries use.
+use conference_splash_screen::{ConferenceMedia, ConferenceVideo, SpeakerScene, SponsorScene};
+use fframes::{
+ CombinedMediaProvider, EncoderOptions, MediaDirectory, MediaProvider, RenderOptions,
+};
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+use std::sync::LazyLock;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Talk {
+ #[serde(rename = "abstract")]
+ pub description: String,
+ pub proposal_title: String,
+ pub speaker_name: String,
+ pub social_links: Option<String>,
+ pub avatar: Option<String>,
+}
+
+pub static TALKS: LazyLock<Vec<Talk>> =
+ LazyLock::new(|| serde_json::from_str(include_str!("../sessions.json")).unwrap());
+
+static TMP_FILES_DIRECTORY: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("./test_video"));
+
+pub fn video<'a>(media: &'a ConferenceMedia, talk: &'a Talk) -> ConferenceVideo<'a> {
+ ConferenceVideo {
+ media,
+ sponsor_scene: SponsorScene { media },
+ speaker_scene: SpeakerScene {
+ avatar: talk.avatar.as_deref(),
+ media,
+ speaker_name: &talk.speaker_name,
+ talk_title: &talk.proposal_title,
+ talk_description: &talk.description,
+ },
+ }
+}
+
+pub fn dynamic_media() -> MediaDirectory {
+ MediaDirectory::read_folder("./dynamic_media").unwrap()
+}
+
+pub fn render_options<'a>(media: &'a CombinedMediaProvider<'a, 2>) -> RenderOptions<'a, 'a> {
+ RenderOptions {
+ media: Some(media as &dyn MediaProvider),
+ load_system_fonts: true,
+ tmp_files_directory: Some(&TMP_FILES_DIRECTORY),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx265"),
+ qmin: 0,
+ qmax: 69,
+ qcompress: 0.6,
+ max_qdiff: 4,
+ gop_size: 250,
+ ..Default::default()
+ },
+ ..Default::default()
+ }
+}
+
+pub fn backend() -> fframes::cpu::CpuRenderingBackend {
+ fframes::cpu::CpuRenderingBackend {
+ concurrency: 1,
+ cache_capacity: 200,
+ ..Default::default()
+ }
+}
diff --git a/examples/conference-splash-screen/test_video/0.mp4 b/examples/conference-splash-screen/test_video/0.mp4
new file mode 100644
index 00000000..7aa6bff5
Binary files /dev/null and b/examples/conference-splash-screen/test_video/0.mp4 differ
diff --git a/examples/hello-world/Cargo.toml b/examples/hello-world/Cargo.toml
index 2f6629cb..8e52e097 100644
--- a/examples/hello-world/Cargo.toml
+++ b/examples/hello-world/Cargo.toml
@@ -5,11 +5,12 @@ edition = "2024"
[dependencies]
fframes = { workspace = true, features = ["h264", "h265", "vpx", "libav-agree-gpl"] }
+
clap = { version = "4.3.4", features = ["derive"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
crate-type = ["cdylib", "rlib"]
diff --git a/examples/hello-world/src/main.rs b/examples/hello-world/src/main.rs
index 3d80de90..582b831b 100644
--- a/examples/hello-world/src/main.rs
+++ b/examples/hello-world/src/main.rs
@@ -1,66 +1,35 @@
-use clap::Parser;
-use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, fframes_logger};
+use clap::Args;
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, cli};
use hello_world_example::{HelloWorldMedia, HelloWorldVideo};
use std::path::PathBuf;
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
-struct Args {
- #[clap(short, long)]
- gpu: bool,
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long, default_value = "libx264")]
- video_codec: Option<String>,
- #[clap(long)]
- audio_codec: Option<String>,
- #[clap(short, long)]
- concurrency: Option<usize>,
- #[clap(long, default_value = "Renderer!")]
+/// Flags of this video, next to the standard ones of `fframes::cli`.
+#[derive(Debug, Args)]
+struct HelloWorldArgs {
+ /// The text after "Hello".
+ #[arg(long, default_value = "Renderer!", global = true)]
slug: String,
- #[clap(short, long)]
- verbose: bool,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<HelloWorldArgs>();
let media = HelloWorldMedia::prepare().unwrap();
+ let video = HelloWorldVideo {
+ media: &media,
+ slug: &args.app.slug.clone(),
+ };
+ let tmp = PathBuf::from("test_render");
- fframes::render(
- "out.mp4",
- &HelloWorldVideo {
- media: &media,
- slug: &args.slug,
- },
- if let Some(concurrency) = args.concurrency {
- fframes::cpu::CpuRenderingBackend {
- concurrency,
- cache_capacity: 5,
- ..Default::default()
- }
- } else {
- fframes::cpu::CpuRenderingBackend {
- cache_capacity: 5,
- ..Default::default()
- }
- },
- &RenderOptions {
+ cli::new(
+ &video,
+ RenderOptions {
media: Some(&media),
load_system_fonts: true,
- logger: if args.verbose {
- fframes_logger::FFramesLoggerVariant::Debug
- } else {
- fframes_logger::FFramesLoggerVariant::Compact
- },
- tmp_files_directory: Some(&PathBuf::from("test_render")),
- audio_encoder_options: EncoderOptions {
- preferred_encoder: args.audio_codec.as_deref(),
- ..Default::default()
- },
+ tmp_files_directory: Some(&tmp),
video_encoder_options: EncoderOptions {
- preferred_encoder: args.video_codec.as_deref(),
- codec_params: (args.video_codec.as_deref() == Some("libx264")
- || args.video_codec.as_deref() == Some("libx265"))
- .then_some(&[
+ preferred_encoder: Some("libx264"),
+ codec_params: Some(&[
("crf", "23"),
("preset", "ultrafast"),
("tune", "animation"),
@@ -70,5 +39,6 @@ fn main() {
..Default::default()
},
)
- .unwrap();
+ .args(args)
+ .run()
}
diff --git a/examples/low-poly-art/Cargo.toml b/examples/low-poly-art/Cargo.toml
index 9b1bc091..4f7d822c 100644
--- a/examples/low-poly-art/Cargo.toml
+++ b/examples/low-poly-art/Cargo.toml
@@ -13,7 +13,7 @@ fframes_test_utils = { path = "../../fframes-test-utils" }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
name = "low_poly_art_example"
diff --git a/examples/low-poly-art/src/main.rs b/examples/low-poly-art/src/main.rs
index 72ca0f3f..2c937330 100644
--- a/examples/low-poly-art/src/main.rs
+++ b/examples/low-poly-art/src/main.rs
@@ -1,10 +1,10 @@
-use fframes::{CombinedMediaProvider, MediaProvider, RenderOptions, fframes_logger};
+use fframes::{CombinedMediaProvider, MediaProvider, RenderOptions, cli};
use low_poly_art_example::{LowPolyMedia, LowPolyVideo, owl};
+use std::process::ExitCode;
-/// Make sure that this example will compile very slowly but the rendering will be (relatively) fast.
-/// This is because fframes inlines and parses all the svg at compile time and skipping mostly all
-/// the runtime work for processng and preparing svg.
-fn main() {
+/// This example compiles slowly but renders fast: fframes parses all of its SVG at compile
+/// time, so the renderer does almost no SVG work per frame.
+fn main() -> ExitCode {
let media = LowPolyMedia::new().unwrap();
let owl_media = owl::OwlMedia::new().unwrap();
@@ -13,22 +13,20 @@ fn main() {
&owl_media as &dyn MediaProvider,
]);
- fframes::render(
- "out.mp4",
+ cli::new(
&LowPolyVideo {
media: &media,
scene: &owl::Owl { media: &owl_media },
},
- fframes::cpu::CpuRenderingBackend {
- // Don't need a lot of capacity because the whole sub-svg of animal scene will be cached
- cache_capacity: 5,
- ..Default::default()
- },
- &RenderOptions {
+ RenderOptions {
media: Some(&combined_media),
- logger: fframes_logger::FFramesLoggerVariant::Compact,
..Default::default()
},
)
- .unwrap();
+ // The whole animal scene is cached as one subtree, so a small cache is enough.
+ .backend(fframes::cpu::CpuRenderingBackend {
+ cache_capacity: 5,
+ ..Default::default()
+ })
+ .run()
}
diff --git a/examples/marketing/Cargo.toml b/examples/marketing/Cargo.toml
index 21b08a27..d60a235d 100644
--- a/examples/marketing/Cargo.toml
+++ b/examples/marketing/Cargo.toml
@@ -12,4 +12,4 @@ futures = "0.3.17"
[features]
default=["renderer"]
-renderer=["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
diff --git a/examples/marketing/src/main.rs b/examples/marketing/src/main.rs
index 7e5deeb7..9f87142d 100644
--- a/examples/marketing/src/main.rs
+++ b/examples/marketing/src/main.rs
@@ -1,23 +1,18 @@
-use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, fframes_logger};
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, cli};
use marketing_example::{MarketingMedia, MarketingVideo};
+use std::process::ExitCode;
-fn main() {
+fn main() -> ExitCode {
let media = MarketingMedia::prepare().unwrap();
- fframes::render(
- "out.mp4",
+ cli::new(
&MarketingVideo {
audio_track: "marketing.mp3",
media: &media,
},
- fframes::cpu::CpuRenderingBackend {
- cache_capacity: 30,
- ..Default::default()
- },
- &RenderOptions {
+ RenderOptions {
media: Some(&media),
load_system_fonts: true,
- logger: fframes_logger::FFramesLoggerVariant::Compact,
video_encoder_options: EncoderOptions {
preferred_encoder: Some("libx265"),
sample_rate: 44100,
@@ -26,5 +21,9 @@ fn main() {
..Default::default()
},
)
- .unwrap();
+ .backend(fframes::cpu::CpuRenderingBackend {
+ cache_capacity: 30,
+ ..Default::default()
+ })
+ .run()
}
diff --git a/examples/motion-graphics/Cargo.toml b/examples/motion-graphics/Cargo.toml
index df5121a6..5b46a595 100644
--- a/examples/motion-graphics/Cargo.toml
+++ b/examples/motion-graphics/Cargo.toml
@@ -9,7 +9,7 @@ clap = { version = "4.3.4", features = ["derive"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
crate-type = ["cdylib", "rlib"]
diff --git a/examples/motion-graphics/src/bin/install_scene.rs b/examples/motion-graphics/src/bin/install_scene.rs
index 292f7786..04386218 100644
--- a/examples/motion-graphics/src/bin/install_scene.rs
+++ b/examples/motion-graphics/src/bin/install_scene.rs
@@ -1,33 +1,30 @@
-use clap::Parser;
use fframes::StaticMediaProvider;
+use fframes::cli::{self, clap};
use motion_graphics_example::{InstallSceneVideo, MotionGraphicsMedia, render_options};
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
-#[clap(name = "install_scene", about = "Render the install fff scene")]
+/// Render the install fff scene.
+#[derive(Debug, clap::Args)]
struct Args {
- #[clap(short, long, default_value = "install_fff.mp4")]
- output: String,
- #[clap(long, default_value = "libx264")]
- video_codec: Option<String>,
- #[clap(short, long)]
- verbose: bool,
+ #[arg(long, default_value = "libx264", global = true)]
+ video_codec: String,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = MotionGraphicsMedia::prepare().unwrap();
+ let video_codec = args.app.video_codec.clone();
- let backend = fframes::cpu::CpuRenderingBackend {
+ cli::new(
+ &InstallSceneVideo::new(&media),
+ render_options(&media, Some(&video_codec), false),
+ )
+ .args(args)
+ .backend(fframes::cpu::CpuRenderingBackend {
concurrency: 1,
cache_capacity: 10,
..Default::default()
- };
-
- fframes::render(
- args.output.as_str(),
- &InstallSceneVideo::new(&media),
- backend,
- &render_options(&media, args.video_codec.as_deref(), args.verbose),
- )
- .unwrap();
+ })
+ .default_output("install_fff.mp4")
+ .run()
}
diff --git a/examples/motion-graphics/src/bin/quote.rs b/examples/motion-graphics/src/bin/quote.rs
index 28e28aad..fb348a7a 100644
--- a/examples/motion-graphics/src/bin/quote.rs
+++ b/examples/motion-graphics/src/bin/quote.rs
@@ -1,50 +1,43 @@
-use clap::Parser;
use fframes::StaticMediaProvider;
+use fframes::cli::{self, clap};
use motion_graphics_example::{MotionGraphicsMedia, QuoteCardVideo, render_options};
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
-#[clap(
- name = "quote",
- about = "Render a quote card video with auto-sized text"
-)]
+/// A quote card video with auto-sized text.
+#[derive(Debug, clap::Args)]
struct Args {
- /// The text to render, e.g. "PERFORMANCE" or "SPEED\n!=\nFAST" for multi-line
+ /// The text, e.g. "PERFORMANCE" or "SPEED\n!=\nFAST" for several lines.
+ #[arg(long, default_value = "PERFORMANCE", global = true)]
text: String,
- #[clap(short, long)]
- output: Option<String>,
- #[clap(long, default_value = "libx264")]
- video_codec: Option<String>,
- #[clap(short, long)]
+ #[arg(long, default_value = "libx264", global = true)]
+ video_codec: String,
+ #[arg(short, long, global = true)]
concurrency: Option<usize>,
- #[clap(short, long)]
- verbose: bool,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = MotionGraphicsMedia::prepare().unwrap();
- // Support literal \n in shell args as line breaks
- let text = args.text.replace("\\n", "\n");
+ // A literal \n in the shell argument is a line break.
+ let text = args.app.text.replace("\\n", "\n");
+ let video_codec = args.app.video_codec.clone();
+ let concurrency = args.app.concurrency.unwrap_or(1);
+ let output = format!(
+ "quote_{}.mp4",
+ text.to_lowercase().replace(['\n', ' '], "_")
+ );
- let output = args.output.unwrap_or_else(|| {
- format!(
- "quote_{}.mp4",
- text.to_lowercase().replace(['\n', ' '], "_")
- )
- });
-
- let backend = fframes::cpu::CpuRenderingBackend {
- concurrency: args.concurrency.unwrap_or(1),
- cache_capacity: 10,
- ..Default::default()
- };
-
- fframes::render(
- output.as_str(),
+ cli::new(
&QuoteCardVideo::new(&media, &text),
- backend,
- &render_options(&media, args.video_codec.as_deref(), args.verbose),
+ render_options(&media, Some(&video_codec), false),
)
- .unwrap();
+ .args(args)
+ .default_output(output)
+ .backend(fframes::cpu::CpuRenderingBackend {
+ concurrency,
+ cache_capacity: 10,
+ ..Default::default()
+ })
+ .run()
}
diff --git a/examples/motion-graphics/src/install_scene.rs b/examples/motion-graphics/src/install_scene.rs
index aad5aea1..acd45a5a 100644
--- a/examples/motion-graphics/src/install_scene.rs
+++ b/examples/motion-graphics/src/install_scene.rs
@@ -148,7 +148,7 @@ impl fframes::Video for InstallSceneVideo<'_> {
// === Accent line below title ===
let accent_width = frame.animate(&fframes::timeline!(
- at 0.4 => 1.0, animate 0.0_f32 => 600.0, Easing::EaseInOut,
+ at 0.4 => 1.0, animate 0.5_f32 => 600.0, Easing::EaseInOut,
));
// === Fade out ===
diff --git a/examples/motion-graphics/src/main.rs b/examples/motion-graphics/src/main.rs
index 4ac60c92..89f74f77 100644
--- a/examples/motion-graphics/src/main.rs
+++ b/examples/motion-graphics/src/main.rs
@@ -1,32 +1,28 @@
-use clap::Parser;
use fframes::StaticMediaProvider;
+use fframes::cli::{self, clap};
use motion_graphics_example::{MotionGraphicsMedia, MotionGraphicsVideo, render_options};
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
+#[derive(Debug, clap::Args)]
struct Args {
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long, default_value = "libx264")]
- video_codec: Option<String>,
- #[clap(short, long)]
- verbose: bool,
+ #[arg(long, default_value = "libx264", global = true)]
+ video_codec: String,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = MotionGraphicsMedia::prepare().unwrap();
+ let video_codec = args.app.video_codec.clone();
- let backend = fframes::cpu::CpuRenderingBackend {
+ cli::new(
+ &MotionGraphicsVideo { media: &media },
+ render_options(&media, Some(&video_codec), false),
+ )
+ .args(args)
+ .backend(fframes::cpu::CpuRenderingBackend {
concurrency: 1,
cache_capacity: 10,
..Default::default()
- };
-
- fframes::render(
- args.output.as_str(),
- &MotionGraphicsVideo { media: &media },
- backend,
- &render_options(&media, args.video_codec.as_deref(), args.verbose),
- )
- .unwrap();
+ })
+ .run()
}
diff --git a/examples/motion-graphics/src/motion_graphics.rs b/examples/motion-graphics/src/motion_graphics.rs
index 12c54e49..187672ef 100644
--- a/examples/motion-graphics/src/motion_graphics.rs
+++ b/examples/motion-graphics/src/motion_graphics.rs
@@ -46,9 +46,9 @@ impl fframes::Video for MotionGraphicsVideo<'_> {
at 0.8 => 1.5, animate 720.0_f32 => 620.0, Easing::EaseInOut,
));
- // Accent line expands from center
+ // Accent line expands from center (from a hairline: SVG skips zero-width rects)
let accent_width = frame.animate(&fframes::timeline!(
- at 1.0 => 1.6, animate 0.0_f32 => 1000.0, Easing::EaseInOut,
+ at 1.0 => 1.6, animate 0.5_f32 => 1000.0, Easing::EaseInOut,
));
// "(for real)" — slides up from below into a clip box
diff --git a/examples/neon-triangle/Cargo.toml b/examples/neon-triangle/Cargo.toml
index 0569ff24..60290d40 100644
--- a/examples/neon-triangle/Cargo.toml
+++ b/examples/neon-triangle/Cargo.toml
@@ -12,10 +12,15 @@ clap = { version = "4.3.4", features = ["derive"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fframes_skia_renderer = { workspace = true, features = ["vulkan"] }
image = "0.25.5"
+# `preview`: real-time GPU window
+fframes_native_player.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_native_player = { workspace = true, features = ["metal"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
crate-type = ["cdylib", "rlib"]
diff --git a/examples/neon-triangle/src/main.rs b/examples/neon-triangle/src/main.rs
index affecfe7..3eac5953 100644
--- a/examples/neon-triangle/src/main.rs
+++ b/examples/neon-triangle/src/main.rs
@@ -1,66 +1,43 @@
-use clap::Parser;
-use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, Video, fframes_logger};
+use fframes::cli::{self, clap};
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, Video};
use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig, vulkan::SkiaVulkanCtx};
-use image::{ImageBuffer, Rgba};
use neon_triangle_example::{NeonTriangleMedia, NeonTriangleVideo};
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
+#[derive(Debug, clap::Args)]
struct Args {
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long, default_value = "libx264")]
- video_codec: Option<String>,
- #[clap(short, long)]
- verbose: bool,
- /// Render a single frame to PNG instead of the full video
- #[clap(long)]
- preview: bool,
- /// Frame index to render with --preview
- #[clap(long, default_value = "90")]
- preview_frame: usize,
+ #[arg(long, default_value = "libx264", global = true)]
+ video_codec: String,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = NeonTriangleMedia::prepare().unwrap();
let video = NeonTriangleVideo::new(&media);
+ let video_codec = args.app.video_codec.clone();
// Shaders run on the Skia backend's own GPU surface; the tiny-skia CPU
- // backend would draw nothing in their place.
+ // backend would draw nothing in their place, so previews use Skia too.
let vulkan_ctx =
SkiaVulkanCtx::new(NeonTriangleVideo::WIDTH, NeonTriangleVideo::HEIGHT).unwrap();
- let backend = SkiaFFramesRenderer::new_vulkan(&vulkan_ctx, SkiaPipelineConfig::default())
- .expect("Failed to create renderer");
- let options = RenderOptions {
- media: Some(&media),
- logger: if args.verbose {
- fframes_logger::FFramesLoggerVariant::Debug
- } else {
- fframes_logger::FFramesLoggerVariant::Compact
- },
- video_encoder_options: EncoderOptions {
- preferred_encoder: args.video_codec.as_deref(),
- codec_params: Some(&[("crf", "16"), ("preset", "slow")]),
+ cli::new(
+ &video,
+ RenderOptions {
+ media: Some(&media),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some(&video_codec),
+ codec_params: Some(&[("crf", "16"), ("preset", "slow")]),
+ ..Default::default()
+ },
..Default::default()
},
- ..Default::default()
- };
-
- if args.preview {
- let pixels = fframes::render_frame(args.preview_frame, &video, backend, &options)
- .expect("Failed to render preview frame");
- ImageBuffer::<Rgba<u8>, Vec<u8>>::from_raw(
- NeonTriangleVideo::WIDTH as u32,
- NeonTriangleVideo::HEIGHT as u32,
- pixels,
- )
- .expect("Failed to create image buffer")
- .save("frame_preview.png")
- .expect("Failed to save preview image");
-
- println!("Saved frame {} to frame_preview.png", args.preview_frame);
- } else {
- fframes::render(args.output.as_str(), &video, backend, &options).unwrap();
- }
+ )
+ .args(args)
+ .backend(
+ SkiaFFramesRenderer::new_vulkan(&vulkan_ctx, SkiaPipelineConfig::default())
+ .expect("Failed to create renderer"),
+ )
+ .preview(fframes_native_player::cli_preview)
+ .run()
}
diff --git a/examples/pixel-memory/Cargo.toml b/examples/pixel-memory/Cargo.toml
index be9003d7..ba47798d 100644
--- a/examples/pixel-memory/Cargo.toml
+++ b/examples/pixel-memory/Cargo.toml
@@ -12,11 +12,16 @@ fframes = { workspace = true, features = ["h264", "h265", "libav-agree-gpl", "ex
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fframes_skia_renderer = { workspace = true, features = ["vulkan", "debug"] }
+# `preview`: real-time GPU window
+fframes_native_player.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_native_player = { workspace = true, features = ["metal"] }
[features]
cpu = []
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
crate-type = ["cdylib", "rlib"]
diff --git a/examples/pixel-memory/src/main.rs b/examples/pixel-memory/src/main.rs
index 6b182ee6..abbf9c79 100644
--- a/examples/pixel-memory/src/main.rs
+++ b/examples/pixel-memory/src/main.rs
@@ -1,113 +1,103 @@
-use clap::Parser;
+#[cfg(not(feature = "cpu"))]
+use fframes::Video;
+use fframes::cli::{self, clap};
use fframes::{
CombinedMediaProvider, EncoderOptions, MediaDirectory, MediaProvider, RenderOptions,
- StaticMediaProvider, Video, fframes_logger, render,
+ StaticMediaProvider,
};
#[cfg(not(feature = "cpu"))]
use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig, vulkan::SkiaVulkanCtx};
use pixel_memory_example::{ALL_SONGS, PixelMedia, PixelVideo, RandomPhotos};
use rand::prelude::*;
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
+#[derive(Debug, clap::Args)]
struct Args {
- #[clap(
+ #[arg(
short,
long,
+ global = true,
default_value = "They say dogs live shorter lives because they already know how to love unconditionally"
)]
enter_text: String,
- #[clap(short, long)]
+ /// Song file. Without it the seed picks one from the collection.
+ #[arg(short, long, global = true)]
song: Option<String>,
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long, default_value = "libx265")]
- video_codec: Option<String>,
- #[clap(long)]
- audio_codec: Option<String>,
- #[clap(short, long)]
- concurrency: Option<usize>,
- #[clap(long, default_value = "Renderer!")]
- slug: String,
- #[clap(short, long)]
- verbose: bool,
+ /// Picks the photos, scenes and song. Commands run with the same seed see the same video.
+ #[arg(long, default_value_t = 48, global = true)]
+ seed: u64,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = PixelMedia::prepare().unwrap();
let photos = MediaDirectory::read_folder("photos").unwrap();
let photos_media = photos.process_media_source().unwrap();
+ let all_media = CombinedMediaProvider::from([
+ &media as &dyn MediaProvider,
+ &photos_media as &dyn MediaProvider,
+ ]);
- let rng = &mut rand::thread_rng();
- // more randomized experience
- // let rng = &mut rand::rngs::StdRng::seed_from_u64(48);
-
+ let rng = &mut rand::rngs::StdRng::seed_from_u64(args.app.seed);
let photos = RandomPhotos::new_from_media_provider(rng, &photos_media);
- #[cfg(not(feature = "cpu"))]
- let vulkan_ctx = SkiaVulkanCtx::new(PixelVideo::WIDTH, PixelVideo::HEIGHT).unwrap();
-
let song = args
+ .app
.song
- .as_deref()
- .unwrap_or_else(|| ALL_SONGS.choose(rng).expect("Failed to pick a random song"));
+ .clone()
+ .unwrap_or_else(|| ALL_SONGS.choose(rng).expect("no songs").to_string());
+ let enter_text = args.app.enter_text.clone();
+ let video = PixelVideo::new_random_scenes(&song, &enter_text, rng, Some(&media), photos);
- let video = PixelVideo::new_random_scenes(song, &args.enter_text, rng, Some(&media), photos);
- render(
- "out.mp4",
- &video,
- #[cfg(feature = "cpu")]
- {
- fframes::cpu::CpuRenderingBackend {
- cache_capacity: 300,
- ..Default::default()
- }
- },
- #[cfg(not(feature = "cpu"))]
- {
- SkiaFFramesRenderer::new_vulkan(
- &vulkan_ctx,
- SkiaPipelineConfig {
- buffer_queue_size: 20,
- concurrency_policy:
- fframes_skia_renderer::SkiaPipelineConcurrencyPolicy::MaxPerformance,
- ..Default::default()
- },
- )
- .expect("Failed to create metal renderer")
- },
- &RenderOptions {
- media: Some(&CombinedMediaProvider::from([
- &media as &dyn MediaProvider,
- &photos_media as &dyn MediaProvider,
- ])),
- load_system_fonts: true,
- logger: if args.verbose {
- fframes_logger::FFramesLoggerVariant::Debug
- } else {
- fframes_logger::FFramesLoggerVariant::Compact
- },
- video_encoder_options: EncoderOptions {
- preferred_encoder: Some("libx264"),
- qmin: 0,
- qmax: 69,
- qcompress: 0.6,
- max_qdiff: 4,
- gop_size: 24,
- codec_params: Some(&[
- ("crf", "23"),
- #[cfg(not(feature = "cpu"))]
- ("preset", "slower"),
- #[cfg(feature = "cpu")]
- ("preset", "slower"),
- ("profile:v", "high"),
- ("level:v", "5.1"),
- ("g", "24"),
- ("sc_threshold", "0"), // Disable scene cut detection
- ]),
- ..Default::default()
- },
+ let options = RenderOptions {
+ media: Some(&all_media),
+ load_system_fonts: true,
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ qmin: 0,
+ qmax: 69,
+ qcompress: 0.6,
+ max_qdiff: 4,
+ gop_size: 24,
+ codec_params: Some(&[
+ ("crf", "23"),
+ ("preset", "slower"),
+ ("profile:v", "high"),
+ ("level:v", "5.1"),
+ ("g", "24"),
+ ("sc_threshold", "0"), // Disable scene cut detection
+ ]),
..Default::default()
},
- )
- .unwrap();
+ ..Default::default()
+ };
+
+ #[cfg(feature = "cpu")]
+ return cli::new(&video, options)
+ .args(args)
+ .backend(fframes::cpu::CpuRenderingBackend {
+ cache_capacity: 300,
+ ..Default::default()
+ })
+ .run();
+
+ #[cfg(not(feature = "cpu"))]
+ {
+ let vulkan_ctx = SkiaVulkanCtx::new(PixelVideo::WIDTH, PixelVideo::HEIGHT).unwrap();
+ cli::new(&video, options)
+ .args(args)
+ .backend(
+ SkiaFFramesRenderer::new_vulkan(
+ &vulkan_ctx,
+ SkiaPipelineConfig {
+ buffer_queue_size: 20,
+ concurrency_policy:
+ fframes_skia_renderer::SkiaPipelineConcurrencyPolicy::MaxPerformance,
+ ..Default::default()
+ },
+ )
+ .expect("Failed to create the skia renderer"),
+ )
+ .preview(fframes_native_player::cli_preview)
+ .run()
+ }
}
diff --git a/examples/podcast/Cargo.toml b/examples/podcast/Cargo.toml
index c3969339..3e5a9ba6 100644
--- a/examples/podcast/Cargo.toml
+++ b/examples/podcast/Cargo.toml
@@ -11,7 +11,7 @@ fframes_skia_renderer = { workspace = true, features = ["vulkan"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
name = "podcast_example"
diff --git a/examples/podcast/src/main.rs b/examples/podcast/src/main.rs
index 9a620bd1..ba5146e9 100644
--- a/examples/podcast/src/main.rs
+++ b/examples/podcast/src/main.rs
@@ -1,22 +1,20 @@
-use fframes::{EncoderOptions, MediaDirectory, RenderOptions, fframes_logger};
+use fframes::{EncoderOptions, MediaDirectory, RenderOptions, cli};
use podcast_example::PodcastVideo;
use std::path::Path;
+use std::process::ExitCode;
-fn main() {
+fn main() -> ExitCode {
let media_folder = MediaDirectory::read_folder(Path::new("./media")).unwrap();
let media = media_folder.process_media_source().unwrap();
- fframes::render(
- "out.mp4",
+ cli::new(
&PodcastVideo {
goose_audio: "final.mp3",
duck_audio: "final.mp3",
guest_audio: "final.mp3",
},
- fframes::cpu::CpuRenderingBackend::default(),
- &RenderOptions {
+ RenderOptions {
media: Some(&media),
- logger: fframes_logger::FFramesLoggerVariant::Compact,
video_encoder_options: EncoderOptions {
preferred_encoder: Some("libx264"),
..Default::default()
@@ -24,5 +22,5 @@ fn main() {
..Default::default()
},
)
- .unwrap();
+ .run()
}
diff --git a/examples/shaders/Cargo.toml b/examples/shaders/Cargo.toml
index 34f9411f..0cb65172 100644
--- a/examples/shaders/Cargo.toml
+++ b/examples/shaders/Cargo.toml
@@ -12,10 +12,15 @@ clap = { version = "4.3.4", features = ["derive"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fframes_skia_renderer = { workspace = true, features = ["vulkan"] }
image = "0.25.5"
+# `preview`: real-time GPU window
+fframes_native_player.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_native_player = { workspace = true, features = ["metal"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
crate-type = ["cdylib", "rlib"]
diff --git a/examples/shaders/src/main.rs b/examples/shaders/src/main.rs
index a4232327..4b769ecb 100644
--- a/examples/shaders/src/main.rs
+++ b/examples/shaders/src/main.rs
@@ -1,65 +1,42 @@
-use clap::Parser;
-use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, Video, fframes_logger};
+use fframes::cli::{self, clap};
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, Video};
use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig, vulkan::SkiaVulkanCtx};
-use image::{ImageBuffer, Rgba};
use shaders_example::{ShadersMedia, ShadersVideo};
+use std::process::ExitCode;
-#[derive(Debug, Parser)]
+#[derive(Debug, clap::Args)]
struct Args {
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long, default_value = "libx264")]
- video_codec: Option<String>,
- #[clap(short, long)]
- verbose: bool,
- /// Render a single frame to PNG instead of the full video
- #[clap(long)]
- preview: bool,
- /// Frame index to render with --preview
- #[clap(long, default_value = "90")]
- preview_frame: usize,
+ #[arg(long, default_value = "libx264", global = true)]
+ video_codec: String,
}
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
+ let args = cli::parse::<Args>();
let media = ShadersMedia::prepare().unwrap();
let video = ShadersVideo::new(&media);
+ let video_codec = args.app.video_codec.clone();
// Shaders run on the Skia backend's own GPU surface; the tiny-skia CPU
- // backend would draw nothing in their place.
+ // backend would draw nothing in their place, so previews use Skia too.
let vulkan_ctx = SkiaVulkanCtx::new(ShadersVideo::WIDTH, ShadersVideo::HEIGHT).unwrap();
- let backend = SkiaFFramesRenderer::new_vulkan(&vulkan_ctx, SkiaPipelineConfig::default())
- .expect("Failed to create renderer");
- let options = RenderOptions {
- media: Some(&media),
- logger: if args.verbose {
- fframes_logger::FFramesLoggerVariant::Debug
- } else {
- fframes_logger::FFramesLoggerVariant::Compact
- },
- video_encoder_options: EncoderOptions {
- preferred_encoder: args.video_codec.as_deref(),
- codec_params: Some(&[("crf", "20"), ("preset", "slow")]),
+ cli::new(
+ &video,
+ RenderOptions {
+ media: Some(&media),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some(&video_codec),
+ codec_params: Some(&[("crf", "20"), ("preset", "slow")]),
+ ..Default::default()
+ },
..Default::default()
},
- ..Default::default()
- };
-
- if args.preview {
- let pixels = fframes::render_frame(args.preview_frame, &video, backend, &options)
- .expect("Failed to render preview frame");
- ImageBuffer::<Rgba<u8>, Vec<u8>>::from_raw(
- ShadersVideo::WIDTH as u32,
- ShadersVideo::HEIGHT as u32,
- pixels,
- )
- .expect("Failed to create image buffer")
- .save("frame_preview.png")
- .expect("Failed to save preview image");
-
- println!("Saved frame {} to frame_preview.png", args.preview_frame);
- } else {
- fframes::render(args.output.as_str(), &video, backend, &options).unwrap();
- }
+ )
+ .args(args)
+ .backend(
+ SkiaFFramesRenderer::new_vulkan(&vulkan_ctx, SkiaPipelineConfig::default())
+ .expect("Failed to create renderer"),
+ )
+ .preview(fframes_native_player::cli_preview)
+ .run()
}
diff --git a/examples/signal-lab/.gitignore b/examples/signal-lab/.gitignore
new file mode 100644
index 00000000..b5dc1103
--- /dev/null
+++ b/examples/signal-lab/.gitignore
@@ -0,0 +1,12 @@
+/target
+out.mp4
+*.mp4
+!media/*.mp4
+frames/
+strip.png
+onion.png
+*.wav
+!media/*.wav
+test_render/
+_frame_snapshots/*.actual.png
+_frame_snapshots/*.diff.png
diff --git a/examples/signal-lab/Cargo.toml b/examples/signal-lab/Cargo.toml
new file mode 100644
index 00000000..30bf455c
--- /dev/null
+++ b/examples/signal-lab/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "signal-lab"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+fframes = { workspace = true, features = ["compile-time-svgtree", "cli"] }
+fframes_skia_renderer = { workspace = true, features = ["metal"] }
+fframes_native_player = { workspace = true, features = ["metal"] }
+
+[target.'cfg(not(windows))'.dependencies]
+fframes = { workspace = true, features = ["h264", "libav-agree-gpl"] }
+
+[lib]
+name = "signal_lab"
+path = "src/lib.rs"
+doctest = false
+
+[[bin]]
+name = "signal-lab"
+path = "src/main.rs"
+
diff --git a/examples/signal-lab/_frame_snapshots/datascene_3s.png b/examples/signal-lab/_frame_snapshots/datascene_3s.png
new file mode 100644
index 00000000..d36fa553
Binary files /dev/null and b/examples/signal-lab/_frame_snapshots/datascene_3s.png differ
diff --git a/examples/signal-lab/_frame_snapshots/finalscene_3s.png b/examples/signal-lab/_frame_snapshots/finalscene_3s.png
new file mode 100644
index 00000000..32bd25ec
Binary files /dev/null and b/examples/signal-lab/_frame_snapshots/finalscene_3s.png differ
diff --git a/examples/signal-lab/_frame_snapshots/productscene_3s.png b/examples/signal-lab/_frame_snapshots/productscene_3s.png
new file mode 100644
index 00000000..e683d6ce
Binary files /dev/null and b/examples/signal-lab/_frame_snapshots/productscene_3s.png differ
diff --git a/examples/signal-lab/_frame_snapshots/systemscene_3s.png b/examples/signal-lab/_frame_snapshots/systemscene_3s.png
new file mode 100644
index 00000000..ba9fcb0a
Binary files /dev/null and b/examples/signal-lab/_frame_snapshots/systemscene_3s.png differ
diff --git a/examples/signal-lab/media/DMSans-Medium.ttf b/examples/signal-lab/media/DMSans-Medium.ttf
new file mode 100644
index 00000000..fc8a5ebd
Binary files /dev/null and b/examples/signal-lab/media/DMSans-Medium.ttf differ
diff --git a/examples/signal-lab/media/pulse.wav b/examples/signal-lab/media/pulse.wav
new file mode 100644
index 00000000..8e927c3b
Binary files /dev/null and b/examples/signal-lab/media/pulse.wav differ
diff --git a/examples/signal-lab/src/lib.rs b/examples/signal-lab/src/lib.rs
new file mode 100644
index 00000000..f499f44a
--- /dev/null
+++ b/examples/signal-lab/src/lib.rs
@@ -0,0 +1,250 @@
+//! A 24-second motion study: product UI, data storytelling, and a technical explainer.
+use std::sync::LazyLock;
+
+use fframes::{
+ AnimateRuntimeInput, AudioMap, AudioTimestamp, AudioTrack, Color, Duration, FFramesContext,
+ FontQuery, Frame, Scene, Scenes, Svgr, TextOverflow, Transform, Video,
+ animation::{AnimationRuntime, Easing},
+ include_media_dir,
+};
+
+include_media_dir!(pub struct SignalLabMedia, "examples/signal-lab/media");
+
+pub const WIDTH: usize = 1920;
+pub const HEIGHT: usize = 1080;
+pub const SCENE_SECONDS: f32 = 6.0;
+const PAPER: &str = "#eeeae2";
+const INK: &str = "#152c2b";
+const MUTED: &str = "#53645e";
+const LIME: &str = "#d2f87a";
+const FONT: &str = "DM Sans";
+static EASE: LazyLock<AnimationRuntime> =
+ LazyLock::new(|| AnimationRuntime::new(0.8, &Easing::CubicBezier(0.16, 1.0, 0.3, 1.0)));
+static SPRING: LazyLock<AnimationRuntime> = LazyLock::new(|| {
+ AnimationRuntime::new(
+ 3.0,
+ &Easing::Spring {
+ mass: 1.0,
+ stiffness: 180.0,
+ damping: 20.0,
+ },
+ )
+});
+
+/// Four motion studies with an embedded synthesized soundtrack.
+#[derive(Debug)]
+pub struct SignalLabVideo;
+
+impl Video for SignalLabVideo {
+ const FPS: usize = 30;
+ const WIDTH: usize = WIDTH;
+ const HEIGHT: usize = HEIGHT;
+ const BACKGROUND_COLOR: Color = Color::WHITE;
+
+ fn duration(&self) -> Duration<'_> {
+ Duration::Auto
+ }
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::from([AudioTrack::new(
+ "pulse.wav",
+ AudioTimestamp::Second(0.0)..AudioTimestamp::Eof,
+ )
+ .gain_db(6.5)
+ .fade_in(0.08)
+ .fade_out(0.6)])
+ }
+ fn define_scenes(&self) -> Scenes<'_> {
+ Scenes::from(vec![
+ &ProductScene as &dyn Scene,
+ &DataScene,
+ &SystemScene,
+ &FinalScene,
+ ])
+ }
+ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let progress = (frame.seconds() / 24.0 * 1536.0).max(0.5);
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
+ <rect width="1920" height="1080" fill={PAPER} />
+ {ctx.render_scenes(&frame)}
+ <path d="M192 946 H1728" stroke="#b4bdb1" stroke-width="2" />
+ <rect x="192" y="945" width={progress} height="3" fill="#709542" />
+ <text x="192" y="1002" font-family="DM Sans" font-weight="500" font-size="28" fill={MUTED}>"FFRAMES / MOTION STUDIES"</text>
+ <text x="1728" y="1002" text-anchor="end" font-family="DM Sans" font-weight="500" font-size="28" fill={MUTED}>"24 SECONDS / SVG + RUST"</text>
+ </svg>
+ )
+ }
+}
+
+fn ramp(frame: &Frame, start: f32) -> f32 {
+ frame.animate_runtime(AnimateRuntimeInput {
+ on_second: start,
+ from: 0.0,
+ to: 1.0,
+ animation_runtime: &EASE,
+ })
+}
+fn rise(frame: &Frame, start: f32) -> f32 {
+ frame.animate_runtime(AnimateRuntimeInput {
+ on_second: start,
+ from: 56.0,
+ to: 0.0,
+ animation_runtime: &SPRING,
+ })
+}
+fn label<'a>(number: &'a str, title: &'a str) -> Svgr<'a> {
+ fframes::svgr!(<g font-family="DM Sans" font-size="30" font-weight="500" fill={INK}>
+ <circle cx="209" cy="147" r="17" fill="#709542" />
+ <text x="252" y="158">{title}</text>
+ <text x="1728" y="158" text-anchor="end">{number}</text>
+ </g>)
+}
+fn heading<'a>(frame: &mut Frame, ctx: &FFramesContext<'a, '_>, text: &'a str) -> Svgr<'a> {
+ let text = frame
+ .text_fit(
+ ctx,
+ FontQuery {
+ family: FONT,
+ size: 108,
+ weight: 500,
+ ..Default::default()
+ },
+ text,
+ 1536,
+ TextOverflow::Ellipsis,
+ )
+ .unwrap_or_else(|| text.into())
+ .into_owned();
+ fframes::svgr!(<text x="192" y="314" font-family="DM Sans" font-weight="500" font-size="108" letter-spacing="-4" fill={INK}>{text}</text>)
+}
+
+#[derive(Debug)]
+struct ProductScene;
+impl Scene for ProductScene {
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(SCENE_SECONDS)
+ }
+ fn render_frame<'a>(&'a self, frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let rows: Vec<_> = [("Build", "Ready"), ("Review", "Ready"), ("Publish", "Ready")].into_iter().enumerate().map(|(i, (name, status))| {
+ let y = 470 + i * 105;
+ let p = ramp(&frame, 0.7 + i as f32 * 0.12);
+ fframes::svgr!(<g opacity={p} transform={Transform::translate(0, rise(&frame, 0.7 + i as f32 * 0.12))}>
+ <rect x="1088" y={y - 46} width="540" height="82" rx="14" fill="#29403d" />
+ <text x="1124" y={y + 8} font-size="38" fill={PAPER}>{name}</text>
+ <text x="1586" y={y + 8} text-anchor="end" font-size="30" fill={LIME}>{status}</text>
+ </g>)
+ }).collect();
+ let angle = frame.seconds() * 8.0;
+ fframes::svgr!(<g font-family="DM Sans" font-weight="500">
+ {label("01 / 04", "PRODUCT ANNOUNCEMENT")}
+ <text x="183" y="445" font-size="208" letter-spacing="-10" fill={INK}>"Signal."</text>
+ <text x="192" y="543" font-size="52" fill={INK}>"Your next release,"</text>
+ <text x="192" y="610" font-size="52" fill={INK}>"in motion."</text>
+ <g opacity={ramp(&frame, 0.4)}>
+ <rect x="192" y="703" width="380" height="76" rx="38" fill={INK} />
+ <text x="382" y="753" text-anchor="middle" font-size="32" fill={LIME}>"A FICTIONAL PRODUCT"</text>
+ </g>
+ <g transform={Transform::translate(0, rise(&frame, 0.0))}>
+ <rect x="1000" y="262" width="728" height="576" rx="32" fill={INK} />
+ <circle cx="1095" cy="352" r="14" fill={LIME} />
+ <text x="1138" y="365" font-size="38" fill={PAPER}>"Release / 01"</text>
+ {rows}
+ <g transform={format!("translate(1650 278) rotate({angle})")}>
+ <circle r="73" fill={LIME} />
+ <path d="M-34 0 H34 M0 -34 V34 M-24 -24 L24 24 M-24 24 L24 -24" stroke={INK} stroke-width="7" />
+ </g>
+ </g>
+ </g>)
+ }
+}
+
+#[derive(Debug)]
+struct DataScene;
+impl Scene for DataScene {
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(SCENE_SECONDS)
+ }
+ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let bars: Vec<_> = [("01", 24.0), ("02", 41.0), ("03", 58.0), ("04", 76.0)].into_iter().enumerate().map(|(i, (name, value))| {
+ let p = ramp(&frame, 0.25 + i as f32 * 0.1);
+ let h = (value * 4.3 * p).max(0.5);
+ let x = 982 + i * 188;
+ fframes::svgr!(<g>
+ <rect x={x} y={798.0 - h} width="126" height={h} rx="8" fill={if i == 3 { "#709542" } else { "#b4bdb1" }} />
+ <text x={x + 63} y={775.0 - h} text-anchor="middle" font-size="36" fill={INK}>{format!("{:.0}", value * p)}</text>
+ <text x={x + 63} y="851" text-anchor="middle" font-size="30" fill={MUTED}>{name}</text>
+ </g>)
+ }).collect();
+ let count = 76.0 * ramp(&frame, 0.55);
+ fframes::svgr!(<g font-family="DM Sans" font-weight="500">
+ {label("02 / 04", "DATA STORY")}
+ {heading(&mut frame, ctx, "Give numbers a rhythm.")}
+ <text x="180" y="646" font-size="248" letter-spacing="-12" fill={INK}>{format!("{count:.0}")}</text>
+ <text x="192" y="734" font-size="46" fill={INK}>"Weekly activations"</text>
+ <text x="192" y="802" font-size="30" fill={MUTED}>"ILLUSTRATIVE DATA / WEEKS 01–04"</text>
+ {bars}
+ </g>)
+ }
+}
+
+#[derive(Debug)]
+struct SystemScene;
+impl Scene for SystemScene {
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(SCENE_SECONDS)
+ }
+ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let cards: Vec<_> = [("01", "Describe", "Rust + SVG"), ("02", "Inspect", "Frames + sound"), ("03", "Render", "Video file")].into_iter().enumerate().map(|(i, (n, title, subtitle))| {
+ let x = 192 + i * 548;
+ fframes::svgr!(<g opacity={ramp(&frame, 0.12 + i as f32 * 0.1)} transform={Transform::translate(0, rise(&frame, 0.12 + i as f32 * 0.1))}>
+ <rect x={x} y="440" width="440" height="302" rx="24" fill={INK} />
+ <text x={x + 36} y="505" font-size="30" fill={LIME}>{n}</text>
+ <text x={x + 36} y="612" font-size="64" fill={PAPER}>{title}</text>
+ <text x={x + 36} y="684" font-size="32" fill="#b4bdb1">{subtitle}</text>
+ </g>)
+ }).collect();
+ let travel = ((frame.seconds() - 1.2).max(0.0) / 2.8).min(1.0);
+ let x = 1508.0 - 1096.0 * travel;
+ fframes::svgr!(<g font-family="DM Sans" font-weight="500">
+ {label("03 / 04", "TECHNICAL EXPLAINER")}
+ {heading(&mut frame, ctx, "Make the process visible.")}
+ <g opacity={ramp(&frame, 0.4)}>
+ <path d="M632 591 H740 M1180 591 H1288" stroke="#709542" stroke-width="5" />
+ <path d="M718 577 L740 591 L718 605 M1266 577 L1288 591 L1266 605" stroke="#709542" stroke-width="5" fill="none" />
+ </g>
+ {cards}
+ <g opacity={ramp(&frame, 0.65)}>
+ <path d="M412 780 V824 H1508 V780" stroke="#b4bdb1" stroke-width="3" fill="none" />
+ <circle cx={x} cy="824" r="12" fill="#709542" />
+ <text x="960" y="894" text-anchor="middle" font-size="30" fill={MUTED}>"REVISE AND REPEAT"</text>
+ </g>
+ </g>)
+ }
+}
+
+#[derive(Debug)]
+struct FinalScene;
+impl Scene for FinalScene {
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(SCENE_SECONDS)
+ }
+ fn render_frame<'a>(&'a self, frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let p = ramp(&frame, 0.2);
+ let shift = rise(&frame, 0.2);
+ fframes::svgr!(<g font-family="DM Sans" font-weight="500">
+ {label("04 / 04", "CREATED WITH FFRAMES")}
+ <g transform={Transform::translate(0, shift)}>
+ <text x="183" y="457" font-size="146" letter-spacing="-6" fill={INK}>"Built from code."</text>
+ <text x="183" y="631" font-size="146" letter-spacing="-6" fill={INK}>"Ready to revise."</text>
+ </g>
+ <g opacity={p}>
+ <rect x="192" y="750" width="1536" height="90" rx="16" fill={INK} />
+ <text x="240" y="809" font-size="34" fill={PAPER}>"PRODUCT DEMOS"</text>
+ <circle cx="664" cy="797" r="7" fill={LIME} />
+ <text x="716" y="809" font-size="34" fill={PAPER}>"DATA STORIES"</text>
+ <circle cx="1100" cy="797" r="7" fill={LIME} />
+ <text x="1152" y="809" font-size="34" fill={PAPER}>"VISUAL EXPLAINERS"</text>
+ </g>
+ </g>)
+ }
+}
diff --git a/examples/signal-lab/src/main.rs b/examples/signal-lab/src/main.rs
new file mode 100644
index 00000000..7df31064
--- /dev/null
+++ b/examples/signal-lab/src/main.rs
@@ -0,0 +1,45 @@
+use fframes::cli::clap; // the derive below expands to `clap::...`
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, cli};
+use fframes_skia_renderer::{
+ SkiaFFramesRenderer, SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig, metal::SkiaMetalCtx,
+};
+use signal_lab::{HEIGHT, SignalLabMedia, SignalLabVideo, WIDTH};
+use std::process::ExitCode;
+
+/// Flags of this video next to the standard ones of `fframes::cli` (render, frame, strip,
+/// inspect, audio, ...). Run `cargo run --release -- --help`.
+#[derive(Debug, clap::Args)]
+struct VideoArgs {}
+
+fn main() -> ExitCode {
+ let args = cli::parse::<VideoArgs>();
+ let media = SignalLabMedia::prepare().expect("media");
+ let video = SignalLabVideo;
+ let gpu = SkiaMetalCtx::new(WIDTH, HEIGHT).expect("GPU context");
+
+ cli::new(
+ &video,
+ RenderOptions {
+ media: Some(&media),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ codec_params: Some(&[("crf", "20"), ("preset", "medium"), ("tune", "animation")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ )
+ .args(args)
+ .backend(
+ SkiaFFramesRenderer::new_metal(
+ &gpu,
+ SkiaPipelineConfig {
+ concurrency_policy: SkiaPipelineConcurrencyPolicy::MaxPerformance,
+ ..Default::default()
+ },
+ )
+ .expect("skia renderer"),
+ )
+ .preview(fframes_native_player::cli_preview)
+ .run()
+}
diff --git a/examples/signal-lab/tests/frames.rs b/examples/signal-lab/tests/frames.rs
new file mode 100644
index 00000000..d84327d6
--- /dev/null
+++ b/examples/signal-lab/tests/frames.rs
@@ -0,0 +1,56 @@
+//! 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/examples/signal-lab/tools/soundtrack.py b/examples/signal-lab/tools/soundtrack.py
new file mode 100644
index 00000000..3671aa73
--- /dev/null
+++ b/examples/signal-lab/tools/soundtrack.py
@@ -0,0 +1,33 @@
+"""Deterministic synthesized placeholder music; no downloaded or licensed recordings."""
+import math
+import pathlib
+import struct
+import wave
+
+RATE = 48000
+SECONDS = 24
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+# Four six-second scenes, with a soft pluck every half second.
+CHORDS = [(130.81, 164.81, 196.00), (110.00, 130.81, 164.81),
+ (87.31, 110.00, 130.81), (98.00, 123.47, 146.83)]
+output = bytearray()
+for i in range(RATE * SECONDS):
+ t = i / RATE
+ scene = min(int(t / 6), 3)
+ chord = CHORDS[scene]
+ beat = t % 0.5
+ note = chord[int(t * 2) % 3] * 4
+ env = (1 - math.exp(-beat * 100)) * math.exp(-beat * 7)
+ pluck = (math.sin(2 * math.pi * note * t) + 0.25 * math.sin(4 * math.pi * note * t)) * env
+ local = t % 6
+ pad_env = min(local / 0.2, 1) * min((6 - local) / 0.25, 1)
+ pad = sum(math.sin(2 * math.pi * f * t) for f in chord) / 3 * pad_env
+ tick = math.sin(2 * math.pi * 1200 * beat) * math.exp(-beat * 100) * (1 - math.exp(-beat * 2000))
+ fade = min(t / 0.02, 1) * min((SECONDS - t) / 0.6, 1)
+ sample = (0.20 * pluck + 0.14 * pad + 0.05 * tick) * fade
+ output.extend(struct.pack('<h', int(max(-1, min(1, sample)) * 32767)))
+with wave.open(str(ROOT / 'media' / 'pulse.wav'), 'wb') as audio:
+ audio.setnchannels(1)
+ audio.setsampwidth(2)
+ audio.setframerate(RATE)
+ audio.writeframes(output)
diff --git a/examples/teej-podcast/Cargo.toml b/examples/teej-podcast/Cargo.toml
index 8e88e51e..5fdf72f2 100644
--- a/examples/teej-podcast/Cargo.toml
+++ b/examples/teej-podcast/Cargo.toml
@@ -6,19 +6,22 @@ edition = "2024"
[dependencies]
clap = { version = "4.3.4", features = ["derive"] }
fframes = { workspace = true, features = ["h264", "h265", "libav-agree-gpl"] }
-image = "0.25.5"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fframes_skia_renderer = { workspace = true, features = ["vulkan"] }
+# `preview`: real-time GPU window
+fframes_native_player.workspace = true
# `main.rs` asks for `hevc_videotoolbox` on macOS, which only exists when
# ffmpeg is built with VideoToolbox.
[target.'cfg(target_os = "macos")'.dependencies]
fframes = { workspace = true, features = ["videotoolbox"] }
+# Metal for the preview window, no MoltenVK needed
+fframes_native_player = { workspace = true, features = ["metal"] }
[features]
default = ["renderer"]
-renderer = ["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
name = "teej_podcast_example"
diff --git a/examples/teej-podcast/src/main.rs b/examples/teej-podcast/src/main.rs
index 1aaa0b78..62b553cc 100644
--- a/examples/teej-podcast/src/main.rs
+++ b/examples/teej-podcast/src/main.rs
@@ -1,32 +1,10 @@
-use clap::Parser;
-use fframes::{EncoderOptions, MediaDirectory, RenderOptions, Video, fframes_logger};
+use fframes::{EncoderOptions, MediaDirectory, RenderOptions, Video, cli};
use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig, vulkan::SkiaVulkanCtx};
-use image::{ImageBuffer, Rgba};
use std::path::Path;
+use std::process::ExitCode;
use teej_podcast_example::{Chapter, TeejPodcast};
-#[derive(Debug, Parser)]
-struct Args {
- #[clap(short, long, default_value = "out.mp4")]
- output: String,
- #[clap(long)]
- video_codec: Option<String>,
- #[clap(long)]
- audio_codec: Option<String>,
- #[clap(short, long)]
- concurrency: Option<usize>,
- #[clap(short, long)]
- pub font: Option<String>,
- /// Render a single frame to PNG for preview instead of the full video
- #[clap(long)]
- preview: bool,
- /// Frame index to render when using --preview (default: 24, i.e. 1 second at 24fps)
- #[clap(long, default_value = "24")]
- preview_frame: usize,
-}
-
-fn main() {
- let args = Args::parse();
+fn main() -> ExitCode {
let media_folder = MediaDirectory::read_folder(Path::new("./dynamic_media")).unwrap();
let dynamic_media = media_folder.process_media_source().unwrap();
let vulkan_ctx = SkiaVulkanCtx::new(TeejPodcast::WIDTH, TeejPodcast::HEIGHT).unwrap();
@@ -51,7 +29,6 @@ fn main() {
let options = RenderOptions {
media: Some(&dynamic_media),
load_system_fonts: true,
- logger: fframes_logger::FFramesLoggerVariant::Compact,
video_encoder_options: EncoderOptions {
#[cfg(target_os = "macos")]
preferred_encoder: Some("hevc_videotoolbox"),
@@ -73,38 +50,19 @@ fn main() {
..Default::default()
};
- let backend = SkiaFFramesRenderer::new_vulkan(
- &vulkan_ctx,
- SkiaPipelineConfig {
- buffer_queue_size: 20,
- concurrency_policy:
- fframes_skia_renderer::SkiaPipelineConcurrencyPolicy::MaxPerformance,
- ..Default::default()
- },
- )
- .expect("Failed to create renderer");
-
- if args.preview {
- let frame_buffer = fframes::render_frame(args.preview_frame, &video, backend, &options)
- .expect("Failed to render preview frame");
-
- let img = ImageBuffer::<Rgba<u8>, Vec<u8>>::from_raw(
- TeejPodcast::WIDTH as u32,
- TeejPodcast::HEIGHT as u32,
- frame_buffer,
+ cli::new(&video, options)
+ .backend(
+ SkiaFFramesRenderer::new_vulkan(
+ &vulkan_ctx,
+ SkiaPipelineConfig {
+ buffer_queue_size: 20,
+ concurrency_policy:
+ fframes_skia_renderer::SkiaPipelineConcurrencyPolicy::MaxPerformance,
+ ..Default::default()
+ },
+ )
+ .expect("Failed to create renderer"),
)
- .expect("Failed to create image buffer");
-
- img.save("frame_preview.png")
- .expect("Failed to save preview image");
-
- println!(
- "Saved frame {} preview to frame_preview.png ({}x{})",
- args.preview_frame,
- TeejPodcast::WIDTH,
- TeejPodcast::HEIGHT
- );
- } else {
- fframes::render(args.output.as_str(), &video, backend, &options).unwrap();
- }
+ .preview(fframes_native_player::cli_preview)
+ .run()
}
diff --git a/examples/tiktok/Cargo.toml b/examples/tiktok/Cargo.toml
index 06c5208c..955b8fb4 100644
--- a/examples/tiktok/Cargo.toml
+++ b/examples/tiktok/Cargo.toml
@@ -10,7 +10,7 @@ libm="0.2.8"
[features]
default=["renderer"]
-renderer=["fframes/compile-time-svgtree"]
+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]
[lib]
name = "tiktok_example"
diff --git a/examples/tiktok/src/main.rs b/examples/tiktok/src/main.rs
index a24bb3f5..0f03d8c6 100644
--- a/examples/tiktok/src/main.rs
+++ b/examples/tiktok/src/main.rs
@@ -1,22 +1,19 @@
+use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, cli};
use std::path::PathBuf;
-
-use fframes::{EncoderOptions, RenderOptions, StaticMediaProvider, fframes_logger, render};
+use std::process::ExitCode;
use tiktok_example::{GooseMedia, GooseVideo};
-fn main() {
+fn main() -> ExitCode {
+ // VP9 with alpha: the video has a transparent background.
+
let media = GooseMedia::prepare().unwrap();
+ let tmp = PathBuf::from("test_render");
- render(
- "out.webm",
+ cli::new(
&GooseVideo { media: &media },
- fframes::cpu::CpuRenderingBackend {
- cache_capacity: 200,
- ..Default::default()
- },
- &RenderOptions {
+ RenderOptions {
media: Some(&media),
- logger: fframes_logger::FFramesLoggerVariant::Compact,
- tmp_files_directory: Some(&PathBuf::from("test_render")),
+ tmp_files_directory: Some(&tmp),
video_encoder_options: EncoderOptions {
preferred_encoder: Some("libvpx-vp9"),
pixel_format: fframes::AVPixelFormat::AV_PIX_FMT_YUVA420P,
@@ -31,5 +28,10 @@ fn main() {
..Default::default()
},
)
- .unwrap();
+ .backend(fframes::cpu::CpuRenderingBackend {
+ cache_capacity: 200,
+ ..Default::default()
+ })
+ .default_output("out.webm")
+ .run()
}
diff --git a/fframes-editor-controller/src/wasm_audio.rs b/fframes-editor-controller/src/wasm_audio.rs
index e9eb9657..07ec0266 100644
--- a/fframes-editor-controller/src/wasm_audio.rs
+++ b/fframes-editor-controller/src/wasm_audio.rs
@@ -58,14 +58,14 @@ impl AudioData {
/// (`resolve_video_duration`, in seconds), falling back to the audio track
/// when the metadata is not registered yet.
async fn resolve_used_media_durations<'a, 'media: 'a, TStaticMedia: StaticMediaProvider<'media>>(
- tb: &TimeBase,
duration: &'a Duration<'a>,
scene_audios: &'a ScenesWithAudio<'media>,
global_audio_map: &'a fframes::AudioMap<'a>,
static_media: &'media TStaticMedia,
resolve_video_duration: impl Fn(&str) -> Option<f32>,
-) -> fframes::error::Result<HashMap<String, usize>> {
- let mut duration_map: HashMap<String, usize> = HashMap::new();
+) -> fframes::error::Result<HashMap<String, f64>> {
+ // Durations in seconds, the timeline converts them to frames or samples.
+ let mut duration_map: HashMap<String, f64> = HashMap::new();
let mut all_used_files = global_audio_map
.used_audio_files::<Vec<&str>>()
@@ -81,7 +81,7 @@ async fn resolve_used_media_durations<'a, 'media: 'a, TStaticMedia: StaticMediaP
// The editor registers video metadata while `prepare` is already
// running, so a video that is not registered yet is measured through
// its audio track instead (like any audio file).
- let mut video_durations: HashMap<String, usize> = HashMap::new();
+ let mut video_durations: HashMap<String, f64> = HashMap::new();
for file in duration
.used_video_files()
.into_iter()
@@ -90,8 +90,7 @@ async fn resolve_used_media_durations<'a, 'media: 'a, TStaticMedia: StaticMediaP
{
match resolve_video_duration(file) {
Some(seconds) => {
- video_durations
- .insert(file.to_string(), (seconds * tb.fps as f32).round() as usize);
+ video_durations.insert(file.to_string(), seconds as f64);
}
None => all_used_files.push(file),
}
@@ -112,8 +111,7 @@ async fn resolve_used_media_durations<'a, 'media: 'a, TStaticMedia: StaticMediaP
// if audio is not static than we need to fetch and load it through the browser xhr
static_audio
.map(|audio| {
- let duration = audio.duration_in_frames(tb);
- duration_map.insert(file.to_string(), duration);
+ duration_map.insert(file.to_string(), audio.duration_in_seconds() as f64);
})
.is_none()
})
@@ -135,9 +133,8 @@ async fn resolve_used_media_durations<'a, 'media: 'a, TStaticMedia: StaticMediaP
.try_for_each(|(js_value, file)| match js_value {
Ok(val) => val
.as_f64()
- .map(|val| {
- let frames = val * tb.fps as f64;
- duration_map.insert(file.to_string(), frames as usize);
+ .map(|seconds| {
+ duration_map.insert(file.to_string(), seconds);
})
.ok_or_else(|| FFramesError::CanNotProcessAudioDuration(file.to_string())),
Err(_) => Err(FFramesError::CanNotProcessAudioDuration(file.to_string())),
@@ -169,7 +166,6 @@ pub async fn prepare_video_with_audio<
let scene_audios = ScenesWithAudio::new(scenes);
let audio_durations = resolve_used_media_durations(
- tb,
&video_duration,
&scene_audios,
&audio_map,
diff --git a/fframes-editor-controller/src/wasm_editor.rs b/fframes-editor-controller/src/wasm_editor.rs
index a7c81b65..71f83147 100644
--- a/fframes-editor-controller/src/wasm_editor.rs
+++ b/fframes-editor-controller/src/wasm_editor.rs
@@ -166,6 +166,7 @@ impl<TVideo: Video, TMedia: StaticMediaProvider<'static> + 'static> WasmEditor<T
sample_rate: sample_rate as u32,
// Can't guarantee the lifetime of the input slice
samples: std::borrow::Cow::Owned(input.to_vec()),
+ right: None,
};
let mut media_provider = self.media_provider.lock().unwrap();
diff --git a/fframes-media/src/audio.rs b/fframes-media/src/audio.rs
index 11886e6d..43d7e562 100644
--- a/fframes-media/src/audio.rs
+++ b/fframes-media/src/audio.rs
@@ -2,11 +2,24 @@ use std::borrow::Cow;
#[derive(Clone, Debug)]
pub struct PreloadedAudioData<'a> {
+ /// The only channel of a mono file or the left channel of a stereo file.
pub samples: Cow<'a, [f32]>,
pub sample_rate: u32,
+ /// The right channel of a stereo file, same length as `samples`.
+ pub right: Option<Cow<'a, [f32]>>,
}
impl PreloadedAudioData<'_> {
+ pub fn is_stereo(&self) -> bool {
+ self.right.is_some()
+ }
+
+ /// `(left, right)`; for mono files both are the same channel.
+ pub fn channels(&self) -> (&[f32], &[f32]) {
+ let left = self.samples.as_ref();
+ (left, self.right.as_deref().unwrap_or(left))
+ }
+
pub fn duration_in_seconds(&self) -> f32 {
self.samples.len() as f32 / self.sample_rate as f32
}
@@ -25,6 +38,27 @@ impl PreloadedAudioData<'_> {
self.samples.get(start_index..start_index + length)
}
+ /// Like `get_frame_data` but averages both channels of stereo files.
+ pub fn get_frame_data_mono(
+ &self,
+ length: usize,
+ frame: usize,
+ fps: i64,
+ ) -> Option<Cow<'_, [f32]>> {
+ let start_index = frame * self.sample_rate as usize / fps as usize;
+ let range = start_index..start_index + length;
+ let left = self.samples.get(range.clone())?;
+ match self.right.as_deref() {
+ Some(right) => Some(Cow::Owned(
+ left.iter()
+ .zip(right.get(range)?)
+ .map(|(l, r)| (l + r) * 0.5)
+ .collect(),
+ )),
+ None => Some(Cow::Borrowed(left)),
+ }
+ }
+
#[cfg(not(target_arch = "wasm32"))]
pub fn decode_raw_file(
sample_rate: Option<u32>,
@@ -38,6 +72,29 @@ impl PreloadedAudioData<'_> {
Ok(PreloadedAudioData {
samples: Cow::Owned(samples),
sample_rate,
+ right: None,
+ })
+ }
+
+ /// Decodes a file keeping stereo: mono files stay mono, stereo files keep both channels
+ /// and files with more channels are downmixed to stereo.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn decode_raw_file_stereo(
+ sample_rate: Option<u32>,
+ filename: &std::path::PathBuf,
+ ) -> crate::error::Result<Self> {
+ use crate::audio_decoder::{AudioDecoder, ChannelMode};
+
+ let mut decoder =
+ AudioDecoder::new_with_channels(filename, sample_rate, ChannelMode::KeepStereo)?;
+ let (sample_rate, mut channels) = decoder.decode_all_channels()?;
+ let right = (channels.len() > 1).then(|| Cow::Owned(channels.pop().unwrap_or_default()));
+ let samples = channels.pop().unwrap_or_default();
+
+ Ok(PreloadedAudioData {
+ samples: Cow::Owned(samples),
+ sample_rate,
+ right,
})
}
}
diff --git a/fframes-media/src/audio_decoder.rs b/fframes-media/src/audio_decoder.rs
index 9d9e2c3b..bcb7e8a2 100644
--- a/fframes-media/src/audio_decoder.rs
+++ b/fframes-media/src/audio_decoder.rs
@@ -5,7 +5,17 @@ use std::ffi::CString;
use std::path::Path;
use std::ptr;
+/// How the decoder maps the file's channels to the output.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ChannelMode {
+ /// Everything is downmixed to one channel.
+ Mono,
+ /// Mono stays mono, stereo stays stereo, anything larger is downmixed to stereo.
+ KeepStereo,
+}
+
pub struct AudioDecoder {
+ out_channels: usize,
fmt_context: *mut AVFormatContext,
decoding_ctx: *mut AVCodecContext,
swr_ctx: *mut SwrContext,
@@ -17,6 +27,14 @@ pub struct AudioDecoder {
impl AudioDecoder {
pub fn new(filename: impl AsRef<Path>, sample_rate: Option<u32>) -> Result<Self> {
+ Self::new_with_channels(filename, sample_rate, ChannelMode::Mono)
+ }
+
+ pub fn new_with_channels(
+ filename: impl AsRef<Path>,
+ sample_rate: Option<u32>,
+ channel_mode: ChannelMode,
+ ) -> Result<Self> {
unsafe {
av_log_set_level(AV_LOG_FATAL);
@@ -120,17 +138,32 @@ impl AudioDecoder {
0,
);
+ // Some containers leave the layout unspecified, swr needs a real one.
+ let mut in_layout = (*decoding_ctx).ch_layout;
+ if in_layout.order == AVChannelOrder::AV_CHANNEL_ORDER_UNSPEC {
+ av_channel_layout_default(&mut in_layout, in_layout.nb_channels.max(1));
+ }
+
+ let out_channels = match channel_mode {
+ ChannelMode::KeepStereo if in_layout.nb_channels >= 2 => 2,
+ _ => 1,
+ };
+
av_opt_set_chlayout(
swr_ctx as *mut _ as *mut std::ffi::c_void,
CString::new("in_chlayout")?.as_ptr(),
- &(*decoding_ctx).ch_layout,
+ &in_layout,
0,
);
av_opt_set_chlayout(
swr_ctx as *mut _ as *mut std::ffi::c_void,
CString::new("out_chlayout")?.as_ptr(),
- &MONO_CH_LAYOUT,
+ if out_channels == 2 {
+ &STEREO_CH_LAYOUT
+ } else {
+ &MONO_CH_LAYOUT
+ },
0,
);
@@ -177,6 +210,7 @@ impl AudioDecoder {
}
Ok(Self {
+ out_channels,
fmt_context,
decoding_ctx,
swr_ctx,
@@ -188,7 +222,48 @@ impl AudioDecoder {
}
}
- unsafe fn decode_packet(&mut self, samples: &mut Vec<f32>) -> Result<()> {
+ /// Appends `max_samples` of swr output to every channel buffer. `input` is null to drain.
+ unsafe fn convert_into(
+ &mut self,
+ channels: &mut [Vec<f32>],
+ max_samples: i32,
+ input: *mut *const u8,
+ input_samples: i32,
+ ) -> Result<()> {
+ unsafe {
+ let lengths: Vec<usize> = channels.iter().map(Vec::len).collect();
+ let mut planes: Vec<*mut u8> = channels
+ .iter_mut()
+ .zip(&lengths)
+ .map(|(channel, len)| {
+ channel.reserve(max_samples.max(0) as usize);
+ channel.as_mut_ptr().add(*len) as *mut u8
+ })
+ .collect();
+
+ let ret = swr_convert(
+ self.swr_ctx,
+ planes.as_mut_ptr(),
+ max_samples,
+ input,
+ input_samples,
+ );
+ if ret < 0 {
+ return Err(FFramesMediaError::LibAVAudioDecodingError((
+ ret,
+ "Error while resampling".to_string(),
+ )));
+ }
+
+ for (channel, len) in channels.iter_mut().zip(lengths) {
+ channel.set_len(len + ret as usize);
+ }
+
+ Ok(())
+ }
+ }
+
+ unsafe fn decode_packet(&mut self, channels: &mut [Vec<f32>]) -> Result<()> {
unsafe {
let mut ret;
@@ -227,33 +302,28 @@ impl AudioDecoder {
AVRounding::AV_ROUND_UP,
);
- let current_length = samples.len();
- samples.reserve(nb_samples as usize);
- let ret = swr_convert(
- self.swr_ctx,
- [samples.as_mut_ptr().add(current_length)].as_ptr() as *mut *mut _,
+ self.convert_into(
+ channels,
nb_samples as i32,
- (*self.frame).data.as_mut_ptr() as *mut _ as *mut *const u8,
+ (*self.frame).extended_data as *mut *const u8,
(*self.frame).nb_samples,
- );
-
- if ret < 0 {
- return Err(FFramesMediaError::LibAVAudioDecodingError((
- ret,
- "Error while resampling".to_string(),
- )));
- }
-
- samples.set_len(current_length + ret as usize);
+ )?;
}
Ok(())
}
}
+ /// Decodes the whole file into one mono channel (see `ChannelMode`).
pub fn decode_all_samples(&mut self) -> Result<(u32, Vec<f32>)> {
+ let (sample_rate, mut channels) = self.decode_all_channels()?;
+ Ok((sample_rate, channels.swap_remove(0)))
+ }
+
+ /// Decodes the whole file, one buffer per output channel.
+ pub fn decode_all_channels(&mut self) -> Result<(u32, Vec<Vec<f32>>)> {
unsafe {
- let mut samples = Vec::new();
+ let mut samples = vec![Vec::new(); self.out_channels];
while av_read_frame(self.fmt_context, self.avpkt) >= 0 {
if (*self.avpkt).stream_index == self.stream_idx
@@ -276,22 +346,7 @@ impl AudioDecoder {
// Drain samples the resampler still buffers.
let delay = swr_get_delay(self.swr_ctx, self.out_sample_rate as i64);
if delay > 0 {
- let current_length = samples.len();
- samples.reserve(delay as usize);
- let ret = swr_convert(
- self.swr_ctx,
- [samples.as_mut_ptr().add(current_length)].as_ptr() as *mut *mut _,
- delay as i32,
- std::ptr::null_mut(),
- 0,
- );
- if ret < 0 {
- return Err(FFramesMediaError::LibAVAudioDecodingError((
- ret,
- "Error while draining the resampler".to_string(),
- )));
- }
- samples.set_len(current_length + ret as usize);
+ self.convert_into(&mut samples, delay as i32, std::ptr::null_mut(), 0)?;
}
Ok((self.out_sample_rate, samples))
@@ -327,6 +382,15 @@ pub const fn FFMPEG_AVERROR(e: std::os::raw::c_int) -> std::os::raw::c_int {
-e
}
+const STEREO_CH_LAYOUT: AVChannelLayout = AVChannelLayout {
+ order: AVChannelOrder::AV_CHANNEL_ORDER_NATIVE,
+ nb_channels: 2,
+ u: AVChannelLayout__bindgen_ty_1 {
+ mask: AV_CH_LAYOUT_STEREO,
+ },
+ opaque: std::ptr::null_mut(),
+};
+
const MONO_CH_LAYOUT: AVChannelLayout = AVChannelLayout {
order: AVChannelOrder::AV_CHANNEL_ORDER_NATIVE,
nb_channels: 1,
@@ -368,4 +432,20 @@ mod tests {
let result = decoder.decode_all_samples();
assert_eq!(result.unwrap().1.len(), 927744);
}
+
+ #[test]
+ fn keeps_stereo_channels() {
+ let mut decoder = AudioDecoder::new_with_channels(
+ PathBuf::from("test_audio/audio.wav"),
+ None,
+ ChannelMode::KeepStereo,
+ )
+ .unwrap();
+ let (_, channels) = decoder.decode_all_channels().unwrap();
+ let mut mono = AudioDecoder::new(PathBuf::from("test_audio/audio.wav"), None).unwrap();
+ let (_, mono) = mono.decode_all_samples().unwrap();
+
+ assert_eq!(channels.len(), 2, "the test files are stereo");
+ assert!(channels.iter().all(|c| c.len() == mono.len()));
+ }
}
diff --git a/fframes-native-player/Cargo.toml b/fframes-native-player/Cargo.toml
index 197336f7..bd2d2b72 100644
--- a/fframes-native-player/Cargo.toml
+++ b/fframes-native-player/Cargo.toml
@@ -4,6 +4,8 @@ description = "Real-time native preview window for fframes videos, rendered with
version = "1.0.0-beta.6.rc-3.2"
edition = "2024"
license = "MIT"
+repository = "https://github.com/dmtrKovalenko/fframes"
+homepage = "https://fframes.studio"
authors = ["Dmitriy Kovalenko <[email protected]>"]
[lib]
diff --git a/fframes-native-player/src/audio.rs b/fframes-native-player/src/audio.rs
index 82b670e7..472523a9 100644
--- a/fframes-native-player/src/audio.rs
+++ b/fframes-native-player/src/audio.rs
@@ -1,6 +1,9 @@
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{FromSample, SizedSample};
-use fframes::{AudioTimelineSamples, AudioTimelineUnit, FFramesContext, ResolvedAudioMap};
+use fframes::{
+ AudioMixOptions, AudioMixer, AudioTimelineSamples, AudioTimelineUnit, FFramesContext,
+ ResolvedAudioMap,
+};
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
@@ -22,7 +25,8 @@ struct Shared {
}
struct Queue {
- samples: VecDeque<f32>,
+ /// Stereo frames `(left, right)`.
+ samples: VecDeque<(f32, f32)>,
playing: bool,
looping: bool,
/// Next position to mix, in samples since the start of the (possibly looped) playback.
@@ -99,11 +103,26 @@ impl AudioOutput {
&self,
ctx: &FFramesContext<'_, '_>,
audio_map: &ResolvedAudioMap<AudioTimelineSamples>,
+ mix_options: AudioMixOptions,
) {
let total_samples =
AudioTimelineSamples::from_frames(ctx.duration_in_frames, &ctx.time_base)
.as_usize()
.max(1) as u64;
+ // The same mixer as the encoder: what plays here is what gets rendered.
+ let mut mixer = AudioMixer::new(
+ Some(audio_map),
+ ctx.media_source,
+ self.sample_rate,
+ 0..total_samples as usize,
+ total_samples as usize,
+ mix_options,
+ );
+ for file in mixer.missing_files() {
+ eprintln!("fframes player: audio \"{file}\" is not in the media provider");
+ }
+ let mut left = vec![0.; CHUNK];
+ let mut right = vec![0.; CHUNK];
loop {
let (position, looping, epoch) = {
@@ -133,16 +152,21 @@ impl AudioOutput {
// Do not mix across the end of the video in one chunk.
let len = CHUNK.min((total_samples - timeline_sample) as usize);
- let mut chunk = ctx.get_mixed_audio_data_in_fltp(
- audio_map,
- AudioTimelineSamples::from_usize(timeline_sample as usize),
- len,
+ // The mixer keeps limiter state between consecutive chunks and resets it on seeks.
+ mixer.render(
+ timeline_sample as usize,
+ &mut left[..len],
+ &mut right[..len],
);
- chunk.resize(len, 0.0);
let mut queue = self.shared.lock();
if queue.epoch == epoch {
- queue.samples.extend(chunk);
+ queue.samples.extend(
+ left[..len]
+ .iter()
+ .copied()
+ .zip(right[..len].iter().copied()),
+ );
queue.feed_position += len as u64;
}
}
@@ -165,12 +189,21 @@ fn build_stream<T: SizedSample + FromSample<f32>>(
let playing = queue.playing;
for frame in data.chunks_mut(channels) {
- let sample = if playing {
- queue.samples.pop_front().unwrap_or(0.0)
+ let (left, right) = if playing {
+ queue.samples.pop_front().unwrap_or((0.0, 0.0))
} else {
- 0.0
+ (0.0, 0.0)
};
- frame.fill(T::from_sample(sample));
+ match frame {
+ [mono] => *mono = T::from_sample((left + right) * 0.5),
+ [l, r, rest @ ..] => {
+ *l = T::from_sample(left);
+ *r = T::from_sample(right);
+ // Surround outputs: stereo on the front pair only.
+ rest.fill(T::from_sample(0.0));
+ }
+ [] => {}
+ }
}
let needs_more = playing && queue.samples.len() < shared.target_len;
diff --git a/fframes-native-player/src/lib.rs b/fframes-native-player/src/lib.rs
index 4d8e0707..e4b29cb4 100644
--- a/fframes-native-player/src/lib.rs
+++ b/fframes-native-player/src/lib.rs
@@ -164,7 +164,7 @@ pub fn play<'a, 'media: 'a, TVideo: Video + Sync>(
#[cfg(feature = "audio")]
if let (Some(audio), Some(audio_map)) = (audio.as_ref(), timeline.audio_map.as_ref()) {
- scope.spawn(|| audio.run_feeder(&ctx, audio_map));
+ scope.spawn(|| audio.run_feeder(&ctx, audio_map, options.audio_mix));
}
// The event loop has to run on the main thread (macOS).
@@ -186,6 +186,67 @@ pub fn play<'a, 'media: 'a, TVideo: Video + Sync>(
Ok(result?)
}
+/// The `preview` command of `fframes::cli`: plays the video with the media, fonts and audio
+/// mix of the render options.
+///
+/// ```rust,ignore
+/// fframes::cli::run_with_preview(cli, &video, options, make_backend, &mut frame_renderer,
+/// fframes_native_player::cli_preview)
+/// ```
+pub fn cli_preview<'a, 'media: 'a, TVideo: Video + Sync>(
+ video: &'a TVideo,
+ options: &fframes::RenderOptions<'a, 'media>,
+ request: &fframes::PreviewRequest,
+) -> Result<(), String> {
+ let backend = match request.backend.as_str() {
+ "auto" => PlayerBackend::Auto,
+ "cpu" => PlayerBackend::Cpu,
+ #[cfg(feature = "metal")]
+ "metal" => PlayerBackend::Metal,
+ #[cfg(feature = "vulkan")]
+ "vulkan" => PlayerBackend::Vulkan,
+ other => {
+ let mut available = vec!["auto"];
+ #[cfg(feature = "metal")]
+ available.push("metal");
+ #[cfg(feature = "vulkan")]
+ available.push("vulkan");
+ available.push("cpu");
+ return Err(format!(
+ "backend \"{other}\" is not available in this build, use one of: {}",
+ available.join(", ")
+ ));
+ }
+ };
+
+ let title = std::env::args()
+ .next()
+ .and_then(|program| {
+ std::path::Path::new(&program)
+ .file_stem()
+ .map(|name| name.to_string_lossy().into_owned())
+ })
+ .unwrap_or_else(|| "fframes".to_owned());
+
+ play(
+ video,
+ &PlayerOptions {
+ media: options.media,
+ load_system_fonts: options.load_system_fonts,
+ default_font: options.default_font,
+ title: &title,
+ backend,
+ autoplay: request.autoplay,
+ looping: request.looping,
+ start_frame: request.start_frame,
+ audio: request.audio,
+ audio_mix: options.audio_mix,
+ ..Default::default()
+ },
+ )
+ .map_err(|err| err.to_string())
+}
+
fn initial_window_size<TVideo: Video>(options: &PlayerOptions) -> LogicalSize<u32> {
if let Some((width, height)) = options.window_size {
return LogicalSize::new(width, height);
diff --git a/fframes-native-player/src/options.rs b/fframes-native-player/src/options.rs
index c53ef42d..0f64f490 100644
--- a/fframes-native-player/src/options.rs
+++ b/fframes-native-player/src/options.rs
@@ -41,6 +41,8 @@ pub struct PlayerOptions<'a, 'media> {
pub render_threads: Option<usize>,
/// How many frames ahead of the playhead may be prepared.
pub prefetch_frames: usize,
+ /// Master bus of the audio mix, see `RenderOptions::audio_mix`.
+ pub audio_mix: fframes::AudioMixOptions,
}
impl Default for PlayerOptions<'_, '_> {
@@ -58,6 +60,7 @@ impl Default for PlayerOptions<'_, '_> {
audio: true,
render_threads: None,
prefetch_frames: 12,
+ audio_mix: Default::default(),
}
}
}
diff --git a/fframes-native-player/src/scheduler.rs b/fframes-native-player/src/scheduler.rs
index a17daf3d..978effff 100644
--- a/fframes-native-player/src/scheduler.rs
+++ b/fframes-native-player/src/scheduler.rs
@@ -175,11 +175,14 @@ impl Scheduler {
video_decoders.clone(),
);
- match video.render_frame(frame, ctx).into_svg_tree(
- usvg_options,
- &mut converter_cache,
- font_db,
- ) {
+ // A panicking frame is reported with its time and scene and skipped.
+ let tree = fframes::render_frame_guarded(video, frame, ctx)
+ .map_err(fframes::FFramesRendererError::from)
+ .and_then(|svgr| {
+ Ok(svgr.into_svg_tree(usvg_options, &mut converter_cache, font_db)?)
+ });
+
+ match tree {
Ok(tree) => {
if self.complete(&job, tree) {
on_frame_ready();
diff --git a/fframes-skia-renderer/src/backends/metal.rs b/fframes-skia-renderer/src/backends/metal.rs
index 0674623a..2e64d248 100644
--- a/fframes-skia-renderer/src/backends/metal.rs
+++ b/fframes-skia-renderer/src/backends/metal.rs
@@ -48,27 +48,6 @@ impl SkiaMetalCtx {
)
};
- let mut gpu_context_opts = gpu::ContextOptions::new();
-
- // Cache configuration
- gpu_context_opts.glyph_cache_texture_maximum_bytes = 64 * 1024 * 1024; // 64MB
- gpu_context_opts.allow_multiple_glyph_cache_textures = Enable::Yes;
- gpu_context_opts.buffer_map_threshold = 4096;
- gpu_context_opts.minimum_staging_buffer_size = 1_048_576;
-
- // Path rendering optimizations
- gpu_context_opts.allow_path_mask_caching = true;
- gpu_context_opts.disable_distance_field_paths = false;
- gpu_context_opts.disable_coverage_counting_paths = true;
-
- // Shader configuration
- gpu_context_opts.runtime_program_cache_size = 256;
- gpu_context_opts.shader_cache_strategy = ShaderCacheStrategy::BackendBinary;
- gpu_context_opts.reduced_shader_variations = false;
-
- // Batch processing
- gpu_context_opts.reduce_ops_task_splitting = Enable::Yes;
-
Ok(SkiaMetalCtx {
device,
command_queue,
@@ -101,7 +80,8 @@ impl SkiaMetalCtx {
)
};
- let mut gpu_context = gpu::direct_contexts::make_metal(&backend, None).unwrap();
+ let mut gpu_context =
+ gpu::direct_contexts::make_metal(&backend, Some(&gpu_context_options())).unwrap();
let ctx = Self::new_with_device(device, command_queue, width, height)?;
let surface = {
let backend_render_target =
@@ -124,9 +104,36 @@ impl SkiaMetalCtx {
}
}
+/// Skia GPU context settings, the same as the Vulkan backend uses.
+fn gpu_context_options() -> gpu::ContextOptions {
+ let mut gpu_context_opts = gpu::ContextOptions::new();
+
+ // Cache configuration
+ gpu_context_opts.glyph_cache_texture_maximum_bytes = 64 * 1024 * 1024; // 64MB
+ gpu_context_opts.allow_multiple_glyph_cache_textures = Enable::Yes;
+ gpu_context_opts.buffer_map_threshold = 4096;
+ gpu_context_opts.minimum_staging_buffer_size = 1_048_576;
+
+ // Path rendering optimizations
+ gpu_context_opts.allow_path_mask_caching = true;
+ gpu_context_opts.disable_distance_field_paths = false;
+ gpu_context_opts.disable_coverage_counting_paths = true;
+
+ // Shader configuration
+ gpu_context_opts.runtime_program_cache_size = 256;
+ gpu_context_opts.shader_cache_strategy = ShaderCacheStrategy::BackendBinary;
+ gpu_context_opts.reduced_shader_variations = false;
+
+ // Batch processing
+ gpu_context_opts.reduce_ops_task_splitting = Enable::Yes;
+
+ gpu_context_opts
+}
+
impl SkiaBackend for SkiaMetalCtx {
fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)> {
- let mut gpu_context = gpu::direct_contexts::make_metal(&self.backend, None).unwrap();
+ let mut gpu_context =
+ gpu::direct_contexts::make_metal(&self.backend, Some(&gpu_context_options())).unwrap();
let texture_descriptor = TextureDescriptor::new();
texture_descriptor.set_width(self.width as u64);
diff --git a/fframes-skia-renderer/src/frame_renderer.rs b/fframes-skia-renderer/src/frame_renderer.rs
new file mode 100644
index 00000000..1e8c9c3f
--- /dev/null
+++ b/fframes-skia-renderer/src/frame_renderer.rs
@@ -0,0 +1,123 @@
+use crate::SkiaBackend;
+use fframes::{
+ Color, FFramesRendererError, FFramesRendererResult, FrameRenderer, RgbaFrame, usvgr,
+};
+use skia_safe::{AlphaType, Canvas, ColorType, ImageInfo, Surface, gpu, surfaces};
+
+/// Creates a surface of the requested size. The backends create surfaces of the size they
+/// were constructed with; scaled renders (`scale_resolution`, previews) need another size.
+pub fn surface_with_size<TBackend: SkiaBackend + ?Sized>(
+ backend: &TBackend,
+ width: i32,
+ height: i32,
+) -> FFramesRendererResult<(Surface, Option<gpu::DirectContext>)> {
+ let (surface, mut gpu_context) = backend.create_skia_surface()?;
+ if surface.width() == width && surface.height() == height {
+ return Ok((surface, gpu_context));
+ }
+
+ let info = ImageInfo::new(
+ (width, height),
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ None,
+ );
+ let surface = match gpu_context.as_mut() {
+ Some(gpu_context) => gpu::surfaces::render_target(
+ gpu_context,
+ gpu::Budgeted::Yes,
+ &info,
+ None,
+ gpu::SurfaceOrigin::TopLeft,
+ None,
+ false,
+ None,
+ ),
+ None => surfaces::raster(&info, None, None),
+ }
+ .ok_or_else(|| {
+ FFramesRendererError::Skia(format!("can not create a {width}x{height} surface"))
+ })?;
+
+ Ok((surface, gpu_context))
+}
+
+/// Scales the canvas so `tree` fills `width`x`height`, see `fframes::fit_transform`.
+pub fn apply_fit(canvas: &Canvas, tree: &usvgr::Tree, width: i32, height: i32) {
+ let fit = fframes::fit_transform(tree, width as u32, height as u32);
+ if !fit.is_identity() {
+ canvas.scale((fit.sx, fit.sy));
+ }
+}
+
+/// Skia as a `fframes::FrameRenderer` for `fframes::Previewer` and the CLI. Keeps the surface,
+/// GPU context and render cache between frames.
+pub struct SkiaFrameRenderer<'a, TBackend: SkiaBackend> {
+ backend: &'a TBackend,
+ surface: Option<(Surface, Option<gpu::DirectContext>)>,
+ render_cache: crate::render::RenderCache,
+}
+
+impl<'a, TBackend: SkiaBackend> SkiaFrameRenderer<'a, TBackend> {
+ pub fn new(backend: &'a TBackend) -> Self {
+ Self {
+ backend,
+ surface: None,
+ render_cache: crate::render::RenderCache::new(),
+ }
+ }
+}
+
+impl<TBackend: SkiaBackend> FrameRenderer for SkiaFrameRenderer<'_, TBackend> {
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: Color,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<RgbaFrame> {
+ let (w, h) = (width as i32, height as i32);
+ if !matches!(&self.surface, Some((s, _)) if s.width() == w && s.height() == h) {
+ self.surface = Some(surface_with_size(self.backend, w, h)?);
+ }
+ let (surface, gpu_context) = self.surface.as_mut().expect("surface was just created");
+
+ let canvas = surface.canvas();
+ canvas.clear(skia_safe::Color::from_argb(
+ background.a,
+ background.r,
+ background.g,
+ background.b,
+ ));
+ canvas.save();
+ apply_fit(canvas, tree, w, h);
+ crate::render::render_tree(tree, canvas, &mut self.render_cache);
+ canvas.restore();
+
+ if let Some(gpu_context) = gpu_context.as_mut() {
+ gpu_context.flush_submit_and_sync_cpu();
+ }
+
+ // Always read back as RGBA regardless of the surface's native (often BGRA) order.
+ let info = ImageInfo::new((w, h), ColorType::RGBA8888, AlphaType::Premul, None);
+ let row_bytes = info.min_row_bytes();
+ let mut pixels = vec![0; row_bytes * height as usize];
+ let image = surface.image_snapshot();
+ let pixmap = skia_safe::Pixmap::new(&info, &mut pixels, row_bytes)
+ .ok_or_else(|| FFramesRendererError::Skia("can not create a pixmap".to_owned()))?;
+
+ if !image.read_pixels_to_pixmap_with_context(
+ gpu_context.as_mut(),
+ &pixmap,
+ (0, 0),
+ skia_safe::image::CachingHint::Allow,
+ ) {
+ return Err(FFramesRendererError::Skia(
+ "failed to read pixels from the Skia surface".to_owned(),
+ ));
+ }
+ drop(pixmap);
+
+ Ok(RgbaFrame::from_premultiplied(width, height, pixels))
+ }
+}
diff --git a/fframes-skia-renderer/src/instant_rendering.rs b/fframes-skia-renderer/src/instant_rendering.rs
index 8b87b68d..32ea5192 100644
--- a/fframes-skia-renderer/src/instant_rendering.rs
+++ b/fframes-skia-renderer/src/instant_rendering.rs
@@ -135,13 +135,22 @@ impl<TBackend: SkiaBackend> SkiaFFramesRenderer<'_, TBackend> {
fframes_ctx.video_decoders.clone(),
);
- let tree = video.render_frame(fframe, &ctx).into_svg_tree(
+ let tree = fframes::render_frame_guarded(video, fframe, &ctx)?.into_svg_tree(
&fframes_ctx.usvg_options,
&mut native_ctx.converter_cache,
fframes_ctx.runtime.font_source.as_db_ref(),
)?;
- native_ctx.surface.canvas().clear(skia_safe::Color::BLACK);
+ let background = TVideo::BACKGROUND_COLOR;
+ native_ctx
+ .surface
+ .canvas()
+ .clear(skia_safe::Color::from_argb(
+ background.a,
+ background.r,
+ background.g,
+ background.b,
+ ));
crate::render::render_tree(
&tree,
native_ctx.surface.canvas(),
diff --git a/fframes-skia-renderer/src/lib.rs b/fframes-skia-renderer/src/lib.rs
index 006f55bd..29dcb952 100644
--- a/fframes-skia-renderer/src/lib.rs
+++ b/fframes-skia-renderer/src/lib.rs
@@ -12,6 +12,9 @@ pub use skia_backend::*;
mod instant_rendering;
pub use instant_rendering::*;
+mod frame_renderer;
+pub use frame_renderer::*;
+
pub mod render;
#[cfg(feature = "debug")]
diff --git a/fframes-skia-renderer/src/skia_backend.rs b/fframes-skia-renderer/src/skia_backend.rs
index 43d2eaf8..a3d84692 100644
--- a/fframes-skia-renderer/src/skia_backend.rs
+++ b/fframes-skia-renderer/src/skia_backend.rs
@@ -4,7 +4,7 @@ use crate::backends::SkiaBackend;
use crate::skia_pipeline;
use crate::skia_pipeline::Pipeline;
pub use crate::skia_pipeline::{SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig};
-use fframes::{AudioTimelineSamples, ResolvedRenderingTimeline, Video, usvgr};
+use fframes::{AudioTimelineSamples, FrameRenderer, ResolvedRenderingTimeline, Video, usvgr};
use fframes::{FFramesRenderBackend, FFramesRendererResult};
#[derive(Clone)]
@@ -30,6 +30,11 @@ impl<'a, TSkiaBackend: SkiaBackend> SkiaFFramesRenderer<'a, TSkiaBackend> {
}
impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBackend> {
+ /// Skia previews on the same GPU context: shaders and filters look like in the video.
+ fn frame_renderer(&self) -> Option<Box<dyn FrameRenderer + '_>> {
+ Some(Box::new(crate::SkiaFrameRenderer::new(self.backend)))
+ }
+
fn render_frame<'a, 'media: 'a, TVideo: Video + Sync + Sized>(
self,
frame: fframes::Frame,
@@ -38,55 +43,21 @@ impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBa
font_db: &usvgr::fontdb::Database,
ctx: fframes::FFramesContext<'a, 'media>,
) -> FFramesRendererResult<Vec<u8>> {
- let (mut surface, mut gpu_context) = self.backend.create_skia_surface()?;
- let image_info = surface.image_info();
- let frame_datavec_size = image_info.compute_byte_size(image_info.min_row_bytes());
-
- let mut pixels = vec![0; frame_datavec_size];
- let pixmap = skia_safe::Pixmap::new(&image_info, &mut pixels, image_info.min_row_bytes())
- .ok_or_else(|| {
- fframes::FFramesRendererError::Custom("Failed to create pixmap".to_string())
- })?;
-
let mut converter_cache = usvgr::Cache::default();
- let rtree = video.render_frame(frame, &ctx).into_svg_tree(
+ let rtree = fframes::render_frame_guarded(video, frame, &ctx)?.into_svg_tree(
usvg_options,
&mut converter_cache,
font_db,
)?;
- // A fresh GPU surface holds undefined memory; match the pipeline,
- // which clears every frame to the video background.
- let background = TVideo::BACKGROUND_COLOR;
- surface.canvas().clear(skia_safe::Color::from_argb(
- background.a,
- background.r,
- background.g,
- background.b,
- ));
-
- let mut render_cache = crate::render::RenderCache::new();
- crate::render::render_tree(&rtree, surface.canvas(), &mut render_cache);
-
- if let Some(gpu_context) = gpu_context.as_mut() {
- gpu_context.flush_and_submit();
- }
-
- let image = surface.image_snapshot();
- let result = image.read_pixels_to_pixmap_with_context(
- gpu_context.as_mut(),
- &pixmap,
- (0, 0),
- skia_safe::image::CachingHint::Allow,
- );
-
- if !result {
- return Err(fframes::FFramesRendererError::Custom(
- "Failed to read pixels from Skia image".to_string(),
- ));
- }
+ let frame = crate::SkiaFrameRenderer::new(self.backend).render_tree(
+ &rtree,
+ TVideo::BACKGROUND_COLOR,
+ ctx.current_video_size.width as u32,
+ ctx.current_video_size.height as u32,
+ )?;
- Ok(pixels)
+ Ok(frame.pixels)
}
fn render<'a, 'media: 'a, TVideo: Video + Sync + Sized + Send>(
diff --git a/fframes-skia-renderer/src/skia_pipeline.rs b/fframes-skia-renderer/src/skia_pipeline.rs
index 7281267c..7c5bb25f 100644
--- a/fframes-skia-renderer/src/skia_pipeline.rs
+++ b/fframes-skia-renderer/src/skia_pipeline.rs
@@ -139,8 +139,12 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
// encoded at once. Half of the threads is plenty to feed the GPU and leaves the rest
// to the encoders.
let generators = (workers / 2).max(1);
+ // The scheduler and segments work in output frames; `frame_offset` maps them back to
+ // video frames when only a range is rendered.
+ let frame_range = render_options.output_frame_range(ctx.duration_in_frames);
+ let frame_offset = frame_range.start;
let scheduler = FrameScheduler::new(
- ctx.duration_in_frames,
+ frame_range.len(),
generators,
render_options
.video_encoder_options
@@ -187,6 +191,7 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
worker,
video,
scheduler,
+ frame_offset,
usvg_options,
font_db,
tree_sender,
@@ -285,6 +290,7 @@ fn generate_frames<'a, 'media: 'a, TVideo: Video + Sync + Send>(
worker: usize,
video: &'a TVideo,
scheduler: &FrameScheduler,
+ frame_offset: usize,
usvg_options: &'a usvgr::Options<'a>,
font_db: &'a usvgr::fontdb::Database,
tree_sender: SyncSender<(FrameClaim, usvgr::Tree)>,
@@ -312,16 +318,17 @@ fn generate_frames<'a, 'media: 'a, TVideo: Video + Sync + Send>(
return Err(FFramesRendererError::Aborted);
}
+ let video_frame = claim.frame + frame_offset;
let frame = fframes::Frame::__internal_make_for_renderer(
- claim.frame,
- claim.frame,
+ video_frame,
+ video_frame,
ctx.time_base.fps,
break_lines_cache.clone(),
video_decoders_worker.clone(),
);
// Direct path: Svgr -> usvgr::Tree (no string serialization, no Dom parsing)
- let tree = video.render_frame(frame, ctx).into_svg_tree(
+ let tree = fframes::render_frame_guarded(video, frame, ctx)?.into_svg_tree(
usvg_options,
&mut converter_cache,
font_db,
@@ -359,7 +366,14 @@ fn render_frames<TBackend: SkiaBackend>(
background_color: skia_safe::Color,
#[cfg(feature = "debug")] metrics: Arc<crate::metrics::ThreadMetrics>,
) -> FFramesRendererResult<()> {
- let (mut surface, mut gpu_context) = backend.create_skia_surface()?;
+ // Scaled renders (`scale_resolution`) need a surface of the output size, not the one the
+ // backend was created with.
+ let output_size = (
+ ctx.current_video_size.width as i32,
+ ctx.current_video_size.height as i32,
+ );
+ let (mut surface, mut gpu_context) =
+ crate::surface_with_size(backend, output_size.0, output_size.1)?;
let image_info = surface.image_info();
let frame_size = image_info.compute_byte_size(image_info.min_row_bytes());
let row_bytes = image_info.min_row_bytes();
@@ -394,8 +408,12 @@ fn render_frames<TBackend: SkiaBackend>(
let pixmap = skia_safe::Pixmap::new(&image_info, &mut pixels, row_bytes)
.ok_or_else(|| FFramesRendererError::Custom("Failed to create pixmap".to_string()))?;
- surface.canvas().clear(background_color);
- crate::render::render_tree(&tree, surface.canvas(), &mut render_cache);
+ let canvas = surface.canvas();
+ canvas.clear(background_color);
+ canvas.save();
+ crate::apply_fit(canvas, &tree, output_size.0, output_size.1);
+ crate::render::render_tree(&tree, canvas, &mut render_cache);
+ canvas.restore();
if let Some(gpu_context) = gpu_context.as_mut() {
gpu_context.flush_submit_and_sync_cpu();
diff --git a/fframes/Cargo.toml b/fframes/Cargo.toml
index dded6ba3..d9e7270a 100644
--- a/fframes/Cargo.toml
+++ b/fframes/Cargo.toml
@@ -26,6 +26,7 @@ ttf-parser = "0.25.1"
lru = "0.14.0"
serde = { version = "1.0", features = ["derive"] }
parking_lot = "0.12.1"
+log = "0.4"
# fframes dependencies
usvgr.workspace = true
@@ -42,9 +43,11 @@ colored = "2"
futures = "0.3.24"
image = "0.25.0"
memmap = "0.7.0"
-indicatif = "0.16.2"
+indicatif = "0.18"
once_cell = "1.10.0"
uuid = { version = "1.8.0", features = ["v4"] }
+clap = { version = "4.5", features = ["derive"], optional = true }
+serde_json = { version = "1.0", optional = true }
[dev-dependencies]
approx = "0.5.0"
@@ -59,6 +62,8 @@ wasm-bindgen = "0.2.100"
# would be always populated by the platform sysroot itself
default = ["cpu_renderer"]
cpu_renderer = ["svgr"]
+# `fframes::cli`: a ready made command line (render, frames, contact sheets, inspect, audio)
+cli = ["cpu_renderer", "dep:clap", "dep:serde_json"]
exif = ["fframes-media/exif", "fframes-media-dir-macro/exif"]
compile-time-svgtree = ["svgr-macro/compile-time-svgtree"]
diff --git a/fframes/src/audio_analysis.rs b/fframes/src/audio_analysis.rs
new file mode 100644
index 00000000..0e84190a
--- /dev/null
+++ b/fframes/src/audio_analysis.rs
@@ -0,0 +1,498 @@
+//! Measuring a mix: loudness (ITU-R BS.1770 / EBU R128), true peak, clipping and silence.
+//! Use them to check a render's sound without listening to it.
+//!
+//! K-weighting follows libebur128's analog-prototype formulas (exact at 48 kHz, valid for any
+//! rate), gating follows BS.1770 (-70 LUFS absolute, -10 LU relative, 400 ms blocks with 75%
+//! overlap) and true peak uses the 4x polyphase interpolator of BS.1770 Annex 2.
+use serde::Serialize;
+use std::ops::Range;
+
+/// Biquad in transposed direct form II, f64 state.
+#[derive(Clone, Copy)]
+struct Biquad {
+ b: [f64; 3],
+ a: [f64; 2],
+ z: [f64; 2],
+}
+
+impl Biquad {
+ fn process(&mut self, x: f64) -> f64 {
+ let y = self.b[0] * x + self.z[0];
+ self.z[0] = self.b[1] * x - self.a[0] * y + self.z[1];
+ self.z[1] = self.b[2] * x - self.a[1] * y;
+ y
+ }
+}
+
+/// The two K-weighting stages for a sample rate (libebur128 `ebur128_init_filter`).
+fn k_weighting(sample_rate: f64) -> [Biquad; 2] {
+ let shelf = {
+ let f0 = 1681.974450955533;
+ let g = 3.999843853973347;
+ let q = 0.7071752369554196;
+ let k = (std::f64::consts::PI * f0 / sample_rate).tan();
+ let vh = 10f64.powf(g / 20.);
+ let vb = vh.powf(0.4996667741545416);
+ let a0 = 1. + k / q + k * k;
+ Biquad {
+ b: [
+ (vh + vb * k / q + k * k) / a0,
+ 2. * (k * k - vh) / a0,
+ (vh - vb * k / q + k * k) / a0,
+ ],
+ a: [2. * (k * k - 1.) / a0, (1. - k / q + k * k) / a0],
+ z: [0.; 2],
+ }
+ };
+ let high_pass = {
+ let f0 = 38.13547087602444;
+ let q = 0.5003270373238773;
+ let k = (std::f64::consts::PI * f0 / sample_rate).tan();
+ let a0 = 1. + k / q + k * k;
+ Biquad {
+ b: [1., -2., 1.],
+ a: [2. * (k * k - 1.) / a0, (1. - k / q + k * k) / a0],
+ z: [0.; 2],
+ }
+ };
+ [shelf, high_pass]
+}
+
+/// BS.1770 Annex 2: 4x oversampling interpolator, 4 phases of 12 taps.
+const TRUE_PEAK_PHASES: [[f64; 12]; 4] = [
+ [
+ 0.0017089843750,
+ 0.0109863281250,
+ -0.0196533203125,
+ 0.0332031250000,
+ -0.0594482421875,
+ 0.1373291015625,
+ 0.9721679687500,
+ -0.1022949218750,
+ 0.0476074218750,
+ -0.0266113281250,
+ 0.0148925781250,
+ -0.0083007812500,
+ ],
+ [
+ -0.0291748046875,
+ 0.0292968750000,
+ -0.0517578125000,
+ 0.0891113281250,
+ -0.1665039062500,
+ 0.4650878906250,
+ 0.7797851562500,
+ -0.2003173828125,
+ 0.1015625000000,
+ -0.0582275390625,
+ 0.0330810546875,
+ -0.0189208984375,
+ ],
+ [
+ -0.0189208984375,
+ 0.0330810546875,
+ -0.0582275390625,
+ 0.1015625000000,
+ -0.2003173828125,
+ 0.7797851562500,
+ 0.4650878906250,
+ -0.1665039062500,
+ 0.0891113281250,
+ -0.0517578125000,
+ 0.0292968750000,
+ -0.0291748046875,
+ ],
+ [
+ -0.0083007812500,
+ 0.0148925781250,
+ -0.0266113281250,
+ 0.0476074218750,
+ -0.1022949218750,
+ 0.9721679687500,
+ 0.1373291015625,
+ -0.0594482421875,
+ 0.0332031250000,
+ -0.0196533203125,
+ 0.0109863281250,
+ 0.0017089843750,
+ ],
+];
+
+fn true_peak(channel: &[f32]) -> f64 {
+ let mut peak: f64 = channel.iter().fold(0., |m, s| m.max(s.abs() as f64));
+ for n in 0..channel.len() {
+ for phase in &TRUE_PEAK_PHASES {
+ let mut acc = 0.;
+ for (k, coefficient) in phase.iter().enumerate() {
+ if n >= k {
+ acc += coefficient * channel[n - k] as f64;
+ }
+ }
+ peak = peak.max(acc.abs());
+ }
+ }
+ peak
+}
+
+fn to_db(linear: f64) -> f64 {
+ if linear > 0. {
+ 20. * linear.log10()
+ } else {
+ f64::NEG_INFINITY
+ }
+}
+
+fn energy_to_lufs(mean_square: f64) -> f64 {
+ if mean_square > 0. {
+ -0.691 + 10. * mean_square.log10()
+ } else {
+ f64::NEG_INFINITY
+ }
+}
+
+/// Loudness values are `-inf` for digital silence; JSON gets `null` for them.
+fn finite(value: f64) -> Option<f64> {
+ value.is_finite().then_some((value * 100.).round() / 100.)
+}
+
+/// Per 100 ms energies of a K-weighted stereo signal, the base of every loudness value.
+pub struct LoudnessAnalysis {
+ sample_rate: usize,
+ hop: usize,
+ /// Sum over channels of the squared K-weighted samples in each 100 ms hop.
+ hops: Vec<f64>,
+}
+
+impl LoudnessAnalysis {
+ pub fn new(left: &[f32], right: &[f32], sample_rate: usize) -> Self {
+ let hop = (sample_rate / 10).max(1);
+ let mut hops = vec![0.; left.len() / hop];
+ for channel in [left, right] {
+ let [mut shelf, mut high_pass] = k_weighting(sample_rate as f64);
+ for (i, sample) in channel.iter().enumerate().take(hops.len() * hop) {
+ let y = high_pass.process(shelf.process(*sample as f64));
+ hops[i / hop] += y * y;
+ }
+ }
+ Self {
+ sample_rate,
+ hop,
+ hops,
+ }
+ }
+
+ fn hop_range(&self, samples: Range<usize>) -> Range<usize> {
+ (samples.start / self.hop).min(self.hops.len())
+ ..(samples.end / self.hop).min(self.hops.len())
+ }
+
+ /// Mean square of windows of `hops_per_window` hops starting at every hop of `range`.
+ fn windows(&self, range: Range<usize>, hops_per_window: usize) -> Vec<f64> {
+ if range.len() < hops_per_window {
+ return Vec::new();
+ }
+ (range.start..=range.end - hops_per_window)
+ .map(|i| {
+ self.hops[i..i + hops_per_window].iter().sum::<f64>()
+ / (hops_per_window * self.hop) as f64
+ })
+ .collect()
+ }
+
+ /// Integrated (gated) loudness of a part of the signal in LUFS.
+ pub fn integrated(&self, samples: Range<usize>) -> f64 {
+ let blocks = self.windows(self.hop_range(samples), 4);
+ let absolute = 10f64.powf((-70. + 0.691) / 10.);
+ let gated: Vec<f64> = blocks.into_iter().filter(|z| *z >= absolute).collect();
+ if gated.is_empty() {
+ return f64::NEG_INFINITY;
+ }
+ let relative = gated.iter().sum::<f64>() / gated.len() as f64 * 0.1;
+ let kept: Vec<&f64> = gated.iter().filter(|z| **z >= relative).collect();
+ energy_to_lufs(kept.iter().copied().sum::<f64>() / kept.len() as f64)
+ }
+
+ /// Momentary (400 ms) loudness every 100 ms.
+ pub fn momentary(&self) -> Vec<f64> {
+ self.windows(0..self.hops.len(), 4)
+ .into_iter()
+ .map(energy_to_lufs)
+ .collect()
+ }
+
+ /// Short-term (3 s) loudness every 100 ms.
+ pub fn short_term(&self) -> Vec<f64> {
+ self.windows(0..self.hops.len(), 30)
+ .into_iter()
+ .map(energy_to_lufs)
+ .collect()
+ }
+
+ /// Loudness range (EBU Tech 3342) in LU.
+ pub fn loudness_range(&self) -> Option<f64> {
+ let short_term: Vec<f64> = self
+ .windows(0..self.hops.len(), 30)
+ .into_iter()
+ .filter(|z| *z >= 10f64.powf((-70. + 0.691) / 10.))
+ .collect();
+ if short_term.is_empty() {
+ return None;
+ }
+ let relative = short_term.iter().sum::<f64>() / short_term.len() as f64 * 0.01;
+ let mut kept: Vec<f64> = short_term
+ .into_iter()
+ .filter(|z| *z >= relative)
+ .map(energy_to_lufs)
+ .collect();
+ kept.sort_by(f64::total_cmp);
+ let n = kept.len();
+ let low = kept[((n - 1) as f64 * 0.10).round() as usize];
+ let high = kept[((n - 1) as f64 * 0.95).round() as usize];
+ Some(high - low)
+ }
+
+ /// Ranges (seconds) of at least `min_seconds` where the momentary loudness is below
+ /// `threshold_lufs`.
+ pub fn quiet_ranges(&self, threshold_lufs: f64, min_seconds: f64) -> Vec<Range<f64>> {
+ let hop_seconds = self.hop as f64 / self.sample_rate as f64;
+ let mut ranges = Vec::new();
+ let mut start = None;
+ let momentary = self.momentary();
+ for (i, loudness) in momentary.iter().chain([&f64::INFINITY]).enumerate() {
+ match (start, *loudness < threshold_lufs) {
+ (None, true) => start = Some(i),
+ (Some(s), false) => {
+ // A momentary block covers 4 hops: the quiet part ends where the block
+ // that hears the sound begins plus its length.
+ let range = s as f64 * hop_seconds..(i + 3) as f64 * hop_seconds;
+ if range.end - range.start >= min_seconds {
+ ranges.push(range);
+ }
+ start = None;
+ }
+ _ => {}
+ }
+ }
+ ranges
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct SectionLoudness {
+ pub name: String,
+ pub start_seconds: f64,
+ pub end_seconds: f64,
+ /// Integrated loudness in LUFS, `null` for silence.
+ pub integrated_lufs: Option<f64>,
+ pub true_peak_dbtp: Option<f64>,
+}
+
+/// Everything `fframes audio analyze` reports.
+#[derive(Debug, Clone, Serialize)]
+pub struct AudioReport {
+ pub duration_seconds: f64,
+ pub sample_rate: usize,
+ pub integrated_lufs: Option<f64>,
+ pub loudness_range_lu: Option<f64>,
+ pub max_momentary_lufs: Option<f64>,
+ pub max_short_term_lufs: Option<f64>,
+ pub sample_peak_dbfs: Option<f64>,
+ pub true_peak_dbtp: Option<f64>,
+ /// Samples beyond full scale (either channel), they distort once encoded.
+ pub clipped_samples: usize,
+ /// Parts quieter than -60 LUFS for at least a second.
+ pub silent_ranges: Vec<[f64; 2]>,
+ /// Loudness per scene or other named part.
+ pub sections: Vec<SectionLoudness>,
+}
+
+/// Analyzes a stereo mix. `sections` are named sample ranges (usually the scenes).
+pub fn analyze_audio(
+ left: &[f32],
+ right: &[f32],
+ sample_rate: usize,
+ sections: &[(String, Range<usize>)],
+) -> AudioReport {
+ let loudness = LoudnessAnalysis::new(left, right, sample_rate);
+ let sample_peak = left.iter().chain(right).fold(0f32, |m, s| m.max(s.abs())) as f64;
+ let peak_of = |range: Range<usize>| {
+ let range = range.start.min(left.len())..range.end.min(left.len());
+ true_peak(&left[range.clone()]).max(true_peak(&right[range]))
+ };
+ let max = |values: Vec<f64>| values.into_iter().fold(f64::NEG_INFINITY, f64::max);
+
+ AudioReport {
+ duration_seconds: left.len() as f64 / sample_rate as f64,
+ sample_rate,
+ integrated_lufs: finite(loudness.integrated(0..left.len())),
+ loudness_range_lu: loudness.loudness_range().and_then(finite),
+ max_momentary_lufs: finite(max(loudness.momentary())),
+ max_short_term_lufs: finite(max(loudness.short_term())),
+ sample_peak_dbfs: finite(to_db(sample_peak)),
+ true_peak_dbtp: finite(to_db(peak_of(0..left.len()))),
+ clipped_samples: left.iter().chain(right).filter(|s| s.abs() > 1.).count(),
+ silent_ranges: loudness
+ .quiet_ranges(-60., 1.)
+ .into_iter()
+ .map(|r| {
+ [
+ (r.start * 100.).round() / 100.,
+ (r.end * 100.).round() / 100.,
+ ]
+ })
+ .collect(),
+ sections: sections
+ .iter()
+ .map(|(name, range)| SectionLoudness {
+ name: name.clone(),
+ start_seconds: range.start as f64 / sample_rate as f64,
+ end_seconds: range.end as f64 / sample_rate as f64,
+ integrated_lufs: finite(loudness.integrated(range.clone())),
+ true_peak_dbtp: finite(to_db(peak_of(range.clone()))),
+ })
+ .collect(),
+ }
+}
+
+/// Encodes stereo samples as a WAV file: 16-bit PCM with TPDF dither (plays everywhere) or
+/// 32-bit float (keeps levels above full scale).
+pub fn encode_wav(left: &[f32], right: &[f32], sample_rate: usize, float: bool) -> Vec<u8> {
+ let frames = left.len().min(right.len());
+ let channels: u16 = 2;
+ let bytes_per_sample: u16 = if float { 4 } else { 2 };
+ let data_len = frames * channels as usize * bytes_per_sample as usize;
+ let mut out = Vec::with_capacity(data_len + 58);
+
+ let fmt_len: u32 = if float { 18 } else { 16 };
+ let fact_len: u32 = if float { 12 } else { 0 };
+ let riff_len = 4 + (8 + fmt_len) + fact_len + 8 + data_len as u32;
+ out.extend_from_slice(b"RIFF");
+ out.extend_from_slice(&riff_len.to_le_bytes());
+ out.extend_from_slice(b"WAVE");
+ out.extend_from_slice(b"fmt ");
+ out.extend_from_slice(&fmt_len.to_le_bytes());
+ out.extend_from_slice(&(if float { 3u16 } else { 1u16 }).to_le_bytes());
+ out.extend_from_slice(&channels.to_le_bytes());
+ out.extend_from_slice(&(sample_rate as u32).to_le_bytes());
+ out.extend_from_slice(
+ &(sample_rate as u32 * channels as u32 * bytes_per_sample as u32).to_le_bytes(),
+ );
+ out.extend_from_slice(&(channels * bytes_per_sample).to_le_bytes());
+ out.extend_from_slice(&(bytes_per_sample * 8).to_le_bytes());
+ if float {
+ out.extend_from_slice(&0u16.to_le_bytes());
+ out.extend_from_slice(b"fact");
+ out.extend_from_slice(&4u32.to_le_bytes());
+ out.extend_from_slice(&(frames as u32).to_le_bytes());
+ }
+ out.extend_from_slice(b"data");
+ out.extend_from_slice(&(data_len as u32).to_le_bytes());
+
+ // Deterministic TPDF dither: two uniform values from a xorshift generator.
+ let mut state: u32 = 0x9E37_79B9;
+ let mut uniform = move || {
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ state as f32 / u32::MAX as f32
+ };
+
+ for i in 0..frames {
+ for sample in [left[i], right[i]] {
+ if float {
+ out.extend_from_slice(&sample.to_le_bytes());
+ } else {
+ let dither = uniform() - uniform();
+ let value = (sample * 32767. + dither).round().clamp(-32768., 32767.) as i16;
+ out.extend_from_slice(&value.to_le_bytes());
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sine(frequency: f64, amplitude: f32, seconds: f64, rate: usize) -> Vec<f32> {
+ (0..(seconds * rate as f64) as usize)
+ .map(|i| {
+ amplitude
+ * (2. * std::f64::consts::PI * frequency * i as f64 / rate as f64).sin() as f32
+ })
+ .collect()
+ }
+
+ #[test]
+ fn k_weighting_matches_the_spec_at_48k() {
+ let [shelf, high_pass] = k_weighting(48000.);
+ let close = |a: f64, b: f64| (a - b).abs() < 1e-12;
+ assert!(close(shelf.b[0], 1.53512485958697));
+ assert!(close(shelf.b[1], -2.69169618940638));
+ assert!(close(shelf.b[2], 1.19839281085285));
+ assert!(close(shelf.a[0], -1.69065929318241));
+ assert!(close(shelf.a[1], 0.73248077421585));
+ assert!(close(high_pass.a[0], -1.99004745483398));
+ assert!(close(high_pass.a[1], 0.99007225036621));
+ }
+
+ #[test]
+ fn full_scale_997hz_sine_in_one_channel_reads_minus_3_lufs() {
+ // BS.1770: a 0 dBFS 997 Hz sine in one front channel measures -3.01 LKFS.
+ let rate = 48000;
+ let left = sine(997., 1., 5., rate);
+ let right = vec![0.; left.len()];
+ let report = analyze_audio(&left, &right, rate, &[]);
+ let lufs = report.integrated_lufs.unwrap();
+ assert!((lufs + 3.01).abs() < 0.05, "{lufs}");
+ assert!(report.true_peak_dbtp.unwrap().abs() < 0.1);
+ assert_eq!(report.clipped_samples, 0);
+ }
+
+ #[test]
+ fn stereo_minus_23() {
+ // EBU Tech 3341 test 1: stereo 1 kHz sine at -23 dBFS reads -23 LUFS.
+ let rate = 48000;
+ let tone = sine(1000., 10f32.powf(-23. / 20.), 20., rate);
+ let report = analyze_audio(&tone, &tone, rate, &[]);
+ let lufs = report.integrated_lufs.unwrap();
+ assert!((lufs + 23.).abs() < 0.1, "{lufs}");
+ }
+
+ #[test]
+ fn silence_and_sections() {
+ let rate = 44100;
+ let mut left = vec![0.; rate * 3];
+ left.extend(sine(440., 0.5, 3., rate));
+ let report = analyze_audio(
+ &left,
+ &left,
+ rate,
+ &[
+ ("quiet".into(), 0..rate * 3),
+ ("tone".into(), rate * 3..rate * 6),
+ ],
+ );
+ assert_eq!(report.silent_ranges.len(), 1);
+ assert!(report.silent_ranges[0][0] < 0.1 && report.silent_ranges[0][1] > 2.9);
+ assert_eq!(report.sections[0].integrated_lufs, None);
+ assert!(report.sections[1].integrated_lufs.is_some());
+ }
+
+ #[test]
+ fn wav_headers() {
+ let pcm = encode_wav(&[0.5, -0.5], &[0., 1.], 44100, false);
+ assert_eq!(&pcm[0..4], b"RIFF");
+ assert_eq!(
+ u32::from_le_bytes(pcm[4..8].try_into().unwrap()) as usize,
+ pcm.len() - 8
+ );
+ assert_eq!(pcm.len(), 44 + 8);
+
+ let float = encode_wav(&[0.5], &[0.25], 48000, true);
+ assert_eq!(float.len(), 58 + 8);
+ assert_eq!(u16::from_le_bytes(float[20..22].try_into().unwrap()), 3);
+ assert_eq!(&float[58..62], &0.5f32.to_le_bytes());
+ }
+}
diff --git a/fframes/src/audio_map.rs b/fframes/src/audio_map.rs
index 36dba54b..dccd8b4b 100644
--- a/fframes/src/audio_map.rs
+++ b/fframes/src/audio_map.rs
@@ -1,4 +1,5 @@
use crate::{FFramesContext, ResolvedScenesTimeline, ScenesWithAudio, TimeBase, error};
+use serde::Serialize;
use std::{
iter::FromIterator,
ops::{Add, Range, Sub},
@@ -46,9 +47,12 @@ impl<'a> Sub for AudioTimestamp<'a> {
pub trait AudioTimelineUnit {
fn from_frames(frames: usize, tb: &TimeBase) -> Self;
+ /// Converts an exact timestamp. Frames are truncated like frame indexes, samples rounded.
+ fn from_seconds(seconds: f64, tb: &TimeBase) -> Self;
fn from_usize(val: usize) -> Self;
fn as_usize(&self) -> usize;
fn to_frames(&self, tb: &TimeBase) -> usize;
+ fn to_seconds(&self, tb: &TimeBase) -> f64;
}
#[derive(PartialEq, PartialOrd, Debug, Copy, Clone)]
@@ -58,6 +62,9 @@ impl AudioTimelineUnit for AudioTimelineFrames {
fn from_frames(frames: usize, _: &TimeBase) -> Self {
AudioTimelineFrames(frames)
}
+ fn from_seconds(seconds: f64, tb: &TimeBase) -> Self {
+ AudioTimelineFrames(seconds_to_frames_floor(seconds, tb.fps))
+ }
fn as_usize(&self) -> usize {
self.0
}
@@ -67,6 +74,9 @@ impl AudioTimelineUnit for AudioTimelineFrames {
fn to_frames(&self, _: &TimeBase) -> usize {
self.0
}
+ fn to_seconds(&self, tb: &TimeBase) -> f64 {
+ self.0 as f64 / tb.fps as f64
+ }
}
#[derive(PartialEq, PartialOrd, Debug, Clone, Copy)]
@@ -76,6 +86,9 @@ impl AudioTimelineUnit for AudioTimelineSamples {
fn from_frames(frames: usize, tb: &TimeBase) -> Self {
AudioTimelineSamples(frames * tb.sample_rate / tb.fps)
}
+ fn from_seconds(seconds: f64, tb: &TimeBase) -> Self {
+ AudioTimelineSamples((seconds.max(0.) * tb.sample_rate as f64).round() as usize)
+ }
fn as_usize(&self) -> usize {
self.0
}
@@ -85,6 +98,15 @@ impl AudioTimelineUnit for AudioTimelineSamples {
fn to_frames(&self, tb: &TimeBase) -> usize {
self.0 * tb.fps / tb.sample_rate
}
+ fn to_seconds(&self, tb: &TimeBase) -> f64 {
+ self.0 as f64 / tb.sample_rate as f64
+ }
+}
+
+/// Seconds to whole frames, truncating like `(seconds * fps) as usize` but tolerant to
+/// floating point error (`0.99999` frames of a whole second is still a whole frame).
+pub(crate) fn seconds_to_frames_floor(seconds: f64, fps: usize) -> usize {
+ (seconds.max(0.) * fps as f64 + 1e-6).floor() as usize
}
impl AudioTimestamp<'_> {
@@ -116,53 +138,223 @@ impl AudioTimestamp<'_> {
}
}
- pub(crate) fn to_frames(
+ /// The timestamp in exact seconds. `eof_base` is added to the file duration for `Eof`
+ /// (the start of the range minus the part of the file that is skipped).
+ pub(crate) fn to_seconds(
&self,
filename: &str,
- tb: &TimeBase,
- eof_offset: Option<usize>,
- resolve_audio_duration_in_frames: &impl Fn(&str) -> error::Result<usize>,
- ) -> error::Result<usize> {
+ fps: usize,
+ eof_base: Option<f64>,
+ resolve_audio_duration: &impl Fn(&str) -> error::Result<f64>,
+ ) -> error::Result<f64> {
Ok(match self {
- AudioTimestamp::Frame(frame) => *frame,
- AudioTimestamp::Second(seconds) => (*seconds * tb.fps as f32) as usize,
- AudioTimestamp::Eof => {
- resolve_audio_duration_in_frames(filename)? + eof_offset.unwrap_or(0)
- }
- AudioTimestamp::DurationOfAudio(filename) => {
- resolve_audio_duration_in_frames(filename)?
- }
- AudioTimestamp::Time {
- minutes: minute,
- seconds: second,
- } => ((*minute * 60.0 + *second) * tb.fps as f32) as usize,
+ AudioTimestamp::Frame(frame) => *frame as f64 / fps as f64,
+ AudioTimestamp::Second(seconds) => *seconds as f64,
+ AudioTimestamp::Eof => resolve_audio_duration(filename)? + eof_base.unwrap_or(0.),
+ AudioTimestamp::DurationOfAudio(filename) => resolve_audio_duration(filename)?,
+ AudioTimestamp::Time { minutes, seconds } => *minutes as f64 * 60. + *seconds as f64,
AudioTimestamp::__Add(add) => {
let (a, b) = &**add;
- a.to_frames(filename, tb, eof_offset, resolve_audio_duration_in_frames)?
- + b.to_frames(filename, tb, eof_offset, resolve_audio_duration_in_frames)?
+ a.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
+ + b.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
}
- AudioTimestamp::__Subtract(add) => {
- let (a, b) = &**add;
- a.to_frames(filename, tb, eof_offset, resolve_audio_duration_in_frames)?
- - b.to_frames(filename, tb, eof_offset, resolve_audio_duration_in_frames)?
+ AudioTimestamp::__Subtract(sub) => {
+ let (a, b) = &**sub;
+ a.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
+ - b.to_seconds(filename, fps, eof_base, resolve_audio_duration)?
}
- })
+ }
+ .max(0.))
}
+}
- pub(crate) fn to_unit<TUnit: AudioTimelineUnit>(
- &self,
- filename: &str,
- tb: &TimeBase,
- eof_offset: Option<usize>,
- resolve_audio_duration_in_frames: impl Fn(&str) -> error::Result<usize>,
- ) -> error::Result<TUnit> {
- let frames = self.to_frames(filename, tb, eof_offset, &resolve_audio_duration_in_frames)?;
+type AudioDuration<'a> = Range<AudioTimestamp<'a>>;
+
+/// Shape of a fade.
+#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FadeCurve {
+ /// Amplitude changes linearly. Good for very short de-click fades.
+ Linear,
+ /// `sin(t * PI / 2)`: constant power, the default for music fades and crossfades of
+ /// different material.
+ #[default]
+ EqualPower,
+ /// Raised cosine: gentle start and end.
+ SCurve,
+ /// Linear in decibels (-60 dB to 0 dB): perceptually even, for long music fade outs.
+ Exponential,
+}
+
+impl FadeCurve {
+ /// Gain for the fade progress `t` in `0..=1` (0 silent, 1 full level).
+ pub fn gain(self, t: f32) -> f32 {
+ let t = t.clamp(0., 1.);
+ match self {
+ FadeCurve::Linear => t,
+ FadeCurve::EqualPower => (t * std::f32::consts::FRAC_PI_2).sin(),
+ FadeCurve::SCurve => (1. - (t * std::f32::consts::PI).cos()) * 0.5,
+ FadeCurve::Exponential => {
+ if t <= 0. {
+ 0.
+ } else {
+ 10f32.powf(-60. * (1. - t) / 20.)
+ }
+ }
+ }
+ }
+}
+
+/// Lowers a track while voice tracks (see `AudioTrack::voice`) play. Driven by the timeline,
+/// not the signal: the level drops before the voice starts and comes back after it ends.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
+pub struct Ducking {
+ /// Attenuation while a voice plays, e.g. `-12.0`.
+ pub depth_db: f32,
+ /// Seconds before the voice starts over which the level goes down.
+ pub attack: f32,
+ /// Seconds the level stays down after the voice ends.
+ pub hold: f32,
+ /// Seconds over which the level comes back.
+ pub release: f32,
+ /// Voice ranges closer than this (seconds) are merged so the music does not pump
+ /// between phrases.
+ pub merge_gap: f32,
+}
- Ok(TUnit::from_frames(frames, tb))
+impl Default for Ducking {
+ fn default() -> Self {
+ Self {
+ depth_db: -12.,
+ attack: 0.2,
+ hold: 0.3,
+ release: 0.8,
+ merge_gap: 0.8,
+ }
}
}
-type AudioDuration<'a> = Range<AudioTimestamp<'a>>;
+/// How a track is mixed. Everything defaults to "play the file as is".
+#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
+pub struct TrackMix {
+ /// Level in decibels, `0.0` is the file's level.
+ pub gain_db: f32,
+ /// `-1.0` left .. `1.0` right. Mono files are centered at unity gain.
+ pub pan: f32,
+ /// Seconds.
+ pub fade_in: f32,
+ /// Seconds, ending at the end of the track's range.
+ pub fade_out: f32,
+ pub fade_curve: FadeCurve,
+ /// Seconds of the file skipped before the track starts playing.
+ pub offset: f32,
+ /// Duck this track under voice tracks.
+ pub duck: Option<Ducking>,
+ /// This track is a voice: other tracks with `duck` get quieter while it plays.
+ pub voice: bool,
+}
+
+impl Default for TrackMix {
+ fn default() -> Self {
+ Self {
+ gain_db: 0.,
+ pan: 0.,
+ fade_in: 0.,
+ fade_out: 0.,
+ fade_curve: FadeCurve::default(),
+ offset: 0.,
+ duck: None,
+ voice: false,
+ }
+ }
+}
+
+/// One audio file placed on the timeline, with its mix settings.
+///
+/// ```ignore
+/// use fframes::{AudioTrack, AudioTimestamp::*};
+///
+/// AudioMap::from([
+/// AudioTrack::new("music.mp3", Second(0.)..Eof).gain_db(-14.).fade_out(2.).duck_under_voice(),
+/// AudioTrack::new("voice.wav", Second(1.5)..Eof).voice(),
+/// AudioTrack::new("whoosh.wav", Second(4.2)..Eof).pan(-0.5),
+/// ])
+/// ```
+#[derive(Debug, Clone)]
+pub struct AudioTrack<'a> {
+ pub file: &'a str,
+ pub range: AudioDuration<'a>,
+ pub mix: TrackMix,
+}
+
+impl<'a> AudioTrack<'a> {
+ pub fn new(file: &'a str, range: AudioDuration<'a>) -> Self {
+ Self {
+ file,
+ range,
+ mix: TrackMix::default(),
+ }
+ }
+
+ pub fn gain_db(mut self, gain_db: f32) -> Self {
+ self.mix.gain_db = gain_db;
+ self
+ }
+
+ /// Linear level, `0.5` is about -6 dB.
+ pub fn volume(mut self, volume: f32) -> Self {
+ self.mix.gain_db = 20. * volume.max(1e-6).log10();
+ self
+ }
+
+ pub fn pan(mut self, pan: f32) -> Self {
+ self.mix.pan = pan.clamp(-1., 1.);
+ self
+ }
+
+ pub fn fade_in(mut self, seconds: f32) -> Self {
+ self.mix.fade_in = seconds.max(0.);
+ self
+ }
+
+ pub fn fade_out(mut self, seconds: f32) -> Self {
+ self.mix.fade_out = seconds.max(0.);
+ self
+ }
+
+ pub fn fade_curve(mut self, curve: FadeCurve) -> Self {
+ self.mix.fade_curve = curve;
+ self
+ }
+
+ /// Starts playing the file `seconds` into it.
+ pub fn offset(mut self, seconds: f32) -> Self {
+ self.mix.offset = seconds.max(0.);
+ self
+ }
+
+ /// Marks the track as a voice that ducks tracks created with `duck_under_voice`.
+ pub fn voice(mut self) -> Self {
+ self.mix.voice = true;
+ self
+ }
+
+ /// Lowers this track by 12 dB while voice tracks play.
+ pub fn duck_under_voice(self) -> Self {
+ self.duck(Ducking::default())
+ }
+
+ pub fn duck(mut self, ducking: Ducking) -> Self {
+ self.mix.duck = Some(ducking);
+ self
+ }
+}
+
+impl<'a> From<(&'a str, AudioDuration<'a>)> for AudioTrack<'a> {
+ fn from((file, range): (&'a str, AudioDuration<'a>)) -> Self {
+ AudioTrack::new(file, range)
+ }
+}
#[derive(Debug, Clone)]
/// Audio map represents when and how long each audio file should be played within a video or a scene.
@@ -186,9 +378,18 @@ type AudioDuration<'a> = Range<AudioTimestamp<'a>>;
/// ```
///
/// In this case audio 1 will be playing from second 10 to second 20 and audio 2 will be playing from second 5 to the end of file.
-pub struct AudioMap<'a>(pub Option<Vec<(&'a str, AudioDuration<'a>)>>);
+/// Use `AudioTrack` entries instead of tuples for gain, pan, fades, offsets and ducking.
+pub struct AudioMap<'a>(pub Option<Vec<AudioTrack<'a>>>);
+
+/// A track with its position on the timeline resolved.
+#[derive(Debug, Clone, PartialEq)]
+pub struct ResolvedAudioTrack<TUnit: AudioTimelineUnit> {
+ pub file: String,
+ pub range: Range<TUnit>,
+ pub mix: TrackMix,
+}
-type AudioTimeline<TUnit> = Vec<(String, Range<TUnit>)>;
+type AudioTimeline<TUnit> = Vec<ResolvedAudioTrack<TUnit>>;
/// The resolved audio_map contain each audio file position and duration in specified units.
#[derive(Debug)]
@@ -198,20 +399,27 @@ impl<TUnit: AudioTimelineUnit + Copy> ResolvedAudioMap<TUnit> {
pub(crate) fn round_max_duration(&mut self, max_duration: TUnit) {
let max_duration_usize = max_duration.as_usize();
- for (_, range) in self.0.iter_mut() {
- if range.end.as_usize() > max_duration_usize {
- range.end = max_duration;
+ for track in self.0.iter_mut() {
+ if track.range.end.as_usize() > max_duration_usize {
+ track.range.end = max_duration;
}
}
+ // Tracks starting after the end are not played at all.
+ self.0
+ .retain(|track| track.range.start.as_usize() < max_duration_usize);
}
pub fn calc_stream_duration(&self) -> usize {
self.0
.iter()
- .map(|(_, range)| range.start.as_usize() + range.end.as_usize())
+ .map(|track| track.range.end.as_usize())
.max()
.unwrap_or(0)
}
+
+ pub fn tracks(&self) -> &[ResolvedAudioTrack<TUnit>] {
+ &self.0
+ }
}
impl<'a> AudioMap<'a> {
@@ -242,14 +450,14 @@ impl<'a> AudioMap<'a> {
pub fn used_audio_files<T: FromIterator<&'a str>>(&'a self) -> Option<T> {
self.0.as_ref().map(|map| {
map.iter()
- .filter_map(|(filename, range)| {
+ .filter_map(|AudioTrack { file, range, .. }| {
let start = range
.start
- .infer_relying_on_dynamic_duration_audio_files(filename);
+ .infer_relying_on_dynamic_duration_audio_files(file);
let end = range
.end
- .infer_relying_on_dynamic_duration_audio_files(filename);
+ .infer_relying_on_dynamic_duration_audio_files(file);
match (start, end) {
(Some(mut start), Some(mut end)) => {
@@ -266,38 +474,38 @@ impl<'a> AudioMap<'a> {
})
}
+ /// `resolve_audio_duration` returns the duration of a file in seconds.
pub(crate) fn resolve<TUnit: AudioTimelineUnit + std::fmt::Debug>(
&self,
offset: TUnit,
tb: &TimeBase,
- resolve_audio_duration_in_frames: impl Fn(&str) -> error::Result<usize>,
+ resolve_audio_duration: impl Fn(&str) -> error::Result<f64>,
) -> error::Result<Option<AudioTimeline<TUnit>>> {
- let offset = offset.as_usize();
+ let offset = offset.to_seconds(tb);
self.0
.as_ref()
- .map(|file_durations| {
- file_durations
+ .map(|tracks| {
+ tracks
.iter()
- .map(|(filename, range)| {
- let start_unit = range.start.to_unit::<TUnit>(
- filename,
- tb,
- None,
- &resolve_audio_duration_in_frames,
+ .map(|AudioTrack { file, range, mix }| {
+ let start =
+ range
+ .start
+ .to_seconds(file, tb.fps, None, &resolve_audio_duration)?;
+
+ let end = range.end.to_seconds(
+ file,
+ tb.fps,
+ Some(start - mix.offset as f64),
+ &resolve_audio_duration,
)?;
- let end_unit = range.end.to_unit::<TUnit>(
- filename,
- tb,
- Some(start_unit.to_frames(tb)),
- &resolve_audio_duration_in_frames,
- )?;
-
- Ok((
- filename.to_string(),
- TUnit::from_usize(start_unit.as_usize() + offset)
- ..TUnit::from_usize(end_unit.as_usize() + offset),
- ))
+ Ok(ResolvedAudioTrack {
+ file: file.to_string(),
+ range: TUnit::from_seconds(start + offset, tb)
+ ..TUnit::from_seconds(end.max(start) + offset, tb),
+ mix: *mix,
+ })
})
.collect::<error::Result<Vec<_>>>()
})
@@ -308,10 +516,10 @@ impl<'a> AudioMap<'a> {
&'a self,
scenes: Option<&ResolvedScenesTimeline>,
tb: &TimeBase,
- resolve_audio_duration_in_frames: impl Fn(&str) -> error::Result<usize>,
+ resolve_audio_duration: impl Fn(&str) -> error::Result<f64>,
) -> error::Result<Option<ResolvedAudioMap<TUnit>>> {
let global_resolved_map =
- self.resolve(TUnit::from_usize(0), tb, &resolve_audio_duration_in_frames)?;
+ self.resolve(TUnit::from_usize(0), tb, &resolve_audio_duration)?;
let scenes_resolved_map = scenes
.map(|scenes| -> crate::error::Result<_> {
@@ -321,7 +529,7 @@ impl<'a> AudioMap<'a> {
scene.audio().resolve(
TUnit::from_frames(range.start, tb),
tb,
- &resolve_audio_duration_in_frames,
+ &resolve_audio_duration,
)
})
.collect::<error::Result<Vec<_>>>()?
@@ -351,19 +559,37 @@ impl<'a> AudioMap<'a> {
let audio_data = ctx.get_audio(filename).ok_or_else(|| {
crate::error::FFramesError::RequiredAudioNotFound(filename.to_string())
})?;
- Ok(audio_data.duration_in_frames(&ctx.time_base))
+ Ok(audio_data.duration_in_seconds() as f64)
})
}
}
impl<'a, const N: usize> From<[(&'a str, AudioDuration<'a>); N]> for AudioMap<'a> {
fn from(arr: [(&'a str, AudioDuration<'a>); N]) -> Self {
+ AudioMap(Some(arr.into_iter().map(AudioTrack::from).collect()))
+ }
+}
+
+impl<'a, const N: usize> From<[AudioTrack<'a>; N]> for AudioMap<'a> {
+ fn from(arr: [AudioTrack<'a>; N]) -> Self {
AudioMap(Some(arr.to_vec()))
}
}
+impl<'a> From<Vec<AudioTrack<'a>>> for AudioMap<'a> {
+ fn from(tracks: Vec<AudioTrack<'a>>) -> Self {
+ AudioMap(Some(tracks))
+ }
+}
+
impl<'a> FromIterator<(&'a str, AudioDuration<'a>)> for AudioMap<'a> {
fn from_iter<T: IntoIterator<Item = (&'a str, AudioDuration<'a>)>>(iter: T) -> Self {
+ AudioMap(Some(iter.into_iter().map(AudioTrack::from).collect()))
+ }
+}
+
+impl<'a> FromIterator<AudioTrack<'a>> for AudioMap<'a> {
+ fn from_iter<T: IntoIterator<Item = AudioTrack<'a>>>(iter: T) -> Self {
AudioMap(Some(iter.into_iter().collect()))
}
}
diff --git a/fframes/src/audio_mix.rs b/fframes/src/audio_mix.rs
new file mode 100644
index 00000000..68c22218
--- /dev/null
+++ b/fframes/src/audio_mix.rs
@@ -0,0 +1,943 @@
+//! The audio mixer: places every track of the resolved audio map on the output timeline
+//! with sample accuracy and mixes them to stereo.
+//!
+//! - tracks start and end at their exact sample, also in the middle of an encoder frame,
+//! - each track has gain, pan, fades, a file offset and range-driven ducking (`TrackMix`),
+//! - a Kaiser-windowed sinc resamples sources at other sample rates,
+//! - the mixer sums overlapping tracks linearly and runs the sum through a lookahead peak
+//! limiter, so loud overlaps neither intermodulate nor clip.
+use crate::{
+ AudioData, AudioTimelineSamples, AudioTimelineUnit, Ducking, MediaProvider, ResolvedAudioMap,
+ TrackMix,
+};
+use std::collections::VecDeque;
+use std::ops::Range;
+
+/// Master bus settings.
+#[derive(Debug, Clone, Copy)]
+pub struct AudioMixOptions {
+ pub master_gain_db: f32,
+ /// Peak limiter on the master bus. `None` sums without any protection against clipping.
+ pub limiter: Option<LimiterOptions>,
+ /// 5 ms fades wherever a track or the rendered range cuts into a sound, so cuts do not
+ /// click.
+ pub declick: bool,
+}
+
+impl Default for AudioMixOptions {
+ fn default() -> Self {
+ Self {
+ master_gain_db: 0.,
+ limiter: Some(LimiterOptions::default()),
+ declick: true,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct LimiterOptions {
+ /// Maximum sample level in dBFS.
+ pub ceiling_db: f32,
+ /// The limiter starts reducing the level this long before a peak.
+ pub lookahead_ms: f32,
+ /// Time constant of the level coming back after a peak.
+ pub release_ms: f32,
+}
+
+impl Default for LimiterOptions {
+ fn default() -> Self {
+ Self {
+ ceiling_db: -1.,
+ lookahead_ms: 5.,
+ release_ms: 80.,
+ }
+ }
+}
+
+fn db_to_gain(db: f32) -> f32 {
+ 10f32.powf(db / 20.)
+}
+
+const DECLICK_SECONDS: f64 = 0.005;
+
+/// Modified Bessel function of the first kind, order 0 (for the Kaiser window).
+fn bessel_i0(x: f64) -> f64 {
+ let mut sum = 1.;
+ let mut term = 1.;
+ let half = x / 2.;
+ for k in 1..50 {
+ term *= (half / k as f64) * (half / k as f64);
+ sum += term;
+ if term < sum * 1e-12 {
+ break;
+ }
+ }
+ sum
+}
+
+/// Polyphase table of a Kaiser-windowed sinc low-pass. When downsampling the cutoff drops to
+/// the output Nyquist so nothing above it aliases.
+struct SincResampler {
+ half: usize,
+ phases: usize,
+ table: Vec<f32>,
+}
+
+impl SincResampler {
+ const ZERO_CROSSINGS: f64 = 8.;
+ const PHASES: usize = 256;
+ const KAISER_BETA: f64 = 8.6;
+
+ fn new(source_rate: f64, output_rate: f64) -> Self {
+ let cutoff = (output_rate / source_rate).min(1.) * 0.95;
+ let half = (Self::ZERO_CROSSINGS / cutoff).ceil() as usize;
+ let taps = 2 * half;
+ let phases = Self::PHASES;
+ let norm = bessel_i0(Self::KAISER_BETA);
+ let mut table = Vec::with_capacity((phases + 1) * taps);
+
+ for p in 0..=phases {
+ let frac = p as f64 / phases as f64;
+ let row_start = table.len();
+ for j in 0..taps {
+ // Distance between the interpolated position and source sample `floor + k`.
+ let k = j as f64 - half as f64 + 1.;
+ let d = k - frac;
+ let v = d / half as f64;
+ let window = if v.abs() < 1. {
+ bessel_i0(Self::KAISER_BETA * (1. - v * v).sqrt()) / norm
+ } else {
+ 0.
+ };
+ let x = cutoff * d;
+ let sinc = if x.abs() < 1e-12 {
+ 1.
+ } else {
+ (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x)
+ };
+ table.push((cutoff * sinc * window) as f32);
+ }
+ // Unity DC gain for every phase.
+ let sum: f32 = table[row_start..].iter().sum();
+ if sum.abs() > 1e-9 {
+ table[row_start..].iter_mut().for_each(|c| *c /= sum);
+ }
+ }
+
+ Self {
+ half,
+ phases,
+ table,
+ }
+ }
+
+ /// Value of `samples` at the fractional position `t`.
+ fn sample(&self, samples: &[f32], t: f64) -> f32 {
+ let base = t.floor();
+ let frac = t - base;
+ let base = base as isize;
+ let p = frac * self.phases as f64;
+ let p0 = (p.floor() as usize).min(self.phases - 1);
+ let w = (p - p0 as f64) as f32;
+ let taps = 2 * self.half;
+ let row0 = &self.table[p0 * taps..(p0 + 1) * taps];
+ let row1 = &self.table[(p0 + 1) * taps..(p0 + 2) * taps];
+
+ let mut acc = 0.;
+ for j in 0..taps {
+ let index = base + j as isize - self.half as isize + 1;
+ if index >= 0 && (index as usize) < samples.len() {
+ let coef = row0[j] + (row1[j] - row0[j]) * w;
+ acc += samples[index as usize] * coef;
+ }
+ }
+ acc
+ }
+}
+
+/// Lookahead brickwall limiter (linked stereo). The gain is the sliding minimum of the gain
+/// each sample needs, released exponentially and smoothed by a moving average as long as the
+/// lookahead, so it reaches the required gain exactly at the (delayed) peak.
+struct Limiter {
+ ceiling: f64,
+ lookahead: usize,
+ beta: f64,
+ delay: VecDeque<(f32, f32)>,
+ min_window: VecDeque<(u64, f64)>,
+ released: f64,
+ boxcar: Vec<f64>,
+ boxcar_sum: f64,
+ n: u64,
+}
+
+impl Limiter {
+ fn new(options: LimiterOptions, sample_rate: usize) -> Self {
+ let lookahead =
+ ((options.lookahead_ms as f64 / 1000. * sample_rate as f64).round() as usize).max(1);
+ let release = (options.release_ms as f64 / 1000.).max(1e-4);
+ let mut limiter = Self {
+ ceiling: 10f64.powf(options.ceiling_db as f64 / 20.),
+ lookahead,
+ beta: 1. - (-1. / (release * sample_rate as f64)).exp(),
+ delay: VecDeque::with_capacity(lookahead),
+ min_window: VecDeque::new(),
+ released: 1.,
+ boxcar: vec![1.; lookahead],
+ boxcar_sum: lookahead as f64,
+ n: 0,
+ };
+ limiter.reset();
+ limiter
+ }
+
+ /// Output samples lag the input by this many samples.
+ fn latency(&self) -> usize {
+ self.lookahead - 1
+ }
+
+ fn reset(&mut self) {
+ self.delay.clear();
+ for _ in 0..self.latency() {
+ self.delay.push_back((0., 0.));
+ }
+ self.min_window.clear();
+ self.released = 1.;
+ self.boxcar.iter_mut().for_each(|g| *g = 1.);
+ self.boxcar_sum = self.lookahead as f64;
+ self.n = 0;
+ }
+
+ fn process(&mut self, left: f32, right: f32) -> (f32, f32) {
+ let peak = left.abs().max(right.abs()) as f64;
+ let required = if peak > self.ceiling {
+ self.ceiling / peak
+ } else {
+ 1.
+ };
+
+ while self.min_window.back().is_some_and(|(_, g)| *g >= required) {
+ self.min_window.pop_back();
+ }
+ self.min_window.push_back((self.n, required));
+ while self
+ .min_window
+ .front()
+ .is_some_and(|(i, _)| *i + self.lookahead as u64 <= self.n)
+ {
+ self.min_window.pop_front();
+ }
+ let hold = self.min_window.front().map_or(1., |(_, g)| *g);
+
+ self.released = if hold < self.released {
+ hold
+ } else {
+ self.released + (hold - self.released) * self.beta
+ };
+
+ let slot = (self.n % self.lookahead as u64) as usize;
+ self.boxcar_sum += self.released - self.boxcar[slot];
+ self.boxcar[slot] = self.released;
+ if self.n.is_multiple_of(1_000_000) {
+ // Kill floating point drift of the running sum.
+ self.boxcar_sum = self.boxcar.iter().sum();
+ }
+ let gain = (self.boxcar_sum / self.lookahead as f64) as f32;
+ self.n += 1;
+
+ self.delay.push_back((left, right));
+ let (dl, dr) = self.delay.pop_front().unwrap_or((0., 0.));
+ let ceiling = self.ceiling as f32;
+ (
+ (dl * gain).clamp(-ceiling, ceiling),
+ (dr * gain).clamp(-ceiling, ceiling),
+ )
+ }
+}
+
+struct PreparedTrack<'m> {
+ file: String,
+ left: &'m [f32],
+ right: Option<&'m [f32]>,
+ /// Output samples.
+ range: Range<usize>,
+ /// Position in the file (source samples) at `range.start`.
+ source_start: f64,
+ /// Source samples per output sample.
+ ratio: f64,
+ resampler: Option<SincResampler>,
+ gain: f32,
+ /// Mono: equal-power pan gains; stereo: balance attenuation per side.
+ pan: (f32, f32),
+ mix: TrackMix,
+ fade_in: f64,
+ fade_out: f64,
+ declick_in: bool,
+ declick_out: bool,
+ /// Voice ranges (output samples) this track is ducked under, merged.
+ duck_under: Vec<Range<f64>>,
+}
+
+impl PreparedTrack<'_> {
+ fn source_sample(&self, channel: &[f32], position: f64) -> f32 {
+ match &self.resampler {
+ None => channel
+ .get(position.round() as usize)
+ .copied()
+ .unwrap_or(0.),
+ Some(resampler) => resampler.sample(channel, position),
+ }
+ }
+
+ fn envelope(&self, n: usize, sample_rate: f64) -> f32 {
+ let from_start = (n - self.range.start) as f64;
+ let to_end = (self.range.end - n) as f64;
+ let mut gain = self.gain;
+
+ if self.fade_in > 0. && from_start < self.fade_in {
+ gain *= self.mix.fade_curve.gain((from_start / self.fade_in) as f32);
+ } else if self.declick_in && from_start < DECLICK_SECONDS * sample_rate {
+ gain *= (from_start / (DECLICK_SECONDS * sample_rate)) as f32;
+ }
+
+ if self.fade_out > 0. && to_end <= self.fade_out {
+ gain *= self
+ .mix
+ .fade_curve
+ .gain(((to_end - 1.) / self.fade_out) as f32);
+ } else if self.declick_out && to_end <= DECLICK_SECONDS * sample_rate {
+ gain *= ((to_end - 1.) / (DECLICK_SECONDS * sample_rate)).max(0.) as f32;
+ }
+
+ if let Some(ducking) = self.mix.duck {
+ gain *= db_to_gain(duck_db(&self.duck_under, &ducking, n as f64, sample_rate));
+ }
+
+ gain
+ }
+}
+
+/// Attenuation of a ducked track at output sample `n`.
+fn duck_db(voices: &[Range<f64>], ducking: &Ducking, n: f64, sample_rate: f64) -> f32 {
+ let attack = ducking.attack as f64 * sample_rate;
+ let hold = ducking.hold as f64 * sample_rate;
+ let release = ducking.release as f64 * sample_rate;
+ let raised_cosine = |t: f64| (1. - (t.clamp(0., 1.) * std::f64::consts::PI).cos()) * 0.5;
+
+ let mut depth: f64 = 0.;
+ for voice in voices {
+ let down_from = voice.start - attack;
+ let up_from = voice.end + hold;
+ if n < down_from || n >= up_from + release {
+ continue;
+ }
+ let amount = if n < voice.start {
+ if attack > 0. {
+ raised_cosine((n - down_from) / attack)
+ } else {
+ 1.
+ }
+ } else if n < up_from {
+ 1.
+ } else {
+ 1. - raised_cosine((n - up_from) / release.max(1.))
+ };
+ depth = depth.max(amount);
+ }
+ ducking.depth_db * depth as f32
+}
+
+/// Mixes the resolved audio map block by block. Blocks are expected in order (the limiter is
+/// stateful); jumping elsewhere resets the limiter.
+pub struct AudioMixer<'m> {
+ tracks: Vec<PreparedTrack<'m>>,
+ sample_rate: usize,
+ master_gain: f32,
+ limiter: Option<Limiter>,
+ /// The next raw sample the limiter expects.
+ next_raw: Option<usize>,
+ output_range: Range<usize>,
+ total_samples: usize,
+ declick: bool,
+ missing: Vec<String>,
+}
+
+impl<'m> AudioMixer<'m> {
+ /// `output_range` is the part of the timeline being rendered (in samples at
+ /// `sample_rate`), `total_samples` the length of the whole video.
+ pub fn new(
+ audio_map: Option<&ResolvedAudioMap<AudioTimelineSamples>>,
+ media: Option<&'m dyn MediaProvider<'m>>,
+ sample_rate: usize,
+ output_range: Range<usize>,
+ total_samples: usize,
+ options: AudioMixOptions,
+ ) -> Self {
+ Self::new_rescaled(
+ audio_map,
+ sample_rate,
+ media,
+ sample_rate,
+ output_range,
+ total_samples,
+ options,
+ )
+ }
+
+ /// Like `new` for an audio map resolved at `map_sample_rate` while the output runs at
+ /// `sample_rate`, e.g. when the encoder does not support the requested rate (Opus is
+ /// 48 kHz only). `output_range` and `total_samples` are at `sample_rate`.
+ pub fn new_rescaled(
+ audio_map: Option<&ResolvedAudioMap<AudioTimelineSamples>>,
+ map_sample_rate: usize,
+ media: Option<&'m dyn MediaProvider<'m>>,
+ sample_rate: usize,
+ output_range: Range<usize>,
+ total_samples: usize,
+ options: AudioMixOptions,
+ ) -> Self {
+ let mut missing = Vec::new();
+ let resolved = audio_map.map(|map| map.tracks()).unwrap_or_default();
+ let rate = sample_rate as f64;
+ let rescale = sample_rate as f64 / map_sample_rate.max(1) as f64;
+ let to_output = |sample: usize| (sample as f64 * rescale).round() as usize;
+
+ let voices: Vec<Range<f64>> = resolved
+ .iter()
+ .filter(|t| t.mix.voice)
+ .map(|t| {
+ to_output(t.range.start.as_usize()) as f64..to_output(t.range.end.as_usize()) as f64
+ })
+ .collect();
+
+ let mut tracks = Vec::new();
+ for track in resolved {
+ let audio = match media.and_then(|m| m.resolve_audio(&track.file)) {
+ Some(AudioData::Preloaded(data)) => data,
+ Some(AudioData::Lazy) => continue,
+ None => {
+ crate::diagnostics::report_missing_media(
+ crate::diagnostics::MediaKind::Audio,
+ &track.file,
+ );
+ missing.push(track.file.clone());
+ continue;
+ }
+ };
+
+ let range =
+ to_output(track.range.start.as_usize())..to_output(track.range.end.as_usize());
+ if range.is_empty() || audio.sample_rate == 0 {
+ continue;
+ }
+
+ let source_rate = audio.sample_rate as f64;
+ let ratio = source_rate / rate;
+ let source_start = track.mix.offset as f64 * source_rate;
+ let natural_end =
+ range.start as f64 + (audio.samples.len() as f64 - source_start) / ratio;
+ let resampler = (audio.sample_rate as usize != sample_rate)
+ .then(|| SincResampler::new(source_rate, rate));
+
+ let pan = track.mix.pan.clamp(-1., 1.);
+ let pan = if pan.abs() < 1e-6 {
+ (1., 1.)
+ } else if audio.is_stereo() {
+ // Balance: attenuate the opposite side.
+ let attenuation = (pan.abs() * std::f32::consts::FRAC_PI_2).cos();
+ if pan > 0. {
+ (attenuation, 1.)
+ } else {
+ (1., attenuation)
+ }
+ } else {
+ // Equal power, compensated to unity at the center.
+ let x = (pan + 1.) * 0.5 * std::f32::consts::FRAC_PI_2;
+ (
+ (std::f32::consts::SQRT_2 * x.cos()).min(1.),
+ (std::f32::consts::SQRT_2 * x.sin()).min(1.),
+ )
+ };
+
+ let duck_under = match track.mix.duck {
+ Some(ducking) => merge_ranges(
+ voices
+ .iter()
+ // A voice track does not duck itself.
+ .filter(|v| {
+ !(track.mix.voice && **v == (range.start as f64..range.end as f64))
+ })
+ .cloned()
+ .collect(),
+ ducking.merge_gap as f64 * rate,
+ ),
+ None => Vec::new(),
+ };
+
+ tracks.push(PreparedTrack {
+ file: track.file.clone(),
+ left: audio.samples.as_ref(),
+ right: audio.right.as_deref(),
+ source_start,
+ ratio,
+ resampler,
+ gain: db_to_gain(track.mix.gain_db),
+ pan,
+ mix: track.mix,
+ fade_in: track.mix.fade_in as f64 * rate,
+ fade_out: track.mix.fade_out as f64 * rate,
+ declick_in: options.declick && track.mix.offset > 0.,
+ declick_out: options.declick && (range.end as f64) < natural_end - 1.,
+ range,
+ duck_under,
+ });
+ }
+
+ Self {
+ tracks,
+ sample_rate,
+ master_gain: db_to_gain(options.master_gain_db),
+ limiter: options.limiter.map(|l| Limiter::new(l, sample_rate)),
+ next_raw: None,
+ output_range,
+ total_samples,
+ declick: options.declick,
+ missing,
+ }
+ }
+
+ /// Audio files of the map the media provider does not have.
+ pub fn missing_files(&self) -> &[String] {
+ &self.missing
+ }
+
+ pub fn sample_rate(&self) -> usize {
+ self.sample_rate
+ }
+
+ /// Sums all tracks for `start..start + left.len()` without the master bus.
+ fn mix_raw(&self, start: usize, left: &mut [f32], right: &mut [f32]) {
+ left.fill(0.);
+ right.fill(0.);
+ let end = start + left.len();
+ let rate = self.sample_rate as f64;
+
+ for track in &self.tracks {
+ let from = track.range.start.max(start);
+ let to = track.range.end.min(end);
+ if from >= to {
+ continue;
+ }
+
+ for n in from..to {
+ let position = track.source_start + (n - track.range.start) as f64 * track.ratio;
+ let gain = track.envelope(n, rate);
+ if gain == 0. {
+ continue;
+ }
+
+ let i = n - start;
+ let l = track.source_sample(track.left, position);
+ match track.right {
+ Some(right_channel) => {
+ let r = track.source_sample(right_channel, position);
+ left[i] += l * gain * track.pan.0;
+ right[i] += r * gain * track.pan.1;
+ }
+ None => {
+ left[i] += l * gain * track.pan.0;
+ right[i] += l * gain * track.pan.1;
+ }
+ }
+ }
+ }
+
+ if self.master_gain != 1. {
+ left.iter_mut().for_each(|s| *s *= self.master_gain);
+ right.iter_mut().for_each(|s| *s *= self.master_gain);
+ }
+ }
+
+ /// Fills `left`/`right` with the final mix of the timeline samples starting at `start`.
+ pub fn render(&mut self, start: usize, left: &mut [f32], right: &mut [f32]) {
+ let len = left.len().min(right.len());
+ let (left, right) = (&mut left[..len], &mut right[..len]);
+
+ if self.limiter.is_none() {
+ self.mix_raw(start, left, right);
+ } else {
+ let latency = self.limiter.as_ref().map_or(0, Limiter::latency);
+ let mut raw_l = vec![0.; len];
+ let mut raw_r = vec![0.; len];
+
+ // The limiter delays by `latency`, so it runs that far ahead of the output.
+ if self.next_raw != Some(start + latency) {
+ let mut prime_l = vec![0.; latency];
+ let mut prime_r = vec![0.; latency];
+ self.mix_raw(start, &mut prime_l, &mut prime_r);
+ let limiter = self.limiter.as_mut().expect("limiter is set");
+ limiter.reset();
+ for (l, r) in prime_l.into_iter().zip(prime_r) {
+ limiter.process(l, r);
+ }
+ }
+
+ self.mix_raw(start + latency, &mut raw_l, &mut raw_r);
+ let limiter = self.limiter.as_mut().expect("limiter is set");
+ for i in 0..len {
+ let (l, r) = limiter.process(raw_l[i], raw_r[i]);
+ left[i] = l;
+ right[i] = r;
+ }
+ self.next_raw = Some(start + latency + len);
+ }
+
+ if self.declick {
+ let edge = (DECLICK_SECONDS * self.sample_rate as f64) as usize;
+ for i in 0..len {
+ let n = start + i;
+ let mut gain = 1.;
+ if self.output_range.start > 0 && n < self.output_range.start + edge {
+ gain *= n.saturating_sub(self.output_range.start) as f32 / edge as f32;
+ }
+ if self.output_range.end < self.total_samples && n + edge >= self.output_range.end {
+ gain *= self.output_range.end.saturating_sub(n + 1) as f32 / edge as f32;
+ }
+ if gain < 1. {
+ left[i] *= gain;
+ right[i] *= gain;
+ }
+ }
+ }
+ }
+
+ /// Mixes the whole output range into two channel buffers.
+ pub fn render_all(&mut self) -> (Vec<f32>, Vec<f32>) {
+ let len = self.output_range.len();
+ let mut left = vec![0.; len];
+ let mut right = vec![0.; len];
+ let block = 4096;
+ let mut offset = 0;
+ while offset < len {
+ let n = block.min(len - offset);
+ let start = self.output_range.start + offset;
+ self.render(
+ start,
+ &mut left[offset..offset + n],
+ &mut right[offset..offset + n],
+ );
+ offset += n;
+ }
+ (left, right)
+ }
+
+ /// The tracks audible at a timeline sample with their position in the file and level.
+ pub fn active_tracks_at(&self, sample: usize) -> Vec<ActiveTrack> {
+ let rate = self.sample_rate as f64;
+ self.tracks
+ .iter()
+ .filter(|t| t.range.contains(&sample))
+ .map(|t| {
+ let position = t.source_start + (sample - t.range.start) as f64 * t.ratio;
+ let source_rate = t.ratio * rate;
+ let gain = t.envelope(sample, rate);
+ ActiveTrack {
+ file: t.file.clone(),
+ file_seconds: position / source_rate,
+ gain_db: if gain > 0. {
+ 20. * gain.log10()
+ } else {
+ f32::NEG_INFINITY
+ },
+ voice: t.mix.voice,
+ ducked_db: t
+ .mix
+ .duck
+ .map(|d| duck_db(&t.duck_under, &d, sample as f64, rate))
+ .unwrap_or(0.),
+ }
+ })
+ .collect()
+ }
+}
+
+/// A track playing at some moment, see `AudioMixer::active_tracks_at`.
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ActiveTrack {
+ pub file: String,
+ /// Position inside the file.
+ pub file_seconds: f64,
+ /// Effective level (gain, fades and ducking) in dB.
+ pub gain_db: f32,
+ pub voice: bool,
+ /// Current ducking attenuation (0 when not ducked).
+ pub ducked_db: f32,
+}
+
+fn merge_ranges(mut ranges: Vec<Range<f64>>, gap: f64) -> Vec<Range<f64>> {
+ ranges.sort_by(|a, b| a.start.total_cmp(&b.start));
+ let mut merged: Vec<Range<f64>> = Vec::with_capacity(ranges.len());
+ for range in ranges {
+ match merged.last_mut() {
+ Some(last) if range.start <= last.end + gap => last.end = last.end.max(range.end),
+ _ => merged.push(range),
+ }
+ }
+ merged
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{AudioMap, AudioTimestamp::*, AudioTrack, TimeBase};
+ use std::borrow::Cow;
+ use std::collections::HashMap;
+
+ #[derive(Debug)]
+ struct Media(HashMap<String, AudioData<'static>>);
+
+ impl<'a> MediaProvider<'a> for Media {
+ fn resolve_audio(&'a self, name: &str) -> Option<&'a AudioData<'a>> {
+ self.0.get(name)
+ }
+ fn resolve_image(&'a self, _: &str) -> Option<&'a crate::media::ImageData<'a>> {
+ None
+ }
+ fn resolve_subtitles(&'a self, _: &str) -> Option<&'a crate::media::Subtitles<'a>> {
+ None
+ }
+ fn resolve_video(&'a self, _: &str) -> Option<&'a crate::media::VideoMedia> {
+ None
+ }
+ fn populate_font_source(&'a self, _: &mut dyn crate::FontSource) {}
+ fn populate_image_source(
+ &'a self,
+ _: &mut HashMap<String, std::sync::Arc<crate::usvgr::PreloadedImageData>>,
+ ) {
+ }
+ }
+
+ fn audio(samples: Vec<f32>, sample_rate: u32) -> AudioData<'static> {
+ AudioData::Preloaded(crate::media::PreloadedAudioData {
+ samples: Cow::Owned(samples),
+ sample_rate,
+ right: None,
+ })
+ }
+
+ const RATE: usize = 44100;
+
+ fn resolve(map: AudioMap, media: &Media) -> ResolvedAudioMap<AudioTimelineSamples> {
+ map.resolve_with_scenes(
+ None,
+ &TimeBase {
+ fps: 30,
+ sample_rate: RATE,
+ },
+ |file| Ok(media.0[file].duration_in_seconds() as f64),
+ )
+ .unwrap()
+ .unwrap()
+ }
+
+ fn no_master() -> AudioMixOptions {
+ AudioMixOptions {
+ limiter: None,
+ declick: false,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn short_sounds_start_at_their_exact_sample() {
+ // A click of 1000 samples at 0.51s: not frame aligned and in the middle of a 1024
+ // sample encoder block. The old mixer dropped its beginning.
+ let media = Media(HashMap::from([(
+ "click".into(),
+ audio(vec![0.5; 1000], RATE as u32),
+ )]));
+ let map = resolve(AudioMap::from([("click", Second(0.51)..Eof)]), &media);
+ let start = (0.51 * RATE as f64).round() as usize;
+ assert_eq!(map.tracks()[0].range.start.as_usize(), start);
+
+ let mut mixer = AudioMixer::new(Some(&map), Some(&media), RATE, 0..RATE, RATE, no_master());
+ let (left, right) = mixer.render_all();
+ assert_eq!(left[start - 1], 0.);
+ assert_eq!(left[start], 0.5);
+ assert_eq!(right[start + 999], 0.5);
+ assert_eq!(left[start + 1000], 0.);
+ assert_eq!(left.iter().filter(|s| **s != 0.).count(), 1000);
+ }
+
+ #[test]
+ fn overlapping_tracks_sum_linearly_and_the_limiter_catches_peaks() {
+ let media = Media(HashMap::from([
+ ("a".into(), audio(vec![0.6; RATE], RATE as u32)),
+ ("b".into(), audio(vec![0.3; RATE], RATE as u32)),
+ ]));
+ let map = resolve(
+ AudioMap::from([("a", Second(0.)..Eof), ("b", Second(0.)..Eof)]),
+ &media,
+ );
+
+ let mut mixer = AudioMixer::new(Some(&map), Some(&media), RATE, 0..RATE, RATE, no_master());
+ let (left, _) = mixer.render_all();
+ assert!((left[100] - 0.9).abs() < 1e-6, "{}", left[100]);
+
+ let loud = Media(HashMap::from([
+ ("a".into(), audio(vec![0.9; RATE], RATE as u32)),
+ ("b".into(), audio(vec![0.9; RATE], RATE as u32)),
+ ]));
+ let mut limited = AudioMixer::new(
+ Some(&map),
+ Some(&loud),
+ RATE,
+ 0..RATE,
+ RATE,
+ AudioMixOptions::default(),
+ );
+ let (left, _) = limited.render_all();
+ let ceiling = db_to_gain(-1.);
+ assert!(left.iter().all(|s| s.abs() <= ceiling + 1e-6));
+ assert!((left[RATE / 2] - ceiling).abs() < 1e-3);
+ }
+
+ #[test]
+ fn gain_pan_fades_and_offset() {
+ let ramp: Vec<f32> = (0..RATE).map(|i| i as f32 / RATE as f32).collect();
+ let media = Media(HashMap::from([("ramp".into(), audio(ramp, RATE as u32))]));
+ let map = resolve(
+ AudioMap::from([AudioTrack::new("ramp", Second(0.)..Second(0.5))
+ .offset(0.25)
+ .gain_db(-6.0206)
+ .pan(1.)]),
+ &media,
+ );
+ let mut mixer = AudioMixer::new(Some(&map), Some(&media), RATE, 0..RATE, RATE, no_master());
+ let (left, right) = mixer.render_all();
+
+ // Offset: the first output sample is the file at 0.25s, at half the level.
+ assert!((right[0] - 0.125).abs() < 1e-3, "{}", right[0]);
+ // Hard right: nothing on the left.
+ assert!(left.iter().all(|s| s.abs() < 1e-6));
+ // Range end: silent after 0.5s.
+ assert_eq!(right[RATE / 2 + 1], 0.);
+
+ let media = Media(HashMap::from([(
+ "tone".into(),
+ audio(vec![1.; RATE], RATE as u32),
+ )]));
+ let map = resolve(
+ AudioMap::from([AudioTrack::new("tone", Second(0.)..Eof)
+ .fade_in(0.5)
+ .fade_curve(crate::FadeCurve::Linear)]),
+ &media,
+ );
+ let mut mixer = AudioMixer::new(Some(&map), Some(&media), RATE, 0..RATE, RATE, no_master());
+ let (left, _) = mixer.render_all();
+ assert!((left[RATE / 4] - 0.5).abs() < 1e-3);
+ assert_eq!(left[RATE - 1], 1.);
+ }
+
+ #[test]
+ fn ducking_follows_voice_ranges() {
+ let media = Media(HashMap::from([
+ ("music".into(), audio(vec![0.5; 4 * RATE], RATE as u32)),
+ ("voice".into(), audio(vec![0.; RATE], RATE as u32)),
+ ]));
+ let map = resolve(
+ AudioMap::from([
+ AudioTrack::new("music", Second(0.)..Eof).duck_under_voice(),
+ AudioTrack::new("voice", Second(1.)..Eof).voice(),
+ ]),
+ &media,
+ );
+ let mut mixer = AudioMixer::new(
+ Some(&map),
+ Some(&media),
+ RATE,
+ 0..4 * RATE,
+ 4 * RATE,
+ no_master(),
+ );
+ let (left, _) = mixer.render_all();
+
+ assert!((left[RATE / 4] - 0.5).abs() < 1e-6, "before the attack");
+ let ducked = 0.5 * db_to_gain(-12.);
+ assert!(
+ (left[RATE + RATE / 2] - ducked).abs() < 1e-4,
+ "during the voice"
+ );
+ assert!(
+ left[RATE - RATE / 10] < 0.5 && left[RATE - RATE / 10] > ducked,
+ "attack"
+ );
+ // Voice ends at 2s, hold 0.3s, release 0.8s: back to full level at 3.1s.
+ assert!(
+ left[2 * RATE + RATE / 2] > ducked && left[2 * RATE + RATE / 2] < 0.5,
+ "release"
+ );
+ assert!((left[3 * RATE + RATE / 5] - 0.5).abs() < 1e-6, "released");
+ }
+
+ #[test]
+ fn resampling_keeps_a_tone_at_its_frequency_and_level() {
+ let source_rate = 48000.;
+ let tone: Vec<f32> = (0..48000)
+ .map(|i| (2. * std::f64::consts::PI * 1000. * i as f64 / source_rate).sin() as f32)
+ .collect();
+ let media = Media(HashMap::from([("tone".into(), audio(tone, 48000))]));
+ let map = resolve(AudioMap::from([("tone", Second(0.)..Eof)]), &media);
+ let mut mixer = AudioMixer::new(Some(&map), Some(&media), RATE, 0..RATE, RATE, no_master());
+ let (left, _) = mixer.render_all();
+
+ for i in [1000usize, 20000, 40000] {
+ let expected =
+ (2. * std::f64::consts::PI * 1000. * i as f64 / RATE as f64).sin() as f32;
+ assert!(
+ (left[i] - expected).abs() < 2e-3,
+ "{i}: {} vs {expected}",
+ left[i]
+ );
+ }
+ }
+
+ #[test]
+ fn maps_resolved_at_another_rate_are_rescaled() {
+ let media = Media(HashMap::from([(
+ "click".into(),
+ audio(vec![0.5; 100], RATE as u32),
+ )]));
+ // Resolved at 44.1 kHz, mixed at 48 kHz: the click still starts at 0.5s.
+ let map = resolve(AudioMap::from([("click", Second(0.5)..Eof)]), &media);
+ let mut mixer = AudioMixer::new_rescaled(
+ Some(&map),
+ RATE,
+ Some(&media),
+ 48000,
+ 0..48000,
+ 48000,
+ no_master(),
+ );
+ let (left, _) = mixer.render_all();
+ assert_eq!(left[23999], 0.);
+ assert!(left[24000] > 0.4);
+ }
+
+ #[test]
+ fn range_renders_start_in_the_middle_of_a_track() {
+ let ramp: Vec<f32> = (0..RATE).map(|i| i as f32 / RATE as f32).collect();
+ let media = Media(HashMap::from([("ramp".into(), audio(ramp, RATE as u32))]));
+ let map = resolve(AudioMap::from([("ramp", Second(0.)..Eof)]), &media);
+ let mut mixer = AudioMixer::new(
+ Some(&map),
+ Some(&media),
+ RATE,
+ RATE / 2..RATE,
+ RATE,
+ no_master(),
+ );
+ let (left, _) = mixer.render_all();
+ assert_eq!(left.len(), RATE / 2);
+ assert!((left[0] - 0.5).abs() < 1e-4);
+ }
+}
diff --git a/fframes/src/diagnostics.rs b/fframes/src/diagnostics.rs
new file mode 100644
index 00000000..5bdb7a52
--- /dev/null
+++ b/fframes/src/diagnostics.rs
@@ -0,0 +1,384 @@
+//! Frame diagnostics: problems that do not fail a render but produce a wrong picture, such as
+//! a missing image, an unknown font family or text pushed off the canvas. The collector reports
+//! them without rasterizing anything, from three sources:
+//!
+//! - media lookups through `FFramesContext::get_*` that return `None`,
+//! - warnings of the SVG converter (missing fonts, glyphs, font fallbacks),
+//! - a walk over the converted tree (text outside the canvas, non-finite transforms, empty frames).
+//!
+//! Collection is scoped to the current thread, so it costs nothing unless a caller opted in:
+//!
+//! ```ignore
+//! let (pixels, diagnostics) = fframes::diagnostics::collect(|| previewer.render(frame));
+//! ```
+use serde::Serialize;
+use std::cell::RefCell;
+use std::collections::BTreeSet;
+use std::sync::Mutex;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Severity {
+ Info,
+ Warning,
+ Error,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MediaKind {
+ Image,
+ Audio,
+ Video,
+ Subtitles,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum Diagnostic {
+ /// `ctx.get_image/get_audio/get_video/get_subtitles` did not find the file.
+ MissingMedia { media: MediaKind, name: String },
+ /// No font in the database matches the requested family, the text is drawn with a fallback.
+ MissingFont { message: String },
+ /// None of the loaded fonts has a glyph for a character, it is not drawn.
+ MissingGlyph { message: String },
+ /// Any other warning of the SVG converter.
+ RendererWarning { message: String },
+ /// Text is partially outside the canvas, it is cut off in the video.
+ TextClipped { text: String, bbox: [f32; 4] },
+ /// Text is entirely outside the canvas (fine while it animates in or out).
+ TextOffCanvas { text: String, bbox: [f32; 4] },
+ /// A node's transform contains NaN or infinity, the node is not drawn.
+ InvalidTransform { id: String },
+ /// The frame has no visible content besides the background color.
+ EmptyFrame,
+ /// `render_frame` panicked.
+ Panic { message: String },
+}
+
+impl Diagnostic {
+ /// Identity of a finding across frames: the same text moving around is one finding.
+ pub fn group_key(&self) -> String {
+ match self {
+ Diagnostic::TextClipped { text, .. } => format!("text_clipped:{text}"),
+ Diagnostic::TextOffCanvas { text, .. } => format!("text_off_canvas:{text}"),
+ other => other.to_string(),
+ }
+ }
+
+ pub fn severity(&self) -> Severity {
+ match self {
+ Diagnostic::Panic { .. }
+ | Diagnostic::MissingMedia { .. }
+ | Diagnostic::MissingGlyph { .. }
+ | Diagnostic::InvalidTransform { .. } => Severity::Error,
+ Diagnostic::MissingFont { .. }
+ | Diagnostic::TextClipped { .. }
+ | Diagnostic::EmptyFrame
+ | Diagnostic::RendererWarning { .. } => Severity::Warning,
+ Diagnostic::TextOffCanvas { .. } => Severity::Info,
+ }
+ }
+}
+
+impl std::fmt::Display for Diagnostic {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let [x, y, w, h] = match self {
+ Diagnostic::TextClipped { bbox, .. } | Diagnostic::TextOffCanvas { bbox, .. } => *bbox,
+ _ => [0.; 4],
+ };
+
+ match self {
+ Diagnostic::MissingMedia { media, name } => {
+ write!(f, "{media:?} \"{name}\" is not in the media provider")
+ }
+ Diagnostic::MissingFont { message }
+ | Diagnostic::MissingGlyph { message }
+ | Diagnostic::RendererWarning { message } => write!(f, "{message}"),
+ Diagnostic::TextClipped { text, .. } => write!(
+ f,
+ "text \"{text}\" is cut off by the canvas edge (x={x:.0} y={y:.0} w={w:.0} h={h:.0})"
+ ),
+ Diagnostic::TextOffCanvas { text, .. } => write!(
+ f,
+ "text \"{text}\" is outside the canvas (x={x:.0} y={y:.0} w={w:.0} h={h:.0})"
+ ),
+ Diagnostic::InvalidTransform { id } => {
+ write!(f, "node \"{id}\" has a NaN or infinite transform")
+ }
+ Diagnostic::EmptyFrame => write!(f, "frame is empty"),
+ Diagnostic::Panic { message } => write!(f, "render_frame panicked: {message}"),
+ }
+ }
+}
+
+thread_local! {
+ static COLLECTOR: RefCell<Option<Vec<Diagnostic>>> = const { RefCell::new(None) };
+}
+
+/// Media that was requested but missing during any render in this process. Unlike the scoped
+/// collector this is always on (it only records on a miss) so full renders can report it.
+static MISSING_MEDIA: Mutex<BTreeSet<(MediaKind, String)>> = Mutex::new(BTreeSet::new());
+
+/// Runs `f` and returns everything reported on this thread while it ran. Nested calls report
+/// to the innermost collector.
+pub fn collect<R>(f: impl FnOnce() -> R) -> (R, Vec<Diagnostic>) {
+ install_log_capture();
+ let previous = COLLECTOR.with(|c| c.borrow_mut().replace(Vec::new()));
+ let result = f();
+ let collected = COLLECTOR.with(|c| std::mem::replace(&mut *c.borrow_mut(), previous));
+
+ (result, dedup(collected.unwrap_or_default()))
+}
+
+/// Reports a diagnostic to the collector of the current thread, if there is one.
+pub fn report(diagnostic: Diagnostic) {
+ COLLECTOR.with(|c| {
+ if let Some(collected) = c.borrow_mut().as_mut() {
+ collected.push(diagnostic);
+ }
+ });
+}
+
+pub(crate) fn report_missing_media(media: MediaKind, name: &str) {
+ if let Ok(mut missing) = MISSING_MEDIA.lock()
+ && !missing.iter().any(|(k, n)| *k == media && n == name)
+ {
+ missing.insert((media, name.to_owned()));
+ }
+
+ report(Diagnostic::MissingMedia {
+ media,
+ name: name.to_owned(),
+ });
+}
+
+/// Drains the media files that were requested but missing since the last call.
+pub fn take_missing_media() -> Vec<(MediaKind, String)> {
+ MISSING_MEDIA
+ .lock()
+ .map(|mut missing| std::mem::take(&mut *missing).into_iter().collect())
+ .unwrap_or_default()
+}
+
+fn dedup(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
+ let mut unique: Vec<Diagnostic> = Vec::with_capacity(diagnostics.len());
+ for diagnostic in diagnostics {
+ if !unique.contains(&diagnostic) {
+ unique.push(diagnostic);
+ }
+ }
+ unique
+}
+
+/// Classifies a warning of the SVG converter.
+fn from_renderer_warning(message: String) -> Diagnostic {
+ if message.starts_with("No match for") {
+ Diagnostic::MissingFont { message }
+ } else if message.starts_with("No fonts with a") {
+ Diagnostic::MissingGlyph { message }
+ } else {
+ Diagnostic::RendererWarning { message }
+ }
+}
+
+struct CaptureLogger;
+
+impl log::Log for CaptureLogger {
+ fn enabled(&self, metadata: &log::Metadata) -> bool {
+ metadata.level() <= log::Level::Warn
+ }
+
+ fn log(&self, record: &log::Record) {
+ if self.enabled(record.metadata()) {
+ report(from_renderer_warning(record.args().to_string()));
+ }
+ }
+
+ fn flush(&self) {}
+}
+
+static CAPTURE_LOGGER: CaptureLogger = CaptureLogger;
+
+/// Routes `log` warnings (the SVG converter reports missing fonts through it) into the
+/// diagnostics collector. Does nothing if the application installed its own logger.
+pub fn install_log_capture() {
+ static INSTALLED: std::sync::Once = std::sync::Once::new();
+ INSTALLED.call_once(|| {
+ if log::set_logger(&CAPTURE_LOGGER).is_ok() {
+ log::set_max_level(log::LevelFilter::Warn);
+ }
+ });
+}
+
+/// Walks a converted frame and reports layout problems. `width`/`height` is the canvas size.
+pub fn inspect_tree(tree: &usvgr::Tree, width: f32, height: f32) -> Vec<Diagnostic> {
+ let mut diagnostics = Vec::new();
+ let root = tree.root();
+
+ if !root.has_children() {
+ diagnostics.push(Diagnostic::EmptyFrame);
+ }
+
+ inspect_group(root, width, height, &mut diagnostics);
+ diagnostics
+}
+
+fn inspect_group(group: &usvgr::Group, width: f32, height: f32, out: &mut Vec<Diagnostic>) {
+ if !group.abs_transform().is_finite() {
+ out.push(Diagnostic::InvalidTransform {
+ id: group.id().to_owned(),
+ });
+ return;
+ }
+
+ for node in group.children() {
+ match node {
+ usvgr::Node::Group(group) => {
+ // Content under a clip path or mask is cut on purpose (scrolling lists,
+ // reveals) and invisible groups do not matter.
+ if group.clip_path().is_some()
+ || group.mask().is_some()
+ || group.opacity().get() == 0.
+ {
+ check_transforms(group, out);
+ } else {
+ inspect_group(group, width, height, out)
+ }
+ }
+ usvgr::Node::Text(text) => {
+ if !text.abs_transform().is_finite() {
+ out.push(Diagnostic::InvalidTransform {
+ id: text.id().to_owned(),
+ });
+ continue;
+ }
+
+ let bbox = text.abs_bounding_box();
+ let rect = [bbox.x(), bbox.y(), bbox.width(), bbox.height()];
+ let content = text
+ .chunks()
+ .iter()
+ .map(|chunk| chunk.text())
+ .collect::<Vec<_>>()
+ .join(" ");
+ // A pixel of tolerance for anti-aliasing and rounding at the edges.
+ let inside = bbox.left() >= -1.
+ && bbox.top() >= -1.
+ && bbox.right() <= width + 1.
+ && bbox.bottom() <= height + 1.;
+ let disjoint = bbox.right() <= 0.
+ || bbox.bottom() <= 0.
+ || bbox.left() >= width
+ || bbox.top() >= height;
+
+ if disjoint {
+ out.push(Diagnostic::TextOffCanvas {
+ text: content,
+ bbox: rect,
+ });
+ } else if !inside {
+ out.push(Diagnostic::TextClipped {
+ text: content,
+ bbox: rect,
+ });
+ }
+ }
+ usvgr::Node::Path(path) => {
+ if !path.abs_transform().is_finite() {
+ out.push(Diagnostic::InvalidTransform {
+ id: path.id().to_owned(),
+ });
+ }
+ }
+ usvgr::Node::Image(image) => {
+ if !image.abs_transform().is_finite() {
+ out.push(Diagnostic::InvalidTransform {
+ id: image.id().to_owned(),
+ });
+ }
+ }
+ }
+ }
+}
+
+/// Only the transform check, for subtrees whose layout is intentionally cut.
+fn check_transforms(group: &usvgr::Group, out: &mut Vec<Diagnostic>) {
+ if !group.abs_transform().is_finite() {
+ out.push(Diagnostic::InvalidTransform {
+ id: group.id().to_owned(),
+ });
+ return;
+ }
+ for node in group.children() {
+ if let usvgr::Node::Group(group) = node {
+ check_transforms(group, out);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn collects_only_inside_the_scope() {
+ report(Diagnostic::EmptyFrame);
+ let ((), collected) = collect(|| {
+ report(Diagnostic::EmptyFrame);
+ report(Diagnostic::EmptyFrame);
+ });
+ assert_eq!(collected, vec![Diagnostic::EmptyFrame]);
+
+ let ((), nothing) = collect(|| ());
+ assert!(nothing.is_empty());
+ }
+
+ #[test]
+ fn classifies_converter_warnings() {
+ assert!(matches!(
+ from_renderer_warning("No match for '\"Foo\"' font-family.".into()),
+ Diagnostic::MissingFont { .. }
+ ));
+ assert!(matches!(
+ from_renderer_warning("No fonts with a x/U+78 character were found.".into()),
+ Diagnostic::MissingGlyph { .. }
+ ));
+ }
+
+ #[test]
+ fn finds_clipped_and_off_canvas_text() {
+ let mut fontdb = usvgr::fontdb::Database::new();
+ fontdb.load_system_fonts();
+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">
+ <text x="150" y="50" font-size="40">clipped</text>
+ <text x="500" y="50" font-size="40">gone</text>
+ <text x="10" y="50" font-size="10">ok</text>
+ <clipPath id="c"><rect width="200" height="100"/></clipPath>
+ <g clip-path="url(#c)"><text x="150" y="50" font-size="40">scrolling</text></g>
+ </svg>"#;
+ let tree = usvgr::Tree::from_str(svg, &usvgr::Options::default(), &fontdb).unwrap();
+ let diagnostics = inspect_tree(&tree, 200., 100.);
+
+ // Without any system font no text is laid out, which is not what this test is about.
+ if fontdb.is_empty() {
+ return;
+ }
+
+ assert!(
+ diagnostics
+ .iter()
+ .any(|d| matches!(d, Diagnostic::TextClipped { text, .. } if text == "clipped"))
+ );
+ assert!(
+ diagnostics
+ .iter()
+ .any(|d| matches!(d, Diagnostic::TextOffCanvas { text, .. } if text == "gone"))
+ );
+ assert!(
+ !diagnostics
+ .iter()
+ .any(|d| matches!(d, Diagnostic::TextClipped { text, .. } | Diagnostic::TextOffCanvas { text, .. } if text == "ok" || text == "scrolling"))
+ );
+ }
+}
diff --git a/fframes/src/duration.rs b/fframes/src/duration.rs
index a3806f3b..6e740150 100644
--- a/fframes/src/duration.rs
+++ b/fframes/src/duration.rs
@@ -80,16 +80,17 @@ impl<'a> Duration<'a> {
}
}
- pub(super) fn to_frames_async<TFun: Fn(&str) -> super::error::Result<usize>>(
+ /// `resolve_audio_duration` returns the duration of a media file in seconds.
+ pub(super) fn to_frames_async<TFun: Fn(&str) -> super::error::Result<f64>>(
&'a self,
fps: usize,
related_audio_map: &AudioMap,
resolve_audio_duration: &'a TFun,
) -> crate::error::Result<usize> {
match self {
- Duration::FromAudio(audio) | Duration::FromVideo(audio) => {
- resolve_audio_duration(audio)
- }
+ Duration::FromAudio(audio) | Duration::FromVideo(audio) => Ok(
+ crate::audio_map::seconds_to_frames_floor(resolve_audio_duration(audio)?, fps),
+ ),
Duration::Seconds(seconds) => Ok((seconds * fps as f32) as usize),
Duration::Frames(frames) => Ok(*frames),
Duration::Auto => {
@@ -106,7 +107,7 @@ impl<'a> Duration<'a> {
let max_frame = resolved_audio_map
.into_iter()
- .map(|(_, range)| range.end.as_usize())
+ .map(|track| track.range.end.as_usize())
.max()
.ok_or(crate::error::FFramesError::MissingDurationOrScenes)?;
diff --git a/fframes/src/fframes_context.rs b/fframes/src/fframes_context.rs
index 9c06f1d9..ec4ec0e9 100644
--- a/fframes/src/fframes_context.rs
+++ b/fframes/src/fframes_context.rs
@@ -1,8 +1,5 @@
use crate::media::{ImageData, Subtitles};
-use crate::{
- AudioData, AudioTimelineSamples, AudioTimelineUnit, FontSource, Frame, MediaProvider,
- ResolvedAudioMap, ResolvedScenesTimeline, Svgr,
-};
+use crate::{AudioData, FontSource, Frame, MediaProvider, ResolvedScenesTimeline, Svgr};
use fframes_media::VideoMedia;
use std::iter::FromIterator;
use std::sync::atomic::AtomicBool;
@@ -32,9 +29,11 @@ impl VideoSize {
return Self { width, height };
}
+ // Rounded to even sizes: yuv420 encoders reject odd dimensions.
+ let even = |size: usize| (((size as f64 * scale) / 2.).round() as usize * 2).max(2);
Self {
- width: (width as f64 * scale) as usize,
- height: (height as f64 * scale) as usize,
+ width: even(width),
+ height: even(height),
}
}
}
@@ -60,19 +59,53 @@ pub struct FFramesContext<'a, 'media: 'a> {
impl<'a, 'media: 'a> FFramesContext<'a, 'media> {
pub fn get_audio(&self, filename: impl AsRef<str>) -> Option<&'media AudioData<'media>> {
- self.media_source?.resolve_audio(filename.as_ref())
+ let filename = filename.as_ref();
+ let audio = self.media_source.and_then(|m| m.resolve_audio(filename));
+ if audio.is_none() {
+ crate::diagnostics::report_missing_media(
+ crate::diagnostics::MediaKind::Audio,
+ filename,
+ );
+ }
+ audio
}
pub fn get_subtitles(&self, filename: impl AsRef<str>) -> Option<&'media Subtitles<'media>> {
- self.media_source?.resolve_subtitles(filename.as_ref())
+ let filename = filename.as_ref();
+ let subtitles = self
+ .media_source
+ .and_then(|m| m.resolve_subtitles(filename));
+ if subtitles.is_none() {
+ crate::diagnostics::report_missing_media(
+ crate::diagnostics::MediaKind::Subtitles,
+ filename,
+ );
+ }
+ subtitles
}
pub fn get_image(&self, filename: impl AsRef<str>) -> Option<&'media ImageData<'media>> {
- self.media_source?.resolve_image(filename.as_ref())
+ let filename = filename.as_ref();
+ let image = self.media_source.and_then(|m| m.resolve_image(filename));
+ if image.is_none() {
+ crate::diagnostics::report_missing_media(
+ crate::diagnostics::MediaKind::Image,
+ filename,
+ );
+ }
+ image
}
pub fn get_video(&self, filename: impl AsRef<str>) -> Option<&'media VideoMedia> {
- self.media_source?.resolve_video(filename.as_ref())
+ let filename = filename.as_ref();
+ let video = self.media_source.and_then(|m| m.resolve_video(filename));
+ if video.is_none() {
+ crate::diagnostics::report_missing_media(
+ crate::diagnostics::MediaKind::Video,
+ filename,
+ );
+ }
+ video
}
pub fn render_scenes(&self, global_frame: &Frame) -> Svgr<'a> {
@@ -104,91 +137,6 @@ impl<'a, 'media: 'a> FFramesContext<'a, 'media> {
pointers_equal.then_some(info)
})
}
-
- /// This is internal method that is used by the renderer which mixes audio data and returns the final as fltp in a vector.
- #[allow(clippy::option_map_unit_fn)]
- pub fn get_mixed_audio_data_in_fltp(
- &self,
- audio_map: &ResolvedAudioMap<AudioTimelineSamples>,
- start_sample: AudioTimelineSamples,
- frame_size: usize,
- ) -> Vec<f32> {
- let mut audio_data = vec![0.0; frame_size];
- let encoder_rate = self.time_base.sample_rate;
-
- let media_source = if let Some(media_source) = self.media_source {
- media_source
- } else {
- return vec![];
- };
-
- audio_map.0.iter().for_each(|(f, sample_range)| {
- if sample_range.contains(&start_sample) {
- let start_of_this_frame_in_file =
- start_sample.as_usize() - sample_range.start.as_usize();
-
- let audio = media_source.resolve_audio(f);
-
- if let Some(audio) = audio {
- let source_rate = audio.sample_rate() as usize;
-
- if source_rate == 0 {
- return;
- }
-
- if source_rate == encoder_rate {
- // The last frame of a file is usually partial: mix what is left.
- let end = (start_of_this_frame_in_file + frame_size)
- .min(audio.duration_in_samples());
- if let Some(range) = audio.get_range(start_of_this_frame_in_file..end) {
- Self::mix_audio_samples(&mut audio_data, range);
- }
- } else {
- // The source runs at a different rate: linearly interpolate
- // the encoder's sample positions from the source samples.
- let ratio = source_rate as f64 / encoder_rate as f64;
- let source_start = (start_of_this_frame_in_file as f64 * ratio) as usize;
- let source_needed = ((frame_size as f64 * ratio).ceil() as usize) + 2;
- let source_len = audio.duration_in_samples();
- let source_end = (source_start + source_needed).min(source_len);
-
- if let Some(range) = audio.get_range(source_start..source_end) {
- let source_at = |index: usize| range.get(index).copied().unwrap_or(0.0);
- let resampled: Vec<f32> = (0..frame_size)
- .map(|i| {
- // Positions are computed from the file start so
- // consecutive encoder frames stay phase aligned.
- let exact = (start_of_this_frame_in_file + i) as f64 * ratio;
- let index = exact as usize - source_start;
- let frac = (exact - exact.floor()) as f32;
- source_at(index) * (1.0 - frac) + source_at(index + 1) * frac
- })
- .collect();
- Self::mix_audio_samples(&mut audio_data, &resampled);
- }
- }
- }
- }
- });
-
- audio_data
- }
-
- /// Mixes `range` into `audio_data` so that overlapping tracks stay within
- /// `[-1, 1]` without hard clipping: `a + b - a*b` when both samples have
- /// the same sign (mirrored for negative values), a plain sum otherwise.
- #[inline]
- fn mix_audio_samples(audio_data: &mut [f32], range: &[f32]) {
- for (mixed, sample) in audio_data.iter_mut().zip(range) {
- let a = *mixed;
- let b = *sample;
- *mixed = if a * b > 0.0 {
- a + b - a * b * a.signum()
- } else {
- a + b
- };
- }
- }
}
/// A signal that can be used to abort the rendering process from the other thread to stop the
diff --git a/fframes/src/lib.rs b/fframes/src/lib.rs
index 2c80418b..e3c3f582 100644
--- a/fframes/src/lib.rs
+++ b/fframes/src/lib.rs
@@ -1,5 +1,7 @@
+mod audio_analysis;
mod audio_data;
mod audio_map;
+mod audio_mix;
mod audio_window_functions;
mod color;
mod duration;
@@ -12,6 +14,7 @@ mod scenes;
mod shader;
mod svgr;
mod text;
+mod time_spec;
mod video;
#[cfg(not(target_arch = "wasm32"))]
@@ -21,6 +24,7 @@ pub use renderer::*;
// Methods that we are not pub use ::* should be declared here:
pub mod animation;
+pub mod diagnostics;
pub mod error;
pub mod log;
@@ -29,8 +33,10 @@ mod tests;
mod transform;
mod video_data;
+pub use audio_analysis::*;
pub use audio_data::*;
pub use audio_map::*;
+pub use audio_mix::*;
pub use audio_window_functions::*;
pub use color::*;
pub use duration::*;
@@ -44,6 +50,7 @@ pub use shader::*;
pub use svgr::*;
pub use svgr_macro::*;
pub use text::*;
+pub use time_spec::*;
pub use transform::*;
pub use video::*;
pub use video_data::*;
diff --git a/fframes/src/named_range.rs b/fframes/src/named_range.rs
index f8840430..7b3b82d5 100644
--- a/fframes/src/named_range.rs
+++ b/fframes/src/named_range.rs
@@ -22,10 +22,10 @@ impl Into<Vec<NamedRange>> for ResolvedAudioMap<AudioTimelineFrames> {
fn into(self) -> Vec<NamedRange> {
self.0
.into_iter()
- .map(|(name, range)| NamedRange {
- name,
- start: range.start.as_usize(),
- end: range.end.as_usize(),
+ .map(|track| NamedRange {
+ name: track.file,
+ start: track.range.start.as_usize(),
+ end: track.range.end.as_usize(),
})
.collect::<Vec<_>>()
}
diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rs
new file mode 100644
index 00000000..4728e5ee
--- /dev/null
+++ b/fframes/src/renderer/cli.rs
@@ -0,0 +1,1423 @@
+//! A ready-made command line for video binaries (feature `cli`). One call gives every video
+//! the same tools for rendering and for checking the result without watching it:
+//!
+//! ```ignore
+//! fn main() -> std::process::ExitCode {
+//! let media = MyMedia::prepare().unwrap();
+//! let video = MyVideo { media: &media };
+//! fframes::cli::new(&video, RenderOptions { media: Some(&media), ..Default::default() }).run()
+//! }
+//! ```
+//!
+//! Everything else is optional: `.backend(..)` renders with another backend (the Skia renderer;
+//! previews then use it too), `.preview(fframes_native_player::cli_preview)` adds the real-time
+//! window, `.default_output("out.webm")` changes the file `render` writes. Flags of your own go
+//! 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,
+ fframes_logger::FFramesLoggerVariant, sheet, snapshot,
+};
+use crate::diagnostics::Severity;
+use crate::{AudioMixer, AudioTimelineSamples, AudioTimelineUnit, RenderOptions, Video};
+use clap::{Args, Parser, Subcommand, ValueEnum};
+use serde::Serialize;
+use std::io::IsTerminal;
+use std::path::{Path, PathBuf};
+use std::process::ExitCode;
+use std::time::Instant;
+
+pub use clap;
+
+const TIME_SPECS: &str = "\
+TIME SPECS (for --at, ranges and positional times):
+ 120, 120f frame 120 3.2s, 500ms, 1:05.5 a timestamp
+ 50% half of the video start, end first / last frame
+ Intro first frame of a scene (case-insensitive) #3 scene index 3
+ Intro[1] second scene of type Intro
+ [email protected] 1.2s into the scene (also @12, @50%, @end)
+RANGES: a..b (end exclusive), a.., ..b, all, or a scene name for the whole scene.
+Run `timeline` to list scenes. Add --json to any command for machine-readable output.";
+
+/// No application specific flags.
+#[derive(Debug, Clone, Default, Args)]
+pub struct NoArgs {}
+
+#[derive(Debug, Parser)]
+#[command(about = "Render and inspect this fframes video", after_long_help = TIME_SPECS, after_help = TIME_SPECS)]
+pub struct Cli<A: Args = NoArgs> {
+ #[command(flatten)]
+ pub app: A,
+
+ #[command(subcommand)]
+ pub command: Option<Command>,
+
+ /// Print one JSON document to stdout; progress and warnings go to stderr.
+ #[arg(long, global = true)]
+ pub json: bool,
+
+ /// Output resolution factor, e.g. 0.5 for half resolution.
+ #[arg(long, global = true)]
+ pub scale: Option<f64>,
+}
+
+impl<A: Args> Cli<A> {
+ pub fn parse() -> Self {
+ <Self as Parser>::parse()
+ }
+}
+
+/// Parses the command line with application specific flags `A` (available as `.app`). Needed
+/// only when the video is built from those flags; pass the result to `Runner::args`.
+pub fn parse<A: Args>() -> Cli<A> {
+ Cli::<A>::parse()
+}
+
+#[derive(Debug, Clone, Subcommand)]
+pub enum Command {
+ /// Render the video, or a range of it, to a file (default command).
+ Render(RenderArgs),
+ /// Render single frames to PNG and report problems found in them.
+ Frame(FrameArgs),
+ /// A labelled contact sheet of evenly spaced frames: one image to review motion.
+ Strip(StripArgs),
+ /// Blend several frames into one image (later frames stronger) to see a movement's path.
+ Onion(OnionArgs),
+ /// Print a frame as SVG after conversion (text laid out, styles resolved).
+ Svg(SvgArgs),
+ /// Scenes, duration and audio tracks.
+ 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),
+ /// Play the video in real time in a native GPU window (needs `fframes_native_player`).
+ Preview(PreviewArgs),
+}
+
+#[derive(Debug, Clone, Args)]
+pub struct PreviewArgs {
+ /// Where to start, e.g. `Intro`, `12s`.
+ #[arg(default_value = "start")]
+ pub at: String,
+ /// Open paused instead of playing.
+ #[arg(long)]
+ pub paused: bool,
+ /// Stop at the end instead of looping.
+ #[arg(long)]
+ pub no_loop: bool,
+ /// Do not play the audio.
+ #[arg(long)]
+ pub mute: bool,
+ /// Skia backend of the window: auto, metal, vulkan or cpu.
+ #[arg(long, default_value = "auto")]
+ pub backend: String,
+}
+
+#[derive(Debug, Clone, Args, Default)]
+pub struct RenderArgs {
+ /// Only render this range, e.g. `Intro`, `10s..20s`.
+ pub range: Option<String>,
+ /// Output file, `out.mp4` unless the video sets another default.
+ #[arg(short, long)]
+ pub output: Option<PathBuf>,
+ /// Fast low quality preview: half resolution (unless --scale) and fastest encoder preset.
+ #[arg(long)]
+ pub draft: bool,
+}
+
+#[derive(Debug, Clone, Args)]
+pub struct FrameArgs {
+ /// Frames to render (comma or space separated time specs).
+ #[arg(required = true, value_delimiter = ',', num_args = 1..)]
+ pub at: Vec<String>,
+ #[arg(short, long, default_value = "frames")]
+ pub output: PathBuf,
+ /// Also write the converted SVG next to every PNG.
+ #[arg(long)]
+ pub svg: bool,
+}
+
+#[derive(Debug, Clone, Args)]
+pub struct StripArgs {
+ /// Range to sample.
+ #[arg(default_value = "all")]
+ pub range: String,
+ /// Number of frames.
+ #[arg(short = 'n', long, default_value_t = 12)]
+ pub count: usize,
+ #[arg(long, default_value_t = 4)]
+ pub columns: usize,
+ /// Width of one frame in pixels.
+ #[arg(long, default_value_t = 480)]
+ pub width: u32,
+ #[arg(short, long, default_value = "strip.png")]
+ pub output: PathBuf,
+}
+
+#[derive(Debug, Clone, Args)]
+pub struct OnionArgs {
+ /// Range to sample.
+ pub range: String,
+ #[arg(short = 'n', long, default_value_t = 6)]
+ pub count: usize,
+ #[arg(short, long, default_value = "onion.png")]
+ pub output: PathBuf,
+}
+
+#[derive(Debug, Clone, Args)]
+pub struct SvgArgs {
+ pub at: String,
+ /// Write to a file instead of stdout.
+ #[arg(short, long)]
+ pub output: Option<PathBuf>,
+}
+
+#[derive(Debug, Clone, Copy, ValueEnum)]
+pub enum FailOn {
+ Error,
+ Warning,
+ Never,
+}
+
+#[derive(Debug, Clone, Args)]
+pub struct InspectArgs {
+ #[arg(default_value = "all")]
+ pub range: String,
+ /// Distance between checked frames (every scene's first and last frame are always checked).
+ #[arg(long, default_value = "0.25s")]
+ pub every: String,
+ /// Check every single frame.
+ #[arg(long)]
+ pub all_frames: bool,
+ /// Report frames entirely off canvas and other informational findings too.
+ #[arg(long)]
+ pub info: bool,
+ /// Exit with code 2 when a finding of this severity is found.
+ #[arg(long, value_enum, default_value = "error")]
+ pub fail_on: FailOn,
+}
+
+#[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.
+ Render {
+ range: Option<String>,
+ #[arg(short, long, default_value = "audio.wav")]
+ output: PathBuf,
+ /// 32-bit float instead of 16-bit PCM.
+ #[arg(long)]
+ float: bool,
+ },
+ /// Loudness (LUFS), true peak, clipping, silence and loudness per scene.
+ Analyze {
+ range: Option<String>,
+ /// Also draw the waveform with loudness, scenes and cues to a PNG.
+ #[arg(long)]
+ waveform: Option<PathBuf>,
+ },
+ /// Which tracks play at the given times, where in the file and how loud.
+ At {
+ #[arg(required = true, value_delimiter = ',', num_args = 1..)]
+ at: Vec<String>,
+ },
+}
+
+type CliResult<T = ExitCode> = Result<T, String>;
+
+fn err(e: impl std::fmt::Display) -> String {
+ e.to_string()
+}
+
+/// Opens the real-time player for the `preview` command, see `Runner::preview`.
+type Player<'r, 'a, 'media, V> = Box<
+ dyn FnOnce(&'a V, &RenderOptions<'a, 'media>, &super::PreviewRequest) -> Result<(), String>
+ + 'r,
+>;
+
+/// The command line of one video, created with `cli::new`.
+pub struct Runner<'r, 'a, 'media, V, B = crate::cpu::CpuRenderingBackend, A: Args = NoArgs> {
+ video: &'a V,
+ options: RenderOptions<'a, 'media>,
+ backend: B,
+ args: Option<Cli<A>>,
+ player: Option<Player<'r, 'a, 'media, V>>,
+ default_output: PathBuf,
+}
+
+/// The command line for `video`: render, frame, strip, inspect, audio, ... Call `.run()`.
+pub fn new<'a, 'media: 'a, V: Video + Send + Sync>(
+ video: &'a V,
+ options: RenderOptions<'a, 'media>,
+) -> Runner<'static, 'a, 'media, V> {
+ Runner {
+ video,
+ options,
+ backend: crate::cpu::CpuRenderingBackend::default(),
+ args: None,
+ player: None,
+ default_output: PathBuf::from("out.mp4"),
+ }
+}
+
+impl<'r, 'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend, A: Args>
+ Runner<'r, 'a, 'media, V, B, A>
+{
+ /// Renders with another backend, e.g. `SkiaFFramesRenderer`. Frame previews use the
+ /// backend's own renderer, so they look like the rendered video.
+ pub fn backend<B2: FFramesRenderBackend>(
+ self,
+ backend: B2,
+ ) -> Runner<'r, 'a, 'media, V, B2, A> {
+ Runner {
+ video: self.video,
+ options: self.options,
+ backend,
+ args: self.args,
+ player: self.player,
+ default_output: self.default_output,
+ }
+ }
+
+ /// Uses already parsed arguments with application flags (see `cli::parse`).
+ pub fn args<A2: Args>(self, args: Cli<A2>) -> Runner<'r, 'a, 'media, V, B, A2> {
+ Runner {
+ video: self.video,
+ options: self.options,
+ backend: self.backend,
+ args: Some(args),
+ player: self.player,
+ default_output: self.default_output,
+ }
+ }
+
+ /// Enables the `preview` command, usually with `fframes_native_player::cli_preview`.
+ pub fn preview<'r2>(
+ self,
+ play: impl FnOnce(
+ &'a V,
+ &RenderOptions<'a, 'media>,
+ &super::PreviewRequest,
+ ) -> Result<(), String>
+ + 'r2,
+ ) -> Runner<'r2, 'a, 'media, V, B, A> {
+ Runner {
+ video: self.video,
+ options: self.options,
+ backend: self.backend,
+ args: self.args,
+ player: Some(Box::new(play)),
+ default_output: self.default_output,
+ }
+ }
+
+ /// The file `render` writes without `-o`, `out.mp4` by default.
+ pub fn default_output(mut self, path: impl Into<PathBuf>) -> Self {
+ self.default_output = path.into();
+ self
+ }
+
+ /// Parses the command line (unless `args` was given) and runs the command.
+ pub fn run(self) -> ExitCode {
+ let Runner {
+ video,
+ mut options,
+ backend,
+ args,
+ player,
+ default_output,
+ } = self;
+ let cli = args.unwrap_or_else(Cli::<A>::parse);
+
+ let json = cli.json;
+ if let Some(scale) = cli.scale {
+ options.scale_resolution = scale;
+ }
+ if json {
+ options.logger = FFramesLoggerVariant::Json;
+ } else if !std::io::stderr().is_terminal() {
+ options.logger = FFramesLoggerVariant::Lines;
+ }
+ crate::diagnostics::install_log_capture();
+
+ let command = cli
+ .command
+ .clone()
+ .unwrap_or(Command::Render(RenderArgs::default()));
+ let result = match command {
+ Command::Render(mut args) => {
+ args.output = args.output.or(Some(default_output));
+ render(json, cli.scale, video, options, args, backend)
+ }
+ command => {
+ let mut frame_renderer = backend
+ .frame_renderer()
+ .unwrap_or_else(|| Box::new(CpuFrameRenderer::default()));
+ let frame_renderer = frame_renderer.as_mut();
+ Previewer::new(video, &options)
+ .map_err(err)
+ .and_then(|mut previewer| match command {
+ Command::Frame(args) => frame(json, &mut previewer, frame_renderer, args),
+ Command::Strip(args) => strip(json, &mut previewer, frame_renderer, args),
+ Command::Onion(args) => {
+ onion(json, &mut previewer, frame_renderer, cli.scale, args)
+ }
+ Command::Svg(args) => svg(json, &mut previewer, args),
+ Command::Timeline => timeline(json, &previewer),
+ Command::Inspect(args) => inspect(json, &mut previewer, 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 {
+ return Err("this binary has no real-time player: add the \
+ `fframes_native_player` crate and \
+ `.preview(fframes_native_player::cli_preview)`. Without a \
+ window use `strip`, `frame` or `render --draft`."
+ .to_owned());
+ };
+ let request = super::PreviewRequest {
+ start_frame: previewer
+ .timeline()
+ .resolve_frame(&args.at)
+ .map_err(err)?,
+ autoplay: !args.paused,
+ looping: !args.no_loop,
+ audio: !args.mute,
+ backend: args.backend,
+ };
+ let options = previewer.options().clone();
+ // Fonts and caches of the previewer are not needed by the player.
+ drop(previewer);
+ play(video, &options, &request).map(|()| ExitCode::SUCCESS)
+ }
+ Command::Render(_) => unreachable!(),
+ })
+ }
+ };
+
+ match result {
+ Ok(code) => code,
+ Err(message) => {
+ if json {
+ println!("{}", serde_json::json!({ "error": message }));
+ } else {
+ eprintln!("error: {message}");
+ }
+ ExitCode::FAILURE
+ }
+ }
+ }
+}
+
+fn print<T: Serialize>(json: bool, value: &T, text: impl FnOnce() -> String) {
+ if json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(value)
+ .unwrap_or_else(|e| format!("{{\"error\":\"{e}\"}}"))
+ );
+ } else {
+ let text = text();
+ if !text.is_empty() {
+ println!("{text}");
+ }
+ }
+}
+
+fn scenes_label(scenes: &[String]) -> String {
+ if scenes.is_empty() {
+ String::new()
+ } else {
+ format!(" [{}]", scenes.join(" + "))
+ }
+}
+
+/// Warnings and errors of a frame; informational findings only as a count (they are in
+/// the --json output).
+fn diagnostics_text(report: &FrameReport, indent: &str) -> String {
+ let mut text: String = report
+ .diagnostics
+ .iter()
+ .filter(|d| d.severity > Severity::Info)
+ .map(|d| format!("{indent}{:?}: {}\n", d.severity, d.message).to_lowercase_first())
+ .collect();
+ let info = report
+ .diagnostics
+ .iter()
+ .filter(|d| d.severity == Severity::Info)
+ .count();
+ if info > 0 {
+ text.push_str(&format!(
+ "{indent}({info} info findings, e.g. text outside the canvas, see --json)\n"
+ ));
+ }
+ text
+}
+
+trait LowercaseFirst {
+ fn to_lowercase_first(self) -> String;
+}
+
+impl LowercaseFirst for String {
+ fn to_lowercase_first(self) -> String {
+ let mut chars = self.chars();
+ let leading: String = chars.by_ref().take_while(|c| c.is_whitespace()).collect();
+ let rest: String = self.chars().skip(leading.len()).collect();
+ let mut rest_chars = rest.chars();
+ match rest_chars.next() {
+ Some(first) => format!("{leading}{}{}", first.to_lowercase(), rest_chars.as_str()),
+ None => self,
+ }
+ }
+}
+
+fn resolve_frames<'a, 'm: 'a, V: Video>(
+ previewer: &Previewer<'a, 'm, V>,
+ specs: &[String],
+) -> CliResult<Vec<(String, usize)>> {
+ specs
+ .iter()
+ .flat_map(|spec| spec.split_whitespace())
+ .map(|spec| {
+ previewer
+ .timeline()
+ .resolve_frame(spec)
+ .map(|frame| (spec.to_owned(), frame))
+ .map_err(err)
+ })
+ .collect()
+}
+
+/// `count` frames evenly spread over a range, first and last included.
+fn spread(range: std::ops::Range<usize>, count: usize) -> Vec<usize> {
+ let count = count.clamp(1, range.len());
+ if count == 1 {
+ return vec![range.start];
+ }
+ let last = range.end - 1;
+ (0..count)
+ .map(|i| {
+ range.start
+ + ((last - range.start) as f64 * i as f64 / (count - 1) as f64).round() as usize
+ })
+ .collect()
+}
+
+fn ensure_parent(path: &Path) -> CliResult<()> {
+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
+ std::fs::create_dir_all(parent).map_err(err)?;
+ }
+ Ok(())
+}
+
+#[derive(Serialize)]
+struct RenderResult {
+ output: PathBuf,
+ frames: std::ops::Range<usize>,
+ start_seconds: f32,
+ end_seconds: f32,
+ width: usize,
+ height: usize,
+ elapsed_seconds: f32,
+}
+
+fn render<'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend>(
+ json: bool,
+ scale: Option<f64>,
+ video: &'a V,
+ mut options: RenderOptions<'a, 'media>,
+ args: RenderArgs,
+ backend: B,
+) -> CliResult {
+ let started = Instant::now();
+ let previewer = Previewer::new(video, &options).map_err(err)?;
+ let timeline = previewer.timeline().clone();
+ drop(previewer);
+
+ let range = match &args.range {
+ Some(spec) => timeline.resolve_range(spec).map_err(err)?,
+ None => timeline.full_range(),
+ };
+ options.frame_range = Some(range.clone());
+
+ if args.draft {
+ if scale.is_none() {
+ options.scale_resolution = 0.5;
+ }
+ let encoder = options.video_encoder_options.preferred_encoder;
+ if matches!(encoder, None | Some("libx264") | Some("libx265")) {
+ options.video_encoder_options.codec_params =
+ Some(&[("preset", "ultrafast"), ("crf", "30")]);
+ }
+ }
+
+ let output = args.output.unwrap_or_else(|| PathBuf::from("out.mp4"));
+ ensure_parent(&output)?;
+ super::render(&output, video, backend, &options).map_err(err)?;
+
+ let size = crate::VideoSize::new_scaled(V::WIDTH, V::HEIGHT, options.scale_resolution);
+ let result = RenderResult {
+ output,
+ start_seconds: timeline.frame_to_seconds(range.start),
+ end_seconds: timeline.frame_to_seconds(range.end),
+ frames: range,
+ width: size.width,
+ height: size.height,
+ elapsed_seconds: started.elapsed().as_secs_f32(),
+ };
+ print(json, &result, || {
+ format!(
+ "{} frames {}..{} ({:.2}s..{:.2}s) {}x{} in {:.1}s",
+ result.output.display(),
+ result.frames.start,
+ result.frames.end,
+ result.start_seconds,
+ result.end_seconds,
+ result.width,
+ result.height,
+ result.elapsed_seconds
+ )
+ });
+ Ok(ExitCode::SUCCESS)
+}
+
+#[derive(Serialize)]
+struct FrameResult {
+ spec: String,
+ path: PathBuf,
+ svg: Option<PathBuf>,
+ #[serde(flatten)]
+ report: FrameReport,
+}
+
+fn frame<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &mut Previewer<'a, 'm, V>,
+ renderer: &mut dyn FrameRenderer,
+ args: FrameArgs,
+) -> CliResult {
+ std::fs::create_dir_all(&args.output).map_err(err)?;
+ 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 name = snapshot::snapshot_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)?;
+ Some(svg_path)
+ } else {
+ None
+ };
+ results.push(FrameResult {
+ spec,
+ path,
+ svg,
+ report,
+ });
+ }
+
+ print(json, &results, || {
+ results
+ .iter()
+ .map(|r| {
+ format!(
+ "{} frame {} {:.2}s{} -> {}\n{}",
+ r.spec,
+ r.report.frame,
+ r.report.seconds,
+ scenes_label(&r.report.scenes),
+ r.path.display(),
+ diagnostics_text(&r.report, " ")
+ )
+ })
+ .collect::<String>()
+ .trim_end()
+ .to_owned()
+ });
+ Ok(ExitCode::SUCCESS)
+}
+
+#[derive(Serialize)]
+struct SheetResult {
+ output: PathBuf,
+ frames: Vec<usize>,
+ diagnostics: Vec<FrameReport>,
+}
+
+fn render_cells<'a, 'm: 'a, V: Video>(
+ previewer: &mut Previewer<'a, 'm, V>,
+ renderer: &mut dyn FrameRenderer,
+ frames: &[usize],
+) -> 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)?;
+ 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);
+ }
+ }
+ Ok((cells, reports))
+}
+
+fn sheet_text(result: &SheetResult) -> String {
+ let mut text = format!(
+ "{} ({} frames: {})",
+ result.output.display(),
+ result.frames.len(),
+ result
+ .frames
+ .iter()
+ .map(|f| f.to_string())
+ .collect::<Vec<_>>()
+ .join(", ")
+ );
+ for report in &result.diagnostics {
+ text.push_str(&format!(
+ "\nframe {} {:.2}s:\n",
+ report.frame, report.seconds
+ ));
+ text.push_str(diagnostics_text(report, " ").trim_end());
+ }
+ text
+}
+
+fn strip<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &mut Previewer<'a, 'm, V>,
+ 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(args.width as f64 / V::WIDTH as f64);
+ let (cells, diagnostics) = render_cells(previewer, renderer, &frames)?;
+ let image = sheet::contact_sheet(
+ &cells,
+ args.columns,
+ previewer.font_db(),
+ previewer.options().default_font,
+ )
+ .map_err(err)?;
+ ensure_parent(&args.output)?;
+ image.save_png(&args.output).map_err(err)?;
+
+ let result = SheetResult {
+ output: args.output,
+ frames,
+ diagnostics,
+ };
+ print(json, &result, || sheet_text(&result));
+ Ok(ExitCode::SUCCESS)
+}
+
+fn onion<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &mut Previewer<'a, 'm, V>,
+ renderer: &mut dyn FrameRenderer,
+ scale: Option<f64>,
+ args: OnionArgs,
+) -> CliResult {
+ let range = previewer
+ .timeline()
+ .resolve_range(&args.range)
+ .map_err(err)?;
+ let frames = spread(range, args.count);
+ if scale.is_none() {
+ previewer.set_scale(0.5);
+ }
+ let (cells, diagnostics) = render_cells(previewer, renderer, &frames)?;
+ 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)?;
+ image.save_png(&args.output).map_err(err)?;
+
+ let result = SheetResult {
+ output: args.output,
+ frames,
+ diagnostics,
+ };
+ print(json, &result, || sheet_text(&result));
+ Ok(ExitCode::SUCCESS)
+}
+
+fn svg<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &mut Previewer<'a, 'm, V>,
+ args: SvgArgs,
+) -> CliResult {
+ let frame = previewer.timeline().resolve_frame(&args.at).map_err(err)?;
+ let svg = previewer.svg(frame).map_err(err)?;
+ match &args.output {
+ Some(path) => {
+ ensure_parent(path)?;
+ std::fs::write(path, &svg).map_err(err)?;
+ print(
+ json,
+ &serde_json::json!({ "frame": frame, "output": path }),
+ || path.display().to_string(),
+ );
+ }
+ None => print(
+ json,
+ &serde_json::json!({ "frame": frame, "svg": svg }),
+ || svg.clone(),
+ ),
+ }
+ Ok(ExitCode::SUCCESS)
+}
+
+fn timeline<'a, 'm: 'a, V: Video>(json: bool, previewer: &Previewer<'a, 'm, V>) -> CliResult {
+ let report = previewer.timeline_report();
+ print(json, &report, || {
+ let mut text = format!(
+ "{}x{} @ {} fps, {} frames ({:.2}s)\n",
+ report.width,
+ report.height,
+ report.fps,
+ report.duration_frames,
+ report.duration_seconds
+ );
+ if report.scenes.is_empty() {
+ text.push_str("no scenes\n");
+ }
+ for scene in &report.scenes {
+ text.push_str(&format!(
+ "#{:<3} {:<28} frames {:>14} {:>18}\n",
+ scene.index,
+ scene.name,
+ format!("{}..{}", scene.start_frame, scene.end_frame),
+ format!("{:.2}s..{:.2}s", scene.start_seconds, scene.end_seconds)
+ ));
+ }
+ for track in &report.audio {
+ let mix = &track.mix;
+ let mut extra = Vec::new();
+ if mix.gain_db != 0. {
+ extra.push(format!("{:+.1} dB", mix.gain_db));
+ }
+ if mix.pan != 0. {
+ extra.push(format!("pan {:+.2}", mix.pan));
+ }
+ if mix.fade_in > 0. || mix.fade_out > 0. {
+ extra.push(format!("fades {:.2}s/{:.2}s", mix.fade_in, mix.fade_out));
+ }
+ if mix.offset > 0. {
+ extra.push(format!("from {:.2}s of the file", mix.offset));
+ }
+ if mix.voice {
+ extra.push("voice".into());
+ }
+ if mix.duck.is_some() {
+ extra.push("ducked".into());
+ }
+ text.push_str(&format!(
+ "audio {:<28} {:>8.3}s..{:.3}s {}\n",
+ track.file,
+ track.start_seconds,
+ track.end_seconds,
+ extra.join(", ")
+ ));
+ }
+ text.trim_end().to_owned()
+ });
+ Ok(ExitCode::SUCCESS)
+}
+
+#[derive(Serialize)]
+struct Finding {
+ severity: Severity,
+ #[serde(skip)]
+ key: String,
+ /// The message as seen in the first frame.
+ message: String,
+ first_frame: usize,
+ last_frame: usize,
+ first_seconds: f32,
+ last_seconds: f32,
+ /// Number of checked frames it was found in.
+ frames: usize,
+ scenes: Vec<String>,
+}
+
+#[derive(Serialize)]
+struct InspectResult {
+ checked_frames: usize,
+ findings: Vec<Finding>,
+}
+
+fn inspect<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &mut Previewer<'a, 'm, V>,
+ args: InspectArgs,
+) -> CliResult {
+ let timeline = previewer.timeline().clone();
+ let range = timeline.resolve_range(&args.range).map_err(err)?;
+ let step = if args.all_frames {
+ 1
+ } else {
+ // `every` is a duration: resolve it as an offset from the start.
+ timeline
+ .resolve_range(&format!("0..{}", args.every))
+ .map_err(err)?
+ .end
+ .max(1)
+ };
+
+ let mut frames: Vec<usize> = range.clone().step_by(step).collect();
+ for scene in &timeline.scenes {
+ for frame in [scene.frames.start, scene.frames.end.saturating_sub(1)] {
+ if range.contains(&frame) {
+ frames.push(frame);
+ }
+ }
+ }
+ frames.push(range.end - 1);
+ frames.sort_unstable();
+ 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());
+ }
+ }
+ }
+ 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(),
+ }),
+ }
+ }
+ }
+ findings.sort_by(|a, b| {
+ b.severity
+ .cmp(&a.severity)
+ .then(a.first_frame.cmp(&b.first_frame))
+ });
+
+ let failed = findings.iter().any(|f| match args.fail_on {
+ FailOn::Error => f.severity >= Severity::Error,
+ FailOn::Warning => f.severity >= Severity::Warning,
+ FailOn::Never => false,
+ });
+
+ let result = InspectResult {
+ checked_frames: frames.len(),
+ findings,
+ };
+ print(json, &result, || {
+ let mut text = format!("checked {} frames: ", result.checked_frames);
+ if result.findings.is_empty() {
+ text.push_str("no problems found");
+ } else {
+ text.push_str(&format!("{} findings", result.findings.len()));
+ }
+ for f in &result.findings {
+ text.push_str(&format!(
+ "\n{:?} {:.2}s..{:.2}s (frames {}..{}, seen in {}){}: {}",
+ f.severity,
+ f.first_seconds,
+ f.last_seconds,
+ f.first_frame,
+ f.last_frame,
+ f.frames,
+ scenes_label(&f.scenes),
+ f.message
+ ));
+ }
+ text
+ });
+
+ Ok(if failed {
+ ExitCode::from(2)
+ } else {
+ ExitCode::SUCCESS
+ })
+}
+
+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 {
+ line.push_str(&format!(
+ ": {:.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
+ })
+}
+
+fn mixer_for<'a, 'm: 'a, V: Video>(
+ previewer: &Previewer<'a, 'm, V>,
+ range: std::ops::Range<usize>,
+) -> (AudioMixer<'m>, std::ops::Range<usize>) {
+ let options = previewer.options();
+ let time_base = crate::TimeBase {
+ fps: V::FPS,
+ sample_rate: options.audio_encoder_options.sample_rate,
+ };
+ let samples = AudioTimelineSamples::from_frames(range.start, &time_base).as_usize()
+ ..AudioTimelineSamples::from_frames(range.end, &time_base).as_usize();
+ let total =
+ AudioTimelineSamples::from_frames(previewer.timeline().duration_in_frames, &time_base)
+ .as_usize();
+ let mixer = AudioMixer::new(
+ previewer.resolved_timeline().audio_map.as_ref(),
+ previewer.media(),
+ time_base.sample_rate,
+ samples.clone(),
+ total,
+ options.audio_mix,
+ );
+ (mixer, samples)
+}
+
+fn audio<'a, 'm: 'a, V: Video>(
+ json: bool,
+ previewer: &Previewer<'a, 'm, V>,
+ command: AudioCommand,
+) -> CliResult {
+ let timeline = previewer.timeline().clone();
+ let resolve = |range: &Option<String>| match range {
+ Some(spec) => timeline.resolve_range(spec).map_err(err),
+ None => Ok(timeline.full_range()),
+ };
+ let sample_rate = previewer.options().audio_encoder_options.sample_rate;
+
+ match command {
+ AudioCommand::Render {
+ range,
+ output,
+ float,
+ } => {
+ let (mut mixer, samples) = mixer_for(previewer, resolve(&range)?);
+ let (left, right) = mixer.render_all();
+ ensure_parent(&output)?;
+ std::fs::write(
+ &output,
+ crate::encode_wav(&left, &right, sample_rate, float),
+ )
+ .map_err(err)?;
+ print(
+ json,
+ &serde_json::json!({
+ "output": output,
+ "start_seconds": samples.start as f64 / sample_rate as f64,
+ "end_seconds": samples.end as f64 / sample_rate as f64,
+ "missing_files": mixer.missing_files(),
+ }),
+ || {
+ let mut text = format!(
+ "{} {:.2}s..{:.2}s",
+ output.display(),
+ samples.start as f64 / sample_rate as f64,
+ samples.end as f64 / sample_rate as f64
+ );
+ for file in mixer.missing_files() {
+ text.push_str(&format!(
+ "\nwarning: audio \"{file}\" is not in the media provider"
+ ));
+ }
+ text
+ },
+ );
+ }
+ AudioCommand::Analyze { range, waveform } => {
+ let frames = resolve(&range)?;
+ let (mut mixer, samples) = mixer_for(previewer, frames.clone());
+ let (left, right) = mixer.render_all();
+ let to_samples = |frame: usize| {
+ ((frame as f64 / V::FPS as f64 * sample_rate as f64).round() as usize)
+ .clamp(samples.start, samples.end)
+ - samples.start
+ };
+ let sections: Vec<(String, std::ops::Range<usize>)> = timeline
+ .scenes
+ .iter()
+ .filter(|s| s.frames.start < frames.end && s.frames.end > frames.start)
+ .map(|s| {
+ (
+ s.name.clone(),
+ to_samples(s.frames.start)..to_samples(s.frames.end),
+ )
+ })
+ .collect();
+ let mut report = crate::analyze_audio(&left, &right, sample_rate, &sections);
+ let offset = samples.start as f64 / sample_rate as f64;
+ report.sections.iter_mut().for_each(|s| {
+ s.start_seconds += offset;
+ s.end_seconds += offset;
+ });
+ report.silent_ranges.iter_mut().for_each(|r| {
+ r[0] += offset;
+ r[1] += offset;
+ });
+
+ if let Some(path) = &waveform {
+ let cues: Vec<(String, f64)> = previewer
+ .timeline_report()
+ .audio
+ .into_iter()
+ .map(|t| (t.file, t.start_seconds - offset))
+ .collect();
+ let scenes: Vec<(String, f64)> = sections
+ .iter()
+ .map(|(name, range)| (name.clone(), range.start as f64 / sample_rate as f64))
+ .collect();
+ let image = waveform_image(
+ &left,
+ &right,
+ sample_rate,
+ offset,
+ &scenes,
+ &cues,
+ previewer,
+ )?;
+ ensure_parent(path)?;
+ image.save_png(path).map_err(err)?;
+ }
+
+ let missing = mixer.missing_files().to_vec();
+ print(
+ json,
+ &serde_json::json!({ "report": report, "waveform": waveform, "missing_files": missing }),
+ || audio_report_text(&report, waveform.as_deref(), &missing),
+ );
+ }
+ AudioCommand::At { at } => {
+ let (mixer, _) = mixer_for(previewer, timeline.full_range());
+ let mut results = Vec::new();
+ for (spec, frame) in resolve_frames(previewer, &at)? {
+ let sample = (frame as f64 / V::FPS as f64 * sample_rate as f64).round() as usize;
+ results.push(serde_json::json!({
+ "spec": spec,
+ "frame": frame,
+ "seconds": frame as f64 / V::FPS as f64,
+ "tracks": mixer.active_tracks_at(sample),
+ }));
+ }
+ print(json, &results, || {
+ results
+ .iter()
+ .map(|r| {
+ let mut text = format!(
+ "{} ({:.3}s):",
+ r["spec"].as_str().unwrap_or(""),
+ r["seconds"].as_f64().unwrap_or(0.)
+ );
+ let tracks = r["tracks"].as_array().cloned().unwrap_or_default();
+ if tracks.is_empty() {
+ text.push_str(" silence");
+ }
+ for t in tracks {
+ text.push_str(&format!(
+ "\n {} at {:.3}s of the file, {:.1} dB{}{}",
+ t["file"].as_str().unwrap_or(""),
+ t["file_seconds"].as_f64().unwrap_or(0.),
+ t["gain_db"].as_f64().unwrap_or(f64::NEG_INFINITY),
+ if t["voice"].as_bool() == Some(true) {
+ ", voice"
+ } else {
+ ""
+ },
+ match t["ducked_db"].as_f64() {
+ Some(d) if d < -0.05 => format!(", ducked {d:.1} dB"),
+ _ => String::new(),
+ }
+ ));
+ }
+ text
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ });
+ }
+ }
+ Ok(ExitCode::SUCCESS)
+}
+
+fn audio_report_text(
+ report: &crate::AudioReport,
+ waveform: Option<&Path>,
+ missing: &[String],
+) -> String {
+ let db =
+ |v: Option<f64>, unit: &str| v.map_or("silent".to_owned(), |v| format!("{v:.1} {unit}"));
+ let mut text = format!(
+ "integrated {}, range {}, max momentary {}, max short-term {}\n\
+ sample peak {}, true peak {}, clipped samples {}",
+ db(report.integrated_lufs, "LUFS"),
+ report
+ .loudness_range_lu
+ .map_or("-".to_owned(), |v| format!("{v:.1} LU")),
+ db(report.max_momentary_lufs, "LUFS"),
+ db(report.max_short_term_lufs, "LUFS"),
+ db(report.sample_peak_dbfs, "dBFS"),
+ db(report.true_peak_dbtp, "dBTP"),
+ report.clipped_samples
+ );
+ for range in &report.silent_ranges {
+ text.push_str(&format!("\nsilent {:.2}s..{:.2}s", range[0], range[1]));
+ }
+ for section in &report.sections {
+ text.push_str(&format!(
+ "\n{:<28} {:>18} {} / peak {}",
+ section.name,
+ format!("{:.2}s..{:.2}s", section.start_seconds, section.end_seconds),
+ db(section.integrated_lufs, "LUFS"),
+ db(section.true_peak_dbtp, "dBTP")
+ ));
+ }
+ for file in missing {
+ text.push_str(&format!(
+ "\nwarning: audio \"{file}\" is not in the media provider"
+ ));
+ }
+ if let Some(path) = waveform {
+ text.push_str(&format!("\nwaveform {}", path.display()));
+ }
+ text
+}
+
+/// Waveform (min/max per column), momentary loudness, scene starts and cue starts.
+fn waveform_image<'a, 'm: 'a, V: Video>(
+ left: &[f32],
+ right: &[f32],
+ sample_rate: usize,
+ offset_seconds: f64,
+ scenes: &[(String, f64)],
+ cues: &[(String, f64)],
+ previewer: &Previewer<'a, 'm, V>,
+) -> CliResult<RgbaFrame> {
+ let (width, height) = (1600usize, 420usize);
+ let (top, wave_h) = (28usize, 300usize);
+ let duration = left.len().max(1) as f64 / sample_rate as f64;
+ let x_of = |seconds: f64| seconds / duration * width as f64;
+ let per_column = (left.len() / width).max(1);
+
+ let mut wave = String::new();
+ for x in 0..width {
+ let from = (x * per_column).min(left.len());
+ let to = ((x + 1) * per_column).min(left.len());
+ let (mut lo, mut hi) = (0f32, 0f32);
+ for i in from..to {
+ let v = (left[i] + right[i]) * 0.5;
+ lo = lo.min(v);
+ hi = hi.max(v);
+ }
+ let mid = top as f32 + wave_h as f32 / 2.;
+ let scale = wave_h as f32 / 2.;
+ wave.push_str(&format!(
+ "M{x} {:.1}V{:.1}",
+ mid - hi * scale,
+ mid - lo * scale + 0.5
+ ));
+ }
+
+ let loudness = crate::LoudnessAnalysis::new(left, right, sample_rate).momentary();
+ let loudness_y = |lufs: f64| top as f64 + wave_h as f64 * (lufs.clamp(-60., 0.) / -60.);
+ let loudness_path: String = loudness
+ .iter()
+ .enumerate()
+ .map(|(i, lufs)| {
+ let x = x_of((i as f64 + 4.) * 0.1);
+ format!(
+ "{}{x:.1} {:.1}",
+ if i == 0 { "M" } else { "L" },
+ loudness_y(*lufs)
+ )
+ })
+ .collect();
+
+ let mut markers = String::new();
+ for (name, seconds) in scenes {
+ let x = x_of(*seconds);
+ markers.push_str(&format!(
+ r##"<path d="M{x:.1} {top}V{}" stroke="#a78bfa" stroke-width="1"/><text x="{:.1}" y="{}" font-size="13" fill="#c4b5fd">{}</text>"##,
+ top + wave_h,
+ x + 3.,
+ top - 8,
+ name.replace('&', "&amp;").replace('<', "&lt;")
+ ));
+ }
+ for (_, seconds) in cues.iter().filter(|(_, s)| *s >= 0. && *s <= duration) {
+ let x = x_of(*seconds);
+ markers.push_str(&format!(
+ r##"<path d="M{x:.1} {}V{}" stroke="#fbbf24" stroke-width="1.5"/>"##,
+ top + wave_h + 4,
+ top + wave_h + 16
+ ));
+ }
+ let tick = [1., 2., 5., 10., 15., 30., 60.]
+ .into_iter()
+ .find(|t| duration / t <= 16.)
+ .unwrap_or(120.);
+ let mut t = 0.;
+ while t <= duration {
+ markers.push_str(&format!(
+ r##"<text x="{:.1}" y="{}" font-size="12" fill="#a1a1aa">{:.0}s</text>"##,
+ x_of(t) + 2.,
+ height - 12,
+ t + offset_seconds
+ ));
+ t += tick;
+ }
+
+ let family = previewer.options().default_font;
+ let svg = format!(
+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" font-family="'{family}', sans-serif">
+<rect width="100%" height="100%" fill="#18181b"/>
+<path d="M0 {mid}H{width}" stroke="#3f3f46"/>
+<path d="{wave}" stroke="#38bdf8" stroke-width="1"/>
+<path d="{loudness_path}" stroke="#f472b6" stroke-width="1.5" fill="none"/>
+{markers}
+<text x="8" y="{legend}" font-size="12" fill="#a1a1aa">waveform (blue), momentary loudness -60..0 LUFS (pink), scenes (purple), audio cues (yellow)</text>
+</svg>"##,
+ mid = top + wave_h / 2,
+ legend = height - 30,
+ );
+
+ let tree =
+ crate::usvgr::Tree::from_str(&svg, &crate::usvgr::Options::default(), previewer.font_db())
+ .map_err(err)?;
+ CpuFrameRenderer::new(0)
+ .render_tree(&tree, crate::Color::BLACK, width as u32, height as u32)
+ .map_err(err)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn spread_includes_both_ends() {
+ assert_eq!(spread(0..101, 5), vec![0, 25, 50, 75, 100]);
+ assert_eq!(spread(10..11, 5), vec![10]);
+ assert_eq!(spread(0..3, 10), vec![0, 1, 2]);
+ }
+
+ #[test]
+ fn parses_commands() {
+ let cli =
+ Cli::<NoArgs>::try_parse_from(["video", "frame", "1s,Intro@50%", "--json"]).unwrap();
+ assert!(cli.json);
+ assert!(
+ matches!(cli.command, Some(Command::Frame(FrameArgs { ref at, .. })) if at.len() == 2)
+ );
+
+ let cli = Cli::<NoArgs>::try_parse_from(["video", "render", "Intro", "--draft"]).unwrap();
+ assert!(matches!(
+ cli.command,
+ Some(Command::Render(RenderArgs { draft: true, .. }))
+ ));
+
+ let cli = Cli::<NoArgs>::try_parse_from(["video"]).unwrap();
+ assert!(cli.command.is_none());
+
+ let cli = Cli::<NoArgs>::try_parse_from(["video", "preview", "Intro", "--paused"]).unwrap();
+ assert!(
+ matches!(cli.command, Some(Command::Preview(PreviewArgs { paused: true, ref at, .. })) if at == "Intro")
+ );
+
+ let cli =
+ Cli::<NoArgs>::try_parse_from(["video", "audio", "analyze", "--waveform", "w.png"])
+ .unwrap();
+ assert!(matches!(
+ cli.command,
+ Some(Command::Audio(AudioCommand::Analyze { .. }))
+ ));
+ }
+}
diff --git a/fframes/src/renderer/concatenator.rs b/fframes/src/renderer/concatenator.rs
index 494368c7..ecef3851 100644
--- a/fframes/src/renderer/concatenator.rs
+++ b/fframes/src/renderer/concatenator.rs
@@ -202,37 +202,93 @@ impl Encoder {
&self,
audio_map: Option<&ResolvedAudioMap<AudioTimelineSamples>>,
ctx: &FFramesContext,
+ frame_range: std::ops::Range<usize>,
+ mix_options: crate::AudioMixOptions,
logger: &Arc<dyn super::fframes_logger::FFramesLogger>,
) -> Result<(), RenderEncodingError> {
unsafe {
if let (Some(audio_map), Some(audio_stream)) = (audio_map, self.audio_stream.as_ref()) {
- let stream_duration_in_samples =
- AudioTimelineSamples::from_frames(ctx.duration_in_frames, &ctx.time_base);
+ // The encoder may run at another rate than requested (Opus is 48 kHz only);
+ // mix at the rate it actually encodes.
+ let output_time_base = crate::TimeBase {
+ fps: ctx.time_base.fps,
+ sample_rate: (*audio_stream.enc).sample_rate as usize,
+ };
+ let first_sample =
+ AudioTimelineSamples::from_frames(frame_range.start, &output_time_base)
+ .as_usize();
+ let end_sample =
+ AudioTimelineSamples::from_frames(frame_range.end, &output_time_base)
+ .as_usize();
+ let total_samples =
+ AudioTimelineSamples::from_frames(ctx.duration_in_frames, &output_time_base)
+ .as_usize();
+ let stream_samples = end_sample - first_sample;
+
+ let mut mixer = crate::AudioMixer::new_rescaled(
+ Some(audio_map),
+ ctx.time_base.sample_rate,
+ ctx.media_source,
+ output_time_base.sample_rate,
+ first_sample..end_sample,
+ total_samples,
+ mix_options,
+ );
+ for file in mixer.missing_files() {
+ logger.warn(&format!(
+ "audio \"{file}\" is in the audio map but not in the media provider"
+ ));
+ }
let mut audio_frame = EncoderFrame::new(audio_stream)?;
- let mut audio_frame_pts = 0usize;
- let frame_size = (*audio_stream.enc).frame_size as usize;
+ let capabilities = (*(*audio_stream.enc).codec).capabilities;
+ let variable_frame_size =
+ capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE as i32 != 0;
+ let small_last_frame =
+ variable_frame_size || capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME as i32 != 0;
+ // Variable frame size encoders (pcm) report 0, the frame buffer holds 10000.
+ let frame_size = match (*audio_stream.enc).frame_size as usize {
+ 0 => 4096,
+ size => size,
+ };
// Progress reporting must never abort the encoding itself.
- let _ = logger.init_audio_encoding(
- stream_duration_in_samples.as_usize().div_ceil(frame_size),
- );
+ let _ = logger.init_audio_encoding(stream_samples.div_ceil(frame_size));
- while audio_frame_pts < stream_duration_in_samples.as_usize() {
- let audio_data = ctx.get_mixed_audio_data_in_fltp(
- audio_map,
- AudioTimelineSamples::from_usize(audio_frame_pts),
- frame_size,
+ let mut left = vec![0.; frame_size];
+ let mut right = vec![0.; frame_size];
+ let mut audio_frame_pts = 0usize;
+ while audio_frame_pts < stream_samples {
+ let remaining = stream_samples - audio_frame_pts;
+ let samples = if small_last_frame {
+ remaining.min(frame_size)
+ } else {
+ frame_size
+ };
+
+ left.fill(0.);
+ right.fill(0.);
+ let mixed = remaining.min(samples);
+ mixer.render(
+ first_sample + audio_frame_pts,
+ &mut left[..mixed],
+ &mut right[..mixed],
);
- audio_frame.fill_from_audio_data(audio_frame_pts as i64, audio_data);
+ audio_frame.fill_from_stereo(
+ audio_frame_pts as i64,
+ &left[..samples],
+ &right[..samples],
+ )?;
self.send_frame(audio_stream, &audio_frame)?;
logger.log_audio_frame();
- audio_frame_pts += frame_size;
+ audio_frame_pts += samples;
}
self.flush_stream(audio_stream)?;
+ // The encoder holds back its last frames (AAC has a 1024 sample delay).
+ self.flush_stream(audio_stream)?;
logger.finish_audio_encoding();
}
@@ -414,7 +470,13 @@ pub unsafe fn concat_video_files_with_audio(
encoder.fill_streams_from_files(files)?;
if encoder.audio_stream.is_some() {
- encoder.fill_audio_stream(audio_map, ctx, logger)?;
+ encoder.fill_audio_stream(
+ audio_map,
+ ctx,
+ render_options.output_frame_range(ctx.duration_in_frames),
+ render_options.audio_mix,
+ logger,
+ )?;
}
Ok(())
diff --git a/fframes/src/renderer/cpu.rs b/fframes/src/renderer/cpu.rs
index 721ac9dc..c0050967 100644
--- a/fframes/src/renderer/cpu.rs
+++ b/fframes/src/renderer/cpu.rs
@@ -1,6 +1,6 @@
use super::{
- FrameScheduler, SegmentWriter, get_thread_count, render_backend::FFramesRenderBackend,
- renderer_error::RenderEncodingError,
+ FrameRenderer, FrameScheduler, SegmentWriter, get_thread_count,
+ render_backend::FFramesRenderBackend, renderer_error::RenderEncodingError,
};
use crate::{
AbortSignal, AudioTimelineSamples, Frame, RenderOptions, ResolvedRenderingTimeline, TextCache,
@@ -58,6 +58,10 @@ impl Default for CpuRenderingBackend {
}
impl FFramesRenderBackend for CpuRenderingBackend {
+ fn frame_renderer(&self) -> Option<Box<dyn FrameRenderer + '_>> {
+ Some(Box::new(super::CpuFrameRenderer::new(self.cache_capacity)))
+ }
+
fn render<'a, 'media: 'a, TVideo: Video + Sync + Sized>(
self,
output: impl AsRef<Path>,
@@ -88,9 +92,14 @@ impl FFramesRenderBackend for CpuRenderingBackend {
TVideo::BACKGROUND_COLOR.a,
);
+ // The scheduler and segments work in output frames; `frame_offset` maps them back to
+ // video frames when only a range is rendered.
+ let frame_range = render_options.output_frame_range(ctx.duration_in_frames);
+ let frame_offset = frame_range.start;
+
let video_size = &ctx.current_video_size;
let scheduler = FrameScheduler::new(
- ctx.duration_in_frames,
+ frame_range.len(),
self.concurrency,
render_options
.video_encoder_options
@@ -136,22 +145,24 @@ impl FFramesRenderBackend for CpuRenderingBackend {
}
pixmap.fill(background_color);
- let svg = video.render_frame(
+ let video_frame = claim.frame + frame_offset;
+ let svg = super::render_frame_guarded(
+ video,
Frame::__internal_make_for_renderer(
- claim.frame,
- claim.frame,
+ video_frame,
+ video_frame,
ctx.time_base.fps,
break_lines_cache.clone(),
worker_local_decoders.clone(),
),
ctx,
- );
+ )?;
let rtree = svg.into_svg_tree(usvg_options, &mut converter_cache, font_db)?;
svgr::render(
&rtree,
- svgr::tiny_skia::Transform::default(),
+ super::fit_transform(&rtree, pixmap.width(), pixmap.height()),
&mut pixmap.as_mut(),
&mut svgr_cache,
&pixmap_pool,
@@ -221,26 +232,20 @@ impl FFramesRenderBackend for CpuRenderingBackend {
font_db: &usvgr::fontdb::Database,
ctx: crate::FFramesContext<'a, 'media>,
) -> FFramesRendererResult<Vec<u8>> {
- let mut pixmap = svgr::tiny_skia::Pixmap::new(ctx.current_video_size.width as u32, ctx.current_video_size.height as u32)
- .ok_or_else(|| FFramesRendererError::Internal("Failed to allocate pixmap for rendering. This may indicate that this machine is out of memory.".to_owned()))?;
-
let mut converter_cache = usvgr::Cache::default();
- let rtree = video.render_frame(frame, &ctx).into_svg_tree(
+ let rtree = super::render_frame_guarded(video, frame, &ctx)?.into_svg_tree(
usvg_options,
&mut converter_cache,
font_db,
)?;
- let ctx = svgr::Context::new_from_pixmap_unsafe(&pixmap);
- svgr::render(
+ let frame = super::CpuFrameRenderer::new(0).render_tree(
&rtree,
- svgr::tiny_skia::Transform::default(),
- &mut pixmap.as_mut(),
- &mut SvgrCache::none(),
- &PixmapPool::new(),
- &ctx,
- );
+ TVideo::BACKGROUND_COLOR,
+ ctx.current_video_size.width as u32,
+ ctx.current_video_size.height as u32,
+ )?;
- Ok(pixmap.take())
+ Ok(frame.pixels)
}
}
diff --git a/fframes/src/renderer/encoder_frame.rs b/fframes/src/renderer/encoder_frame.rs
index 1af62f56..f27a3d67 100644
--- a/fframes/src/renderer/encoder_frame.rs
+++ b/fframes/src/renderer/encoder_frame.rs
@@ -134,42 +134,95 @@ impl EncoderFrame {
}
}
- pub unsafe fn fill_from_audio_data(
+ /// Writes one block of stereo audio in the encoder's sample format and channel count.
+ pub unsafe fn fill_from_stereo(
&mut self,
- frame_index: i64,
- audio_data: Vec<f32>,
- ) -> *mut AVFrame {
- let is_writable = unsafe { av_frame_make_writable(self.av_frame) };
- if is_writable < 0 {
- panic!("Can not reuse frame allocations");
- }
-
+ pts: i64,
+ left: &[f32],
+ right: &[f32],
+ ) -> RenderEncodingResult<*mut AVFrame> {
unsafe {
- (*self.av_frame).pts = frame_index;
- }
-
- if audio_data.is_empty() {
- return self.av_frame;
- }
-
- let fltp_audio_bytes = audio_data
- .into_iter()
- .flat_map(|data| data.to_le_bytes())
- .collect::<Vec<u8>>();
+ if av_frame_make_writable(self.av_frame) < 0 {
+ return Err(RenderEncodingError::CantAllocate(
+ "writable audio frame".to_owned(),
+ ));
+ }
- unsafe {
- // Copy data into the AVFrame's allocated buffer instead of assigning pointer
- let frame_buffer = (*self.av_frame).data[0];
- let buffer_size = (*self.av_frame).linesize[0] as usize;
- let copy_size = fltp_audio_bytes.len().min(buffer_size);
+ let frame = self.av_frame;
+ let n = left.len().min(right.len());
+ (*frame).pts = pts;
+ (*frame).nb_samples = n as i32;
+ let channels = (*frame).ch_layout.nb_channels.max(1) as usize;
+ let sample = |channel: usize, i: usize| match channels {
+ 1 => (left[i] + right[i]) * 0.5,
+ _ if channel == 0 => left[i],
+ _ if channel == 1 => right[i],
+ // Additional channels of a larger layout stay silent.
+ _ => 0.,
+ };
+ let to_i16 = |v: f32| (v.clamp(-1., 1.) * 32767.).round() as i16;
+ let to_i32 = |v: f32| (v.clamp(-1., 1.) as f64 * 2147483647.).round() as i32;
- std::ptr::copy_nonoverlapping(fltp_audio_bytes.as_ptr(), frame_buffer, copy_size);
+ use AVSampleFormat::*;
+ let format: AVSampleFormat = std::mem::transmute((*frame).format);
+ match format {
+ AV_SAMPLE_FMT_FLTP => {
+ for c in 0..channels {
+ let plane = std::slice::from_raw_parts_mut(
+ (*frame).extended_data.add(c).read() as *mut f32,
+ n,
+ );
+ (0..n).for_each(|i| plane[i] = sample(c, i));
+ }
+ }
+ AV_SAMPLE_FMT_FLT => {
+ let data =
+ std::slice::from_raw_parts_mut((*frame).data[0] as *mut f32, n * channels);
+ (0..n).for_each(|i| {
+ (0..channels).for_each(|c| data[i * channels + c] = sample(c, i))
+ });
+ }
+ AV_SAMPLE_FMT_S16P => {
+ for c in 0..channels {
+ let plane = std::slice::from_raw_parts_mut(
+ (*frame).extended_data.add(c).read() as *mut i16,
+ n,
+ );
+ (0..n).for_each(|i| plane[i] = to_i16(sample(c, i)));
+ }
+ }
+ AV_SAMPLE_FMT_S16 => {
+ let data =
+ std::slice::from_raw_parts_mut((*frame).data[0] as *mut i16, n * channels);
+ (0..n).for_each(|i| {
+ (0..channels).for_each(|c| data[i * channels + c] = to_i16(sample(c, i)))
+ });
+ }
+ AV_SAMPLE_FMT_S32P => {
+ for c in 0..channels {
+ let plane = std::slice::from_raw_parts_mut(
+ (*frame).extended_data.add(c).read() as *mut i32,
+ n,
+ );
+ (0..n).for_each(|i| plane[i] = to_i32(sample(c, i)));
+ }
+ }
+ AV_SAMPLE_FMT_S32 => {
+ let data =
+ std::slice::from_raw_parts_mut((*frame).data[0] as *mut i32, n * channels);
+ (0..n).for_each(|i| {
+ (0..channels).for_each(|c| data[i * channels + c] = to_i32(sample(c, i)))
+ });
+ }
+ format => {
+ return Err(RenderEncodingError::Internal(format!(
+ "audio sample format {format:?} is not supported, use fltp, flt, s16 or s32"
+ )));
+ }
+ }
- // Update the actual number of samples in the frame
- (*self.av_frame).nb_samples = (copy_size / 4) as i32; // 4 bytes per f32
+ Ok(frame)
}
-
- self.av_frame
}
pub unsafe fn fill_from_rgba_pixmap(&mut self, rgba_pixels: &[u8]) -> *mut AVFrame {
diff --git a/fframes/src/renderer/ffmpeg_helper.rs b/fframes/src/renderer/ffmpeg_helper.rs
index 110aeb30..5701f0b6 100644
--- a/fframes/src/renderer/ffmpeg_helper.rs
+++ b/fframes/src/renderer/ffmpeg_helper.rs
@@ -2,6 +2,16 @@ use crate::ffmpeg_sys_fframes::{
AV_CH_LAYOUT_MONO, AVChannelLayout, AVChannelLayout__bindgen_ty_1, AVChannelOrder,
};
+pub const STEREO_CH_LAYOUT: AVChannelLayout = AVChannelLayout {
+ order: AVChannelOrder::AV_CHANNEL_ORDER_NATIVE,
+ nb_channels: 2,
+ u: AVChannelLayout__bindgen_ty_1 {
+ mask: crate::ffmpeg_sys_fframes::AV_CH_LAYOUT_STEREO,
+ },
+ opaque: std::ptr::null_mut(),
+};
+
+#[allow(dead_code)]
pub const MONO_CH_LAYOUT: AVChannelLayout = AVChannelLayout {
order: AVChannelOrder::AV_CHANNEL_ORDER_NATIVE,
nb_channels: 1,
diff --git a/fframes/src/renderer/fframes_logger.rs b/fframes/src/renderer/fframes_logger.rs
index 0f23fc4b..83b2d836 100644
--- a/fframes/src/renderer/fframes_logger.rs
+++ b/fframes/src/renderer/fframes_logger.rs
@@ -7,7 +7,10 @@ use once_cell::sync::OnceCell;
use std::{
ffi::c_int,
path::{Path, PathBuf},
- sync::{Arc, Mutex},
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicUsize, Ordering},
+ },
};
#[allow(unused_variables)]
@@ -41,6 +44,12 @@ pub trait FFramesLogger: Sync + Send {
}
fn success(&self, output_path: &Path, temp_files_dir: Option<&PathBuf>);
+
+ /// A problem that did not stop the render, e.g. media that `render_frame` asked for
+ /// but the media provider does not have.
+ fn warn(&self, message: &str) {
+ eprintln!("{} {message}", "warning:".yellow().bold());
+ }
}
pub struct CompactFFramesLogger {
@@ -139,6 +148,7 @@ pub struct SilentLogger;
impl FFramesLogger for SilentLogger {
fn success(&self, _output_path: &Path, _temp_files_dir: Option<&PathBuf>) {}
+ fn warn(&self, _message: &str) {}
}
pub struct QuietLogger;
@@ -166,6 +176,11 @@ pub enum FFramesLoggerVariant {
Compact,
/// Verbose logging for debugging purpose
Debug,
+ /// One plain line per 10% of progress on stderr, no progress bars or colors. Readable in
+ /// CI logs and by agents that capture the output.
+ Lines,
+ /// One JSON object per line on stderr (`{"event":"progress","done":10,"total":100}`).
+ Json,
/// Pass custom logger functionality by implementing FFramesLogger trait
Custom(Arc<dyn FFramesLogger>),
}
@@ -182,6 +197,134 @@ pub fn make_logger(variant: FFramesLoggerVariant) -> Arc<dyn FFramesLogger> {
audio_progress_bar: Mutex::new(None),
}) as Arc<dyn FFramesLogger>
}
+ FFramesLoggerVariant::Lines => Arc::new(LinesLogger::new(false)),
+ FFramesLoggerVariant::Json => Arc::new(LinesLogger::new(true)),
FFramesLoggerVariant::Custom(logger) => logger,
}
}
+
+/// Backs `FFramesLoggerVariant::Lines` and `FFramesLoggerVariant::Json`.
+pub struct LinesLogger {
+ json: bool,
+ started: std::time::Instant,
+ total: AtomicUsize,
+ done: AtomicUsize,
+ reported_decile: AtomicUsize,
+}
+
+impl LinesLogger {
+ pub fn new(json: bool) -> Self {
+ Self {
+ json,
+ started: std::time::Instant::now(),
+ total: AtomicUsize::new(0),
+ done: AtomicUsize::new(0),
+ reported_decile: AtomicUsize::new(0),
+ }
+ }
+
+ fn emit(&self, event: &str, text: String, fields: &[(&str, String)]) {
+ if self.json {
+ let mut line = format!("{{\"event\":{}", json_string(event));
+ for (key, value) in fields {
+ line.push_str(&format!(",{}:{value}", json_string(key)));
+ }
+ line.push('}');
+ eprintln!("{line}");
+ } else {
+ eprintln!("{text}");
+ }
+ }
+}
+
+/// Minimal JSON string escaping, the logger must not depend on a serializer.
+pub(crate) fn json_string(value: &str) -> String {
+ let mut escaped = String::with_capacity(value.len() + 2);
+ escaped.push('"');
+ for c in value.chars() {
+ match c {
+ '"' => escaped.push_str("\\\""),
+ '\\' => escaped.push_str("\\\\"),
+ '\n' => escaped.push_str("\\n"),
+ c if (c as u32) < 0x20 => escaped.push_str(&format!("\\u{:04x}", c as u32)),
+ c => escaped.push(c),
+ }
+ }
+ escaped.push('"');
+ escaped
+}
+
+impl FFramesLogger for LinesLogger {
+ fn init_frames_rendering(&self, frames_count: usize) -> FFramesRendererResult<()> {
+ self.total.store(frames_count, Ordering::Relaxed);
+ self.done.store(0, Ordering::Relaxed);
+ self.reported_decile.store(0, Ordering::Relaxed);
+ self.emit(
+ "start",
+ format!("rendering {frames_count} frames"),
+ &[("frames", frames_count.to_string())],
+ );
+ Ok(())
+ }
+
+ fn log_frame(&self, _index: usize, _thread_number: usize) {
+ let done = self.done.fetch_add(1, Ordering::Relaxed) + 1;
+ let total = self.total.load(Ordering::Relaxed).max(1);
+ let decile = done * 10 / total;
+ if decile > self.reported_decile.fetch_max(decile, Ordering::Relaxed) {
+ let elapsed = self.started.elapsed().as_secs_f32();
+ self.emit(
+ "progress",
+ format!("frames {done}/{total} ({}%) {elapsed:.1}s", decile * 10),
+ &[
+ ("done", done.to_string()),
+ ("total", total.to_string()),
+ ("elapsed", format!("{elapsed:.3}")),
+ ],
+ );
+ }
+ }
+
+ fn init_audio_encoding(&self, frames_count: usize) -> FFramesRendererResult<()> {
+ self.emit(
+ "audio",
+ "encoding audio".to_owned(),
+ &[("frames", frames_count.to_string())],
+ );
+ Ok(())
+ }
+
+ fn log_unprocessed_media_file(&self, filename: &str) {
+ self.warn(&format!("can not process media file {filename}"));
+ }
+
+ fn init_media_processing(&self, media_count: usize) -> FFramesRendererResult<()> {
+ self.emit(
+ "media",
+ format!("processing {media_count} media files"),
+ &[("files", media_count.to_string())],
+ );
+ Ok(())
+ }
+
+ fn warn(&self, message: &str) {
+ self.emit(
+ "warning",
+ format!("warning: {message}"),
+ &[("message", json_string(message))],
+ );
+ }
+
+ fn success(&self, output_path: &Path, _temp_files_dir: Option<&PathBuf>) {
+ let elapsed = self.started.elapsed().as_secs_f32();
+ let output = output_path.display().to_string();
+ self.emit(
+ "done",
+ format!("wrote {output} in {elapsed:.1}s"),
+ &[
+ ("output", json_string(&output)),
+ ("elapsed", format!("{elapsed:.3}")),
+ ],
+ );
+ }
+}
diff --git a/fframes/src/renderer/frame_guard.rs b/fframes/src/renderer/frame_guard.rs
new file mode 100644
index 00000000..33a4b83a
--- /dev/null
+++ b/fframes/src/renderer/frame_guard.rs
@@ -0,0 +1,62 @@
+use crate::{FFramesContext, Frame, Svgr, Video};
+use serde::Serialize;
+use std::panic::{AssertUnwindSafe, catch_unwind};
+
+/// Where and why `Video::render_frame` panicked.
+#[derive(Debug, Clone, Serialize)]
+pub struct FramePanic {
+ /// Global frame index.
+ pub frame: usize,
+ /// Global timestamp in seconds.
+ pub seconds: f32,
+ /// Name of the scene(s) active at this frame, if the video defines scenes.
+ pub scenes: Vec<String>,
+ pub message: String,
+}
+
+impl std::fmt::Display for FramePanic {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "render_frame panicked at frame {} ({:.3}s)",
+ self.frame, self.seconds
+ )?;
+ if !self.scenes.is_empty() {
+ write!(f, " in scene {}", self.scenes.join(" + "))?;
+ }
+ write!(f, ": {}", self.message)
+ }
+}
+
+/// Calls `Video::render_frame`, turning a panic into an error that says which frame, second
+/// and scene it happened in. Rendering backends should call the video through this function.
+pub fn render_frame_guarded<'a, TVideo: Video>(
+ video: &'a TVideo,
+ frame: Frame,
+ ctx: &FFramesContext<'a, '_>,
+) -> Result<Svgr<'a>, FramePanic> {
+ let index = frame.global_index;
+ let fps = frame.fps.max(1);
+
+ catch_unwind(AssertUnwindSafe(|| video.render_frame(frame, ctx))).map_err(|payload| {
+ let message = payload
+ .downcast_ref::<&str>()
+ .map(|s| s.to_string())
+ .or_else(|| payload.downcast_ref::<String>().cloned())
+ .unwrap_or_else(|| "unknown panic payload".to_owned());
+
+ crate::diagnostics::report(crate::diagnostics::Diagnostic::Panic {
+ message: message.clone(),
+ });
+
+ FramePanic {
+ frame: index,
+ seconds: index as f32 / fps as f32,
+ scenes: ctx
+ .scenes_at(index)
+ .map(|(_, name)| crate::short_scene_name(name).to_owned())
+ .collect(),
+ message,
+ }
+ })
+}
diff --git a/fframes/src/renderer/media_directory.rs b/fframes/src/renderer/media_directory.rs
index f9f4e453..96500253 100644
--- a/fframes/src/renderer/media_directory.rs
+++ b/fframes/src/renderer/media_directory.rs
@@ -78,7 +78,9 @@ impl MediaDirectory {
match (extension, raw_file) {
("mp3" | "wav" | "flac" | "aac" | "pcm" | "ogg" | "mp2", _) => {
let audio_data =
- crate::media::PreloadedAudioData::decode_raw_file(None, path)?;
+ crate::media::PreloadedAudioData::decode_raw_file_stereo(
+ None, path,
+ )?;
audio_hash.lock()?.insert(
filename.to_owned(),
@@ -117,7 +119,7 @@ impl MediaDirectory {
);
if let Ok(audio_data) =
- crate::media::PreloadedAudioData::decode_raw_file(None, path)
+ crate::media::PreloadedAudioData::decode_raw_file_stereo(None, path)
{
audio_hash.lock()?.insert(
filename.to_owned(),
diff --git a/fframes/src/renderer/mod.rs b/fframes/src/renderer/mod.rs
index 38336fcd..efdb3a20 100644
--- a/fframes/src/renderer/mod.rs
+++ b/fframes/src/renderer/mod.rs
@@ -36,6 +36,18 @@ pub use scheduler::*;
mod segment_writer;
pub use segment_writer::*;
+mod frame_guard;
+pub use frame_guard::*;
+
+mod preview;
+pub use preview::*;
+
+#[cfg(feature = "cpu_renderer")]
+pub mod sheet;
+pub mod snapshot;
+
+#[cfg(feature = "cli")]
+pub mod cli;
pub use rayon;
#[cfg(test)]
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
new file mode 100644
index 00000000..0b63ac25
--- /dev/null
+++ b/fframes/src/renderer/preview.rs
@@ -0,0 +1,497 @@
+//! Rendering individual frames quickly and repeatedly: previews, contact sheets, SVG dumps
+//! and frame diagnostics. Unlike `fframes::render_frame` a `Previewer` resolves the timeline,
+//! loads fonts and images once and keeps its caches between frames.
+use super::FFramesRendererRuntime;
+use super::renderer_error::{FFramesRendererError, FFramesRendererResult};
+use crate::diagnostics::{self, Diagnostic};
+use crate::{
+ AudioTimelineSamples, Color, FFramesContext, Frame, RenderOptions, ResolvedRenderingTimeline,
+ TextCache, TimeBase, TimelineIndex, Video, VideoDecodersWorker, VideoSize, usvgr,
+};
+use serde::Serialize;
+use std::collections::HashMap;
+use std::path::Path;
+use std::sync::Arc;
+
+/// Straight (not premultiplied) RGBA8 pixels of one frame.
+#[derive(Clone)]
+pub struct RgbaFrame {
+ pub width: u32,
+ pub height: u32,
+ pub pixels: Vec<u8>,
+}
+
+impl std::fmt::Debug for RgbaFrame {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "RgbaFrame({}x{})", self.width, self.height)
+ }
+}
+
+impl RgbaFrame {
+ /// Wraps premultiplied RGBA pixels (what tiny-skia and Skia produce).
+ pub fn from_premultiplied(width: u32, height: u32, mut pixels: Vec<u8>) -> Self {
+ for px in pixels.chunks_exact_mut(4) {
+ let a = px[3];
+ if a != 255 && a != 0 {
+ for c in &mut px[..3] {
+ *c = ((*c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8;
+ }
+ }
+ }
+
+ Self {
+ width,
+ height,
+ pixels,
+ }
+ }
+
+ pub fn into_image(self) -> image::RgbaImage {
+ image::RgbaImage::from_raw(self.width, self.height, self.pixels)
+ .expect("RgbaFrame pixel buffer matches its size")
+ }
+
+ pub fn save_png(&self, path: impl AsRef<Path>) -> FFramesRendererResult<()> {
+ let path = path.as_ref();
+ image::save_buffer(
+ path,
+ &self.pixels,
+ self.width,
+ self.height,
+ image::ExtendedColorType::Rgba8,
+ )
+ .map_err(|err| FFramesRendererError::ImageError((path.display().to_string(), err)))
+ }
+}
+
+/// Rasterizes converted frames. Implementations keep their surfaces and caches between
+/// calls, so rendering many frames through one renderer is cheap.
+pub trait FrameRenderer {
+ /// Renders `tree` scaled to `width`x`height` over `background`.
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: Color,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<RgbaFrame>;
+}
+
+/// The transform that fits a tree into the output size. Videos that hardcode their `WIDTH`
+/// as the `<svg width>` are scaled this way when rendering with `scale_resolution`.
+pub fn fit_transform(tree: &usvgr::Tree, width: u32, height: u32) -> usvgr::Transform {
+ let size = tree.size();
+ let sx = width as f32 / size.width();
+ let sy = height as f32 / size.height();
+ if (sx - 1.).abs() < f32::EPSILON && (sy - 1.).abs() < f32::EPSILON {
+ usvgr::Transform::default()
+ } else {
+ usvgr::Transform::from_scale(sx, sy)
+ }
+}
+
+/// The built-in tiny-skia rasterizer as a `FrameRenderer`.
+#[cfg(feature = "cpu_renderer")]
+pub struct CpuFrameRenderer {
+ pixmap: Option<svgr::tiny_skia::Pixmap>,
+ cache: svgr::SvgrCache,
+ pixmap_pool: svgr::PixmapPool,
+}
+
+#[cfg(feature = "cpu_renderer")]
+impl CpuFrameRenderer {
+ /// `cache_capacity` is the number of static subtrees kept rasterized between frames.
+ pub fn new(cache_capacity: usize) -> Self {
+ Self {
+ pixmap: None,
+ cache: svgr::SvgrCache::new(cache_capacity),
+ pixmap_pool: svgr::PixmapPool::new(),
+ }
+ }
+}
+
+#[cfg(feature = "cpu_renderer")]
+impl Default for CpuFrameRenderer {
+ fn default() -> Self {
+ Self::new(20)
+ }
+}
+
+#[cfg(feature = "cpu_renderer")]
+impl FrameRenderer for CpuFrameRenderer {
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: Color,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<RgbaFrame> {
+ use svgr::tiny_skia;
+
+ let pixmap = match self.pixmap.take() {
+ Some(pixmap) if pixmap.width() == width && pixmap.height() == height => pixmap,
+ _ => tiny_skia::Pixmap::new(width, height).ok_or_else(|| {
+ FFramesRendererError::Internal(format!(
+ "can not allocate a {width}x{height} pixmap"
+ ))
+ })?,
+ };
+ let mut pixmap = pixmap;
+
+ pixmap.fill(tiny_skia::Color::from_rgba8(
+ background.r,
+ background.g,
+ background.b,
+ background.a,
+ ));
+
+ let ctx = svgr::Context::new_from_pixmap_unsafe(&pixmap);
+ svgr::render(
+ tree,
+ fit_transform(tree, width, height),
+ &mut pixmap.as_mut(),
+ &mut self.cache,
+ &self.pixmap_pool,
+ &ctx,
+ );
+
+ let frame = RgbaFrame::from_premultiplied(width, height, pixmap.data().to_vec());
+ self.pixmap = Some(pixmap);
+ Ok(frame)
+ }
+}
+
+/// What the CLI's `preview` command asks a real-time player to do.
+#[derive(Debug, Clone)]
+pub struct PreviewRequest {
+ pub start_frame: usize,
+ pub autoplay: bool,
+ pub looping: bool,
+ pub audio: bool,
+ /// `auto`, `metal`, `vulkan` or `cpu`.
+ pub backend: String,
+}
+
+/// The resolved structure of a video: size, duration, scenes and audio tracks.
+#[derive(Debug, Clone, Serialize)]
+pub struct TimelineReport {
+ pub fps: usize,
+ pub width: usize,
+ pub height: usize,
+ pub duration_frames: usize,
+ pub duration_seconds: f32,
+ pub scenes: Vec<SceneReport>,
+ pub audio: Vec<AudioTrackReport>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct SceneReport {
+ pub index: usize,
+ pub name: String,
+ pub full_name: String,
+ /// Frames including overlaps with the neighbours, end exclusive.
+ pub start_frame: usize,
+ pub end_frame: usize,
+ pub start_seconds: f32,
+ pub end_seconds: f32,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct AudioTrackReport {
+ pub file: String,
+ pub start_seconds: f64,
+ pub end_seconds: f64,
+ pub mix: crate::TrackMix,
+}
+
+/// What the diagnostics found in one frame.
+#[derive(Debug, Clone, Serialize)]
+pub struct FrameReport {
+ pub frame: usize,
+ pub seconds: f32,
+ pub scenes: Vec<String>,
+ pub diagnostics: Vec<ReportedDiagnostic>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ReportedDiagnostic {
+ pub severity: diagnostics::Severity,
+ /// Same key in different frames means the same problem (see `Diagnostic::group_key`).
+ pub key: String,
+ pub message: String,
+ #[serde(flatten)]
+ pub diagnostic: Diagnostic,
+}
+
+impl From<Diagnostic> for ReportedDiagnostic {
+ fn from(diagnostic: Diagnostic) -> Self {
+ Self {
+ severity: diagnostic.severity(),
+ key: diagnostic.group_key(),
+ message: diagnostic.to_string(),
+ diagnostic,
+ }
+ }
+}
+
+/// A long lived session for rendering arbitrary frames of a video.
+///
+/// ```ignore
+/// let mut previewer = fframes::Previewer::new(&video, &options)?;
+/// let mut renderer = fframes::CpuFrameRenderer::default();
+/// let frame = previewer.timeline().resolve_frame("[email protected]")?;
+/// previewer.render(frame, &mut renderer)?.save_png("intro.png")?;
+/// ```
+pub struct Previewer<'a, 'media, TVideo: Video> {
+ video: &'a TVideo,
+ runtime: FFramesRendererRuntime<'a>,
+ options: RenderOptions<'a, 'media>,
+ image_source: HashMap<String, Arc<usvgr::PreloadedImageData>>,
+ size: VideoSize,
+ timeline_index: TimelineIndex,
+ converter_cache: usvgr::Cache,
+ text_cache: Option<TextCache>,
+ decoders: VideoDecodersWorker,
+}
+
+impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
+ pub fn new(
+ video: &'a TVideo,
+ options: &RenderOptions<'a, 'media>,
+ ) -> FFramesRendererResult<Self> {
+ let scenes = video.define_scenes();
+ let mut runtime = FFramesRendererRuntime::new(
+ TimeBase {
+ fps: TVideo::FPS,
+ sample_rate: options.audio_encoder_options.sample_rate,
+ },
+ video,
+ &scenes,
+ options.media,
+ )?;
+
+ if options.load_system_fonts {
+ runtime.font_source.fontdb.load_system_fonts();
+ }
+
+ let mut image_source = HashMap::new();
+ if let Some(media) = options.media {
+ media.populate_image_source(&mut image_source);
+ }
+
+ let timeline_index = TimelineIndex::new(
+ TVideo::FPS,
+ runtime.timeline.duration_in_frames,
+ runtime.timeline.scenes.as_ref(),
+ );
+
+ Ok(Self {
+ video,
+ size: VideoSize::new_scaled(TVideo::WIDTH, TVideo::HEIGHT, options.scale_resolution),
+ options: options.clone(),
+ runtime,
+ image_source,
+ timeline_index,
+ converter_cache: usvgr::Cache::new_with_text_cache(10),
+ text_cache: TextCache::new(10),
+ decoders: VideoDecodersWorker::new(2),
+ })
+ }
+
+ /// Scenes and duration for resolving time specs like `[email protected]`.
+ pub fn timeline(&self) -> &TimelineIndex {
+ &self.timeline_index
+ }
+
+ pub fn resolved_timeline(&self) -> &ResolvedRenderingTimeline<'a, AudioTimelineSamples> {
+ &self.runtime.timeline
+ }
+
+ pub fn font_db(&self) -> &usvgr::fontdb::Database {
+ self.runtime.font_source.as_db_ref()
+ }
+
+ /// Scenes, duration and audio tracks as resolved for rendering.
+ pub fn timeline_report(&self) -> TimelineReport {
+ let index = &self.timeline_index;
+ let time_base = self.runtime.time_base;
+ TimelineReport {
+ fps: TVideo::FPS,
+ width: TVideo::WIDTH,
+ height: TVideo::HEIGHT,
+ duration_frames: index.duration_in_frames,
+ duration_seconds: index.duration_in_seconds(),
+ scenes: index
+ .scenes
+ .iter()
+ .map(|scene| SceneReport {
+ index: scene.index,
+ name: scene.name.clone(),
+ full_name: scene.full_name.clone(),
+ start_frame: scene.frames.start,
+ end_frame: scene.frames.end,
+ start_seconds: index.frame_to_seconds(scene.frames.start),
+ end_seconds: index.frame_to_seconds(scene.frames.end),
+ })
+ .collect(),
+ audio: self
+ .runtime
+ .timeline
+ .audio_map
+ .as_ref()
+ .map(|map| {
+ use crate::AudioTimelineUnit;
+ map.tracks()
+ .iter()
+ .map(|track| AudioTrackReport {
+ file: track.file.clone(),
+ start_seconds: track.range.start.to_seconds(&time_base),
+ end_seconds: track.range.end.to_seconds(&time_base),
+ mix: track.mix,
+ })
+ .collect()
+ })
+ .unwrap_or_default(),
+ }
+ }
+
+ pub fn media(&self) -> Option<&'media dyn crate::MediaProvider<'media>> {
+ self.options.media
+ }
+
+ pub fn options(&self) -> &RenderOptions<'a, 'media> {
+ &self.options
+ }
+
+ /// Output size in pixels (`WIDTH`x`HEIGHT` times `scale_resolution`).
+ pub fn size(&self) -> (u32, u32) {
+ (self.size.width as u32, self.size.height as u32)
+ }
+
+ /// Changes the output size of the following frames.
+ pub fn set_scale(&mut self, scale: f64) {
+ 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.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(
+ 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(),
+ ..Default::default()
+ };
+
+ Ok(svgr.into_svg_tree(
+ &usvg_options,
+ &mut self.converter_cache,
+ self.runtime.font_source.as_db_ref(),
+ )?)
+ }
+
+ /// The frame as an SVG document, as the renderer sees it after conversion (text is
+ /// already laid out, `use` and styles are resolved).
+ pub fn svg(&mut self, frame: usize) -> FFramesRendererResult<String> {
+ Ok(self
+ .svg_tree(frame)?
+ .to_string(&usvgr::WriteOptions::default()))
+ }
+
+ /// Renders a frame to pixels, over the video's `BACKGROUND_COLOR` exactly like the encoder.
+ pub fn render(
+ &mut self,
+ frame: usize,
+ renderer: &mut dyn FrameRenderer,
+ ) -> FFramesRendererResult<RgbaFrame> {
+ let tree = self.svg_tree(frame)?;
+ let (width, height) = self.size();
+ renderer.render_tree(&tree, TVideo::BACKGROUND_COLOR, width, height)
+ }
+
+ /// Renders a frame and reports the problems found while converting it.
+ pub fn render_inspected(
+ &mut self,
+ frame: usize,
+ renderer: &mut dyn FrameRenderer,
+ ) -> FFramesRendererResult<(RgbaFrame, FrameReport)> {
+ self.check_frame(frame)?;
+ let (width, height) = self.size();
+ let (tree, mut found) = diagnostics::collect(|| self.svg_tree(frame));
+ 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)?;
+
+ Ok((pixels, self.report(frame, found)))
+ }
+
+ 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(),
+ }
+ }
+
+ /// 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));
+
+ 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),
+ }
+
+ Ok(self.report(frame, found))
+ }
+}
diff --git a/fframes/src/renderer/render_backend.rs b/fframes/src/renderer/render_backend.rs
index b53fa7b3..b26194ad 100644
--- a/fframes/src/renderer/render_backend.rs
+++ b/fframes/src/renderer/render_backend.rs
@@ -5,6 +5,13 @@ use usvgr::fontdb;
#[allow(clippy::too_many_arguments)]
pub trait FFramesRenderBackend {
+ /// 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.
+ /// `None` uses the built-in CPU renderer.
+ fn frame_renderer(&self) -> Option<Box<dyn super::FrameRenderer + '_>> {
+ None
+ }
+
fn render_frame<'a, 'media: 'a, TVideo: Video + Sync + Sized + Send>(
self,
frame: crate::Frame,
diff --git a/fframes/src/renderer/renderer.rs b/fframes/src/renderer/renderer.rs
index d6ea386e..1828a039 100644
--- a/fframes/src/renderer/renderer.rs
+++ b/fframes/src/renderer/renderer.rs
@@ -48,6 +48,23 @@ pub struct RenderOptions<'a, 'media> {
pub default_font: &'a str,
/// The abort signal that can be used to abort the rendering process.
pub abort_signal: Option<&'media crate::AbortSignal>,
+ /// Render only these frames of the video (end exclusive). The output starts at the first
+ /// frame of the range and the audio is cut to match. `None` renders the whole video.
+ ///
+ /// Use `TimelineIndex::resolve_range` to build it from specs like `"Intro"` or `"10s..20s"`.
+ pub frame_range: Option<std::ops::Range<usize>>,
+ /// Master bus of the audio mix: limiter, master gain and de-click fades.
+ pub audio_mix: crate::AudioMixOptions,
+}
+
+impl RenderOptions<'_, '_> {
+ /// The frames that will be rendered for a video of `duration_in_frames`, clamped to it.
+ pub fn output_frame_range(&self, duration_in_frames: usize) -> std::ops::Range<usize> {
+ match &self.frame_range {
+ Some(range) => range.start.min(duration_in_frames)..range.end.min(duration_in_frames),
+ None => 0..duration_in_frames,
+ }
+ }
}
impl Default for RenderOptions<'_, '_> {
@@ -63,6 +80,8 @@ impl Default for RenderOptions<'_, '_> {
default_font: "Arial",
abort_signal: None,
tmp_files_directory: None,
+ frame_range: None,
+ audio_mix: Default::default(),
}
}
}
@@ -101,16 +120,16 @@ impl<'a, 'media: 'a> FFramesRendererRuntime<'a> {
let video_duration = media
.resolve_video(name)
.and_then(|video| video.metadata)
- .map(|metadata| (metadata.duration * TVideo::FPS as f32).round() as usize);
+ .map(|metadata| metadata.duration as f64);
video_duration
.or_else(|| {
media
.resolve_audio(name)
.and_then(|main_audio| match main_audio {
- AudioData::Preloaded(data) => Some(
- data.samples.len() * TVideo::FPS / data.sample_rate as usize,
- ),
+ AudioData::Preloaded(data) => {
+ Some(data.samples.len() as f64 / data.sample_rate as f64)
+ }
_ => None,
})
})
@@ -186,7 +205,15 @@ pub fn render<
font_source.fontdb.load_system_fonts();
}
- logger.init_frames_rendering(timeline.duration_in_frames)?;
+ let frame_range = options.output_frame_range(timeline.duration_in_frames);
+ if frame_range.is_empty() {
+ return Err(super::FFramesRendererError::Custom(format!(
+ "frame range {:?} is empty or outside the video (0..{})",
+ options.frame_range, timeline.duration_in_frames
+ )));
+ }
+
+ logger.init_frames_rendering(frame_range.len())?;
let ctx = FFramesContext {
time_base,
mode: crate::FFramesMode::Renderer,
@@ -205,7 +232,7 @@ pub fn render<
render_backend.render(
&output,
video,
- logger,
+ logger.clone(),
&usvg_options,
options,
font_source.as_db_ref(),
@@ -213,6 +240,12 @@ pub fn render<
&ctx,
)?;
+ for (kind, name) in crate::diagnostics::take_missing_media() {
+ logger.warn(&format!(
+ "{kind:?} \"{name}\" was requested by render_frame but is not in the media provider"
+ ));
+ }
+
Ok(())
}
diff --git a/fframes/src/renderer/renderer_error.rs b/fframes/src/renderer/renderer_error.rs
index 54cfb95f..c96a7636 100644
--- a/fframes/src/renderer/renderer_error.rs
+++ b/fframes/src/renderer/renderer_error.rs
@@ -25,6 +25,8 @@ pub enum RenderEncodingError {
RenderError,
CStringError(std::ffi::NulError),
Utf8Error(Utf8Error),
+ /// `Video::render_frame` panicked.
+ FramePanicked(super::FramePanic),
}
impl fmt::Display for RenderEncodingError {
@@ -62,6 +64,7 @@ impl fmt::Display for RenderEncodingError {
Self::CStringError(err) => format!("Failed to convert string to c string: {err:?}"),
Self::RenderError => "Rendering pipeline failed.".to_owned(),
Self::Utf8Error(err) => format!("Failed to convert bytes to utf8 string: {err:?}"),
+ Self::FramePanicked(panic) => panic.to_string(),
}
)
}
@@ -88,6 +91,20 @@ pub enum FFramesRendererError {
/// Any custom rendering backend implementation-specific error
Custom(String),
+
+ /// `Video::render_frame` panicked. Carries the frame, second and scene it happened in.
+ FramePanicked(super::FramePanic),
+}
+
+impl FFramesRendererError {
+ /// Lifts errors that are about a specific frame out of the chunk that rendered it.
+ pub fn from_chunk(chunk: usize, error: RenderEncodingError) -> Self {
+ match error {
+ RenderEncodingError::Aborted => Self::Aborted,
+ RenderEncodingError::FramePanicked(panic) => Self::FramePanicked(panic),
+ error => Self::RenderChunkError(chunk, error),
+ }
+ }
}
impl Error for FFramesRendererError {}
@@ -127,6 +144,7 @@ impl fmt::Debug for FFramesRendererError {
Self::MediaError(err) => format!("Media processing error: {err:?}"),
Self::Skia(err) => format!("Skia error: {err}"),
Self::Aborted => "Aborted by the user".to_owned(),
+ Self::FramePanicked(panic) => panic.to_string(),
}
)
}
@@ -170,3 +188,15 @@ impl From<crate::media::FFramesMediaError> for FFramesRendererError {
Self::MediaError(err)
}
}
+
+impl From<super::FramePanic> for FFramesRendererError {
+ fn from(panic: super::FramePanic) -> Self {
+ Self::FramePanicked(panic)
+ }
+}
+
+impl From<super::FramePanic> for RenderEncodingError {
+ fn from(panic: super::FramePanic) -> Self {
+ Self::FramePanicked(panic)
+ }
+}
diff --git a/fframes/src/renderer/sheet.rs b/fframes/src/renderer/sheet.rs
new file mode 100644
index 00000000..7928206e
--- /dev/null
+++ b/fframes/src/renderer/sheet.rs
@@ -0,0 +1,154 @@
+//! Compositing several frames into one image: labelled contact sheets and onion skins, which
+//! show a movement in a single picture.
+use super::{FFramesRendererError, FFramesRendererResult, RgbaFrame};
+use crate::usvgr;
+use svgr::tiny_skia;
+
+/// A frame of a contact sheet with the label drawn under it.
+pub struct SheetCell {
+ pub frame: RgbaFrame,
+ pub label: String,
+}
+
+fn to_pixmap(frame: &RgbaFrame) -> FFramesRendererResult<tiny_skia::Pixmap> {
+ let mut data = frame.pixels.clone();
+ for px in data.chunks_exact_mut(4) {
+ let a = px[3] as u32;
+ if a != 255 {
+ for c in &mut px[..3] {
+ *c = ((*c as u32 * a + 127) / 255) as u8;
+ }
+ }
+ }
+
+ tiny_skia::Pixmap::from_vec(
+ data,
+ tiny_skia::IntSize::from_wh(frame.width, frame.height)
+ .ok_or_else(|| FFramesRendererError::Internal("empty frame".to_owned()))?,
+ )
+ .ok_or_else(|| FFramesRendererError::Internal("invalid frame buffer".to_owned()))
+}
+
+fn escape_xml(text: &str) -> String {
+ text.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
+}
+
+/// Font families for labels: the requested one, then whatever the database has.
+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()
+ {
+ families.push(format!("'{family}'"));
+ }
+ families.push("sans-serif".to_owned());
+ families.join(", ")
+}
+
+/// Lays `cells` out in a grid with `columns` columns and a label bar under every frame.
+pub fn contact_sheet(
+ cells: &[SheetCell],
+ columns: usize,
+ fontdb: &usvgr::fontdb::Database,
+ font_family: &str,
+) -> FFramesRendererResult<RgbaFrame> {
+ let first = cells
+ .first()
+ .ok_or_else(|| FFramesRendererError::Custom("no frames for the contact sheet".into()))?;
+ let (cell_w, cell_h) = (first.frame.width, first.frame.height);
+ let columns = columns.clamp(1, cells.len()) as u32;
+ let rows = (cells.len() as u32).div_ceil(columns);
+ let gap = 8;
+ let label_h = (cell_w / 16).clamp(18, 40);
+ let sheet_w = columns * cell_w + (columns + 1) * gap;
+ let sheet_h = rows * (cell_h + label_h) + (rows + 1) * gap;
+
+ let mut sheet = tiny_skia::Pixmap::new(sheet_w, sheet_h)
+ .ok_or_else(|| FFramesRendererError::Internal("contact sheet is too large".into()))?;
+ sheet.fill(tiny_skia::Color::from_rgba8(24, 24, 27, 255));
+
+ let mut labels = String::new();
+ let family = escape_xml(&label_font_family(fontdb, font_family));
+ for (i, cell) in cells.iter().enumerate() {
+ let col = i as u32 % columns;
+ let row = i as u32 / columns;
+ let x = gap + col * (cell_w + gap);
+ let y = gap + row * (cell_h + label_h + gap);
+
+ sheet.draw_pixmap(
+ x as i32,
+ y as i32,
+ to_pixmap(&cell.frame)?.as_ref(),
+ &tiny_skia::PixmapPaint::default(),
+ tiny_skia::Transform::identity(),
+ None,
+ );
+
+ labels.push_str(&format!(
+ r##"<text x="{}" y="{}" font-size="{}" font-family="{family}" fill="#f4f4f5">{}</text>"##,
+ x + 6,
+ y + cell_h + label_h * 3 / 4,
+ label_h * 3 / 5,
+ escape_xml(&cell.label),
+ ));
+ }
+
+ let svg = format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="{sheet_w}" height="{sheet_h}">{labels}</svg>"#
+ );
+ let tree = usvgr::Tree::from_str(&svg, &usvgr::Options::default(), fontdb)
+ .map_err(|err| FFramesRendererError::Internal(format!("contact sheet labels: {err}")))?;
+ let ctx = svgr::Context::new_from_pixmap_unsafe(&sheet);
+ svgr::render(
+ &tree,
+ tiny_skia::Transform::identity(),
+ &mut sheet.as_mut(),
+ &mut svgr::SvgrCache::none(),
+ &svgr::PixmapPool::new(),
+ &ctx,
+ );
+
+ Ok(RgbaFrame::from_premultiplied(
+ sheet_w,
+ sheet_h,
+ sheet.take(),
+ ))
+}
+
+/// Blends frames into one image, later frames more opaque, so a movement shows as a trail
+/// ending in the last frame.
+pub fn onion_skin(frames: &[RgbaFrame]) -> FFramesRendererResult<RgbaFrame> {
+ let last = frames
+ .last()
+ .ok_or_else(|| FFramesRendererError::Custom("no frames for the onion skin".into()))?;
+ if frames
+ .iter()
+ .any(|f| f.width != last.width || f.height != last.height)
+ {
+ return Err(FFramesRendererError::Custom(
+ "onion skin frames have different sizes".into(),
+ ));
+ }
+
+ // Weights grow linearly: the last frame dominates, the first is the faintest.
+ let weights: Vec<f32> = (1..=frames.len()).map(|w| w as f32).collect();
+ let total: f32 = weights.iter().sum();
+ let mut pixels = vec![0u8; last.pixels.len()];
+ for (i, px) in pixels.iter_mut().enumerate() {
+ let value: f32 = frames
+ .iter()
+ .zip(&weights)
+ .map(|(frame, w)| frame.pixels[i] as f32 * w)
+ .sum();
+ *px = (value / total).round().clamp(0., 255.) as u8;
+ }
+
+ Ok(RgbaFrame {
+ width: last.width,
+ height: last.height,
+ pixels,
+ })
+}
diff --git a/fframes/src/renderer/snapshot.rs b/fframes/src/renderer/snapshot.rs
new file mode 100644
index 00000000..e9af584e
--- /dev/null
+++ b/fframes/src/renderer/snapshot.rs
@@ -0,0 +1,274 @@
+//! 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
+ .chunks_exact(4)
+ .zip(actual.pixels.chunks_exact(4))
+ {
+ 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 = ((e[0] as u32 + e[1] as u32 + e[2] as u32) / 3 / 4) as u8;
+ diff.extend_from_slice(&[gray, gray, gray, 255]);
+ }
+ }
+
+ let total = (expected.width * expected.height).max(1) as f64;
+ (
+ 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();
+
+ if !failed.is_empty() {
+ panic!(
+ "{} 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/fframes/src/renderer/stream.rs b/fframes/src/renderer/stream.rs
index 96cff406..d3b72191 100644
--- a/fframes/src/renderer/stream.rs
+++ b/fframes/src/renderer/stream.rs
@@ -1,5 +1,5 @@
use super::EncoderOptions;
-use super::ffmpeg_helper::MONO_CH_LAYOUT;
+use super::ffmpeg_helper::STEREO_CH_LAYOUT;
use super::renderer_error::{RenderEncodingError, RenderEncodingResult};
use crate::ffmpeg_action;
use crate::ffmpeg_loggable_action;
@@ -66,6 +66,33 @@ pub unsafe fn validate_sample_rate_fits_codec(codec: *const AVCodec, sample_rate
}
}
+/// The requested sample format if the encoder takes it, otherwise one `fill_from_stereo` can
+/// write (libopus, for example, only accepts `flt` and `s16`).
+unsafe fn fit_sample_format(codec: *const AVCodec, requested: AVSampleFormat) -> AVSampleFormat {
+ use AVSampleFormat::*;
+ let supported = unsafe {
+ supported_codec_config::<AVSampleFormat>(
+ codec,
+ AVCodecConfig::AV_CODEC_CONFIG_SAMPLE_FORMAT,
+ )
+ };
+
+ match supported {
+ Some(formats) if !formats.contains(&requested) => [
+ AV_SAMPLE_FMT_FLTP,
+ AV_SAMPLE_FMT_FLT,
+ AV_SAMPLE_FMT_S16,
+ AV_SAMPLE_FMT_S16P,
+ AV_SAMPLE_FMT_S32,
+ AV_SAMPLE_FMT_S32P,
+ ]
+ .into_iter()
+ .find(|format| formats.contains(format))
+ .unwrap_or(formats[0]),
+ _ => requested,
+ }
+}
+
unsafe fn is_pixel_format_supported(codec: *const AVCodec, pixel_format: AVPixelFormat) -> bool {
let supported = unsafe {
supported_codec_config::<AVPixelFormat>(codec, AVCodecConfig::AV_CODEC_CONFIG_PIX_FORMAT)
@@ -279,7 +306,7 @@ impl Stream {
);
}
- (*c).sample_fmt = encoder_options.sample_format;
+ (*c).sample_fmt = fit_sample_format(codec, encoder_options.sample_format);
(*c).sample_rate = validated_sample_rate;
(*c).bit_rate = encoder_options.bitrate.unwrap_or(192000);
(*st).time_base = AVRational {
@@ -287,7 +314,7 @@ impl Stream {
den: validated_sample_rate,
};
- (*c).ch_layout = MONO_CH_LAYOUT;
+ (*c).ch_layout = STEREO_CH_LAYOUT;
if let Some((tag, options)) = encoder_options.tag.zip((*st).codecpar.as_mut()) {
options.codec_tag = tag as u32;
}
@@ -317,8 +344,8 @@ impl Stream {
Self::set_swr_option(swr_ctx, "in_sample_rate", (*c).sample_rate);
Self::set_swr_option(swr_ctx, "out_sample_rate", (*c).sample_rate);
- Self::set_swr_chlayout(swr_ctx, "in_chlayout", &MONO_CH_LAYOUT);
- Self::set_swr_chlayout(swr_ctx, "out_chlayout", &MONO_CH_LAYOUT);
+ Self::set_swr_chlayout(swr_ctx, "in_chlayout", &STEREO_CH_LAYOUT);
+ Self::set_swr_chlayout(swr_ctx, "out_chlayout", &STEREO_CH_LAYOUT);
Self::set_swr_fmt(swr_ctx, "in_sample_fmt", AVSampleFormat::AV_SAMPLE_FMT_FLTP);
Self::set_swr_fmt(swr_ctx, "out_sample_fmt", (*c).sample_fmt);
diff --git a/fframes/src/renderer/tests/mod.rs b/fframes/src/renderer/tests/mod.rs
index 6d6a91d0..355a0def 100644
--- a/fframes/src/renderer/tests/mod.rs
+++ b/fframes/src/renderer/tests/mod.rs
@@ -1 +1,2 @@
+mod preview_tests;
mod yuv420_conversion_tests;
diff --git a/fframes/src/renderer/tests/preview_tests.rs b/fframes/src/renderer/tests/preview_tests.rs
new file mode 100644
index 00000000..d18e0a2a
--- /dev/null
+++ b/fframes/src/renderer/tests/preview_tests.rs
@@ -0,0 +1,124 @@
+use crate::diagnostics::Diagnostic;
+use crate::{
+ AudioMap, Color, CpuFrameRenderer, FFramesContext, FFramesRendererError, Frame, Previewer,
+ RenderOptions, Scene, Svgr, Video,
+};
+
+#[derive(Debug)]
+struct Intro;
+
+impl Scene for Intro {
+ fn duration(&self) -> crate::Duration<'_> {
+ crate::Duration::Frames(10)
+ }
+
+ fn render_frame(&self, frame: Frame, _: &FFramesContext) -> Svgr<'_> {
+ if frame.index == 5 {
+ panic!("boom at five");
+ }
+ crate::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="40" height="20">
+ <rect x="0" y="0" width="20" height="20" fill="#ff0000" />
+ </svg>
+ )
+ }
+}
+
+#[derive(Debug)]
+struct Outro;
+
+impl Scene for Outro {
+ fn duration(&self) -> crate::Duration<'_> {
+ crate::Duration::Frames(10)
+ }
+
+ fn render_frame(&self, _: Frame, ctx: &FFramesContext) -> Svgr<'_> {
+ let _ = ctx.get_image("missing.png");
+ crate::svgr!(<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"></svg>)
+ }
+}
+
+struct TwoScenes;
+
+impl Video for TwoScenes {
+ const FPS: usize = 10;
+ const WIDTH: usize = 40;
+ const HEIGHT: usize = 20;
+ const BACKGROUND_COLOR: Color = Color::rgb(0, 0, 255);
+
+ fn duration(&self) -> crate::Duration<'_> {
+ crate::Duration::Auto
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+
+ fn define_scenes(&self) -> crate::Scenes<'_> {
+ crate::Scenes::from(vec![&Intro as &dyn Scene, &Outro as &dyn Scene])
+ }
+
+ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ ctx.render_scenes(&frame)
+ }
+}
+
+#[test]
+fn previews_paint_the_background_and_fit_the_output_size() {
+ let video = TwoScenes;
+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();
+ let mut renderer = CpuFrameRenderer::default();
+
+ let frame = previewer.render(0, &mut renderer).unwrap();
+ assert_eq!((frame.width, frame.height), (40, 20));
+ // Left half is the red rect, right half the video's blue background (not transparent).
+ assert_eq!(&frame.pixels[..4], &[255, 0, 0, 255]);
+ let right = (10 * 40 + 35) * 4;
+ assert_eq!(&frame.pixels[right..right + 4], &[0, 0, 255, 255]);
+
+ previewer.set_scale(0.5);
+ let small = previewer.render(0, &mut renderer).unwrap();
+ assert_eq!((small.width, small.height), (20, 10));
+ assert_eq!(&small.pixels[..4], &[255, 0, 0, 255]);
+ let right = (5 * 20 + 18) * 4;
+ assert_eq!(&small.pixels[right..right + 4], &[0, 0, 255, 255]);
+}
+
+#[test]
+fn panics_report_frame_time_and_scene() {
+ let video = TwoScenes;
+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();
+
+ match previewer.svg_tree(5) {
+ Err(FFramesRendererError::FramePanicked(panic)) => {
+ assert_eq!(panic.frame, 5);
+ assert_eq!(panic.seconds, 0.5);
+ assert_eq!(panic.scenes, vec!["Intro".to_owned()]);
+ assert!(panic.message.contains("boom at five"));
+ }
+ other => panic!("expected a frame panic, got {:?}", other.map(|_| ())),
+ }
+
+ let report = previewer.inspect(5).unwrap();
+ assert!(report.diagnostics.iter().any(
+ |d| matches!(&d.diagnostic, Diagnostic::Panic { message } if message.contains("boom"))
+ ));
+}
+
+#[test]
+fn inspect_reports_missing_media_and_empty_frames() {
+ let video = TwoScenes;
+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();
+ let frame = previewer.timeline().resolve_frame("Outro@2").unwrap();
+ assert_eq!(frame, 12);
+
+ let report = previewer.inspect(frame).unwrap();
+ assert_eq!(report.scenes, vec!["Outro".to_owned()]);
+ let kinds: Vec<&Diagnostic> = report.diagnostics.iter().map(|d| &d.diagnostic).collect();
+ assert!(
+ kinds
+ .iter()
+ .any(|d| matches!(d, Diagnostic::MissingMedia { name, .. } if name == "missing.png"))
+ );
+ assert!(kinds.iter().any(|d| matches!(d, Diagnostic::EmptyFrame)));
+}
diff --git a/fframes/src/tests.rs b/fframes/src/tests.rs
index 88b7b715..367f5828 100644
--- a/fframes/src/tests.rs
+++ b/fframes/src/tests.rs
@@ -72,12 +72,19 @@ fn test_audio_map_resolve() {
&crate::ScenesWithAudio::new(&video.define_scenes()),
&tb,
&audio_map,
- |_| Ok(24),
+ |_| Ok(1.),
)
.unwrap();
+ let resolved = audio_map
+ .unwrap()
+ .0
+ .into_iter()
+ .map(|track| (track.file, track.range))
+ .collect::<Vec<_>>();
+
assert_eq!(
- audio_map.unwrap().0,
+ resolved,
vec![
(
"audio1.mp3".to_string(),
diff --git a/fframes/src/time_spec.rs b/fframes/src/time_spec.rs
new file mode 100644
index 00000000..fbff8787
--- /dev/null
+++ b/fframes/src/time_spec.rs
@@ -0,0 +1,437 @@
+//! Addressing frames and frame ranges by frame number, time, percentage or scene.
+//!
+//! | spec | meaning |
+//! |-------------------|--------------------------------------------------------------|
+//! | `120`, `120f` | frame 120 |
+//! | `3.2s`, `1:05.5` | a timestamp (`m:ss`, `h:mm:ss` work too) |
+//! | `50%` | a fraction of the whole video |
+//! | `start`, `end` | the first / last frame of the video |
+//! | `Intro` | the first frame of the scene named `Intro` (case-insensitive)|
+//! | `#3` | the first frame of the scene with index 3 (0-based) |
+//! | `Intro[1]` | the second scene of type `Intro` |
+//! | `[email protected]` | 1.2 seconds into the scene (also `@12`, `@50%`, `@end`) |
+//!
+//! Ranges are `a..b` (end exclusive), `a..`, `..b`, or a single scene (`Intro`) for the whole
+//! scene. A scene name on the right side of `..` means the end of that scene.
+use crate::{ResolvedScenesTimeline, SceneInfo};
+use std::fmt;
+use std::ops::Range;
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum TimeSpecError {
+ Invalid(String),
+ UnknownScene {
+ query: String,
+ available: Vec<String>,
+ },
+ AmbiguousScene {
+ query: String,
+ indexes: Vec<usize>,
+ },
+ OutOfRange {
+ frame: usize,
+ duration: usize,
+ },
+ EmptyRange(Range<usize>),
+}
+
+impl fmt::Display for TimeSpecError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Invalid(spec) => write!(
+ f,
+ "can not parse \"{spec}\": use a frame (120), time (3.2s, 1:05), percentage (50%), \
+ scene (Intro, #3, [email protected]) or start/end"
+ ),
+ Self::UnknownScene { query, available } => {
+ write!(f, "no scene \"{query}\"")?;
+ if available.is_empty() {
+ write!(f, ", the video does not define scenes")
+ } else {
+ write!(f, ", available: {}", available.join(", "))
+ }
+ }
+ Self::AmbiguousScene { query, indexes } => write!(
+ f,
+ "\"{query}\" matches scenes {indexes:?}, use {query}[n] or #index"
+ ),
+ Self::OutOfRange { frame, duration } => {
+ write!(f, "frame {frame} is outside the video (0..{duration})")
+ }
+ Self::EmptyRange(range) => write!(f, "range {range:?} is empty"),
+ }
+ }
+}
+
+impl std::error::Error for TimeSpecError {}
+
+/// A scene as seen by the addressing: its name and resolved frames (overlaps included).
+#[derive(Debug, Clone)]
+pub struct TimelineScene {
+ pub index: usize,
+ /// Short name, e.g. `Intro` for `my_video::scenes::Intro`.
+ pub name: String,
+ /// Name as returned by `Scene::name`.
+ pub full_name: String,
+ pub frames: Range<usize>,
+}
+
+/// Everything needed to resolve time specs of one video.
+#[derive(Debug, Clone)]
+pub struct TimelineIndex {
+ pub fps: usize,
+ pub duration_in_frames: usize,
+ pub scenes: Vec<TimelineScene>,
+}
+
+/// `my_video::scenes::Intro<'_>` -> `Intro`
+pub fn short_scene_name(name: &str) -> &str {
+ let without_generics = name.split('<').next().unwrap_or(name);
+ without_generics
+ .rsplit("::")
+ .next()
+ .unwrap_or(without_generics)
+}
+
+impl TimelineIndex {
+ pub fn new(
+ fps: usize,
+ duration_in_frames: usize,
+ scenes: Option<&ResolvedScenesTimeline<'_>>,
+ ) -> Self {
+ Self {
+ fps,
+ duration_in_frames,
+ scenes: scenes
+ .map(|scenes| {
+ scenes
+ .timeline
+ .iter()
+ .map(|(range, info, scene)| TimelineScene {
+ index: info.index,
+ name: short_scene_name(scene.name()).to_owned(),
+ full_name: scene.name().to_owned(),
+ frames: range.clone(),
+ })
+ .collect()
+ })
+ .unwrap_or_default(),
+ }
+ }
+
+ pub fn duration_in_seconds(&self) -> f32 {
+ self.duration_in_frames as f32 / self.fps as f32
+ }
+
+ pub fn frame_to_seconds(&self, frame: usize) -> f32 {
+ frame as f32 / self.fps as f32
+ }
+
+ /// Scenes that are visible at a frame (two while scenes overlap).
+ pub fn scenes_at(&self, frame: usize) -> impl Iterator<Item = &TimelineScene> {
+ self.scenes
+ .iter()
+ .filter(move |s| s.frames.contains(&frame))
+ }
+
+ pub fn full_range(&self) -> Range<usize> {
+ 0..self.duration_in_frames
+ }
+
+ fn find_scene(&self, query: &str) -> Result<&TimelineScene, TimeSpecError> {
+ if let Some(index) = query.strip_prefix('#') {
+ let index: usize = index
+ .parse()
+ .map_err(|_| TimeSpecError::Invalid(query.to_owned()))?;
+ return self
+ .scenes
+ .get(index)
+ .ok_or_else(|| self.unknown_scene(query));
+ }
+
+ let (name, nth) = match query.strip_suffix(']').and_then(|q| q.split_once('[')) {
+ Some((name, nth)) => (
+ name,
+ Some(
+ nth.parse::<usize>()
+ .map_err(|_| TimeSpecError::Invalid(query.to_owned()))?,
+ ),
+ ),
+ None => (query, None),
+ };
+
+ // `intro`, `Intro`, `intro_scene` and `IntroScene` all name the scene `IntroScene`.
+ let normalize = |s: &str| {
+ let s = s.replace(['_', '-', ' '], "").to_lowercase();
+ match s.strip_suffix("scene") {
+ Some(name) if !name.is_empty() => name.to_owned(),
+ _ => s,
+ }
+ };
+ let wanted = normalize(name);
+ let matches: Vec<&TimelineScene> = self
+ .scenes
+ .iter()
+ .filter(|s| normalize(&s.name) == wanted || normalize(&s.full_name) == wanted)
+ .collect();
+
+ match (matches.as_slice(), nth) {
+ ([], _) => Err(self.unknown_scene(query)),
+ ([scene], None) => Ok(scene),
+ (all, None) => Err(TimeSpecError::AmbiguousScene {
+ query: name.to_owned(),
+ indexes: all.iter().map(|s| s.index).collect(),
+ }),
+ (all, Some(nth)) => all
+ .get(nth)
+ .copied()
+ .ok_or_else(|| self.unknown_scene(query)),
+ }
+ }
+
+ fn unknown_scene(&self, query: &str) -> TimeSpecError {
+ TimeSpecError::UnknownScene {
+ query: query.to_owned(),
+ available: self
+ .scenes
+ .iter()
+ .map(|s| format!("#{} {}", s.index, s.name))
+ .collect(),
+ }
+ }
+
+ /// Resolves a single point (`3.2s`, `Intro@50%`, ...) to a frame index inside the video.
+ pub fn resolve_frame(&self, spec: &str) -> Result<usize, TimeSpecError> {
+ let frame = self.resolve_point(spec.trim(), Side::Start)?;
+ if frame >= self.duration_in_frames {
+ return Err(TimeSpecError::OutOfRange {
+ frame,
+ duration: self.duration_in_frames,
+ });
+ }
+ Ok(frame)
+ }
+
+ /// Resolves a range (`10s..20s`, `Intro`, `Intro..Outro`, `5s..`) to frames, end exclusive,
+ /// clamped to the video.
+ pub fn resolve_range(&self, spec: &str) -> Result<Range<usize>, TimeSpecError> {
+ let spec = spec.trim();
+ let range = if let Some((start, end)) = spec.split_once("..") {
+ let start = if start.trim().is_empty() {
+ 0
+ } else {
+ self.resolve_point(start.trim(), Side::Start)?
+ };
+ let end = if end.trim().is_empty() {
+ self.duration_in_frames
+ } else {
+ self.resolve_point(end.trim(), Side::End)?
+ };
+ start..end
+ } else if matches!(spec, "all" | "*") {
+ self.full_range()
+ } else if let Ok(scene) = self.find_scene(spec) {
+ scene.frames.clone()
+ } else {
+ // A single point is a one-frame range.
+ let frame = self.resolve_point(spec, Side::Start)?;
+ frame..frame + 1
+ };
+
+ let range =
+ range.start.min(self.duration_in_frames)..range.end.min(self.duration_in_frames);
+ if range.is_empty() {
+ return Err(TimeSpecError::EmptyRange(range));
+ }
+ Ok(range)
+ }
+
+ fn resolve_point(&self, spec: &str, side: Side) -> Result<usize, TimeSpecError> {
+ match spec {
+ "start" => return Ok(0),
+ "end" => {
+ return Ok(match side {
+ Side::Start => self.duration_in_frames.saturating_sub(1),
+ Side::End => self.duration_in_frames,
+ });
+ }
+ _ => {}
+ }
+
+ if let Some((scene, offset)) = spec.split_once('@') {
+ let scene = self.find_scene(scene.trim())?;
+ let length = scene.frames.len();
+ let offset = match offset.trim() {
+ "start" => 0,
+ "end" => match side {
+ Side::Start => length.saturating_sub(1),
+ Side::End => length,
+ },
+ offset => self.parse_offset(offset, length)?,
+ };
+ return Ok(scene.frames.start + offset);
+ }
+
+ if let Some(offset) = self.try_parse_offset(spec, self.duration_in_frames) {
+ return Ok(offset);
+ }
+
+ let scene = self.find_scene(spec).map_err(|err| match err {
+ // Not a number and not a scene, the most useful message is the syntax.
+ TimeSpecError::UnknownScene { available, .. } if available.is_empty() => {
+ TimeSpecError::Invalid(spec.to_owned())
+ }
+ err => err,
+ })?;
+
+ Ok(match side {
+ Side::Start => scene.frames.start,
+ Side::End => scene.frames.end,
+ })
+ }
+
+ fn parse_offset(&self, spec: &str, length: usize) -> Result<usize, TimeSpecError> {
+ self.try_parse_offset(spec, length)
+ .ok_or_else(|| TimeSpecError::Invalid(spec.to_owned()))
+ }
+
+ /// Frames, seconds, clock time or a percentage of `length` frames.
+ fn try_parse_offset(&self, spec: &str, length: usize) -> Option<usize> {
+ let to_frames = |seconds: f64| (seconds * self.fps as f64).round().max(0.) as usize;
+
+ if let Some(percent) = spec.strip_suffix('%') {
+ let percent: f64 = percent.trim().parse().ok()?;
+ let frame = (length as f64 * percent / 100.).floor() as usize;
+ // 100% is the last frame, not one past it.
+ return Some(frame.min(length.saturating_sub(1)));
+ }
+
+ if let Some(seconds) = spec.strip_suffix("ms") {
+ return Some(to_frames(seconds.trim().parse::<f64>().ok()? / 1000.));
+ }
+
+ if let Some(seconds) = spec.strip_suffix('s') {
+ return Some(to_frames(seconds.trim().parse().ok()?));
+ }
+
+ if spec.contains(':') {
+ let mut seconds = 0.;
+ for part in spec.split(':') {
+ seconds = seconds * 60. + part.trim().parse::<f64>().ok()?;
+ }
+ return Some(to_frames(seconds));
+ }
+
+ spec.strip_suffix('f').unwrap_or(spec).parse().ok()
+ }
+}
+
+#[derive(Clone, Copy)]
+enum Side {
+ Start,
+ End,
+}
+
+impl<'a> crate::FFramesContext<'a, '_> {
+ /// Scenes active at a global frame together with their `Scene::name`. More than one scene
+ /// is active while scenes overlap.
+ pub fn scenes_at(
+ &self,
+ global_frame: usize,
+ ) -> impl Iterator<Item = (&'a SceneInfo, &'static str)> + 'a {
+ self.scenes
+ .into_iter()
+ .flat_map(|scenes| scenes.timeline.iter())
+ .filter(move |(range, _, _)| range.contains(&global_frame))
+ .map(|(_, info, scene)| (info, scene.name()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn index() -> TimelineIndex {
+ TimelineIndex {
+ fps: 30,
+ duration_in_frames: 300,
+ scenes: vec![
+ TimelineScene {
+ index: 0,
+ name: "Intro".into(),
+ full_name: "video::Intro".into(),
+ frames: 0..100,
+ },
+ TimelineScene {
+ index: 1,
+ name: "Speaker".into(),
+ full_name: "video::Speaker".into(),
+ frames: 90..200,
+ },
+ TimelineScene {
+ index: 2,
+ name: "Speaker".into(),
+ full_name: "video::Speaker".into(),
+ frames: 200..300,
+ },
+ ],
+ }
+ }
+
+ #[test]
+ fn points() {
+ let t = index();
+ assert_eq!(t.resolve_frame("120"), Ok(120));
+ assert_eq!(t.resolve_frame("120f"), Ok(120));
+ assert_eq!(t.resolve_frame("2s"), Ok(60));
+ assert_eq!(t.resolve_frame("500ms"), Ok(15));
+ assert_eq!(t.resolve_frame("0:02.5"), Ok(75));
+ assert_eq!(t.resolve_frame("50%"), Ok(150));
+ assert_eq!(t.resolve_frame("100%"), Ok(299));
+ assert_eq!(t.resolve_frame("end"), Ok(299));
+ assert_eq!(t.resolve_frame("intro"), Ok(0));
+ assert_eq!(t.resolve_frame("IntroScene"), Ok(0));
+ assert_eq!(t.resolve_frame("intro_scene@1s"), Ok(30));
+ assert_eq!(t.resolve_frame("#1"), Ok(90));
+ assert_eq!(t.resolve_frame("Speaker[1]"), Ok(200));
+ assert_eq!(t.resolve_frame("Intro@1s"), Ok(30));
+ assert_eq!(t.resolve_frame("Intro@50%"), Ok(50));
+ assert_eq!(t.resolve_frame("Intro@end"), Ok(99));
+ assert!(matches!(
+ t.resolve_frame("Speaker"),
+ Err(TimeSpecError::AmbiguousScene { .. })
+ ));
+ assert!(matches!(
+ t.resolve_frame("Outro"),
+ Err(TimeSpecError::UnknownScene { .. })
+ ));
+ assert!(matches!(
+ t.resolve_frame("11s"),
+ Err(TimeSpecError::OutOfRange { .. })
+ ));
+ }
+
+ #[test]
+ fn ranges() {
+ let t = index();
+ assert_eq!(t.resolve_range("1s..2s"), Ok(30..60));
+ assert_eq!(t.resolve_range("Intro"), Ok(0..100));
+ assert_eq!(t.resolve_range("#2"), Ok(200..300));
+ assert_eq!(t.resolve_range("Intro..#1"), Ok(0..200));
+ assert_eq!(t.resolve_range("5s.."), Ok(150..300));
+ assert_eq!(t.resolve_range("..1s"), Ok(0..30));
+ assert_eq!(t.resolve_range("0..1000"), Ok(0..300));
+ assert_eq!(t.resolve_range("all"), Ok(0..300));
+ assert_eq!(t.resolve_range("42"), Ok(42..43));
+ assert!(matches!(
+ t.resolve_range("2s..1s"),
+ Err(TimeSpecError::EmptyRange(_))
+ ));
+ }
+
+ #[test]
+ fn short_names() {
+ assert_eq!(short_scene_name("a::b::Intro<'_>"), "Intro");
+ assert_eq!(short_scene_name("Intro"), "Intro");
+ }
+}
diff --git a/fframes/src/video.rs b/fframes/src/video.rs
index 93363d84..bdd8214b 100644
--- a/fframes/src/video.rs
+++ b/fframes/src/video.rs
@@ -94,7 +94,7 @@ impl<'a> ResolvedScenesTimeline<'a> {
fn from_scenes(
time_base: &TimeBase,
scenes: &[SceneWithAudio<'a>],
- resolve_audio_duration: &impl Fn(&str) -> super::error::Result<usize>,
+ resolve_audio_duration: &impl Fn(&str) -> super::error::Result<f64>,
) -> Result<Self> {
let scenes_count = scenes.len();
let mut final_duration = 0;
@@ -144,7 +144,7 @@ pub struct ResolvedRenderingTimeline<'a, TAudioUnit: AudioTimelineUnit + std::fm
pub fn resolve_timeline<
'a,
TAudioUnit: AudioTimelineUnit + std::fmt::Debug + Copy,
- TFun: Fn(&str) -> super::error::Result<usize>,
+ TFun: Fn(&str) -> super::error::Result<f64>,
>(
duration: &Duration,
scenes: &ScenesWithAudio<'a>,
diff --git a/justfile b/justfile
index 3821ee37..f5042c08 100644
--- a/justfile
+++ b/justfile
@@ -77,6 +77,10 @@ hyperfine example *ARGS:
)
hyperfine $EXECUTABLE --warmup 2
+# Create a video crate in examples/ (flags: --format portrait --fps 60 --backend skia-metal ...)
+new name *ARGS:
+ cargo run -q -p cargo-fframes -- fframes new {{name}} --dir examples/{{name}} --yes {{ARGS}}
+
check-wasm example:
cd examples/{{example}}/editor/editor-bridge && cargo check --lib --target wasm32-unknown-unknown
diff --git a/media-dir-macro/src/lib.rs b/media-dir-macro/src/lib.rs
index 86fb7361..084e801f 100644
--- a/media-dir-macro/src/lib.rs
+++ b/media-dir-macro/src/lib.rs
@@ -221,7 +221,8 @@ enum MediaVariant {
impl MediaVariant {
fn from_extension(file_name: &str, path: &Path) -> Option<Self> {
match path.extension()?.to_str()? {
- "mp3" => Some(MediaVariant::Audio),
+ // Decoded to mono samples at compile time, 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),
"vtt" => Some(MediaVariant::Subtitles),
@@ -276,6 +277,7 @@ impl MediaFile {
let fframes_media::PreloadedAudioData {
samples,
sample_rate,
+ ..
} = fframes_media::PreloadedAudioData::decode_raw_file(None, &self.path).unwrap();
let bytes = bytemuck::cast_slice::<f32, u8>(&samples);
@@ -295,6 +297,7 @@ impl MediaFile {
)
},
sample_rate: #sample_rate,
+ right: None,
}
)
}
diff --git a/release.sh b/release.sh
index 46ccf1ce..457f8884 100644
--- a/release.sh
+++ b/release.sh
@@ -10,15 +10,22 @@ fi
cargo install cargo-edit
cargo set-version "$VERSION"
+# Crates first, in dependency order, so a failing npm publish can not hold back the Rust
+# release. `cargo publish` waits until each crate is in the index before the next one.
+for crate in \
+ webvtt-parser \
+ svgr-macro \
+ fframes-media \
+ media-dir-macro \
+ fframes \
+ fframes-editor-controller \
+ fframes-skia-renderer \
+ fframes-native-player \
+ cargo-fframes; do
+ echo "Publishing $crate"
+ (cd "$crate" && cargo publish --allow-dirty --no-verify)
+done
+
cd fframes-editor
yarn build:prod
yarn publish --no-git-tag-version --access public --new-version "$VERSION"
-
-cd ../webvtt-parser && cargo publish --allow-dirty --no-verify
-cd ../svgr-macro && cargo publish --allow-dirty --no-verify
-cd ../fframes-media && cargo publish --allow-dirty --no-verify
-cd ../media-dir-macro && cargo publish --allow-dirty --no-verify
-cd ../fframes && cargo publish --allow-dirty --no-verify
-cd ../fframes-editor-controller && cargo publish --allow-dirty --no-verify
-cd ../fframes-renderer && cargo publish --allow-dirty --no-verify
-cd ../fframes-skia-renderer && cargo publish --allow-dirty --no-verify
diff --git a/scripts/new-video.sh b/scripts/new-video.sh
new file mode 100755
index 00000000..08239254
--- /dev/null
+++ b/scripts/new-video.sh
@@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+# Creates a new fframes video project.
+#
+# curl -fsSL https://raw.githubusercontent.com/dmtrKovalenko/fframes/main/scripts/new-video.sh | bash -s -- my-video
+#
+# Every argument is passed to `cargo fframes new`, e.g.:
+#
+# ... | bash -s -- my-video --format portrait --fps 60 --backend skia-metal --yes
+#
+# Without --yes it asks for anything not passed when a terminal is attached. It installs
+# `cargo-fframes` from crates.io if it is missing (FFRAMES_FROM_GIT=1 installs the `main`
+# branch instead) and checks the system dependencies (Rust, ffmpeg, pkg-config) first.
+set -euo pipefail
+
+REPO="${FFRAMES_REPO:-https://github.com/dmtrKovalenko/fframes}"
+BRANCH="${FFRAMES_BRANCH:-main}"
+
+say() { printf '\033[1m%s\033[0m\n' "$*" >&2; }
+fail() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
+
+command -v cargo >/dev/null 2>&1 || fail "Rust is not installed. Install it from https://rustup.rs and run this again."
+
+missing=()
+command -v pkg-config >/dev/null 2>&1 || missing+=("pkg-config")
+command -v ffmpeg >/dev/null 2>&1 || missing+=("ffmpeg (for ffprobe/ffplay; the renderer links its own ffmpeg)")
+if ((${#missing[@]})); then
+ say "Optional tools not found: ${missing[*]}"
+ case "$(uname -s)" in
+ Darwin) say " brew install pkg-config ffmpeg nasm" ;;
+ Linux) say " sudo apt install pkg-config ffmpeg nasm clang libfontconfig1-dev" ;;
+ esac
+fi
+
+if ! cargo fframes --help >/dev/null 2>&1 || [[ "${FFRAMES_REINSTALL:-}" == "1" ]]; then
+ if [[ "${FFRAMES_FROM_GIT:-}" == "1" ]]; then
+ say "Installing cargo-fframes from $REPO ($BRANCH)"
+ cargo install --locked --git "$REPO" --branch "$BRANCH" cargo-fframes
+ else
+ say "Installing cargo-fframes from crates.io"
+ cargo install --locked cargo-fframes
+ fi
+fi
+
+# When piped from curl stdin is the script itself, give the prompts the terminal back.
+if [[ ! -t 0 ]] && [[ -r /dev/tty ]] && [[ " $* " != *" --yes "* ]] && [[ " $* " != *" -y "* ]]; then
+ exec cargo fframes new "$@" </dev/tty
+fi
+exec cargo fframes new "$@"
diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.md
new file mode 100644
index 00000000..996c234d
--- /dev/null
+++ b/skills/fframes-video/SKILL.md
@@ -0,0 +1,252 @@
+---
+name: fframes-video
+description: >-
+ Create, animate, review and render videos in code with fframes (Rust, SVG scenes, ffmpeg
+ encoding, Skia GPU rendering). Use whenever the user wants a video, animation, motion graphic,
+ explainer, promo, social clip, title card, podcast visual, lyric/caption video or any rendered
+ .mp4/.webm made programmatically, or asks to change, fix, speed up or check an fframes video.
+ Covers installing fframes, creating a project, designing good-looking motion, sound (music,
+ voice, SFX, loudness), watching it in a real-time preview window, and checking the result
+ without watching it: frames and contact sheets as PNG, automatic problem detection, loudness
+ numbers, fast draft and range renders.
+---
+
+# Making videos with fframes
+
+[fframes](https://github.com/dmtrKovalenko/fframes) is a Rust library that renders video from
+code. A video is a Rust struct with a `render_frame(frame) -> Svgr` method: for every frame it
+returns an SVG tree, built with the `svgr!` macro (SVG markup with `{rust expressions}`).
+Scenes split the timeline, `timeline!` and springs animate values, an audio map places sound,
+and ffmpeg encodes the result.
+
+Each project gets a command line (from `fframes::cli`). Use it for everything: render a video,
+open the real-time preview window, and look at frames, contact sheets and loudness numbers as
+files you can read. Read `references/design.md` before designing, `references/api.md` while
+writing code and `references/audio.md` for sound.
+
+## 1. Install
+
+Rust from <https://rustup.rs>, then the system libraries ffmpeg is built with:
+
+```bash
+# macOS
+brew install pkg-config ffmpeg x264 x265 opus nasm ninja
+# Debian / Ubuntu
+sudo apt-get install -y yasm nasm ffmpeg libx264-dev libx265-dev libopus-dev libclang-dev clang ninja-build libvpx-dev libasound2-dev
+# Arch
+sudo pacman -S ninja yasm nasm ffmpeg x264 x265 opus clang
+```
+
+Windows links a prebuilt FFmpeg 9 shared build instead (set `FFMPEG_DIR` to the unzipped
+`ffmpeg-n9.0-latest-win64-gpl-shared` build from BtbN/FFmpeg-Builds, add its `bin` to `PATH`,
+install LLVM with `winget install LLVM.LLVM` and set `LIBCLANG_PATH`). Details are in the
+fframes README.
+
+## 2. Create a project
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/dmtrKovalenko/fframes/main/scripts/new-video.sh | bash -s -- my-video --yes
+# or install the generator once and use it directly:
+cargo install --locked cargo-fframes
+cargo fframes new my-video --format landscape --fps 30 --yes
+```
+
+Options: `--template single-scene|multi-scene`, `--format landscape|portrait|square|uhd`,
+`--fps`, `--title`, `--backend`, `--dir`. The project depends on the fframes release that
+matches the installed `cargo-fframes`; `--git` uses the repository's `main` branch instead. Always pass `--yes` so nothing waits for input.
+
+Templates:
+- `single-scene` (default): one scene with a greeting that springs in over a moving glow. It
+ adapts to every format; start here for single-shot clips, title cards and portrait video.
+- `multi-scene`: two scenes (a product announcement and an animated chart) on a 16:9 grid,
+ with a shared footer and progress bar. Start here for anything with several scenes; it only
+ accepts `landscape` and `uhd`.
+
+**Use the Skia GPU backend (the default).** `cargo fframes new` picks Skia on Metal (macOS) or
+Vulkan (Linux, Windows). It renders about 10x faster than the CPU backend and gives you the
+real-time `preview` window. The first build compiles Skia and ffmpeg from source and takes
+about 20 minutes, so start it right away and write the video while it runs:
+
+```bash
+cd my-video && cargo build --release # run in the background, it is slow only once
+```
+
+`--backend cpu` needs no Skia build but has no preview window; pick it only when there is no
+GPU or no time for the first build.
+
+The project renders as generated:
+
+```
+my-video/
+ src/lib.rs # the video (from the template)
+ src/main.rs # the command line
+ media/ # fonts, images and audio compiled into the binary (DM Sans to start)
+ tests/frames.rs # frame snapshots and a check of every frame for problems
+ README.md # the commands below
+```
+
+Every command below is `cargo run --release -- <command>`. Define a short alias:
+
+```bash
+R="cargo run --release --"
+```
+
+## 3. The loop
+
+After every change:
+
+1. `$R timeline` lists the scenes with their frame and second ranges, and every audio track.
+ Check structure and pacing here before looking at pixels.
+2. `$R inspect` checks a frame every 0.25 s plus the first and last frame of every scene. It
+ reports missing images, fonts or glyphs, text cut off by the edge of the canvas, invalid
+ SVG (zero-sized rectangles, bad radii), broken transforms and panics, each with its time
+ and scene. It exits with code 2 on errors. Fix everything it reports. A warning that only
+ 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.
+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.
+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
+ play/pause, h/l seek a second, j/k step a frame, q quit). It blocks until closed, so start
+ it in the background or ask the user to run it. Offer it whenever the user wants to see
+ the video; you review with strips and frames, the user watches in the preview.
+7. `$R render Intro --draft` encodes one scene at half resolution in about a second;
+ `$R render` writes the final `out.mp4`.
+
+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.
+- Add `--json` when parsing output: the result goes to stdout, progress to stderr.
+- Keep `--release`: debug builds render many times slower.
+- `cargo test` compares settled frames with approved snapshots in `_frame_snapshots/` and
+ fails if any frame has warnings. The first run only creates the snapshots: look at the PNGs
+ before committing them, a created baseline is not a reviewed one.
+ `FFRAMES_UPDATE_SNAPSHOTS=1 cargo test` accepts intended changes. Snapshot the middle of a
+ scene (`Intro@3s`), not its end where it fades out.
+
+### Addressing time
+
+`120` (frame), `3.2s`, `500ms`, `1:05.5`, `50%`, `start`, `end`; scenes by struct name, `Intro`
+(also matches `IntroScene`, case-insensitive), `#3` (scene index), `Intro[1]` (second scene of
+that type); inside a scene `[email protected]`, `Intro@12`, `Intro@50%`, `Intro@end`. Ranges: `a..b`
+(end exclusive), `a..`, `..b`, `all`, or a scene name for the whole scene. Separate several
+times with commas.
+
+### All commands
+
+| 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 |
+| `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 |
+| `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 |
+
+### Browser editor
+
+fframes also has a web editor with a timeline and scrubbing, useful when a person wants to
+tweak a video interactively. It runs the video compiled to WebAssembly and needs Node.js plus
+`wasm-pack`; the setup is the `editor/` folder of the hello-world example in the fframes
+repository (<https://github.com/dmtrKovalenko/fframes/tree/main/examples/hello-world>).
+Mention it when the user asks for a GUI editor. For watching use `preview`, and for your own
+review use the CLI.
+
+## 4. Writing the video
+
+```rust
+impl Video for MyVideo<'_> {
+ const FPS: usize = 30; const WIDTH: usize = 1920; const HEIGHT: usize = 1080;
+ fn duration(&self) -> Duration<'_> { Duration::Auto } // sum of the scenes
+ fn audio(&self) -> AudioMap<'_> { AudioMap::none() } // see references/audio.md
+ fn define_scenes(&self) -> Scenes<'_> { Scenes::from(vec![&self.intro as &dyn Scene, &self.main]) }
+ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ fframes::svgr!(<svg xmlns="http://www.w3.org/2000/svg" width={Self::WIDTH} height={Self::HEIGHT}>
+ <rect width={Self::WIDTH} height={Self::HEIGHT} fill="#0b1020" />
+ {ctx.render_scenes(&frame)}
+ </svg>)
+ }
+}
+```
+
+- One scene per idea, 2-6 s each. Inside a scene `frame.seconds()` counts from the scene start.
+- Animate with `frame.animate(&fframes::timeline!(at 0.2 => 0.8, animate 0.0_f32 => 1.0, Easing::EaseOut))`
+ and springs, `Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 }`. Leave the end
+ time off a spring so it settles on its own.
+- Markup without `{}` is cached across frames. Keep decoration literal and put animated values
+ on a wrapping `<g transform={..} opacity={..}>`.
+- `render_frame` runs for every frame on several threads: no panics, file reads or heavy work
+ in it. Prepare data in the constructor or a `OnceLock`. Media lookups return `Option`; fall
+ back to `Svgr::empty()` instead of `expect`.
+- Put every font file in `media/` and refer to it by family name, with a numeric
+ `font-weight`.
+- Measure text rather than guess: `frame.text_width`, `frame.text_fit(.., TextOverflow::Ellipsis)`,
+ `frame.text_break_lines` for paragraphs. `inspect` catches text leaving the canvas, not text
+ leaving its own box, so check boxes in a `frame` PNG.
+- GPU shaders (SkSL or Shadertoy GLSL) run on the Skia backend through `fframes::Shader`; see
+ `references/api.md`.
+
+## 5. Making it look good
+
+The short version of `references/design.md`:
+
+- One idea per scene, large type, margins of 8-10% of the width, two or three colors plus
+ neutrals and one accent for emphasis.
+- Elements enter with a spring or ease-out over 300-600 ms and leave faster, with ease-in over
+ 200-300 ms. Related items stagger by 60-120 ms. Give the viewer 1-2 s to read after the
+ motion settles, and never move everything at once.
+- Cross-fade scenes (`fn overlap(&self) -> Overlap { Overlap::Previous(0.4) }`) or carry an
+ element across the cut. A slow background drift keeps holds from looking frozen.
+- At 1920x1080: titles 96-140 px, body 44-60 px, at most about 8 words per line and 3 lines per
+ card. Portrait 1080x1920 is watched on a phone: same pixel sizes or larger, content inside
+ the middle 80% because platform UI covers the top and bottom.
+- Check every scene against the checklist in `references/design.md` with a strip.
+
+## 6. Sound
+
+Put audio files in `media/` (compiled in, mono) or load a folder at runtime with
+`MediaDirectory` for stereo, then place them:
+
+```rust
+AudioMap::from([
+ AudioTrack::new("music.mp3", Second(0.)..Eof).gain_db(-18.).fade_in(1.).fade_out(2.).duck_under_voice(),
+ AudioTrack::new("vo.wav", Second(0.6)..Eof).voice(),
+ AudioTrack::new("whoosh.wav", Second(3.1)..Eof).gain_db(-8.),
+])
+```
+
+Time sound effects from the same constants that drive the animation. Check levels with
+`$R audio analyze --waveform w.png` (about -14 LUFS integrated for web video, true peak below
+-1 dBTP, no unintended silence) and `$R audio at 3.1s` for what plays at an event. Then let
+the user listen in `$R preview`.
+
+## 7. Finish
+
+1. `$R inspect --fail-on warning` passes, or the remaining warnings are understood entrances.
+2. A strip of every scene looks right and key frames are checked at full size.
+3. `$R audio analyze` shows sensible levels.
+4. `$R render -o out.mp4`, then confirm size, frame count and audio with
+ `ffprobe -v error -show_entries stream=codec_type,width,height,nb_frames,duration out.mp4`.
+5. Run `cargo test` if the project keeps snapshots, and commit `_frame_snapshots/*.png`.
+
+Tell the user the output path, the duration, the path of a strip image and the `preview`
+command to watch it.
+
+## Troubleshooting
+
+- Build fails in `ffmpeg-sys-next`: a system library from step 1 is missing (`nasm`,
+ `pkg-config`, the codec `-dev` packages).
+- Build fails in the Skia bindings (`fframes-skia-bindings`) with bindgen or libclang errors: point `LIBCLANG_PATH` at a
+ working libclang (on macOS Xcode's:
+ `export LIBCLANG_PATH=$(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib`).
+- Text renders in the wrong font or not at all: `inspect` shows "No match for ... font-family";
+ add the font file to `media/` and use its exact family name.
diff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.md
new file mode 100644
index 00000000..3614a0f4
--- /dev/null
+++ b/skills/fframes-video/references/api.md
@@ -0,0 +1,206 @@
+# fframes API cheat sheet
+
+Examples in the fframes repository worth reading: [motion-graphics](https://github.com/dmtrKovalenko/fframes/tree/main/examples/motion-graphics)
+(springs, text fitting), [beta](https://github.com/dmtrKovalenko/fframes/tree/main/examples/beta) (scenes, images), [audio-announce](https://github.com/dmtrKovalenko/fframes/tree/main/examples/audio-announce)
+(audio visualisation, video sources), [teej-podcast](https://github.com/dmtrKovalenko/fframes/tree/main/examples/teej-podcast) (Skia backend, stereo
+media loaded at runtime), [shaders](https://github.com/dmtrKovalenko/fframes/tree/main/examples/shaders) and [neon-triangle](https://github.com/dmtrKovalenko/fframes/tree/main/examples/neon-triangle) (GPU
+shaders).
+
+## svgr!
+
+SVG markup with Rust in braces. Attributes and text children take strings, numbers, `Color`,
+`Transform`, another `Svgr`, or a `Vec<Svgr>` / iterator collected to a `Vec`.
+
+```rust
+fframes::svgr!(
+ <g transform={Transform::translate(x, y)} opacity={opacity}>
+ // comments are `//` lines
+ <rect x="0" y="0" width={w} height="80" rx="16" fill={ACCENT} />
+ <text x="24" y="54" font-family="Inter" font-size="40" font-weight="600" fill="#fff">
+ "Label: " {value.to_string()}
+ </text>
+ {items} // Vec<Svgr>
+ </g>
+)
+```
+
+- Literal text children are quoted strings. `Svgr::empty()` renders nothing.
+- Subtrees without `{}` are hashed at compile time and cached by the renderers: keep static
+ decoration static, wrap animated values around it.
+- Gradients, clip paths, masks, filters go into `<defs>` like normal SVG and are referenced
+ with `url(#id)`. Give ids unique names per component instance if repeated.
+- Images: `href={self.media.logo_png.href()}` (field named after the file in `media/`) or
+ `ctx.get_image("logo.png").map(|i| i.href())`.
+
+## Video and Scene
+
+```rust
+impl Video for MyVideo<'_> {
+ const FPS: usize = 30;
+ const WIDTH: usize = 1920;
+ const HEIGHT: usize = 1080;
+ const BACKGROUND_COLOR: Color = Color::BLACK; // painted under every frame
+ fn duration(&self) -> Duration<'_>; // Seconds(f32), Frames(usize), FromAudio("f"), FromVideo("f"), Auto, a + b
+ fn audio(&self) -> AudioMap<'_>; // AudioMap::none() or tracks
+ fn define_scenes(&self) -> Scenes<'_>; // optional
+ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a>;
+}
+
+impl Scene for Intro<'_> {
+ fn duration(&self) -> Duration<'_>;
+ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a>;
+ fn overlap(&self) -> Overlap { Overlap::Previous(0.4) } // optional cross-fade window
+ fn audio(&self) -> AudioMap<'_> { .. } // optional, relative to the scene
+}
+```
+
+- Scenes must be zero sized or fields of the video (`&self.intro`). Scene names in the CLI
+ are the struct names (`Intro`, `IntroScene` both match `IntroScene`).
+- `ctx.render_scenes(&frame)` in the video's `render_frame` renders the active scene(s).
+- `frame.index` / `frame.seconds()` are scene relative inside a scene; `frame.global_index`
+ is the video frame. `ctx.get_scene_info(&self.intro)` gives a scene's resolved range.
+- `ctx.current_video_size` is the output size (scaled by `--scale`); trees drawn at
+ `WIDTH`x`HEIGHT` are scaled automatically.
+
+## Animation
+
+```rust
+use fframes::{Transform, animation::Easing};
+
+// keyframes: at START [=> END | , duration D], animate FROM => TO, EASING
+let x = frame.animate(&fframes::timeline!(
+ at 0.0, animate -80.0_f32 => 0.0, Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 },
+ at 2.5 => 2.8, animate 0.0_f32 => 60.0, Easing::EaseIn,
+));
+let color = frame.animate(&fframes::timeline!(at 0.0 => 1.0, animate Color::hex("#fff") => Color::hex("#0ea5e9"), Easing::EaseInOut));
+let t = frame.animate(&fframes::timeline!(at 0.0 => 0.5, animate Transform::scale(0.9) => Transform::scale(1.0), Easing::EaseOut));
+let drift = frame.animate_loop(&fframes::timeline!(at 0.0 => 8.0, animate 0.0_f32 => 1.0, Easing::Linear));
+```
+
+- Before the first keyframe the value is `from`, after the last it stays at `to`.
+- Values: `f32`, `f64`, `Color`, `Transform`.
+- Runtime start times (staggering, data driven): `frame.animate_runtime(AnimateRuntimeInput {
+ on_second, from, to, animation_runtime: &AnimationRuntime::new(duration, &easing) })`.
+ For springs pass a generous duration (3.0): the spring stops at its own settle time.
+- Easing: `Linear`, `EaseIn`, `EaseOut`, `EaseInOut`, `CubicBezier(x1, y1, x2, y2)`, `Spring {..}`.
+- `Transform { translate_x, translate_y, scale: Scale { x, y }, rotate, .. }`,
+ `Transform::translate(x, y)`. Scale around a point by translating by `p * (1 - s)`.
+
+## Text
+
+```rust
+use fframes::{BreakLinesOpts, FontQuery, TextAlign, TextOverflow};
+let font = FontQuery { family: "Inter", size: 48, weight: 500, ..Default::default() };
+let w: Option<usize> = frame.text_width(ctx, font, "Title");
+// text_fit returns Option<Cow<str>>; svgr! needs a String or &str, so convert it
+let fitted: String = frame
+ .text_fit(ctx, font, long_title, 900, TextOverflow::Ellipsis)
+ .map(|text| text.into_owned())
+ .unwrap_or_else(|| long_title.to_owned());
+// text_break_lines returns Option<Svgr>: a ready <text> with one <tspan> per line
+let paragraph: Svgr = frame
+ .text_break_lines(ctx, text, BreakLinesOpts {
+ font, width: 900, x: 160, y: 400, align: TextAlign::Left, fill: "#0f172a", ..Default::default()
+ })
+ .unwrap_or_default();
+```
+
+The helpers take `&mut frame` and return `None` when the font is not loaded; use the same
+family, size and weight in the `<text>` attributes. `text-anchor="middle"` centers on `x`.
+
+## Media
+
+- `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.
+- 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 })`
+ then `<image href={video_frame.href()} .../>` (needs the `compile-time-svgtree` feature).
+- Subtitles: `ctx.get_subtitles("subs.vtt").and_then(|s| frame.get_subtitle_phrase(s))`.
+- Audio spectrum: `frame.visualize_audio_frame(VisualizeFrameInput { audio, sample_size: SampleSize::S256, smooth_level: 4, window: Some(WindowFunction::Hann) })`.
+
+## GPU shaders (Skia backend)
+
+`fframes::Shader` runs SkSL, or pasted Shadertoy GLSL, on the Skia GPU surface while the frame
+is drawn. SVG transforms, clips, masks and opacity apply to the layer like to any element.
+
+```rust
+use fframes::{Shader, ShaderUniforms};
+
+// once, in the constructor (the renderer compiles and caches it)
+let aurora = Shader::sksl(include_str!("shaders/aurora.sksl")); // half4 main(float2 coord)
+let torus = Shader::shadertoy(include_str!("shaders/torus.glsl")); // void mainImage(out vec4, in vec2)
+
+// in render_frame
+let layer = self.aurora.draw(&frame, ShaderUniforms::new()
+ .float("uSpeed", 0.6)
+ .color("uTint", frame.animate(&tint)));
+fframes::svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080" />)
+```
+
+- Built-in uniforms when declared: `iResolution` (the `<image>` size), `iTime`, `iTimeDelta`,
+ `iFrame`. Pass images with `.image("iChannel0", photo)` where `photo` comes from
+ `ctx.get_image("photo.jpg")` (an `Option`: return `Svgr::empty()` when it is missing).
+- SkSL follows GLSL ES 2: constant loop bounds, no `while`, no dynamic array indexing, no
+ preprocessor. `Shader::shadertoy` expands simple `#define`s; rewrite macros with arguments
+ and `texture()` calls.
+- A compile error is logged once and the layer is skipped. Test compilation with
+ `fframes_skia_renderer::render::compile_shader(&shader)`.
+- Only the Skia backend runs shaders; the CPU backend draws nothing in their place.
+
+## Rendering from code
+
+```rust
+let options = RenderOptions {
+ media: Some(&media),
+ frame_range: Some(10 * 30..20 * 30), // optional: part of the video, audio cut to match
+ scale_resolution: 0.5, // optional: half size
+ audio_mix: AudioMixOptions::default(), // limiter -1 dBFS, de-click fades
+ default_font: "Inter",
+ ..Default::default()
+};
+fframes::render("out.mp4", &video, fframes::cpu::CpuRenderingBackend::default(), &options)?;
+
+// many frames quickly, and checks:
+let mut previewer = fframes::Previewer::new(&video, &options)?;
+let frame = previewer.timeline().resolve_frame("[email protected]")?;
+let (png, report) = previewer.render_inspected(frame, &mut fframes::CpuFrameRenderer::default())?;
+png.save_png("intro.png")?;
+let svg = previewer.svg(frame)?;
+let problems = previewer.inspect(frame)?.diagnostics;
+fframes::snapshot::assert_frames(&mut previewer, &mut renderer, &["Intro@end"], &Default::default());
+```
+
+Skia: `SkiaFFramesRenderer::new_metal(&SkiaMetalCtx::new(W, H)?, SkiaPipelineConfig::default())`
+(`fframes_skia_renderer` feature `metal`) or `new_vulkan` with `SkiaVulkanCtx` (feature
+`vulkan`). `backend.frame_renderer()`
+returns a renderer for single frames that matches the backend (Skia on the GPU for Skia).
+
+## The project's command line
+
+`main.rs` builds it with `fframes::cli::new`; everything after it is optional:
+
+```rust
+let args = fframes::cli::parse::<MyArgs>(); // only when the video uses flags of its own
+let video = MyVideo::new(&media, &args.app.title);
+fframes::cli::new(&video, options)
+ .args(args)
+ .backend(SkiaFFramesRenderer::new_metal(&gpu, SkiaPipelineConfig::default())?)
+ .preview(fframes_native_player::cli_preview)
+ .default_output("out.webm")
+ .run()
+```
+
+## Gotchas
+
+- Zero width/height rects and zero radius circles are invalid SVG and are skipped (inspect
+ reports them): animate from `0.5`, not `0`.
+- A panic in `render_frame` stops the render; the error names frame, second and scene.
+- `font-weight` must be numeric (`600`) or `normal`/`bold`. Unknown families fall back
+ silently in the renderer, `inspect` reports "No match for ... font-family".
+- `Color::TRANSPARENT` backgrounds need an alpha capable encoder and pixel format.
+- Heavy filters (`feGaussianBlur`, `feDropShadow`) on animated subtrees are slow on the CPU
+ backend: keep them static or use Skia.
+- Durations from audio (`Duration::FromAudio`, `Eof`) need the file in the media provider;
+ missing files fail early with `RequiredAudioNotFound`.
diff --git a/skills/fframes-video/references/audio.md b/skills/fframes-video/references/audio.md
new file mode 100644
index 00000000..2a77cb2e
--- /dev/null
+++ b/skills/fframes-video/references/audio.md
@@ -0,0 +1,77 @@
+# Sound for fframes videos
+
+You cannot hear the result. Place sound from the timeline, check it with the numbers below,
+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).
+- Stereo music, voice-overs and anything large: a folder loaded at runtime keeps stereo:
+
+```rust
+let audio_dir = fframes::MediaDirectory::read_folder("audio")?;
+let audio = audio_dir.process_media_source()?;
+let media = fframes::CombinedMediaProvider::from([&static_media as &dyn fframes::MediaProvider, &audio]);
+// RenderOptions { media: Some(&media), .. }
+```
+
+- Generating placeholder sounds without assets: `sox` (`sox -n pop.wav synth 0.08 sine 880 fade 0 0.08 0.07`)
+ or `ffmpeg -f lavfi -i "sine=frequency=440:duration=0.2" tick.wav`. Tell the user they are
+ placeholders.
+
+## Placing tracks
+
+```rust
+use fframes::{AudioMap, AudioTrack, AudioTimestamp::*, Ducking, FadeCurve};
+
+fn audio(&self) -> AudioMap<'_> {
+ AudioMap::from([
+ AudioTrack::new("music.mp3", Second(0.)..Eof).gain_db(-18.).fade_in(1.5).fade_out(2.5)
+ .fade_curve(FadeCurve::EqualPower).duck_under_voice(),
+ AudioTrack::new("vo_01.wav", Second(0.6)..Eof).voice(),
+ AudioTrack::new("vo_02.wav", Second(6.2)..Eof).voice(),
+ AudioTrack::new("whoosh.wav", Second(TRANSITION_AT - 0.15)..Eof).gain_db(-10.),
+ AudioTrack::new("pop.wav", Second(ITEM_AT + 0.05)..Eof).gain_db(-12.).pan(0.3),
+ AudioTrack::new("take.wav", Second(20.)..Second(24.)).offset(3.2), // file 3.2s..7.2s
+ ])
+}
+```
+
+- Timestamps: `Second(f32)` (sample accurate), `Frame(n)`, `Time { minutes, seconds }`,
+ `Eof` as the end (= play to the end of the file), `DurationOfAudio("f")`, and `+`/`-`.
+- Scenes can have their own `fn audio` with times relative to the scene start: sounds move
+ with the scene when durations change.
+- Derive SFX times from the same constants that drive the animation. Whooshes start ~150 ms
+ before the movement peak; pops/clicks land on the frame the element appears (+0-50 ms).
+- Gain guidelines relative to a normalised voice at 0 dB: music under voice -16 to -22 dB
+ (plus ducking), music alone -8 to -12 dB, UI SFX -8 to -14 dB, whooshes -8 to -12 dB.
+- `duck_under_voice()` = -12 dB, 0.2 s attack before the voice, 0.3 s hold, 0.8 s release,
+ voice gaps under 0.8 s merged. `.duck(Ducking { depth_db: -15., ..Default::default() })` to tune.
+- The master bus sums linearly and limits peaks at -1 dBFS (`RenderOptions::audio_mix`), so
+ loud overlaps do not distort, but a limiter working hard squashes the mix: fix gains rather
+ than relying on it.
+
+## Checking without listening
+
+```bash
+$R timeline # every track with its seconds, gain, fades, voice/ducked
+$R audio at 3.1s,6.2s # what plays at an event, position in the file, level, ducking
+$R audio analyze # loudness report, per scene
+$R audio analyze --waveform w.png # read the image: waveform, loudness curve, scene lines, cue ticks
+$R audio render Intro -o intro.wav # the mix of one scene, if the user wants to listen
+```
+
+Targets for the report:
+- Integrated loudness: about -14 LUFS for web/social (-16 for podcasts, -23 for broadcast).
+ More than 2 LU off: adjust gains (all tracks) or `audio_mix.master_gain_db`.
+- True peak at or below -1 dBTP; `clipped_samples` 0.
+- Loudness range 4-10 LU for music videos and explainers; far higher means quiet and loud
+ parts need balancing.
+- `silent_ranges` only where silence is intended (an unexpected one means a track ends early
+ or a file is missing: check `missing_files` and `timeline`).
+- Per scene: scenes with voice should be within ~2 LU of each other.
+
+The waveform image shows cue ticks (yellow) under the scene lines (purple): each sound should
+sit where its visual event is. For a precise check use `audio at` on the event time and a
+`frame` of the same time.
diff --git a/skills/fframes-video/references/design.md b/skills/fframes-video/references/design.md
new file mode 100644
index 00000000..085f3f88
--- /dev/null
+++ b/skills/fframes-video/references/design.md
@@ -0,0 +1,126 @@
+# Designing good-looking fframes videos
+
+Generated videos usually go wrong the same ways: too much text, everything moving at once,
+linear motion, no hierarchy, cramped margins and random colors. A simple design without those
+problems already looks finished.
+
+## Pacing
+
+- Reading time: about 3 words per second plus 1 s to notice the text. A 9 word line needs
+ ~4 s on screen after it finished animating in.
+- Scene lengths: title 2.5-4 s, content 4-8 s, outro 2-3 s. Social clips: first frame must
+ already show something (no fade from black) and the hook lands in the first 1.5 s.
+- Entrances take 0.3-0.6 s, exits 0.2-0.3 s. Holds (nothing moves) of 1-3 s are good; keep a
+ slow background drift so they do not look frozen.
+- Sync cuts and entrances to the beat or the voice (see audio.md).
+
+## Layout
+
+- Safe margins: 8-10% of the width on each side for landscape; portrait keeps content inside
+ x 8-92%, y 12-78% (platform UI covers the top and bottom).
+- Align to a grid: pick 2-3 x positions (left edge, center, 60%) and reuse them. Left-aligned
+ text blocks read better than centered paragraphs; center only short titles.
+- Whitespace is the most effective "design": one element per scene is fine.
+- Vertical rhythm: line height 1.2-1.35 x font size; gaps between groups 2x the line gap.
+
+## Typography
+
+- One family (two at most: a display face for titles, a text face for body). Ship the files
+ in `media/`. Good free choices: Inter, DM Sans, Manrope, Space Grotesk (UI/tech), Playfair
+ Display / Fraunces (editorial), JetBrains Mono (code), Bebas Neue (condensed display).
+- Sizes at 1920x1080: hero 140-200, title 96-120, subtitle 44-56, body 44-60, caption 28-34.
+ Never below 28 px. Portrait at 1080 wide uses about the same pixel sizes.
+- Weights: title 600-800, body 400-500. Letter-spacing: `-1` to `-3` for big titles,
+ `+2` to `+6` for small caps labels.
+- Max ~8 words per line, ~3 lines per card. Measure with `frame.text_width` or wrap with
+ `frame.text_break_lines`; shrink to fit with a loop over sizes (as in the
+ [motion-graphics quote card](https://github.com/dmtrKovalenko/fframes/tree/main/examples/motion-graphics/src/quote_card.rs)) and memoize the result
+ in a `OnceLock`. Generated projects include a `FittedSizes` helper that does this.
+
+## Color
+
+- A background, a foreground (text), one accent, one or two supporting tints. Example sets:
+ - Light: bg `#f8fafc`, text `#0f172a`, muted `#475569`, accent `#6366f1`, tint `#c7d2fe`.
+ - Dark: bg `#0b1020`, text `#e2e8f0`, muted `#94a3b8`, accent `#22d3ee`, tint `#1e293b`.
+ - Warm: bg `#fff7ed`, text `#1c1917`, accent `#ea580c`, tint `#fed7aa`.
+- Contrast: body text at least 4.5:1 against its background. Check suspicious frames at full
+ size.
+- Depth without effects: a large soft radial gradient behind content, slightly different
+ surface color for cards, a 1-2 px border of a lighter tint. Blur and drop shadow filters are
+ expensive on the CPU backend; keep them on static subtrees (no `{}` inside) so they are
+ cached, or use the Skia backend.
+
+## Motion
+
+Easing presets that look good (`use fframes::animation::Easing`):
+
+```rust
+const SPRING_SNAPPY: Easing = Easing::Spring { mass: 1.0, stiffness: 300.0, damping: 26.0 }; // UI-like, tiny overshoot
+const SPRING_SOFT: Easing = Easing::Spring { mass: 1.0, stiffness: 150.0, damping: 18.0 }; // noticeable, friendly
+const SPRING_BOUNCY: Easing = Easing::Spring { mass: 1.0, stiffness: 220.0, damping: 12.0 }; // playful, use rarely
+const EASE_OUT_EXPO: Easing = Easing::CubicBezier(0.16, 1.0, 0.3, 1.0); // fast then settles, great for slides
+const EASE_IN_OUT: Easing = Easing::CubicBezier(0.65, 0.0, 0.35, 1.0); // camera moves, morphs
+```
+
+Principles:
+- Enter with ease-out or a spring from a short distance (40-120 px) plus opacity 0 -> 1.
+ Exit with ease-in, faster, to a shorter distance or just opacity.
+- Stagger related items by 60-120 ms (lists, words, letters by 20-40 ms).
+- Animate transform and opacity; animating font size or layout causes jitter.
+- Scale from 0.9-0.96, not from 0. Rotation within ±6°.
+- One focal movement at a time; secondary elements move less and later.
+- Loops (`frame.animate_loop`) for ambient motion: long (6-12 s), small amplitude.
+
+### Recipes
+
+Staggered entrance with a runtime start time:
+
+```rust
+fn enter(frame: &Frame, start: f32) -> (f32, f32) {
+ let spring = fframes::animation::AnimationRuntime::new(3.0, &SPRING_SOFT);
+ let fade = fframes::animation::AnimationRuntime::new(0.3, &Easing::EaseOut);
+ let y = frame.animate_runtime(fframes::AnimateRuntimeInput { on_second: start, from: 60.0_f32, to: 0.0, animation_runtime: &spring });
+ let opacity = frame.animate_runtime(fframes::AnimateRuntimeInput { on_second: start, from: 0.0_f32, to: 1.0, animation_runtime: &fade });
+ (y, opacity)
+}
+// items.iter().enumerate().map(|(i, item)| { let (y, o) = enter(&frame, 0.4 + i as f32 * 0.09); svgr!(<g opacity={o} transform={Transform::translate(0, y)}>...</g>) })
+```
+
+Word-by-word title reveal: split into words, lay them out with `frame.text_width` per word
+(or `text-anchor="start"` with measured offsets), stagger each word 40-60 ms with a small
+upward spring.
+
+Counter ("0 -> 12,480"): animate an `f32` with `EASE_OUT_EXPO` over 1.2-1.8 s and format with
+thousands separators; use a font with tabular figures (or a monospace font) so digits do not
+jiggle, and right-align it with `text-anchor="end"`.
+
+Progress / highlight bar: animate a `<rect>` width from a hairline (`0.5`, never `0`, SVG
+rejects zero sized rects) to its target with `EASE_IN_OUT`.
+
+Underline or stroke draw-on: `stroke-dasharray={len}` and animate `stroke-dashoffset` from
+`len` to `0`.
+
+Scene transitions: `fn overlap(&self) -> Overlap { Overlap::Previous(0.4) }` plus both
+scenes fading (outgoing 1 -> 0, incoming 0 -> 1) is a clean cross-fade; a "push" moves the
+outgoing scene -80 px while the incoming comes from +80 px.
+
+Lower third: a bar slides in from the left (`EASE_OUT_EXPO`, 0.5 s), the name fades up 0.15 s
+later, the role 0.1 s after that, holds, then everything exits together in 0.25 s.
+
+Background life: two large blurred radial gradients (static markup inside a `<g>`) whose
+wrapping transforms drift 50-150 px over 8-12 s with `animate_loop`.
+
+## Review checklist
+
+Run `strip` for every scene and `frame` for the key moments, then check:
+
+- [ ] Nothing important within the outer 8% (or the portrait UI areas).
+- [ ] Text fits its box and the canvas; no line longer than ~8 words; nothing below 28 px.
+- [ ] Every text is on screen long enough to read (3 words/s + 1 s after it settles).
+- [ ] Only one thing draws the eye at a time; entrances are staggered, not simultaneous.
+- [ ] Consistent margins, alignment and colors across scenes.
+- [ ] Contrast is sufficient on every background (including gradients behind text).
+- [ ] Transitions have no empty or flashing frame (check `Scene@end` and the next scene's
+ first frame, and the `onion` of the transition).
+- [ ] The first frame is not blank for social formats.
+- [ ] `inspect` is clean; audio levels fit (see audio.md).
diff --git a/typos.toml b/typos.toml
index f94d6067..3b09b646 100644
--- a/typos.toml
+++ b/typos.toml
@@ -2,3 +2,5 @@
extend-exclude = ["*.snapshot.txt", "sessions.json"]
[default.extend-words]
hd = "hd"
+# "PNGs" is split into "PN" + "Gs"
+PN = "PN"