programmatic video rendering framework that is actually fast
AGENTS.md - AI Coding Agent Guidelines for fframes
This file provides guidelines for AI coding agents working on the fframes codebase.
Project Overview
fframes is a Rust-based video generation framework that renders videos from SVG-based scene descriptions.
Tech Stack:
- Core: Rust (Edition 2024), Cargo workspace
- Editor: ReScript (compiles to JS), React 19, Tailwind CSS v4
- WASM: wasm-bindgen, wasm-pack for browser preview
- Graphics:
svgr!SVG trees rendered by the built-in CPU backend (tiny-skia) or the optional Skia GPU backend; FFmpeg for encoding/decoding
Build & Development Commands
Task Runner: Just (justfile)
# Full repository setup (run first after clone)
just init-repo
# Build everything (cargo + editor)
just build
# Watch editor during development
just watch-editor
# Run example with live reload (editor + WASM hot reload)
just run <example-name>
# Open an example in the native preview window
just preview <example-name>
# Render example to video file
just render <example-name>
Rust Commands
# Build
cargo build
cargo build --release
just clippy
# Or directly:
cargo clippy -- -D warnings
# Run all tests
just test
# Or:
cargo test
cargo test -p fframes_test_utils --no-default-features
# Run a single test
cargo test <test_name>
cargo test -p <package> <test_name>
# Run tests in specific package
cargo test -p fframes
cargo test -p fframes-media
# Check WASM compilation for examples
just check-wasm <example-name>
just check-examples # checks all examples
Editor (ReScript/TypeScript) Commands
cd fframes-editor
# Build ReScript and bundle
pnpm build
# Development mode with watch
pnpm dev
# Clean ReScript build
pnpm rescript:clean
Package Management
# Lint package.json consistency
pnpm syncpack lint
# Format JS/TS files
pnpm prettier --write .
Code Style Guidelines
Rust Conventions
Imports:
- Group imports: std lib first, then external crates, then local modules
- Use
use crate::for internal module imports - Re-export public API through
lib.rsusingpub use module::*;
use std::{error::Error, fmt};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use crate::error::Result;
use crate::{Color, Duration, Frame, Svgr};
Error Handling:
- Define custom errors as enums in
error.rsmodules - Implement
std::error::Errorandfmt::Displayfor error types - Use
type Result<T> = std::result::Result<T, CustomError>;pattern - Implement
Fromtraits for error conversion
#[derive(Debug)]
pub enum FFramesError {
UserError(String),
MediaError(crate::media::FFramesMediaError),
}
impl From<SomeError> for FFramesError {
fn from(err: SomeError) -> Self { ... }
}
Naming:
- Types:
PascalCase(e.g.,AnimationRuntime,KeyFrame) - Functions/methods:
snake_case(e.g.,render_frame,get_duration) - Constants:
SCREAMING_SNAKE_CASE(e.g.,BACKGROUND_COLOR) - Traits:
PascalCase, often adjectives (e.g.,Animatable,Sync)
Traits:
- Use associated constants for video metadata:
const FPS,const WIDTH,const HEIGHT - Prefer
&selfmethods over consuming self when possible - Use lifetimes explicitly when returning references tied to self
pub trait Video: Sync + Sized {
const FPS: usize;
const WIDTH: usize;
const HEIGHT: usize;
fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a>;
}
Documentation:
- Use
///doc comments for public APIs - Include examples in doc comments with ```rust blocks
- Document panics, safety concerns, and performance considerations
WASM Compatibility:
- Use
#[cfg(not(target_arch = "wasm32"))]for native-only code - Use
#[cfg(target_arch = "wasm32")]for WASM-specific code
ReScript Conventions
File Structure:
- One component per file, named after component (e.g.,
Editor.res) - Use
opensparingly, prefer qualified access - Place bindings in
src/bindings/directory
Components:
@genType.as("ComponentName") @react.component
let make = (~prop1: type1, ~prop2: type2) => {
// hooks first
let (state, setState) = React.useState(_ => initialValue)
// effects
React.useEffect0(() => { ... None })
// render JSX
<div className="tailwind-classes">
{React.string("text")}
</div>
}
Naming:
- Components:
PascalCasefiles, lowercasemakefunction - Types:
lowerCamelCase(ReScript convention) - Variants:
PascalCase(e.g.,MediaList.Grid,MediaList.List)
Styling:
- Use Tailwind CSS classes via
className - Use
Cx.cx([...])for conditional class concatenation
Testing
Rust Tests:
- Unit tests in
#[cfg(test)] mod testsblocks - Integration tests in
/e2e/tests/ - Visual regression tests compare rendered frames using
odiff just e2e cpu|skia-cpu|gpurenders key frames of every example through its CLI and compares them withe2e/snapshots, the same images for every renderer; pass--updateafter an intended change and commit the new PNGs
Running specific tests:
# Run test by name
cargo test test_name
# Run tests matching pattern
cargo test animation
# Run with output
cargo test -- --nocapture
Project Structure
/fframes # Core: Video/Scene traits, svgr! trees, animation, text, CPU renderer, encoding
/fframes-media # Audio/video decoding (ffmpeg), fonts, images, subtitles
/fframes-skia-renderer # Optional Skia backend (GPU via vulkan/metal, or Skia CPU)
/fframes-native-player # Real-time preview window: fframes_native_player::play(&video, &PlayerOptions)
/fframes-editor # Web editor UI (ReScript + React), published as @fframes/editor
/fframes-editor-controller # WASM bridge between a Video impl and the editor
/fframes-test-utils # Snapshot helpers for svgr! trees
/fframes-three-d # 3D: three.js style scene graph, glTF, CPU rasterizer or wgpu (GPU texture shared with Skia)
/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)
Creating a New Video
Every video is a Rust crate under examples/ (or your own crate) with three parts: a library
crate implementing fframes::Video, a binary that renders it, and a small WASM crate that
plugs it into the web editor for live preview. examples/hello-world is the minimal template;
examples/teej-podcast shows video sources, dynamic media and the Skia GPU backend;
examples/beta shows scenes.
1. Scaffold the crate
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
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. Every push to main
publishes a nightly of all crates and @fframes/editor (scripts/publish.sh, version from
scripts/release-version.sh); ./scripts/release.sh 1.2.3 cuts a release: it sets the
versions, commits, pushes the v1.2.3 tag, and CI publishes it and creates the GitHub release.
The generated crate compiles and renders as is:
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, audio)
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. Audio (mp3, wav, flac, aac, ogg, m4a) is decoded to mono at
compile time unless the macro gets the stereo option
(include_media_dir!(pub struct MyVideoMedia, "examples/my-video/media", stereo), twice the
embedded size); files loaded with MediaDirectory keep stereo.
use fframes::include_media_dir;
include_media_dir!(pub struct MyVideoMedia, "examples/my-video/media");
- In
main.rs:let media = MyVideoMedia::prepare()?;and passmedia: Some(&media)inRenderOptions. - Large or changing files (video sources) go into a runtime folder instead (renderer only;
the editor loads the same files over HTTP). The provider borrows the directory, so keep
both bindings alive:
let folder = MediaDirectory::read_folder("./dynamic_media")?;let media = folder.process_media_source()?; - Inside
render_frameresolve media through the context:ctx.get_image("bg.png"),ctx.get_audio("track.mp3"),ctx.get_subtitles("subs.vtt"),ctx.get_video("clip.mp4"),ctx.get_lottie("anim.json")(see 7d). Never.expect()on these in real code; return a fallback element instead. - Fonts are referenced by family name in
font-family=....load_system_fonts: trueis a development convenience only; ship every font inmedia/so renders are reproducible.
3. Implement Video
use fframes::{AudioMap, AudioTimestamp, Color, Duration, FFramesContext, Frame, Svgr, Video};
#[derive(Debug)]
pub struct MyVideo<'a> {
pub media: &'a MyVideoMedia,
pub title: &'a str,
}
impl Video for MyVideo<'_> {
const FPS: usize = 30;
const WIDTH: usize = 1920;
const HEIGHT: usize = 1080;
const BACKGROUND_COLOR: Color = Color::BLACK; // Color::TRANSPARENT needs an alpha-capable encoder
fn duration(&self) -> Duration<'_> {
Duration::Seconds(10.0)
}
fn audio(&self) -> AudioMap<'_> {
AudioMap::from([("track.mp3", AudioTimestamp::Second(0.)..AudioTimestamp::Eof)])
}
fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
fframes::svgr!(
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1920 1080"
width={Self::WIDTH} height={Self::HEIGHT}>
<text x="100" y="300" font-family="DM Sans" font-size="150" fill="#fff">
"Hello " {self.title}
</text>
</svg>
)
}
}
Duration variants: Seconds(f32), Frames(usize), FromAudio("file"),
FromVideo("file") (uses the video's metadata), Auto (inferred from scenes or the audio map).
Durations support + and -. AudioTimestamp supports Second, Frame, Time { minutes, seconds }, Eof, DurationOfAudio("file") and arithmetic.
Rules for render_frame:
- It runs once per frame on several threads. No panics, no I/O, no heavy allocation. Precompute
in the constructor and read from
self; memoise per-video data in astd::sync::OnceLockfield (only store a measurement once it succeeded). svgr!is SVG with Rust interpolation: attributes accept{expr}whereexpris a string, number,Color,Transformor an imagehref(); children accept a string, anotherSvgr, anOption<Svgr>, or an iterator ofSvgr(.collect::<Vec<_>>()). A number as a child needs.to_string(). Comments are// ...lines inside the markup.- Subtrees whose markup contains no
{}get a compile-timestatic_hashand are cached by the renderers across frames (paths, paints, whole groups). Keep decorative geometry lexically static and put the animated values on a wrapping<g transform={...} opacity={...}>. - Return
Svgr::empty()for "nothing this frame".
4. Animate
timeline! builds a keyframe animation once; frame.animate(&anim) samples it at the frame's
time. Keyframes are at <start> [=> <end> | , duration <d>], animate <from> => <to>, <easing>.
Values can be f32/f64, Color, or Transform.
use fframes::{Transform, animation::Easing};
let slide = frame.animate(&fframes::timeline!(
at 0.0, animate Transform::translate(0, 80) => Transform::translate(0, 0),
Easing::Spring { mass: 1.0, stiffness: 300.0, damping: 26.0 },
at 2.2 => 2.8, animate Transform::translate(0, 0) => Transform::translate(0, -80), Easing::EaseIn,
));
let opacity = frame.animate(&fframes::timeline!(at 0.0 => 0.3, animate 0.0_f32 => 1.0, Easing::EaseOut));
- Before the first keyframe the value is
from; after the last it stays atto. frame.animate_loop(&anim)wraps the time around the animation's total duration.- Easings:
Linear,EaseIn,EaseOut,EaseInOut,CubicBezier(x1, y1, x2, y2),Spring { mass, stiffness, damping }. A spring computes its own settle time; an explicit=> endshorter than that cuts it off, so leave the end out unless you want the cut. - Store
timeline!results that never change inself(seeKeyFramesAnimation<f32>inexamples/teej-podcast) instead of rebuilding them every frame.
5. Text
Fonts are measured from the font files, so layout is deterministic and identical in the
renderer. All three helpers return None when the font cannot be resolved (system fonts in the
editor); fall back to the raw text in that case. They take &mut frame.
use fframes::{BreakLinesOpts, FontQuery, TextAlign, TextOverflow};
let font = FontQuery { family: "DM Sans", size: 26, weight: 400, ..Default::default() };
// Width in pixels.
let width = frame.text_width(ctx, font, "Chapter title");
// Single line that must fit into a box: drops what does not fit and ends with "…"
// (or TextOverflow::Clip / TextOverflow::Marker("...")).
let title = frame
.text_fit(ctx, font, chapter.title, 420, TextOverflow::Ellipsis)
.map(std::borrow::Cow::into_owned)
.unwrap_or_else(|| chapter.title.to_owned());
// Multi-line paragraph, returns a ready <text> element (or use
// text_break_lines_structure for the line data).
let paragraph = frame.text_break_lines(ctx, self.description, BreakLinesOpts {
font,
width: 800,
x: 100,
y: 200,
align: TextAlign::Left,
fill: "#fff",
..Default::default()
});
Use the same FontQuery values in the <text> attributes (font-family, font-size,
font-weight) so what is measured is what is drawn. font-weight is a number from 1 to
1000, written or as {expr}, or normal/bold; a number outside that range is ignored.
6. Scenes (optional)
Split a long video into Scene implementations and let the framework place them on the timeline.
use fframes::{Scene, Scenes};
#[derive(Debug)]
struct Intro;
impl Scene for Intro {
fn duration(&self) -> Duration<'_> { Duration::Seconds(3.0) }
fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
// `frame.index` / `frame.seconds()` are relative to the scene start
fframes::svgr!(<g>...</g>)
}
// optional: fn audio(&self), fn overlap(&self) -> Overlap
}
impl Video for MyVideo<'_> {
fn duration(&self) -> Duration<'_> { Duration::Auto } // sum of the scenes
fn define_scenes(&self) -> Scenes<'_> {
let scenes: Vec<&dyn Scene> = vec![&Intro, &self.main_scene];
Scenes::from(scenes)
}
fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
fframes::svgr!(<svg ...>{ctx.render_scenes(&frame)}</svg>)
}
}
Scenes must be zero-sized or borrowed from &self. Overlap::{Previous, Next, PreviousAndNext}
lets scenes cross-fade; ctx.get_scene_info(&scene) gives the resolved frame range.
7. Video sources, audio visualisation, subtitles
// A frame of a video file synced to the timeline. Always give the editor a fallback image.
let Some(video_frame) = frame.get_synced_video_frame(ctx, "clip.mp4", &fframes::SyncVideoFrameInput {
start_from: 0.,
looping: false,
speed: 1.5, // 1.5x from start_from on; 0.5 for slow motion, default 1.0
editor_fallback_image: ctx.get_image("clip_poster.jpg"),
}) else { return Svgr::empty() };
let image = video_frame.into_image(); // <image href={image.href()} .../>
// A part of a file (footage): seconds 19.2..24.7 of the file (`0.0..` to its end), from
// second 1.2 of the scene (`.at`, default 0). `.speed(1.5)`, `.reverse()`, `.looping()`. Each clip has its own decoder,
// so a clip and a picture in picture of the same file do not slow each other down. Store clips
// in the scene, `duration` = `clip.duration()`. The clip gives an image of the current frame:
// draw it with your own size, crop, transform, filter, mask, or pass it to a shader.
let plan = fframes::Clip::new("screen.mov", 19.2..24.7).at(1.2).editor_fallback_image(ctx.get_image("poster.jpg"));
let pip = plan.image_at_width(&frame, ctx, 440).map(|image| svgr!( // decoded at the shown size
<image href={image.href()} x="580" y="1180" width="440" height="660" preserveAspectRatio="xMidYMid slice" />
)); // `{pip}` in svgr!: an Option<Svgr> is nothing when None
// One frame of a file (a freeze frame): seconds of the file, not of the timeline.
let still = frame.video_frame_at(ctx, "IMG_0926.mov", 21.0, None);
// Audio spectrum for the current frame (see examples/audio-announce).
let bars = frame.visualize_audio_frame(fframes::VisualizeFrameInput {
audio: ctx.get_audio("track.mp3")?, // listed in `fn audio`, so it is loaded
sample_size: fframes::SampleSize::S256,
smooth_level: 4,
window: Some(fframes::WindowFunction::Hann),
});
// Current subtitle cue.
let phrase = ctx.get_subtitles("subs.vtt").and_then(|s| frame.get_subtitle_phrase(s));
7b. GPU shaders (Skia backend)
fframes::Shader runs SkSL (or pasted Shadertoy GLSL) on the Skia backend's GPU surface
while it draws the frame. The pixels never leave the GPU, and SVG transforms, clips, masks
and opacity apply to the layer like to any element. See examples/shaders and
examples/neon-triangle.
use fframes::{Shader, ShaderUniforms};
// once, in the constructor (the renderer compiles and caches it by id)
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 Some(photo) = ctx.get_image("photo.jpg") else { return Svgr::empty() };
let layer = self.aurora.draw(&frame, ShaderUniforms::new()
.float("uSpeed", 0.6)
.color("uTint", frame.animate(&tint)) // uniform float4 uTint;
.image("iChannel0", photo)); // uniform shader iChannel0; sample with iChannel0.eval(px)
fframes::svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080" />)
- Built-ins filled in when declared:
iResolution(float3, the<image>width/height),iTime,iTimeDelta,iFrame(int).coordis in the element's units, origin top-left (Shadertoy'sfragCoordis flipped to bottom-left for you). - SkSL follows GLSL ES 2: constant loop bounds, no
while, no dynamic array indexing, no preprocessor.Shader::shadertoyexpands object-like#defines and dropsprecision; function-like macros andtexture()must be rewritten. uniform shader uBackdrop;with no image bound samples what is already painted under the element, in its own coordinates (uBackdrop.eval(coord + offset)refracts the content beneath). It is transparent inside isolated layers (group opacity, masks, filters).- Compile errors are logged once and the layer is skipped. Catch them in a test with
fframes_skia_renderer::render::compile_shader(&shader). - Only the Skia backend (GPU, or
SkiaCpuCtx) executes shaders. The tiny-skia CPU backend draws nothing in their place, and the editor shows a placeholder. - Requires the
compile-time-svgtreefeature (the defaultrendererfeature of the examples).
7d. 3D scenes (fframes::three_d)
fframes = { features = ["3d"] } adds fframes::three_d (the fframes_three_d crate): a
three.js style scene graph with its own renderer. It has 4x MSAA, metal/roughness PBR with
clearcoat, a studio or HDR panorama environment, soft sun shadows, planar reflections,
transparency, additive glows, particles, fog, depth of field, motion blur, bloom and ACES.
It returns an image for <image href>. glTF and STL models load too. The crate docs
(fframes-three-d/src/lib.rs) map three.js classes to their fframes_three_d names.
Two renderers draw the same picture:
- The CPU rasterizer runs everywhere, also in the editor (at half size there).
- With
fframes = { features = ["3d", "wgpu"] }the renderer uses wgpu (Vulkan, Metal, DX12). A frame differs from the CPU frame by less than one 8-bit step on average. Without a GPU it falls back to the CPU.Renderer::new(w, h).cpu()forces the CPU. - With
fframes_skia_renderer = { features = ["vulkan", "wgpu"] }as well, the 3D stays on the GPU: Skia draws the wgpu texture in place and converts the frame for the encoder. Nothing is read back. Other backends (the CPU backend, Metal, the editor) get pixels.
Without these features nothing of wgpu compiles.
use fframes::three_d::*;
// once, in the constructor: geometry is shared by `Arc`, keep the ids you animate
let mut scene = Scene::new().environment(Environment::studio()).background(Background::Transparent);
let body = scene.add(Node::mesh(Geometry::rounded_box(1.0, 1.0, 1.0, 0.08, 4), Material::metal(0xd4d8e0, 0.25)).at(0.0, 0.5, 0.0));
let arm = scene.add_to(body, Node::mesh(Geometry::cylinder(0.1, 0.1, 0.8, 24), Material::standard(0xff5500).clearcoat(1.0)).at(0.6, 0.2, 0.0));
scene.add(Node::mesh(Geometry::floor(30.0, 30.0), Material::shadow_catcher(0.6)).shadows(false, true));
scene.add(Node::light(Light::sun(Rgb::WHITE, 3.0, vec3(3.0, 6.0, 4.0))));
let renderer = Renderer::new(1920, 1080).bloom(Bloom::default());
// render_frame: clone (cheap), pose, render
let mut s = scene.clone();
s[arm].rotation = euler(0.0, 0.0, t * 2.0);
s[body].material_mut().unwrap().emissive_intensity = glow;
let camera = Camera::perspective(35.0).orbit(vec3(0.0, 0.6, 0.0), 6.0, 30.0 + t * 20.0, 15.0);
let image = renderer.render(&s, &camera);
// motion blur for fast shots: renderer.render_motion_blur(3, |o| build(t + o / 120.0))
svgr!(<image href={image.href()} x="0" y="0" width="1920" height="1080" />)
- Y is up, the camera looks down -Z, angles are radians (
deg(),euler_deg()), units are meters. Hex and&strcolors are sRGB like three.js. Multiply anRgbabove 1 for HDR glow (Rgb::hex(0x22e8ff) * 6.0). - Geometry:
cuboid,rounded_box,sphere,cylinder,cone,capsule,torus,plane,floor,ring,lathe,extrude(concave shapes, bevels),tube,icosahedron,text, withtranslate,rotate_*,scale,merge,with_color,flat,smooth. - Materials:
standard,metal,unlit,glow(additive),shadow_catcher,normals, withemissive,clearcoat,opacity,additive,map,normal_map,ao_map. - Pin SVG to 3D:
camera.project(scene.local_to_world(id, local), 1920.0, 1080.0)gives the pixel.camera.pixel_size(..)sizes a bracket. HUD labels then stay on the object. - glTF:
let model = Model::from_gltf(bytes)?; let inst = model.add_to(&mut s, None); inst.play(&mut s, model.animation("Dance").unwrap(), t); - STL (geometry only):
Geometry::from_stl(bytes)?.smooth(40.0)and aMaterial. Most files are millimeters with Z up:.scale(0.001, 0.001, 0.001).rotate_x(-FRAC_PI_2). - Depth of field:
camera.focus_on(point, blur_px)or.focus(distance, blur_px). - Reflections (three.js
Reflector):scene.reflector = Some(Reflector::floor())names the plane..reflection(0.8)on a material on that plane shows the scene mirrored in it, blurred by the roughness. One plane per scene, rendered at half resolution by default. - Highlights do not sparkle: a normal that turns inside a pixel widens the specular lobe.
- Cost of a 1080p frame: 60 to 150 ms on 28 CPU threads, 5 to 20 ms on an Intel iGPU. The
GPU caches meshes and textures by their
Arc, so build geometry once. Only the sun (Light::sun) casts shadows. Set.shadows(false, ..)on floors and far scenery to keep the shadow map tight.fframes-three-d/tests/gpu.rscompares both renderers. examples/armis a short film that uses most of the crate. Itssrc/effects.rsbuilds camera shake, a light beam in hazy air, spark streaks and a printed grid from these blocks.
7e. Your own wgpu passes (fframes::wgpu_layer)
With fframes = { features = ["wgpu"] } and the Skia Vulkan backend's wgpu feature,
anything rendered with wgpu goes into a frame the way fframes_three_d does:
use fframes::wgpu;
let Some(gpu) = fframes::shared_gpu() else { return cpu_fallback() }; // CPU backend, editor
let texture = gpu.device().create_texture(&wgpu::TextureDescriptor {
format: fframes::WGPU_LAYER_FORMAT, // Rgba8Unorm, premultiplied sRGB
usage: fframes::WGPU_LAYER_USAGE | wgpu::TextureUsages::RENDER_ATTACHMENT,
..
});
let mut encoder = gpu.device().create_command_encoder(&Default::default());
// passes rendering into `texture`
fframes::finish_wgpu_layer(&mut encoder, &texture); // leaves it sampled, Skia adds no barrier
gpu.submit([encoder.finish()]); // under the backend's queue lock
let layer = fframes::wgpu_layer(&gpu, &texture);
svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080" />)
- Render into the texture again only after the returned image is dropped. The backend has
submitted the frame that samples it by then. Keep a pool (see
LayerTargetinfframes-three-d/src/gpu/mod.rs) and drop its textures with the device: the GPU can still sample a texture after its image is dropped, and wgpu waits only for its own submissions. - The texture is 2D with one layer and one sample. Other textures draw nothing.
- Keep per-device state in
gpu.state(|gpu| ..). It is dropped with the device. The shared Vulkan device belongs to wgpu and goes with the last wgpu object, so wgpu objects may outlive the backend context (SkiaVulkanCtx); they hold the GPU memory until then. - Every Skia context then submits to the wgpu queue. The queue orders a layer before the
frame that samples it. Submit only with
gpu.submit, which holds the backend's queue lock. - The tiny-skia CPU backend draws no layers. Do not keep a shared
SkiaVulkanCtxalive while it renders.
7c. Audio mix
fn audio places files on the timeline. Tuples still work; AudioTrack adds mix settings:
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,--waveformPNG with scenes and cues) andaudio at 4.2s(which files play, where in the file, at what level, ducked or not, rate and effects). Aim for about -14 LUFS integrated for web video and a true peak below -1 dBTP.
Per-track effects master the takes inside fn audio, no ffmpeg pass before the mix:
use fframes::{AudioTrack, AudioTimestamp::*, Compressor};
AudioTrack::new("voice.wav", Second(1.)..Eof)
.highpass(80.) // 12 dB/oct, Butterworth; twice for 24 dB/oct
.peak(3000., 2.5, 1.2) // hz, db, q
.high_shelf(9000., -3.) // hz, db (half of db at hz); also low_shelf
.compress(Compressor { threshold_db: -24., ratio: 3., ..Default::default() })
.normalize_lufs(-16.) // integrated loudness of the played part
.gain_db(-1.) // applies after the effects
.voice();
AudioTrack::new("whoosh.wav", Second(4.)..Eof).rate(0.8).width(1.5); // a lower, longer, wider variation
- Order: the file is read at
rate, then the effects run in the order of the calls, then gain, pan, fades and ducking. Filters run at the mix rate, after the rate change. rate(f)changes speed and pitch together like a tape. A range that ends atEoffollows the new length.offsetstays in seconds of the file.compress: feed-forward, peak detector, both channels linked;Compressor::default()is -18 dB, 3:1, 10 ms attack, 150 ms release, 6 dB soft knee.width(w): mid/side, 0 mono, 1 unchanged, above 1 wider; the mono sum does not change. A mono file becomes stereo (a delayed, high-passed side signal).normalize_lufsmeasures after the effects before it, so put it aftercompress.- The mixer renders a track with effects once, when it is built (one per render, preview or
audiocommand). It keeps the played part in memory at the mix rate: 23 MB per stereo minute at 48 kHz. Tracks without effects are read from the file as before.
7d. Lottie animations (feature lottie)
With fframes = { features = ["lottie"] }, a Lottie .json file is media like an image. Put it
into the include_media_dir! folder or a MediaDirectory folder and play it by name.
velato reads and evaluates the file. fframes draws each
frame as svgr! vector graphics, on every backend and in the editor. See
examples/lottie.
use fframes::LottieOptions;
fn duration(&self) -> Duration<'_> {
self.media.confetti_json.duration() // each embedded file is a field of the media struct
}
fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
let confetti = frame.play_lottie(ctx, "confetti.json", LottieOptions {
start: 1.5, // second of the video or scene, nothing is drawn before it
looping: true, // without it the last frame stays
x: 660.0,
y: 240.0,
width: Some(600.0), // the height follows; with both, the file fits into the box
..Default::default() // speed 1.0, the size of the file
});
fframes::svgr!(<svg ...>{confetti}</svg>)
}
- A missing file gives an empty element, and
inspectreports it. An invalid file makesprepare()orprocess_media_source()fail. ctx.get_lottie(name)andfframes::Lottie::parse(bytes)give theLottieitself, withwidth(),height(),seconds(),duration()andrender_at(seconds)in the units of the file.- The editor plays embedded files. For
.jsonfiles in the dynamic media folder, enablefframes-editor-controller = { features = ["lottie"] }in the bridge. - Drawn: shapes, fills, strokes, linear and radial gradients, trim paths, repeaters, masks, track mattes, precomps, parenting and solid layers. Exports from bodymovin before 5.5 are converted when they load.
- Not drawn: text and image layers, time remapping, blend modes, effects and expressions.
8. Render it: fframes::cli
main.rs hands the video to fframes::cli (feature cli), which gives every video the same
command line:
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:
cli::new(&video, options)
// Render with Skia. Frame previews (frame, strip, onion) use the backend's own
// renderer, so they match the video; the CPU backend is the default.
.backend(SkiaFFramesRenderer::new_metal(&gpu, SkiaPipelineConfig::default())?)
// The `preview` command: a real-time window with audio (fframes_native_player).
.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:
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] [--crop x,y,w,h] [--zoom N] [--ids] |
PNGs of single frames plus the problems found in them; --crop renders one rectangle sharply (zoomed to about 960 px wide), --ids outlines and labels every element with an id |
strip [RANGE | TIMES] -n 12 [--crop x,y,w,h] |
labelled contact sheet of evenly spaced frames (or of comma separated times), one image to review motion |
onion RANGE -n 6 |
frames blended into one image, shows the path of a movement |
svg TIME |
the frame as SVG after conversion |
timeline |
size, fps, scenes with frame and second ranges, audio tracks |
inspect [RANGE] [--every 0.25s] [--pops] |
missing media/fonts/glyphs, text cut by the canvas edge, NaN transforms, panics; exit code 2 on errors. --pops also renders every frame small and warns about pops: parts that change in one frame between still frames (an element appearing, vanishing or jumping in front of another) |
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, --renderer cpu|skia-cpu|gpu (another backend for this run, see below).
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 fromfframes_skia_rendererwithSkiaFFramesRenderer::new_vulkan(&SkiaVulkanCtx::new(W, H)?, SkiaPipelineConfig { .. })(features = ["vulkan"];new_metalwithmetal). The Skia backend walks thesvgr!tree directly and caches static subtrees as pictures; it is roughly 10x faster than the CPU backend on 1080p (seecargo run --release -p fframes_skia_renderer --features vulkan --example svgr_vs_skia).The Skia backend hands frames to the encoder the fastest way both support (
SkiaFFramesRenderer::frame_export(SkiaFrameExport::Auto), the default):- hardware frames, the encoder reads the texture Skia drew and nothing is read back:
h264_videotoolbox/hevc_videotoolboxwithnew_metal, andh264_vulkan/hevc_vulkanwithSkiaVulkanCtx::new_shared_with_encoder(W, H)andfframes_skia_renderer = { features = ["vulkan-video"] }(the driver needs Vulkan Video encode). Only when the requestedpixel_formatisyuv420p(the default) ornv12; - conversion on the GPU for
yuv420p,nv12,nv21,yuva420p,yuv422pandyuv444p: only the converted planes are read back; - RGBA readback and conversion on the CPU for every other pixel format
(
SkiaFrameExport::CpuConversionforces it). The CPU backend always converts this way.
A backend of your own implements
FFramesRenderBackend::negotiate_encoder_input(a software format orEncoderInput::hardware_frames) andencoder_frame_renderer, which returns libav frames (fframes::VideoFrame) forSegmentWriter::submit_frame.- hardware frames, the encoder reads the texture Skia drew and nothing is read back:
--renderer skia-cpu|gpuneeds.renderers(SkiaRenderers::default())before.run()(fframes_skia_renderer::cli, featurecli): it builds the Skia backend that is asked for (Metal on macOS, Vulkan elsewhere).SkiaRenderers::gpu(SkiaPipelineConfig { .. })also renders on the GPU without the flag. Every example does this.macOS: request
hevc_videotoolboxonly withfframes = { features = ["videotoolbox"] }(seeexamples/teej-podcast/Cargo.toml), otherwise the encoder silently falls back.In code:
fframes::Previewer::new(&video, &options)keeps fonts, images and caches between frames (render,render_inspected,svg,inspect,timeline(),timeline_report());RenderOptions::frame_rangerenders part of a video with matching audio.A panic in
render_framefails the render with the frame, second and scene it happened in.just render my-videorenders and opens the result;just bench my-videotimes it.
9. Editor preview
editor/editor-bridge/lib.rs is the only glue the editor needs:
#![cfg(target_arch = "wasm32")]
use fframes_editor_controller::prelude::*;
use my_video_example::{MyVideo, MyVideoMedia};
impl_wasm_bridge_for!(MyVideo<'static>, MyVideoMedia);
lazy_static! {
static ref MEDIA: MyVideoMedia = MyVideoMedia::prepare().expect("static media");
}
#[wasm_bindgen]
pub fn create_wasm_bridge() -> WasmBridge {
console_error_panic_hook::set_once();
WasmBridge::new(MyVideo { media: &MEDIA, title: "World" }, &MEDIA)
}
just run my-videobuilds the WASM bridge in watch mode, starts the Vite dev server and the editor;just check-wasm my-videotype-checks the bridge without a browser.- Anything renderer-only (
MediaDirectory,RenderOptions, the Skia backend) must be behind#[cfg(not(target_arch = "wasm32"))]; the bridge builds the library withdefault-features = false. - The editor cannot measure system fonts and decodes video frames through WebCodecs, so text
helpers may return
Noneandget_synced_video_framefalls back toeditor_fallback_image.
10. Verify before you finish
Look at the video without playing it (R = cargo run --release -p my-video --):
$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
just clippy && cargo fmt --all && just check-wasm my-video # if it has an editor bridge
Important Notes
- Run
just clippybefore committing - warnings are errors - Use
cargo fmtfor Rust formatting - Use
pnpm prettier --write .for JS/TS/ReScript formatting - Check WASM compilation with
just check-wasm <example>when modifying editor bridge code