Skip to content

programmatic video rendering framework that is actually fast

perf: Add mediabunny to benchmarks + configurable geometry cache (#171)

Dmitriy Kovalenkof89cbd572524
diff --git a/Cargo.lock b/Cargo.lock
index c0313e98..63418c91 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4094,7 +4094,6 @@ dependencies = [
"ash",
"fframes",
"fframes_skia_renderer",
- "png",
"serde_json",
]
diff --git a/examples/fframes-intro/src/facts.rs b/examples/fframes-intro/src/facts.rs
index d4fccc48..496b276e 100644
--- a/examples/fframes-intro/src/facts.rs
+++ b/examples/fframes-intro/src/facts.rs
@@ -10,15 +10,16 @@ pub const RELEASE_LABEL: &str = concat!("v", env!("CARGO_PKG_VERSION"));
pub const LINES_OF_RUST: u64 = 89_372;
/// Frames in this video.
pub const FRAMES: u64 = 7_650;
-/// Wall-clock seconds of the final render of this video (Skia on Metal,
+/// Measured wall-clock seconds for this video on Apple M5 Max (Skia on Metal,
/// libx264, with audio).
-pub const RENDER_SECONDS: f32 = 40.5;
+pub const RENDER_SECONDS: f32 = 79.6;
-/// Median render-and-PNG seconds for 30 frames at 1000×1000.
-/// Measured on Linux ARM64 Docker with Skia CPU and Remotion 4.0.529,
-/// serially, after three warm-up frames. Video encoding is excluded.
-pub const BENCH_REMOTION_S: f32 = 120.801_04;
-pub const BENCH_FFRAMES_S: f32 = 3.876_525_6;
+/// Complete H.264 MP4 export seconds for 300 frames at 3840×2160.
+/// M5 Max, one run per pipeline after a three-frame warm-up. Remotion uses `MediaBunny`.
+/// Source: render-bench/vs-remotion/measurements/m5-max-4k-circles.json.
+pub const BENCH_REMOTION_S: f32 = 121.132_1;
+pub const BENCH_FFRAMES_S: f32 = 7.225_018;
+pub const BENCH_FFRAMES_CPU_S: f32 = 69.740_39;
pub const BENCH_REMOTION_LABEL: &str = "REMOTION 4.0";
pub const BENCH_FFRAMES_LABEL: &str = "FFRAMES · SKIA ON METAL";
-pub const BENCH_NOTE: &str = "M4 MAX · REMOTION 4.0.529, BEST CONCURRENCY, PRE-BUNDLED · VIDEO ENCODING NOT MEASURED · MEDIANS";
+pub const BENCH_NOTE: &str = "M5 MAX · REMOTION 4.0.529 · SERIAL · H.264 MP4 · MEDIANS";
diff --git a/examples/fframes-intro/src/scenes/benchmark.rs b/examples/fframes-intro/src/scenes/benchmark.rs
index f7711c67..859217a9 100644
--- a/examples/fframes-intro/src/scenes/benchmark.rs
+++ b/examples/fframes-intro/src/scenes/benchmark.rs
@@ -1,5 +1,5 @@
//! The drop after the riser. Remotion and fframes render the same 100,000
-//! text nodes; the race runs as a time-lapse of the measured wall-clock times.
+//! elements; the race runs as a time-lapse of complete MP4 export times.
use fframes::{Color, Duration, FFramesContext, Frame, Scene, ShaderUniforms, Svgr};
@@ -61,14 +61,14 @@ fn race(lb: f32) -> Svgr<'static> {
let lanes = [
(
BENCH_REMOTION_LABEL,
- "CHROME + REACT, SCREENSHOT PER FRAME",
+ "CHROME + REACT → H.264 MP4",
BENCH_REMOTION_S,
GREY,
470.0,
),
(
BENCH_FFRAMES_LABEL,
- "RUST, SVG TREE → GPU",
+ "RUST + SKIA → H.264 MP4",
BENCH_FFRAMES_S,
ORANGE,
700.0,
@@ -86,7 +86,7 @@ fn race(lb: f32) -> Svgr<'static> {
let done_at = RACE_START + RACE_BEATS * secs / slowest();
let stamp = snap(lb - done_at);
let flash = if done { (-(lb - done_at) * 6.0).exp() } else { 0.0 };
- let frames_done = (30.0 * p).floor() as u32;
+ let frames_done = (300.0 * p).floor() as u32;
fframes::svgr!(
<g opacity={prog(lb, 0.6 + i as f32 * 0.3, 0.7 + i as f32 * 0.3)} transform={format!("translate({} 0)", (1.0 - appear) * -120.0)}>
<text x="150" y={*y} font-family={DISPLAY} font-size="58" letter-spacing="-2" fill={if i == 1 { ORANGE } else { BONE }}>{*name}</text>
@@ -95,7 +95,7 @@ fn race(lb: f32) -> Svgr<'static> {
<rect x="150" y={*y + 56.0} width={bar_w} height="64" fill={*color} />
<rect x="150" y={*y + 56.0} width="1620" height="64" fill={BONE} opacity={flash * 0.6} />
<text x="1770" y={*y} text-anchor="end" font-family={MONO} font-weight="600" font-size="52" fill={if done { *color } else { BONE }}>{format!("{shown:.3}s")}</text>
- <text x="170" y={*y + 100.0} font-family={MONO} font-weight="600" font-size="22" letter-spacing="2" fill={INK} opacity={if bar_w > 260.0 { 1.0 } else { 0.0 }}>{format!("{frames_done} / 30 FRAMES")}</text>
+ <text x="170" y={*y + 100.0} font-family={MONO} font-weight="600" font-size="22" letter-spacing="2" fill={INK} opacity={if bar_w > 260.0 { 1.0 } else { 0.0 }}>{format!("{frames_done} / 300 FRAMES")}</text>
<g opacity={if done { 1.0 } else { 0.0 }} transform={format!("translate(0 {})", (1.0 - stamp) * 20.0)}>
<text x="1750" y={*y + 100.0} text-anchor="end" font-family={MONO} font-weight="700" font-size="24" letter-spacing="4" fill={INK}>"DONE"</text>
</g>
@@ -106,7 +106,7 @@ fn race(lb: f32) -> Svgr<'static> {
fframes::svgr!(
<g opacity={1.0 - exit}>
{Slam::new(150.0, 250.0, "100,000 TEXT NODES", DISPLAY, 120.0, BONE).draw(lb, 0.0, 140.0)}
- {label(154.0, 310.0, "30 FRAMES · 1000×1000 · PNG · SAME LAYOUT, SAME FONT".to_owned(), GREY, 20.0, "start")}
+ {label(154.0, 310.0, "300 FRAMES · 3840×2160 · H.264 MP4 · SAME LAYOUT, SAME FONT".to_owned(), GREY, 20.0, "start")}
{rows}
<g opacity={prog(lb, RACE_START, RACE_START + 0.2)}>
{label(1770.0, 310.0, format!("TIME-LAPSE ×{speedup:.1} · MEASURED WALL CLOCK"), ORANGE, 20.0, "end")}
@@ -131,7 +131,7 @@ fn result(l: f32) -> Svgr<'static> {
<text x="150" y={900.0 + (1.0 - word) * 60.0} font-family={DISPLAY} font-size="120" letter-spacing="-4" fill={INK} opacity={prog(l, 1.0, 1.08)}>"FASTER THAN REMOTION"</text>
<g font-family={MONO} font-weight="600" font-size="22" letter-spacing="4" fill={INK}>
<text x="150" y="170">"SAME 100,000 TEXT NODES"</text>
- <text x="1770" y="170" text-anchor="end">"NO VIDEO ENCODING · MEDIAN WALL CLOCK"</text>
+ <text x="1770" y="170" text-anchor="end">"COMPLETE MP4 · MEDIAN WALL CLOCK"</text>
</g>
<rect x="150" y="196" width="1620" height="3" fill={INK} />
</g>
@@ -141,6 +141,7 @@ fn result(l: f32) -> Svgr<'static> {
fn table(l: f32) -> Svgr<'static> {
let rows = [
(BENCH_REMOTION_LABEL, BENCH_REMOTION_S, GREY),
+ ("FFRAMES · CPU", BENCH_FFRAMES_CPU_S, BONE),
(BENCH_FFRAMES_LABEL, BENCH_FFRAMES_S, ORANGE),
];
let items: Vec<Svgr> = rows
@@ -155,7 +156,7 @@ fn table(l: f32) -> Svgr<'static> {
<rect x="150" y={y - 70.0} width="1620" height="110" fill="#0f0e0d" fill-opacity="0.85" stroke="#2f2c29" stroke-width="1.5" />
<rect x="150" y={y - 70.0} width="6" height="110" fill={*color} />
<text x="190" y={y} font-family={DISPLAY} font-size="48" letter-spacing="-1" fill={BONE}>{*name}</text>
- <text x="1250" y={y} text-anchor="end" font-family={MONO} font-weight="600" font-size="48" fill={*color}>{format!("{secs:.3} s")}</text>
+ <text x="1740" y={y} text-anchor="end" font-family={MONO} font-weight="600" font-size="48" fill={*color}>{format!("{secs:.3} s")}</text>
</g>
)
})
@@ -164,11 +165,11 @@ fn table(l: f32) -> Svgr<'static> {
fframes::svgr!(
<g opacity={1.0 - exit}>
{Slam::new(150.0, 300.0, "THE NUMBERS", DISPLAY, 110.0, BONE).draw(l, 0.0, 120.0)}
- {label(1250.0, 400.0, "WALL CLOCK".to_owned(), GREY, 18.0, "end")}
+ {label(1740.0, 400.0, "WALL CLOCK".to_owned(), GREY, 18.0, "end")}
{items}
- {label(154.0, 820.0, "VIDEO ENCODING NOT MEASURED".to_owned(), BONE, 18.0, "start")}
- {label(154.0, 860.0, BENCH_NOTE.to_owned(), GREY, 18.0, "start")}
- {label(154.0, 900.0, "REPRODUCE: RENDER-BENCH/VS-REMOTION IN THE FFRAMES REPO".to_owned(), ORANGE, 18.0, "start")}
+ {label(154.0, 860.0, "RENDER + ENCODE + MP4".to_owned(), BONE, 18.0, "start")}
+ {label(154.0, 900.0, BENCH_NOTE.to_owned(), GREY, 18.0, "start")}
+ {label(154.0, 940.0, "REPRODUCE: RENDER-BENCH/VS-REMOTION IN THE FFRAMES REPO".to_owned(), ORANGE, 18.0, "start")}
</g>
)
}
diff --git a/examples/fframes-intro/src/scenes/scale.rs b/examples/fframes-intro/src/scenes/scale.rs
index d195e0fc..7752b1e2 100644
--- a/examples/fframes-intro/src/scenes/scale.rs
+++ b/examples/fframes-intro/src/scenes/scale.rs
@@ -89,7 +89,7 @@ fn wall(lb: f32) -> Svgr<'static> {
<rect x="1010" y="130" width="760" height="140" fill={BG} />
<text x="1770" y="232" text-anchor="end" font-family={DISPLAY} font-size="110" letter-spacing="-3" fill={BONE}>{thousands(count)}</text>
{label(1770.0, 290.0, "TEXT NODES TO RENDER".to_owned(), ORANGE, 20.0, "end")}
- {label(150.0, 940.0, format!("ONE FRAME = {} TEXT NODES × 30 FRAMES", thousands(100_000)), GREY, 20.0, "start")}
+ {label(150.0, 940.0, format!("ONE FRAME = {} TEXT NODES × 300 FRAMES", thousands(100_000)), GREY, 20.0, "start")}
</g>
)
}
diff --git a/fframes-skia-renderer/examples/svgr_vs_skia.rs b/fframes-skia-renderer/examples/svgr_vs_skia.rs
index 329ed795..19ec9f9d 100644
--- a/fframes-skia-renderer/examples/svgr_vs_skia.rs
+++ b/fframes-skia-renderer/examples/svgr_vs_skia.rs
@@ -186,10 +186,7 @@ fn main() {
let decoders = VideoDecodersWorker::new(1);
let mut converter_cache = usvgr::Cache::new_with_text_cache(10);
- println!(
- "low-poly-art owl @ {}x{}, {} frames, single thread\n",
- WIDTH, HEIGHT, frames
- );
+ println!("low-poly-art owl @ {WIDTH}x{HEIGHT}, {frames} frames, single thread\n");
let start = Instant::now();
let trees: Vec<usvgr::Tree> = (0..frames)
diff --git a/fframes-skia-renderer/src/cache.rs b/fframes-skia-renderer/src/cache.rs
new file mode 100644
index 00000000..4046876d
--- /dev/null
+++ b/fframes-skia-renderer/src/cache.rs
@@ -0,0 +1,40 @@
+/// Cache limits shared by Skia frame previews and video exports.
+///
+/// Limits apply independently to each worker. Geometry uses two generations, so
+/// its estimated retained bytes can reach twice `geometry_bytes`. Hash-map and
+/// allocator overhead are additional. Cached geometry is allocated as it is used.
+///
+/// ```
+/// use fframes_skia_renderer::{SkiaCacheConfig, SkiaPipelineConfig};
+///
+/// let pipeline = SkiaPipelineConfig {
+/// cache: SkiaCacheConfig {
+/// text_capacity: 100_000,
+/// geometry_capacity: 100_000,
+/// geometry_bytes: 100_000 * 512,
+/// },
+/// ..Default::default()
+/// };
+/// ```
+#[derive(Debug, Clone, Copy)]
+pub struct SkiaCacheConfig {
+ /// Maximum positioned SVG text layouts retained by each converter.
+ /// Zero disables SVG text caching. The default is 10 layouts.
+ pub text_capacity: usize,
+ /// Maximum dynamic path geometries retained per generation.
+ /// Zero disables dynamic geometry caching. The byte limit also applies.
+ pub geometry_capacity: usize,
+ /// Estimated bytes of dynamic geometry retained per generation.
+ /// Includes source geometry and its Skia conversion. The default is 4 MiB.
+ pub geometry_bytes: usize,
+}
+
+impl Default for SkiaCacheConfig {
+ fn default() -> Self {
+ Self {
+ text_capacity: 10,
+ geometry_capacity: usize::MAX,
+ geometry_bytes: 4 * 1024 * 1024,
+ }
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_export/mod.rs b/fframes-skia-renderer/src/frame_export/mod.rs
index b1a12fb1..306b1f21 100644
--- a/fframes-skia-renderer/src/frame_export/mod.rs
+++ b/fframes-skia-renderer/src/frame_export/mod.rs
@@ -279,6 +279,12 @@ impl<'b> SkiaEncoderFrameRenderer<'b> {
})
}
+ /// Uses these cache limits and clears previously cached render resources.
+ pub fn with_cache_config(mut self, config: crate::SkiaCacheConfig) -> Self {
+ self.render_cache = crate::render::RenderCache::with_config(config);
+ self
+ }
+
/// The way the frames of this renderer take to the encoder.
pub fn path(&self) -> FrameExportPath {
match self.target {
diff --git a/fframes-skia-renderer/src/frame_renderer.rs b/fframes-skia-renderer/src/frame_renderer.rs
index f8deceb3..ca5d4f83 100644
--- a/fframes-skia-renderer/src/frame_renderer.rs
+++ b/fframes-skia-renderer/src/frame_renderer.rs
@@ -65,6 +65,7 @@ pub fn apply_fit(canvas: &Canvas, tree: &usvgr::Tree, width: i32, height: i32) {
/// GPU context and render cache between frames.
pub struct SkiaFrameRenderer<'a, TBackend: SkiaBackend> {
backend: &'a TBackend,
+ cache_config: crate::SkiaCacheConfig,
surface: Option<SkiaContext>,
render_cache: crate::render::RenderCache,
}
@@ -80,7 +81,7 @@ impl<TBackend: SkiaBackend> SkiaFrameRenderer<'_, TBackend> {
}) = self.surface.take()
{
// what lives on the context goes first
- self.render_cache = crate::render::RenderCache::new();
+ self.render_cache = crate::render::RenderCache::with_config(self.cache_config);
drop(surface);
drop(reader);
let _queue = lock_queue(queue_lock.as_ref());
@@ -99,13 +100,25 @@ impl<'a, TBackend: SkiaBackend> SkiaFrameRenderer<'a, TBackend> {
pub fn new(backend: &'a TBackend) -> Self {
Self {
backend,
+ cache_config: crate::SkiaCacheConfig::default(),
surface: None,
render_cache: crate::render::RenderCache::new(),
}
}
+
+ /// Uses these cache limits for subsequent frames. Clears previously cached render resources.
+ pub fn with_cache_config(mut self, config: crate::SkiaCacheConfig) -> Self {
+ self.cache_config = config;
+ self.render_cache = crate::render::RenderCache::with_config(config);
+ self
+ }
}
impl<TBackend: SkiaBackend> FrameRenderer for SkiaFrameRenderer<'_, TBackend> {
+ fn svg_text_cache_capacity(&self) -> Option<usize> {
+ Some(self.cache_config.text_capacity)
+ }
+
fn render_tree(
&mut self,
tree: &usvgr::Tree,
diff --git a/fframes-skia-renderer/src/instant_rendering.rs b/fframes-skia-renderer/src/instant_rendering.rs
index 32ea5192..326905f1 100644
--- a/fframes-skia-renderer/src/instant_rendering.rs
+++ b/fframes-skia-renderer/src/instant_rendering.rs
@@ -38,6 +38,13 @@ impl<TBackend: SkiaBackend> InstantRenderingGPUBackend<TBackend> {
})
}
+ /// Applies cache limits to instant rendering and clears cached resources.
+ pub fn with_cache_config(mut self, config: crate::SkiaCacheConfig) -> Self {
+ self.converter_cache = usvgr::Cache::new_with_text_cache(config.text_capacity);
+ self.render_cache = crate::render::RenderCache::with_config(config);
+ self
+ }
+
pub fn new_from_existing_texture(
backend: TBackend,
surface: Surface,
diff --git a/fframes-skia-renderer/src/lib.rs b/fframes-skia-renderer/src/lib.rs
index b01b0275..abffdc73 100644
--- a/fframes-skia-renderer/src/lib.rs
+++ b/fframes-skia-renderer/src/lib.rs
@@ -1,5 +1,8 @@
mod skia_pipeline;
+mod cache;
+pub use cache::SkiaCacheConfig;
+
mod backends;
pub use backends::*;
diff --git a/fframes-skia-renderer/src/render/convert.rs b/fframes-skia-renderer/src/render/convert.rs
index 5cfbc85b..4c7dd97b 100644
--- a/fframes-skia-renderer/src/render/convert.rs
+++ b/fframes-skia-renderer/src/render/convert.rs
@@ -2,33 +2,49 @@
use fframes::usvgr;
use fframes::usvgr::tiny_skia_path;
-use skia_safe::{self, Paint, PathBuilder};
-
-/// Convert a `tiny_skia_path::Path` to a `skia_safe::Path`.
-pub fn convert_path(path: &tiny_skia_path::Path) -> skia_safe::Path {
- let mut builder = PathBuilder::new();
-
- for segment in path.segments() {
- match segment {
- tiny_skia_path::PathSegment::MoveTo(p) => {
- builder.move_to((p.x, p.y));
- }
- tiny_skia_path::PathSegment::LineTo(p) => {
- builder.line_to((p.x, p.y));
- }
- tiny_skia_path::PathSegment::QuadTo(p1, p2) => {
- builder.quad_to((p1.x, p1.y), (p2.x, p2.y));
- }
- tiny_skia_path::PathSegment::CubicTo(p1, p2, p3) => {
- builder.cubic_to((p1.x, p1.y), (p2.x, p2.y), (p3.x, p3.y));
- }
- tiny_skia_path::PathSegment::Close => {
- builder.close();
- }
+use skia_safe::{self, Paint};
+
+/// Reuses conversion buffers and submits all path segments in one Skia call.
+#[derive(Default)]
+pub(super) struct PathConverter {
+ points: Vec<skia_safe::Point>,
+ verbs: Vec<skia_safe::PathVerb>,
+}
+
+impl PathConverter {
+ pub(super) fn convert(&mut self, path: &tiny_skia_path::Path) -> skia_safe::Path {
+ self.points.clear();
+ self.points.extend(
+ path.points()
+ .iter()
+ .map(|p| skia_safe::Point::new(p.x, p.y)),
+ );
+ self.verbs.clear();
+ self.verbs
+ .extend(path.verbs().iter().map(|verb| match verb {
+ tiny_skia_path::PathVerb::Move => skia_safe::PathVerb::Move,
+ tiny_skia_path::PathVerb::Line => skia_safe::PathVerb::Line,
+ tiny_skia_path::PathVerb::Quad => skia_safe::PathVerb::Quad,
+ tiny_skia_path::PathVerb::Cubic => skia_safe::PathVerb::Cubic,
+ tiny_skia_path::PathVerb::Close => skia_safe::PathVerb::Close,
+ }));
+ let converted = skia_safe::Path::raw(
+ &self.points,
+ &self.verbs,
+ &[],
+ skia_safe::PathFillType::Winding,
+ false,
+ );
+ // A single unusually large path must not permanently retain its scratch space.
+ if self.points.capacity() * std::mem::size_of::<skia_safe::Point>()
+ + self.verbs.capacity() * std::mem::size_of::<skia_safe::PathVerb>()
+ > 512 * 1024
+ {
+ self.points = Vec::new();
+ self.verbs = Vec::new();
}
+ converted
}
-
- builder.detach()
}
/// Convert a usvgr Paint + opacity to a Skia Paint.
diff --git a/fframes-skia-renderer/src/render/fingerprint.rs b/fframes-skia-renderer/src/render/fingerprint.rs
index 02efb8b6..bb51678b 100644
--- a/fframes-skia-renderer/src/render/fingerprint.rs
+++ b/fframes-skia-renderer/src/render/fingerprint.rs
@@ -221,6 +221,20 @@ fn hash_exact_group(
Some(())
}
+/// Every verb and point, for geometry without a compile-time identity.
+pub(super) fn exact_path_fingerprint(path: &tiny_skia_path::Path) -> u64 {
+ let mut h = FxHasher::default();
+ h.write_usize(path.verbs().len());
+ for verb in path.verbs() {
+ h.write_u8(*verb as u8);
+ }
+ for point in path.points() {
+ h.f32(point.x);
+ h.f32(point.y);
+ }
+ h.finish()
+}
+
/// Fingerprint of the geometry a cached `skia_safe::Path` was converted from.
pub(super) fn path_geometry_fingerprint(path: &tiny_skia_path::Path) -> u64 {
let mut hasher = FxHasher::default();
diff --git a/fframes-skia-renderer/src/render/mod.rs b/fframes-skia-renderer/src/render/mod.rs
index 94f4c9a2..01b8126d 100644
--- a/fframes-skia-renderer/src/render/mod.rs
+++ b/fframes-skia-renderer/src/render/mod.rs
@@ -11,21 +11,22 @@ mod convert;
mod filters;
mod fingerprint;
mod image;
+mod occlusion;
+mod resources;
mod shader;
pub use shader::compile_shader;
-use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
-use fframes::usvgr;
+use fframes::usvgr::{self, ahash::AHashMap};
use skia_safe::{Canvas, Matrix};
-use convert::{convert_blend_mode, convert_path, to_skia_paint, to_skia_stroke_paint};
+use convert::{PathConverter, convert_blend_mode, to_skia_paint, to_skia_stroke_paint};
use fingerprint::{
- exact_content_fingerprint, fill_fingerprint, group_fingerprint, image_fingerprint,
- path_geometry_fingerprint, stroke_fingerprint,
+ exact_content_fingerprint, exact_path_fingerprint, fill_fingerprint, group_fingerprint,
+ image_fingerprint, path_geometry_fingerprint, stroke_fingerprint,
};
use image::SkiaImage;
@@ -44,15 +45,15 @@ struct Cached<T> {
/// getting stolen back into `current`, so the cache is bounded by roughly two
/// frames worth of entries.
struct Generational<T> {
- current: HashMap<u64, Cached<T>>,
- previous: HashMap<u64, Cached<T>>,
+ current: AHashMap<u64, Cached<T>>,
+ previous: AHashMap<u64, Cached<T>>,
}
impl<T> Default for Generational<T> {
fn default() -> Self {
Self {
- current: HashMap::new(),
- previous: HashMap::new(),
+ current: AHashMap::new(),
+ previous: AHashMap::new(),
}
}
}
@@ -118,8 +119,10 @@ impl<T> Generational<T> {
///
/// Paths, paints and pictures are keyed by `static_hash` — a stable
/// content-identity hash assigned at compile time by the `svgr!` macro to
-/// nodes whose lexical content never changes. Nodes without a `static_hash`
-/// are frame-dependent and are converted fresh each frame. Images are keyed
+/// nodes whose lexical content never changes. Dynamic paths, fills, and strokes
+/// share converted resources by resolved content, with exact equality checks
+/// and bounded retention. Transforms and group compositing are applied when
+/// drawing, so sharing resources does not change painter order. Images are keyed
/// by the address of their `Arc<PreloadedImageData>`; the cache entry holds
/// a clone of the `Arc`, so the address can not be recycled while the entry
/// exists. Every entry is validated with a runtime [`fingerprint`] of the
@@ -127,8 +130,15 @@ impl<T> Generational<T> {
/// (see [`Generational`]).
#[derive(Default)]
pub struct RenderCache {
+ #[cfg(test)]
+ disable_occlusion: bool,
/// `static_hash` → converted `skia_safe::Path`
paths: Generational<skia_safe::Path>,
+ path_converter: PathConverter,
+ // Bounded reuse for dynamic paths and styles on both raster and GPU surfaces.
+ geometry: resources::ResourceCache<resources::Geometry, { 4 * 1024 * 1024 }>,
+ fills: resources::ResourceCache<resources::Fill, { 256 * 1024 }>,
+ strokes: resources::ResourceCache<resources::Stroke, { 256 * 1024 }>,
/// `static_hash` → recorded `skia_safe::Picture` of an entire static
/// group. Replaying a picture is dramatically cheaper than re-traversing
/// the subtree and re-issuing every draw call.
@@ -146,7 +156,7 @@ pub struct RenderCache {
filtered_layers: Generational<FilteredLayer>,
/// `static_hash` → whether the static subtree contains filters, such subtrees are
/// not recorded as pictures so the filtered groups inside can be rasterized.
- static_has_filters: HashMap<u64, bool>,
+ static_has_filters: AHashMap<u64, bool>,
}
struct FilteredLayer {
@@ -162,8 +172,22 @@ impl RenderCache {
Self::default()
}
+ /// Creates a cache with explicit dynamic geometry entry and memory limits.
+ pub fn with_config(config: crate::SkiaCacheConfig) -> Self {
+ Self {
+ geometry: resources::ResourceCache::with_limits(
+ config.geometry_capacity,
+ config.geometry_bytes,
+ ),
+ ..Default::default()
+ }
+ }
+
fn begin_frame(&mut self) {
self.paths.begin_frame();
+ self.geometry.begin_frame();
+ self.fills.begin_frame();
+ self.strokes.begin_frame();
self.pictures.begin_frame();
self.fill_paints.begin_frame();
self.stroke_paints.begin_frame();
@@ -190,7 +214,21 @@ impl RenderCache {
/// Convert a path, reusing the cached conversion for static paths.
fn convert_path(&mut self, path: &usvgr::Path) -> skia_safe::Path {
let Some(hash) = path.static_hash() else {
- return convert_path(path.data());
+ let data = path.data();
+ let key = exact_path_fingerprint(data);
+ if let Some(geometry) = self.geometry.get(key)
+ && geometry.source == *data
+ {
+ return geometry.path.clone();
+ }
+ let converted = self.path_converter.convert(data);
+ let bytes = (std::mem::size_of_val(data.points()) + data.verbs().len()) * 2 + 256;
+ self.geometry
+ .insert_with(key, bytes, || resources::Geometry {
+ source: data.clone(),
+ path: converted.clone(),
+ });
+ return converted;
};
let fingerprint = path_geometry_fingerprint(path.data());
@@ -199,7 +237,7 @@ impl RenderCache {
}
self.paths
- .insert(hash, fingerprint, convert_path(path.data()))
+ .insert(hash, fingerprint, self.path_converter.convert(path.data()))
.clone()
}
}
@@ -220,8 +258,11 @@ pub fn render_tree(tree: &usvgr::Tree, canvas: &Canvas, cache: &mut RenderCache)
}
fn render_nodes(parent: &usvgr::Group, canvas: &Canvas, cache: &mut RenderCache) {
- for node in parent.children() {
- render_node(node, canvas, cache);
+ let visible = occlusion::visible_nodes(parent, canvas, cache);
+ for (i, node) in parent.children().iter().enumerate() {
+ if visible.as_ref().is_none_or(|visible| visible[i]) {
+ render_node(node, canvas, cache);
+ }
}
}
@@ -837,6 +878,15 @@ fn fill_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alpha
return;
}
+ let dynamic_key = (cache_key.is_none() && !matches!(fill.paint(), usvgr::Paint::Pattern(_)))
+ .then(|| fill_fingerprint(fill, anti_alias));
+ if let Some(cached) = dynamic_key.and_then(|key| cache.fills.get(key))
+ && cached.matches(fill, anti_alias)
+ {
+ draw_path_with_alpha(canvas, &sk_path, &cached.paint, alpha);
+ return;
+ }
+
let Some(mut paint) = to_skia_paint(fill.paint(), fill.opacity(), anti_alias, cache) else {
return;
};
@@ -846,6 +896,16 @@ fn fill_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alpha
if let Some((hash, fingerprint)) = cache_key {
cache.fill_paints.insert(hash, fingerprint, paint);
+ } else if let Some(key) = dynamic_key {
+ cache
+ .fills
+ .insert_with(key, resources::paint_bytes(fill.paint()), || {
+ resources::Fill {
+ source: fill.clone(),
+ anti_alias,
+ paint,
+ }
+ });
}
}
@@ -864,6 +924,15 @@ fn stroke_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alp
return;
}
+ let dynamic_key = (cache_key.is_none() && !matches!(stroke.paint(), usvgr::Paint::Pattern(_)))
+ .then(|| stroke_fingerprint(stroke, anti_alias));
+ if let Some(cached) = dynamic_key.and_then(|key| cache.strokes.get(key))
+ && cached.matches(stroke, anti_alias)
+ {
+ draw_path_with_alpha(canvas, &sk_path, &cached.paint, alpha);
+ return;
+ }
+
let Some(paint) = to_skia_stroke_paint(stroke, anti_alias, cache) else {
return;
};
@@ -872,6 +941,17 @@ fn stroke_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alp
if let Some((hash, fingerprint)) = cache_key {
cache.stroke_paints.insert(hash, fingerprint, paint);
+ } else if let Some(key) = dynamic_key {
+ cache.strokes.insert_with(
+ key,
+ resources::paint_bytes(stroke.paint())
+ + stroke.dasharray().map_or(0, std::mem::size_of_val),
+ || resources::Stroke {
+ source: stroke.clone(),
+ anti_alias,
+ paint,
+ },
+ );
}
}
diff --git a/fframes-skia-renderer/src/render/occlusion.rs b/fframes-skia-renderer/src/render/occlusion.rs
new file mode 100644
index 00000000..f1b0c846
--- /dev/null
+++ b/fframes-skia-renderer/src/render/occlusion.rs
@@ -0,0 +1,320 @@
+use fframes::usvgr;
+use skia_safe::{Canvas, ColorType, Contains, IRect, PathFillType, Rect, RoundOut};
+
+use super::RenderCache;
+
+// Coverage is valid only at this surface's scale, never in a reusable picture.
+pub(super) fn visible_nodes(
+ group: &usvgr::Group,
+ canvas: &Canvas,
+ cache: &mut RenderCache,
+) -> Option<Vec<bool>> {
+ #[cfg(test)]
+ if cache.disable_occlusion {
+ return None;
+ }
+ if group.children().len() < 64
+ || canvas.image_info().color_type() == ColorType::Unknown
+ || !canvas.is_clip_rect()
+ {
+ return None;
+ }
+ let matrix = canvas.local_to_device_as_3x3();
+ if matrix.has_perspective() {
+ return None;
+ }
+ let clip = canvas.device_clip_bounds()?.with_inset((2, 2));
+ let bounds = group.bounding_box();
+ let bounds = matrix
+ .map_rect(Rect::from_xywh(
+ bounds.x(),
+ bounds.y(),
+ bounds.width(),
+ bounds.height(),
+ ))
+ .0;
+ if !bounds.is_finite() || bounds.is_empty() {
+ return None;
+ }
+ let mut covered = Coverage::new(bounds.with_outset((2., 2.)));
+ let mut visible = vec![true; group.children().len()];
+ let mut hidden = 0;
+ for (i, node) in group.children().iter().enumerate().rev() {
+ if group.children().len() - i > 128 && hidden == 0 && !covered.overlaps {
+ return None;
+ }
+ let usvgr::Node::Path(path) = node else {
+ // A group can blend with its backdrop, so coverage cannot cross it.
+ covered.rows.fill(0);
+ covered.overlaps = false;
+ continue;
+ };
+ if path.visibility() != usvgr::Visibility::Visible {
+ continue;
+ }
+ if path.stroke().is_some() {
+ continue;
+ }
+ let bounds = path.data().bounds();
+ let bounds = matrix
+ .map_rect(Rect::from_xywh(
+ bounds.x(),
+ bounds.y(),
+ bounds.width(),
+ bounds.height(),
+ ))
+ .0;
+ if !bounds.is_finite() {
+ covered.rows.fill(0);
+ covered.overlaps = false;
+ continue;
+ }
+ // Keep both antialiased edges and the shared clip's antialiased fringe.
+ let outer: IRect = bounds.with_outset((1., 1.)).round_out();
+ if clip.contains(&outer) && covered.contains(bounds.with_outset((1., 1.))) {
+ visible[i] = false;
+ hidden += 1;
+ continue;
+ }
+ let Some(fill) = path.fill() else { continue };
+ if fill.opacity().get() != 1. || !matches!(fill.paint(), usvgr::Paint::Color(_)) {
+ continue;
+ }
+ let mut shape = cache.convert_path(path).make_transform(&matrix);
+ shape.set_fill_type(match fill.rule() {
+ usvgr::FillRule::NonZero => PathFillType::Winding,
+ usvgr::FillRule::EvenOdd => PathFillType::EvenOdd,
+ });
+ // Convex paths can certify an interior rectangle; concave paths and holes
+ // simply contribute no coverage. No SVG tag-specific rendering is needed.
+ for fraction in [0., 0.125, 0.25, 0.375] {
+ let inner = bounds.with_inset((bounds.width() * fraction, bounds.height() * fraction));
+ if shape.conservatively_contains_rect(inner) {
+ covered.add(inner.with_inset((1., 1.)));
+ break;
+ }
+ }
+ }
+ Some(visible)
+}
+
+struct Coverage {
+ rows: [u64; 64],
+ overlaps: bool,
+ bounds: Rect,
+ sx: f32,
+ sy: f32,
+}
+
+impl Coverage {
+ fn new(bounds: Rect) -> Self {
+ Self {
+ rows: [0; 64],
+ overlaps: false,
+ sx: 64. / bounds.width(),
+ sy: 64. / bounds.height(),
+ bounds,
+ }
+ }
+
+ fn cells(&self, rect: Rect, inward: bool) -> Option<(usize, usize, u64)> {
+ let coordinates = [
+ (rect.left - self.bounds.left) * self.sx,
+ (rect.top - self.bounds.top) * self.sy,
+ (rect.right - self.bounds.left) * self.sx,
+ (rect.bottom - self.bounds.top) * self.sy,
+ ];
+ let [left, top, right, bottom] = coordinates.map(|v| v.clamp(0., 64.));
+ let (left, top, right, bottom) = if inward {
+ (
+ left.ceil() as usize,
+ top.ceil() as usize,
+ right.floor() as usize,
+ bottom.floor() as usize,
+ )
+ } else {
+ if !self.bounds.contains(rect) {
+ return None;
+ }
+ (
+ left.floor() as usize,
+ top.floor() as usize,
+ right.ceil() as usize,
+ bottom.ceil() as usize,
+ )
+ };
+ if left >= right || top >= bottom {
+ return None;
+ }
+ Some((top, bottom, (u64::MAX << left) & (u64::MAX >> (64 - right))))
+ }
+
+ fn contains(&self, rect: Rect) -> bool {
+ self.cells(rect, false).is_some_and(|(top, bottom, mask)| {
+ self.rows[top..bottom].iter().all(|row| row & mask == mask)
+ })
+ }
+
+ fn add(&mut self, rect: Rect) {
+ if let Some((top, bottom, mask)) = self.cells(rect, true) {
+ for row in &mut self.rows[top..bottom] {
+ self.overlaps |= *row & mask != 0;
+ *row |= mask;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fmt::Write;
+
+ use super::*;
+ use crate::{SkiaBackend, SkiaCpuCtx};
+
+ fn parse(content: &str) -> usvgr::Tree {
+ usvgr::Tree::from_str(
+ &format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128">{content}</svg>"#),
+ &usvgr::Options::default(),
+ &usvgr::fontdb::Database::new(),
+ )
+ .unwrap()
+ }
+
+ fn overlapping_paths() -> String {
+ let mut paths = String::new();
+ for i in 0..160 {
+ let x = 20 + i % 7;
+ let y = 20 + i % 11;
+ write!(
+ paths,
+ r##"<path d="M{x} {y} h40 v40 h-40z" fill="#{:06x}"/>"##,
+ i * 7919 % 0x00ff_ffff
+ )
+ .unwrap();
+ }
+ paths
+ }
+
+ fn compare(backend: &impl SkiaBackend, tree: &usvgr::Tree, transform: &skia_safe::Matrix) {
+ let render = |disabled| {
+ let (mut surface, mut context) = backend.create_skia_surface().unwrap();
+ let mut cache = RenderCache {
+ disable_occlusion: disabled,
+ ..Default::default()
+ };
+ surface.canvas().clear(skia_safe::Color::TRANSPARENT);
+ surface.canvas().concat(transform);
+ super::super::render_tree(tree, surface.canvas(), &mut cache);
+ if let Some(context) = context.as_mut() {
+ context.flush_submit_and_sync_cpu();
+ }
+ let info = skia_safe::ImageInfo::new_n32_premul((128, 128), None);
+ let mut pixels = vec![0; 128 * 128 * 4];
+ assert!(surface.read_pixels(&info, &mut pixels, 128 * 4, (0, 0)));
+ pixels
+ };
+ assert_eq!(render(false), render(true), "occlusion changed pixels");
+ }
+
+ fn check_backend(backend: &impl SkiaBackend) {
+ let paths = overlapping_paths();
+ let defs = r#"<defs>
+ <clipPath id="c"><circle cx="55" cy="55" r="37"/></clipPath>
+ <clipPath id="r"><rect x="20.25" y="20.25" width="42.5" height="42.5"/></clipPath>
+ <mask id="m"><rect width="128" height="128" fill="white"/><circle cx="30" cy="40" r="20" fill="black"/></mask>
+ <filter id="f"><feGaussianBlur stdDeviation="2"/></filter>
+ <linearGradient id="g"><stop stop-color="red"/><stop offset="1" stop-color="blue" stop-opacity=".2"/></linearGradient>
+ </defs>"#;
+ for attributes in [
+ "",
+ r#"opacity=".45""#,
+ r#"filter="url(#f)""#,
+ r#"clip-path="url(#c)""#,
+ r#"clip-path="url(#r)""#,
+ r#"mask="url(#m)""#,
+ r#"style="mix-blend-mode:multiply""#,
+ ] {
+ for top in [
+ r#"<path d="M15 15h65v65h-65z" fill="blue"/>"#,
+ r#"<path d="M10 10h75v75h-75z M30 30h30v30h-30z" fill-rule="evenodd"/>"#,
+ r#"<circle cx="45" cy="45" r="44" fill="green"/>"#,
+ r#"<path d="M5 85L50 0L90 85Z" fill="orange"/>"#,
+ r#"<rect x="10" y="10" width="80" height="80" fill="url(#g)"/>"#,
+ r#"<rect x="10" y="10" width="80" height="80" fill="blue" fill-opacity=".5"/>"#,
+ r#"<g style="mix-blend-mode:multiply"><rect x="10" y="10" width="80" height="80" fill="blue"/></g>"#,
+ ] {
+ let tree = parse(&format!("{defs}<g {attributes}>{paths}{top}</g>"));
+ for transform in [
+ skia_safe::Matrix::new_identity(),
+ skia_safe::Matrix::scale((0.25, 0.25)),
+ skia_safe::Matrix::new_all(1.1, 0.2, 0.25, -0.15, 0.9, 12.5, 0., 0., 1.),
+ ] {
+ compare(backend, &tree, &transform);
+ }
+ }
+ }
+ let tree = parse(&format!(
+ r#"{paths}<path d="M15 15h70v70h-70z" fill="blue"/>"#
+ ));
+ let (mut surface, _context) = backend.create_skia_surface().unwrap();
+ let visible =
+ visible_nodes(tree.root(), surface.canvas(), &mut RenderCache::new()).unwrap();
+ assert!(visible.iter().filter(|visible| !**visible).count() >= 150);
+ }
+
+ #[test]
+ fn occlusion_preserves_raster_pixels() {
+ check_backend(&SkiaCpuCtx::new(128, 128));
+ }
+
+ #[test]
+ fn coverage_rounds_inward_and_preserves_gaps() {
+ let mut coverage = Coverage::new(Rect::from_wh(64., 64.));
+ coverage.add(Rect::new(0.25, 0.25, 31.75, 63.75));
+ coverage.add(Rect::new(32.25, 0.25, 63.75, 63.75));
+ assert!(coverage.contains(Rect::new(1., 1., 31., 63.)));
+ assert!(!coverage.contains(Rect::new(0., 0., 31., 63.)));
+ assert!(!coverage.contains(Rect::new(1., 1., 63., 63.)));
+ assert!(!coverage.contains(Rect::new(-1., 1., 31., 63.)));
+ }
+
+ #[test]
+ fn non_overlapping_paths_stop_the_scan() {
+ let mut paths = String::new();
+ for i in 0..160 {
+ write!(
+ paths,
+ r#"<path d="M{} {}h2v2h-2z"/>"#,
+ i % 16 * 8,
+ i / 16 * 8
+ )
+ .unwrap();
+ }
+ let tree = parse(&paths);
+ let (mut surface, _) = SkiaCpuCtx::new(128, 128).create_skia_surface().unwrap();
+ assert!(visible_nodes(tree.root(), surface.canvas(), &mut RenderCache::new()).is_none());
+ }
+
+ #[test]
+ fn partial_overlap_keeps_scanning_for_hidden_paths() {
+ let mut paths = r#"<path d="M50 35h5v5h-5z"/>"#.repeat(100);
+ for i in 0..160 {
+ write!(paths, r#"<path d="M{} 20h50v50h-50z"/>"#, f64::from(i) / 4.).unwrap();
+ }
+ let tree = parse(&paths);
+ let backend = SkiaCpuCtx::new(128, 128);
+ let (mut surface, _) = backend.create_skia_surface().unwrap();
+ let visible =
+ visible_nodes(tree.root(), surface.canvas(), &mut RenderCache::new()).unwrap();
+ assert!(visible[..100].iter().all(|visible| !visible));
+ compare(&backend, &tree, &skia_safe::Matrix::new_identity());
+ }
+
+ #[cfg(all(target_os = "macos", feature = "metal"))]
+ #[test]
+ fn occlusion_preserves_metal_pixels() {
+ let backend = crate::metal::SkiaMetalCtx::new(128, 128).unwrap();
+ check_backend(&backend);
+ }
+}
diff --git a/fframes-skia-renderer/src/render/resources.rs b/fframes-skia-renderer/src/render/resources.rs
new file mode 100644
index 00000000..62bd9e01
--- /dev/null
+++ b/fframes-skia-renderer/src/render/resources.rs
@@ -0,0 +1,188 @@
+use fframes::usvgr;
+use std::collections::HashMap;
+
+struct Entry<T> {
+ value: T,
+ bytes: usize,
+}
+
+/// Two generations, each bounded by entry count and estimated bytes.
+/// Callers must check source equality on cache hits.
+pub(super) struct ResourceCache<T, const BUDGET: usize> {
+ current: HashMap<u64, Entry<T>>,
+ previous: HashMap<u64, Entry<T>>,
+ bytes: usize,
+ capacity: usize,
+ budget: usize,
+}
+
+impl<T, const BUDGET: usize> Default for ResourceCache<T, BUDGET> {
+ fn default() -> Self {
+ Self {
+ current: HashMap::new(),
+ previous: HashMap::new(),
+ bytes: 0,
+ capacity: usize::MAX,
+ budget: BUDGET,
+ }
+ }
+}
+
+impl<T, const BUDGET: usize> ResourceCache<T, BUDGET> {
+ pub(super) fn with_limits(capacity: usize, budget: usize) -> Self {
+ Self {
+ capacity,
+ budget,
+ ..Default::default()
+ }
+ }
+
+ pub(super) fn begin_frame(&mut self) {
+ std::mem::swap(&mut self.current, &mut self.previous);
+ self.current.clear();
+ self.bytes = 0;
+ }
+
+ pub(super) fn get(&mut self, key: u64) -> Option<&T> {
+ if !self.current.contains_key(&key)
+ && self.current.len() < self.capacity
+ && self
+ .previous
+ .get(&key)
+ .is_some_and(|entry| entry.bytes <= self.budget.saturating_sub(self.bytes))
+ {
+ let entry = self.previous.remove(&key)?;
+ self.bytes += entry.bytes;
+ self.current.insert(key, entry);
+ }
+ self.current
+ .get(&key)
+ .or_else(|| self.previous.get(&key))
+ .map(|entry| &entry.value)
+ }
+
+ pub(super) fn insert_with(&mut self, key: u64, bytes: usize, build: impl FnOnce() -> T) {
+ let old = self.current.get(&key).map_or(0, |entry| entry.bytes);
+ if (self.current.contains_key(&key) || self.current.len() < self.capacity)
+ && bytes <= self.budget.saturating_sub(self.bytes - old)
+ {
+ self.bytes = self.bytes - old + bytes;
+ self.current.insert(
+ key,
+ Entry {
+ value: build(),
+ bytes,
+ },
+ );
+ }
+ }
+}
+
+pub(super) struct Geometry {
+ pub source: usvgr::tiny_skia_path::Path,
+ pub path: skia_safe::Path,
+}
+
+pub(super) struct Fill {
+ pub source: usvgr::Fill,
+ pub anti_alias: bool,
+ pub paint: skia_safe::Paint,
+}
+
+pub(super) struct Stroke {
+ pub source: usvgr::Stroke,
+ pub anti_alias: bool,
+ pub paint: skia_safe::Paint,
+}
+
+pub(super) fn same_paint(a: &usvgr::Paint, b: &usvgr::Paint) -> bool {
+ match (a, b) {
+ (usvgr::Paint::Color(a), usvgr::Paint::Color(b)) => a == b,
+ (usvgr::Paint::LinearGradient(a), usvgr::Paint::LinearGradient(b)) => {
+ (a.x1(), a.y1(), a.x2(), a.y2()) == (b.x1(), b.y1(), b.x2(), b.y2())
+ && same_gradient(a, b)
+ }
+ (usvgr::Paint::RadialGradient(a), usvgr::Paint::RadialGradient(b)) => {
+ (a.cx(), a.cy(), a.r(), a.fx(), a.fy()) == (b.cx(), b.cy(), b.r(), b.fx(), b.fy())
+ && same_gradient(a, b)
+ }
+ _ => false, // Patterns may change between frames.
+ }
+}
+
+fn same_gradient(a: &usvgr::BaseGradient, b: &usvgr::BaseGradient) -> bool {
+ a.transform() == b.transform()
+ && a.spread_method() == b.spread_method()
+ && a.stops().len() == b.stops().len()
+ && a.stops().iter().zip(b.stops()).all(|(a, b)| {
+ (a.offset(), a.opacity(), a.color()) == (b.offset(), b.opacity(), b.color())
+ })
+}
+
+impl Fill {
+ pub(super) fn matches(&self, fill: &usvgr::Fill, anti_alias: bool) -> bool {
+ self.anti_alias == anti_alias
+ && self.source.opacity() == fill.opacity()
+ && self.source.rule() == fill.rule()
+ && same_paint(self.source.paint(), fill.paint())
+ }
+}
+
+impl Stroke {
+ pub(super) fn matches(&self, stroke: &usvgr::Stroke, anti_alias: bool) -> bool {
+ self.anti_alias == anti_alias
+ && self.source.opacity() == stroke.opacity()
+ && self.source.width() == stroke.width()
+ && self.source.miterlimit() == stroke.miterlimit()
+ && self.source.dashoffset() == stroke.dashoffset()
+ && self.source.linecap() == stroke.linecap()
+ && self.source.linejoin() == stroke.linejoin()
+ && self.source.dasharray() == stroke.dasharray()
+ && same_paint(self.source.paint(), stroke.paint())
+ }
+}
+
+pub(super) fn paint_bytes(paint: &usvgr::Paint) -> usize {
+ let stops = match paint {
+ usvgr::Paint::LinearGradient(gradient) => gradient.stops().len(),
+ usvgr::Paint::RadialGradient(gradient) => gradient.stops().len(),
+ _ => 0,
+ };
+ 256 + stops * std::mem::size_of::<usvgr::Stop>() * 2
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ResourceCache;
+
+ #[test]
+ fn entry_and_byte_limits_survive_generation_changes() {
+ let mut cache = ResourceCache::<_, 100>::with_limits(2, 10);
+ cache.insert_with(1, 4, || "one");
+ cache.insert_with(2, 4, || "two");
+ cache.insert_with(3, 1, || panic!("entry limit must reject insertion"));
+ assert!(cache.get(3).is_none());
+ cache.insert_with(1, 7, || panic!("replacement must obey byte limit"));
+ assert_eq!(cache.get(1), Some(&"one"));
+ cache.insert_with(1, 6, || "replacement");
+ assert_eq!(cache.get(1), Some(&"replacement"));
+
+ cache.begin_frame();
+ cache.insert_with(3, 7, || "three");
+ assert_eq!(cache.get(1), Some(&"replacement"));
+ assert_eq!(cache.current.len(), 1);
+ assert_eq!(cache.bytes, 7);
+ cache.begin_frame();
+ assert!(cache.get(1).is_none());
+ assert_eq!(cache.get(3), Some(&"three"));
+ }
+
+ #[test]
+ fn zero_limits_disable_geometry_retention() {
+ for (capacity, bytes) in [(0, 10), (10, 0)] {
+ let mut cache = ResourceCache::<_, 100>::with_limits(capacity, bytes);
+ cache.insert_with(1, 1, || panic!("disabled cache must not allocate"));
+ assert!(cache.get(1).is_none());
+ }
+ }
+}
diff --git a/fframes-skia-renderer/src/render/shader.rs b/fframes-skia-renderer/src/render/shader.rs
index fc9f740e..a2332291 100644
--- a/fframes-skia-renderer/src/render/shader.rs
+++ b/fframes-skia-renderer/src/render/shader.rs
@@ -1,5 +1,6 @@
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
+use fframes::usvgr::ahash::AHashMap;
use fframes::{ShaderDraw, ShaderUniformValue, usvgr};
use skia_safe::runtime_effect::{ChildPtr, ChildType, uniform};
use skia_safe::{Canvas, Data, Paint, Rect, RuntimeEffect};
@@ -24,7 +25,7 @@ pub fn compile_shader(shader: &fframes::Shader) -> Result<RuntimeEffect, String>
pub(super) struct ShaderCache {
/// `Shader::id` → compiled effect, or `None` when compilation failed
/// (the error was logged and the layer is skipped from then on).
- effects: HashMap<u64, Option<RuntimeEffect>>,
+ effects: AHashMap<u64, Option<RuntimeEffect>>,
warned: HashSet<(u64, String)>,
}
diff --git a/fframes-skia-renderer/src/skia_backend.rs b/fframes-skia-renderer/src/skia_backend.rs
index 58f8045c..071ed87a 100644
--- a/fframes-skia-renderer/src/skia_backend.rs
+++ b/fframes-skia-renderer/src/skia_backend.rs
@@ -45,7 +45,10 @@ 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<impl FrameRenderer + '_> {
- Some(crate::SkiaFrameRenderer::new(self.backend))
+ Some(
+ crate::SkiaFrameRenderer::new(self.backend)
+ .with_cache_config(self.pipeline_config.cache),
+ )
}
fn negotiate_encoder_input(
@@ -61,7 +64,10 @@ impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBa
width: u32,
height: u32,
) -> FFramesRendererResult<impl EncoderFrameRenderer + '_> {
- SkiaEncoderFrameRenderer::new(self.backend, self.frame_export, input, width, height)
+ Ok(
+ SkiaEncoderFrameRenderer::new(self.backend, self.frame_export, input, width, height)?
+ .with_cache_config(self.pipeline_config.cache),
+ )
}
fn render_frame<'a, 'media: 'a, TVideo: Video + Sync + Sized>(
@@ -72,19 +78,22 @@ impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBa
font_db: &usvgr::fontdb::Database,
ctx: fframes::FFramesContext<'a, 'media>,
) -> FFramesRendererResult<Vec<u8>> {
- let mut converter_cache = usvgr::Cache::default();
+ let mut converter_cache =
+ usvgr::Cache::new_with_text_cache(self.pipeline_config.cache.text_capacity);
let rtree = fframes::render_frame_guarded(video, frame, &ctx)?.into_svg_tree(
usvg_options,
&mut converter_cache,
font_db,
)?;
- 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,
- )?;
+ let frame = crate::SkiaFrameRenderer::new(self.backend)
+ .with_cache_config(self.pipeline_config.cache)
+ .render_tree(
+ &rtree,
+ TVideo::BACKGROUND_COLOR,
+ ctx.current_video_size.width as u32,
+ ctx.current_video_size.height as u32,
+ )?;
Ok(frame.pixels)
}
diff --git a/fframes-skia-renderer/src/skia_pipeline.rs b/fframes-skia-renderer/src/skia_pipeline.rs
index 635e86e1..4583aac8 100644
--- a/fframes-skia-renderer/src/skia_pipeline.rs
+++ b/fframes-skia-renderer/src/skia_pipeline.rs
@@ -1,5 +1,5 @@
use crate::frame_export::Rendered;
-use crate::{SkiaBackend, SkiaEncoderFrameRenderer, SkiaFrameExport};
+use crate::{SkiaBackend, SkiaCacheConfig, SkiaEncoderFrameRenderer, SkiaFrameExport};
use fframes::get_thread_count;
use fframes::{
AudioTimelineSamples, FFramesContext, FrameClaim, FrameScheduler, RenderOptions,
@@ -35,6 +35,8 @@ pub struct SkiaPipelineConfig {
/// The number of threads that build frame trees and encode the rendered frames.
pub encoder_threads: usize,
pub concurrency_policy: SkiaPipelineConcurrencyPolicy,
+ /// Per-worker SVG text and Skia geometry cache limits.
+ pub cache: SkiaCacheConfig,
}
impl Default for SkiaPipelineConfig {
@@ -43,6 +45,7 @@ impl Default for SkiaPipelineConfig {
buffer_queue_size: 10,
encoder_threads: get_thread_count(),
concurrency_policy: SkiaPipelineConcurrencyPolicy::OnePipeline,
+ cache: SkiaCacheConfig::default(),
}
}
}
@@ -212,6 +215,7 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
font_db,
tree_sender,
queue_size,
+ pipeline_config.cache.text_capacity,
ctx,
failed,
#[cfg(feature = "debug")]
@@ -239,6 +243,7 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
ctx,
failed,
background_color,
+ pipeline_config.cache,
#[cfg(feature = "debug")]
metrics,
))
@@ -316,12 +321,13 @@ fn generate_frames<'a, 'media: 'a, TVideo: Video + Sync + Send>(
font_db: &'a usvgr::fontdb::Database,
tree_sender: SyncSender<(FrameClaim, usvgr::Tree)>,
queue_size: usize,
+ text_cache_capacity: usize,
ctx: &'a FFramesContext<'a, 'media>,
failed: &AtomicBool,
#[cfg(feature = "debug")] metrics: Arc<crate::metrics::ThreadMetrics>,
) -> FFramesRendererResult<()> {
let break_lines_cache = TextCache::new(10);
- let mut converter_cache = usvgr::Cache::new_with_text_cache(10);
+ let mut converter_cache = usvgr::Cache::new_with_text_cache(text_cache_capacity);
// x2 because sometimes we might need to decode 2 frames at once
let video_decoders_worker = VideoDecodersWorker::new(queue_size * 2);
@@ -387,6 +393,7 @@ fn render_frames<TBackend: SkiaBackend>(
ctx: &FFramesContext,
failed: &AtomicBool,
background_color: skia_safe::Color,
+ cache_config: SkiaCacheConfig,
#[cfg(feature = "debug")] metrics: Arc<crate::metrics::ThreadMetrics>,
) -> FFramesRendererResult<()> {
// Keeps the surfaces, the GPU context and the render cache (static paths and images are
@@ -397,7 +404,8 @@ fn render_frames<TBackend: SkiaBackend>(
encoder_input,
ctx.current_video_size.width as u32,
ctx.current_video_size.height as u32,
- )?;
+ )?
+ .with_cache_config(cache_config);
while let Some((claim, tree)) = {
#[cfg(feature = "debug")]
diff --git a/fframes-skia-renderer/tests/dynamic_cache.rs b/fframes-skia-renderer/tests/dynamic_cache.rs
new file mode 100644
index 00000000..3d73282e
--- /dev/null
+++ b/fframes-skia-renderer/tests/dynamic_cache.rs
@@ -0,0 +1,146 @@
+//! Cached resources must produce the same full frame as a fresh renderer when
+//! geometry, paint state, and the surrounding compositing state change.
+
+use std::fmt::Write;
+
+use fframes::{Color, FrameRenderer, usvgr};
+use fframes_skia_renderer::{SkiaBackend, SkiaCacheConfig, SkiaCpuCtx, SkiaFrameRenderer};
+
+const SIZE: usize = 100;
+
+fn tree(content: &str) -> usvgr::Tree {
+ usvgr::Tree::from_str(
+ &format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">{content}</svg>"#
+ ),
+ &usvgr::Options::default(),
+ &usvgr::fontdb::Database::new(),
+ )
+ .expect("test SVG")
+}
+
+fn frames() -> Vec<usvgr::Tree> {
+ let mut frames = Vec::new();
+ for i in 0..8 {
+ // Repeat geometry across changing gradients, strokes, fractional
+ // transforms, clip paths, masks, group opacity, and paint order.
+ frames.push(tree(&format!(
+ r##"<defs>
+ <linearGradient id="g" x2="100%" gradientTransform="rotate({i} .5 .5)" spreadMethod="reflect">
+ <stop offset="0" stop-color="#{:06x}" stop-opacity=".7"/>
+ <stop offset="1" stop-color="#aaff33"/>
+ </linearGradient>
+ <radialGradient id="r" cx=".4" cy=".6" r=".8"><stop stop-color="blue"/><stop offset="1" stop-color="red"/></radialGradient>
+ <clipPath id="c"><circle cx="50" cy="50" r="{}"/></clipPath>
+ <mask id="m"><rect width="100" height="100" fill="white"/><circle cx="60" cy="50" r="{}" fill="black"/></mask>
+ <filter id="f"><feGaussianBlur stdDeviation=".8"/></filter>
+ </defs>
+ <g transform="translate({} .25) rotate({i} 50 50)" opacity="{}" clip-path="url(#c)" mask="url(#m)">
+ <path d="M10 10 Q50 80 90 10 L90 90 C60 60 40 100 10 90 Z M30 30 L70 30 L70 70 L30 70 Z"
+ fill="url(#g)" fill-rule="{}" stroke="url(#r)" stroke-width="{}"
+ stroke-dasharray="{} 3" stroke-dashoffset="{i}" stroke-linecap="{}" stroke-linejoin="{}"
+ shape-rendering="{}" paint-order="{}"/>
+ <circle cx="50" cy="50" r="20" fill="#5544ff" opacity=".4"/>
+ </g>
+ <g filter="url(#f)" transform="translate({i} 0)"><path d="M20 20 L70 30 L40 70 Z" fill="#88ccff"/></g>"##,
+ 0x00ff_0000 + i * 31,
+ 42 + i,
+ 4 + i,
+ i as f32 / 4.0,
+ 0.3 + i as f32 / 12.0,
+ if i % 2 == 0 { "evenodd" } else { "nonzero" },
+ 1 + i,
+ 2 + i,
+ if i % 2 == 0 { "round" } else { "square" },
+ if i % 2 == 0 { "bevel" } else { "miter" },
+ if i % 2 == 0 { "crispEdges" } else { "geometricPrecision" },
+ if i % 2 == 0 { "stroke fill" } else { "fill stroke" },
+ )));
+ }
+
+ // Same point count and bounds, but an interior point beyond a strided
+ // fingerprint changes. Dynamic geometry must examine every point.
+ for offset in [0, 12, 0] {
+ let mut d = "M0 0 L100 0 L100 100 L0 100 M0 50".to_owned();
+ for i in 1..300 {
+ let y = if i == 137 { 50 + offset } else { 50 };
+ write!(d, " L{} {y}", i as f32 / 3.0).unwrap();
+ }
+ frames.push(tree(&format!(
+ r#"<path d="{d}" fill="none" stroke="red" stroke-width="2"/>"#
+ )));
+ }
+ // Identical points can describe different curves; verbs are part of identity.
+ for d in [
+ "M10 10 L50 90 L90 10",
+ "M10 10 Q50 90 90 10",
+ "M10 10 L50 90 L90 10",
+ ] {
+ frames.push(tree(&format!(
+ r#"<path d="{d}" fill="none" stroke="blue" stroke-width="3"/>"#
+ )));
+ }
+ frames
+}
+
+fn compare_frames(backend: &impl SkiaBackend, config: SkiaCacheConfig) {
+ let mut cached = SkiaFrameRenderer::new(backend).with_cache_config(config);
+ let mut previous = None;
+ let mut changed = false;
+ let frames = frames();
+ for (i, tree) in frames
+ .iter()
+ .chain(frames.iter().rev())
+ .chain(&frames)
+ .enumerate()
+ {
+ let actual = cached
+ .render_tree(tree, Color::TRANSPARENT, SIZE as u32, SIZE as u32)
+ .expect("cached frame");
+ let expected = SkiaFrameRenderer::new(backend)
+ .render_tree(tree, Color::TRANSPARENT, SIZE as u32, SIZE as u32)
+ .expect("fresh frame");
+ assert_eq!(actual.pixels, expected.pixels, "frame {i}");
+ changed |= previous.as_ref().is_some_and(|p| *p != actual.pixels);
+ previous = Some(actual.pixels);
+ }
+ assert!(changed, "the frames must exercise changing output");
+}
+
+#[test]
+fn dynamic_resources_preserve_raster_output() {
+ let backend = SkiaCpuCtx::new(SIZE, SIZE);
+ for config in configurations() {
+ compare_frames(&backend, config);
+ }
+}
+
+#[cfg(all(target_os = "macos", feature = "metal"))]
+#[test]
+fn dynamic_resources_preserve_metal_output() {
+ if fframes_skia_renderer::metal::metal_rs::Device::system_default().is_none() {
+ eprintln!("Metal device unavailable; skipping GPU comparison");
+ return;
+ }
+ let backend =
+ fframes_skia_renderer::metal::SkiaMetalCtx::new(SIZE, SIZE).expect("Metal context");
+ for config in configurations() {
+ compare_frames(&backend, config);
+ }
+}
+
+fn configurations() -> [SkiaCacheConfig; 3] {
+ [
+ SkiaCacheConfig::default(),
+ SkiaCacheConfig {
+ text_capacity: 0,
+ geometry_capacity: 0,
+ geometry_bytes: 0,
+ },
+ SkiaCacheConfig {
+ text_capacity: 100_000,
+ geometry_capacity: 100_000,
+ geometry_bytes: 100_000 * 512,
+ },
+ ]
+}
diff --git a/fframes/src/renderer/encoder.rs b/fframes/src/renderer/encoder.rs
index 305a9f15..9745508c 100644
--- a/fframes/src/renderer/encoder.rs
+++ b/fframes/src/renderer/encoder.rs
@@ -452,6 +452,11 @@ impl Encoder {
let oc = self.oc;
self.send_customizable_frame_packet(stream, frame, |packet| {
+ // Encoders may omit duration; video frames use a 1/fps time base.
+ if matches!(stream.variant, stream::StreamVariant::Video) && (*packet).duration == 0
+ {
+ (*packet).duration = 1;
+ }
av_packet_rescale_ts(packet, (*stream.enc).time_base, (*stream.st).time_base);
(*packet).stream_index = (*stream.st).index;
@@ -555,6 +560,79 @@ mod tests {
use super::*;
use crate::{FFramesLoggerVariant, renderer::fframes_logger::make_logger};
+ #[test]
+ fn mp4_preserves_final_frame_duration() {
+ let directory =
+ std::env::temp_dir().join(format!("fframes-duration-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir(&directory).unwrap();
+ let path = directory.join("out.mp4");
+ let logger = make_logger(FFramesLoggerVariant::Silent);
+ let options = RenderOptions {
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ codec_params: Some(&[("preset", "medium"), ("threads", "1")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ unsafe {
+ {
+ let encoder = Encoder::new(
+ EncoderOutput::Final { with_audio: false },
+ 64,
+ 64,
+ 30,
+ &path,
+ &options,
+ &logger,
+ )
+ .unwrap_or_else(|err| panic!("test encoder: {err}"));
+ let mut frame = EncoderFrame::new(&encoder.video_stream)
+ .unwrap_or_else(|err| panic!("test frame: {err}"));
+ for pts in 0..4 {
+ frame.fill_from_rgba_pixmap(&[128; 64 * 64 * 4]);
+ frame.set_pts(pts);
+ encoder
+ .send_frame(&encoder.video_stream, &frame)
+ .unwrap_or_else(|err| panic!("test encode: {err}"));
+ }
+ encoder
+ .flush_stream(&encoder.video_stream)
+ .unwrap_or_else(|err| panic!("test drain: {err}"));
+ }
+ let filename = CString::new(path.to_str().unwrap()).unwrap();
+ let mut input = std::ptr::null_mut();
+ assert_eq!(
+ avformat_open_input(
+ &raw mut input,
+ filename.as_ptr(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut()
+ ),
+ 0
+ );
+ assert!(avformat_find_stream_info(input, std::ptr::null_mut()) >= 0);
+ let stream = *(*input).streams;
+ let frames = av_rescale_q(
+ (*stream).duration,
+ (*stream).time_base,
+ AVRational { num: 1, den: 30 },
+ );
+ let mut packet = av_packet_alloc();
+ let mut count = 0;
+ while av_read_frame(input, packet) >= 0 {
+ assert_eq!((*packet).flags & AV_PKT_FLAG_DISCARD, 0);
+ count += 1;
+ av_packet_unref(packet);
+ }
+ av_packet_free(&raw mut packet);
+ avformat_close_input(&raw mut input);
+ assert_eq!(count, 4);
+ assert_eq!(frames, 4);
+ }
+ std::fs::remove_dir_all(directory).unwrap();
+ }
+
#[test]
fn parallel_segments_limit_codec_threads_and_allow_overrides() {
let directory =
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index 51b94862..ff212ae3 100644
--- a/fframes/src/renderer/preview.rs
+++ b/fframes/src/renderer/preview.rs
@@ -67,6 +67,12 @@ impl RgbaFrame {
/// Rasterizes converted frames. Implementations keep their surfaces and caches between
/// calls, so rendering many frames through one renderer is cheap.
pub trait FrameRenderer {
+ /// SVG text cache capacity requested by this renderer. `None` keeps the
+ /// previewer's current setting; zero disables SVG text layout caching.
+ fn svg_text_cache_capacity(&self) -> Option<usize> {
+ None
+ }
+
/// Renders `tree` scaled to `width`x`height` over `background`.
fn render_tree(
&mut self,
@@ -263,6 +269,7 @@ pub struct Previewer<'a, 'media, TVideo: Video> {
size: VideoSize,
timeline_index: TimelineIndex,
converter_cache: usvgr::Cache,
+ converter_text_cache_capacity: usize,
text_cache: Option<TextCache>,
decoders: VideoDecodersWorker,
}
@@ -306,6 +313,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
image_source,
timeline_index,
converter_cache: usvgr::Cache::new_with_text_cache(10),
+ converter_text_cache_capacity: 10,
text_cache: TextCache::new(10),
decoders: VideoDecodersWorker::new(2),
})
@@ -450,11 +458,21 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
frame: usize,
renderer: &mut dyn FrameRenderer,
) -> FFramesRendererResult<RgbaFrame> {
+ self.configure_renderer_cache(renderer);
let tree = self.svg_tree(frame)?;
let (width, height) = self.size();
renderer.render_tree(&tree, TVideo::BACKGROUND_COLOR, width, height)
}
+ fn configure_renderer_cache(&mut self, renderer: &dyn FrameRenderer) {
+ if let Some(capacity) = renderer.svg_text_cache_capacity()
+ && capacity != self.converter_text_cache_capacity
+ {
+ self.converter_cache = usvgr::Cache::new_with_text_cache(capacity);
+ self.converter_text_cache_capacity = capacity;
+ }
+ }
+
/// Renders a frame and reports the problems found while converting it.
pub fn render_inspected(
&mut self,
@@ -462,6 +480,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
renderer: &mut dyn FrameRenderer,
) -> FFramesRendererResult<(RgbaFrame, FrameReport)> {
self.check_frame(frame)?;
+ self.configure_renderer_cache(renderer);
let (width, height) = self.size();
let (tree, mut found) = diagnostics::collect(|| self.svg_tree(frame));
let tree = tree?;
@@ -508,3 +527,64 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
Ok(self.report(frame, found))
}
}
+
+#[cfg(test)]
+mod cache_tests {
+ use super::*;
+ use crate::{AudioMap, Duration, Svgr};
+
+ struct EmptyVideo;
+ impl Video for EmptyVideo {
+ const FPS: usize = 30;
+ const WIDTH: usize = 1;
+ const HEIGHT: usize = 1;
+ fn duration(&self) -> Duration<'_> {
+ Duration::Frames(2)
+ }
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+ fn render_frame<'a>(&'a self, _: Frame, _: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ Svgr::empty()
+ }
+ }
+
+ struct Renderer(Option<usize>);
+ impl FrameRenderer for Renderer {
+ fn svg_text_cache_capacity(&self) -> Option<usize> {
+ self.0
+ }
+ fn render_tree(
+ &mut self,
+ _: &usvgr::Tree,
+ _: Color,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<RgbaFrame> {
+ Ok(RgbaFrame {
+ width,
+ height,
+ pixels: Vec::new(),
+ })
+ }
+ }
+
+ #[test]
+ fn renderer_text_capacity_is_applied_without_recreating_warm_cache() {
+ let mut preview = Previewer::new(&EmptyVideo, &RenderOptions::default()).unwrap();
+ preview.configure_renderer_cache(&Renderer(Some(100_000)));
+ assert_eq!(preview.converter_text_cache_capacity, 100_000);
+ // A value carried by the converter must survive another frame's configuration.
+ preview.converter_cache.paint.insert(
+ "warm".into(),
+ usvgr::Paint::Color(usvgr::Color::new_rgb(1, 2, 3)),
+ );
+ preview.configure_renderer_cache(&Renderer(Some(100_000)));
+ assert!(preview.converter_cache.paint.contains_key("warm"));
+ preview.configure_renderer_cache(&Renderer(None));
+ assert_eq!(preview.converter_text_cache_capacity, 100_000);
+ preview.configure_renderer_cache(&Renderer(Some(0)));
+ assert_eq!(preview.converter_text_cache_capacity, 0);
+ assert!(preview.converter_cache.usvgr_text_cache.is_none());
+ }
+}
diff --git a/landing/benchmark-fable.mp4 b/landing/benchmark-fable.mp4
new file mode 100644
index 00000000..3cbeba73
Binary files /dev/null and b/landing/benchmark-fable.mp4 differ
diff --git a/landing/fframes-demo.av1.mp4 b/landing/fframes-demo.av1.mp4
index 88a2e024..244dc4a9 100644
Binary files a/landing/fframes-demo.av1.mp4 and b/landing/fframes-demo.av1.mp4 differ
diff --git a/landing/fframes-demo.mp4 b/landing/fframes-demo.mp4
index 359ba0d6..52f00e49 100644
Binary files a/landing/fframes-demo.mp4 and b/landing/fframes-demo.mp4 differ
diff --git a/render-bench/vs-remotion/Cargo.toml b/render-bench/vs-remotion/Cargo.toml
index a55bc46b..7b097870 100644
--- a/render-bench/vs-remotion/Cargo.toml
+++ b/render-bench/vs-remotion/Cargo.toml
@@ -7,9 +7,12 @@ publish = false
[dependencies]
fframes = { workspace = true, features = ["compile-time-svgtree"] }
serde_json = "1"
-png = "0.17"
+
+[target.'cfg(not(windows))'.dependencies]
+fframes = { workspace = true, features = ["h264", "libav-agree-gpl"] }
[target.'cfg(target_os = "macos")'.dependencies]
+fframes = { workspace = true, features = ["videotoolbox"] }
fframes_skia_renderer = { workspace = true, features = ["metal"] }
# Match the supported Linux/Windows Skia binary-cache feature set.
diff --git a/render-bench/vs-remotion/README.md b/render-bench/vs-remotion/README.md
index 18fbef13..b89a7e97 100644
--- a/render-bench/vs-remotion/README.md
+++ b/render-bench/vs-remotion/README.md
@@ -1,32 +1,63 @@
-# fframes + Skia vs Remotion
+# fframes vs Remotion
```sh
./render-bench/vs-remotion/run.sh
```
-Requires Rust, Node.js and Chromium (`CHROME_PATH` or `--chrome PATH`).
-Results and frame PNGs go to `out/`; use `--out DIR` to choose a directory.
-
-One fixed scene: 99,000 rectangles and 1,000 changing text digits at 1000×1000.
-Both use DM Sans Regular from `examples/beta/media/DMSans-Regular.ttf`.
-Remotion uses an unkeyed list with 12 dependent effect/state updates per element.
-fframes computes the same content directly with Skia CPU and, when available,
-Skia GPU (Metal on macOS, Vulkan elsewhere). GPU is skipped without a hardware device.
-Results apply to this React workload with many effects.
-
-All render serially without a video encoder. Times are medians of three 30-frame
-runs after three warm-up frames. PNG compression is included; startup, warm-up
-and disk writes are excluded.
-
-The runner writes timings and versions to `results.json`, with a summary in
-`results.md`. Generated results and dependency lockfiles are ignored.
-
-Measured on Linux ARM64 Docker at `8af4abe`, with Remotion 4.0.529:
-
-| Renderer | Median for 30 frames |
-| ------------------ | -----------------------: |
-| fframes + Skia CPU | 3.877 s |
-| fframes + Skia GPU | Skipped: no hardware GPU |
-| Remotion | 120.801 s |
+One scene, four pipelines: fframes CPU (tiny-skia), fframes + Skia GPU,
+Remotion + FFmpeg (`renderMedia`), and Remotion + MediaBunny (`renderMediaOnWeb`).
+
+The scene has 99,000 overlapping circles and 1,000 changing DM Sans digits in
+20 panels. Every circle moves and changes color; 10,000 radii animate between
+16 and 28 SVG units. The 1000×1000 viewBox stretches to 3840×2160. No filters.
+Both implementations use the same animation math. Remotion has one keyed
+component with `useCurrentFrame()` per drawable and a memoized parent tree.
+This is an SVG overdraw stress test, not a claim about all Remotion videos.
+
+Each pipeline exports one complete **300-frame, 10-second H.264 MP4**, without
+audio, after a three-frame warm-up. Timing includes rendering, conversion,
+encoder setup, encoding, draining, muxing and writes. Build, media preparation,
+browser launch, bundling and warm-up are excluded. MediaBunny writes to OPFS;
+copying its completed MP4 to the host is excluded. Output checks run after timing.
+
+Settings: 30 fps, 8 Mbps target, GOP 30, 4:2:0. CPU uses all logical cores and
+x264 medium. Skia uses `MaxPerformance`. Remotion + FFmpeg uses 18 tabs, capped
+by available logical cores, and its default browser graphics settings. Skia
+and Remotion + FFmpeg require hardware VideoToolbox on macOS; elsewhere they
+use x264. Native codecs use one thread per segment. MediaBunny uses WebCodecs
+`prefer-hardware`, which does not guarantee hardware encoding. Equal bitrate
+targets do not guarantee equal quality.
+
+Both fframes backends use 100,000-entry text caches. Skia also uses 100,000
+geometry entries with a 51.2 MB budget per generation. GPU runs are skipped
+when hardware is unavailable.
+
+Measured on an M5 Max, one run each:
+
+| Pipeline | Complete MP4 export | fframes GPU speedup |
+| -------------------------- | ------------------: | ------------------: |
+| fframes + Skia GPU | 7.225 s | — |
+| fframes CPU (tiny-skia) | 69.740 s | 9.65× |
+| Remotion + FFmpeg, 18 tabs | 109.227 s | 15.12× |
+| Remotion + MediaBunny | 121.132 s | 16.77× |
+
+CPU uses software x264 encoding. The FFmpeg browser used default software
+rasterization with hardware encoding; MediaBunny's Chrome reported Metal.
+An eight-tab FFmpeg check was faster at 98.759 s (13.67× versus fframes GPU).
+The fixed comparison above uses the requested 18 tabs.
+
+[Raw measurements and source hashes](measurements/m5-max-4k-circles.json)
+include the separate `usvgr` optimization used by the host build. To reproduce
+that dependency setup, check out the recorded `usvgr` commit beside this repo
+and put this in an untracked `.cargo/config.toml` before running:
+
+```toml
+[patch.crates-io]
+usvgr = { path = "../svgr/crates/usvgr" }
+```
-fframes + Skia CPU was **31.16×** faster for this workload.
+Requires Rust, Node.js, ffprobe and Chrome with H.264 WebCodecs support.
+Use `--chrome PATH` for MediaBunny, `--ffmpeg-chrome PATH` for FFmpeg, and
+`--out DIR` for outputs. Each pipeline has a ten-minute limit. `results.json`
+records settings, versions and output metadata; `results.md` shows all four
+pipelines. Generated exports are ignored. On macOS the runner prevents idle sleep.
diff --git a/render-bench/vs-remotion/browser.jsx b/render-bench/vs-remotion/browser.jsx
index 19108b99..59e5cc76 100644
--- a/render-bench/vs-remotion/browser.jsx
+++ b/render-bench/vs-remotion/browser.jsx
@@ -1,117 +1,107 @@
-import React, { useEffect, useLayoutEffect, useMemo, useState } from "react";
-import {
- Composition,
- registerRoot,
- staticFile,
- useCurrentFrame,
- useDelayRender,
-} from "remotion";
+import { renderMediaOnWeb } from "@remotion/web-renderer";
+import { GridVideo, WIDTH, HEIGHT } from "./scene.jsx";
-const nodes = 100000;
+let fontCss = "";
-const color = (id, frame) =>
- `rgb(${(id * 13 + frame * 17) % 256},${(id * 7 + frame * 29) % 256},${(id * 3 + frame * 43) % 256})`;
-function useDerivedFrame(input) {
- const [value, setValue] = useState(-1);
- useEffect(() => setValue(input), [input]);
- return value;
+async function exportVideo(config, name, frameRange) {
+ const root = await navigator.storage.getDirectory();
+ const start = performance.now();
+ const handle = await root.getFileHandle(name, { create: true });
+ const stream = await handle.createWritable();
+ await renderMediaOnWeb({
+ composition: {
+ id: "MixedGrid",
+ component: GridVideo,
+ width: WIDTH,
+ height: HEIGHT,
+ fps: 30,
+ durationInFrames: config.warmup + config.frames,
+ },
+ inputProps: { fontCss },
+ frameRange,
+ container: "mp4",
+ videoCodec: "h264",
+ videoBitrate: 8_000_000,
+ hardwareAcceleration: "prefer-hardware",
+ keyframeIntervalInSeconds: 1,
+ muted: true,
+ pageResponsiveness: "disabled",
+ delayRenderTimeoutInMilliseconds: config.timeout,
+ outputWritable: stream,
+ logLevel: "warn",
+ onProgress: ({ encodedFrames }) => {
+ fetch("/progress", {
+ method: "POST",
+ body: JSON.stringify({ name, encodedFrames }),
+ });
+ },
+ // Remotion omits duration; give the last frame its full interval in the MP4.
+ onFrame: frame => {
+ const index = Math.round((frame.timestamp * 30) / 1_000_000);
+ fetch("/progress", {
+ method: "POST",
+ body: JSON.stringify({ name, capturedFrame: index }),
+ });
+ const duration =
+ Math.round(((index + 1) * 1_000_000) / 30) - frame.timestamp;
+ return new VideoFrame(frame, { duration });
+ },
+ });
+ const export_ms = performance.now() - start;
+ const file = await handle.getFile();
+ const response = await fetch(`/save/${name}`, { method: "POST", body: file });
+ if (!response.ok)
+ throw new Error(`saving ${name} failed: ${response.status}`);
+ await root.removeEntry(name);
+ return { export_ms, bytes: file.size };
}
-// Twelve dependent effect/commit passes update each element’s visible content.
-function EffectCell({ id, slot, frame, ready }) {
- const a = useDerivedFrame(frame);
- const b = useDerivedFrame(a);
- const c = useDerivedFrame(b);
- const d = useDerivedFrame(c);
- const e = useDerivedFrame(d);
- const f = useDerivedFrame(e);
- const g = useDerivedFrame(f);
- const h = useDerivedFrame(g);
- const i = useDerivedFrame(h);
- const j = useDerivedFrame(i);
- const k = useDerivedFrame(j);
- const l = useDerivedFrame(k);
- useLayoutEffect(() => {
- if (l === frame) ready(frame);
- }, [l, frame, ready]);
- return cell(id, slot, Math.max(0, l));
-}
-function cell(id, slot, frame) {
- if (slot % 100 === 0) {
- const index = slot / 100;
- return (
- <text
- x={(index % 100) * 10 + 1}
- y={Math.floor(index / 100) * 10 + 7}
- fontFamily="DM Sans"
- fontSize="10"
- fill={color(id, frame)}
- >
- {(id + frame) % 10}
- </text>
- );
- }
- return (
- <rect
- x={slot % 1000}
- y={Math.floor(slot / 1000)}
- width="1"
- height="1"
- fill={color(id, frame)}
- />
- );
-}
-function GridVideo() {
- const frame = useCurrentFrame();
- const { delayRender, continueRender, cancelRender } = useDelayRender();
- const [fontHandle] = useState(() =>
- delayRender("benchmark font", { retries: 0 })
- );
- useEffect(() => {
- const font = new FontFace(
- "DM Sans",
- `url(${staticFile("DMSans-Regular.ttf")})`
+
+async function run() {
+ const config = await fetch("/config").then(r => r.json());
+ fontCss = await fetch("/font.css").then(r => r.text());
+ const gl = document.createElement("canvas").getContext("webgl");
+ const debug = gl?.getExtension("WEBGL_debug_renderer_info");
+ const support = await VideoEncoder.isConfigSupported({
+ codec: "avc1.640033",
+ width: WIDTH,
+ height: HEIGHT,
+ bitrate: 8_000_000,
+ framerate: 30,
+ hardwareAcceleration: "prefer-hardware",
+ });
+ if (!support.supported)
+ throw new Error(
+ "WebCodecs H.264 with prefer-hardware is unavailable in this browser"
);
- font
- .load()
- .then(loaded => {
- document.fonts.add(loaded);
- continueRender(fontHandle);
- })
- .catch(cancelRender);
- }, [fontHandle, continueRender, cancelRender]);
- const ready = useMemo(() => {
- const handle = delayRender(`frame ${frame} effects`, { retries: 0 });
- let remaining = nodes;
- return doneFrame => {
- if (doneFrame === frame && --remaining === 0) continueRender(handle);
- };
- }, [frame, delayRender, continueRender]);
- const cells = [];
- const append = slot => {
- const id = (slot + frame * 37) % nodes;
- cells.push(<EffectCell id={id} slot={slot} frame={frame} ready={ready} />);
+ const warmup = await exportVideo(config, "warmup.mp4", [
+ 0,
+ config.warmup - 1,
+ ]);
+ const result = await exportVideo(config, "export.mp4", [
+ config.warmup,
+ config.warmup + config.frames - 1,
+ ]);
+ return {
+ ...result,
+ encoder: "webcodecs-h264",
+ audio: false,
+ hardware_acceleration_preference: "prefer-hardware",
+ codec_configuration: support.config,
+ renderer: "@remotion/web-renderer renderMediaOnWeb",
+ browser: navigator.userAgent,
+ gpu: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : null,
+ output: "OPFS MP4; validation copy excluded",
+ explicit_frame_duration: true,
+ warmup_ms: warmup.export_ms,
+ concurrency: 1,
};
- // Paint text over the rectangles.
- for (let slot = 0; slot < nodes; slot++) if (slot % 100 !== 0) append(slot);
- for (let slot = 0; slot < nodes; slot += 100) append(slot);
- return (
- <svg
- width="1000"
- height="1000"
- style={{ display: "block", background: "#000" }}
- >
- {cells}
- </svg>
- );
}
-const Root = () => (
- <Composition
- id="MixedGrid"
- component={GridVideo}
- width={1000}
- height={1000}
- fps={30}
- durationInFrames={33}
- />
+
+run().then(
+ result => fetch("/result", { method: "POST", body: JSON.stringify(result) }),
+ error =>
+ fetch("/result", {
+ method: "POST",
+ body: JSON.stringify({ error: String(error), stack: error.stack }),
+ })
);
-registerRoot(Root);
diff --git a/render-bench/vs-remotion/ffmpeg.mjs b/render-bench/vs-remotion/ffmpeg.mjs
new file mode 100644
index 00000000..4f7487c6
--- /dev/null
+++ b/render-bench/vs-remotion/ffmpeg.mjs
@@ -0,0 +1,121 @@
+import fs from "node:fs/promises";
+import path from "node:path";
+import os from "node:os";
+import { execFileSync } from "node:child_process";
+import {
+ ensureBrowser,
+ openBrowser,
+ selectComposition,
+ renderMedia,
+} from "@remotion/renderer";
+
+export async function ffmpegWorker(config) {
+ const resolved = await ensureBrowser({
+ browserExecutable: config.ffmpeg_chrome,
+ logLevel: "error",
+ });
+ if (!("path" in resolved))
+ throw new Error(`Remotion browser unavailable: ${resolved.type}`);
+ const chrome = resolved.path;
+ const font = await fs.readFile(
+ new URL("./media/DMSans-Regular.ttf", import.meta.url)
+ );
+ const inputProps = {
+ fontCss: `@font-face{font-family:"DM Sans";font-style:normal;font-weight:400;src:url(data:font/ttf;base64,${font.toString("base64")}) format("truetype");}`,
+ };
+ const chromiumOptions = { disableWebSecurity: false };
+ const browser = await openBrowser("chrome", {
+ browserExecutable: chrome,
+ chromiumOptions,
+ logLevel: "error",
+ });
+ try {
+ const composition = await selectComposition({
+ serveUrl: config.bundle,
+ inputProps,
+ id: "MixedGrid",
+ puppeteerInstance: browser,
+ timeoutInMilliseconds: config.timeout,
+ logLevel: "error",
+ });
+ const hardwareEncoding = process.platform === "darwin";
+ const encoder = hardwareEncoding ? "h264_videotoolbox" : "libx264";
+ let concurrency;
+ const encodingCommands = [];
+ const encoding = {
+ codec: "h264",
+ ...(hardwareEncoding ? {} : { x264Preset: "medium" }),
+ videoBitrate: "8M",
+ gopSize: 30,
+ pixelFormat: "yuv420p",
+ muted: true,
+ hardwareAcceleration: hardwareEncoding ? "required" : "disable",
+ colorSpace: "bt601",
+ ffmpegOverride: ({ args }) => {
+ const videoCodecIndex = args.indexOf("-c:v");
+ const selected = videoCodecIndex < 0 ? null : args[videoCodecIndex + 1];
+ if (selected && selected !== "copy" && selected !== encoder)
+ throw new Error(`unexpected encoder: ${selected}`);
+ const command = [
+ ...args.slice(0, -1),
+ "-threads",
+ "1",
+ ...(hardwareEncoding && selected === encoder
+ ? ["-allow_sw", "0"]
+ : []),
+ args.at(-1),
+ ];
+ encodingCommands.push(command);
+ return command;
+ },
+ };
+ const options = {
+ ...encoding,
+ composition,
+ serveUrl: config.bundle,
+ inputProps,
+ puppeteerInstance: browser,
+ concurrency: Math.min(18, os.availableParallelism()),
+ onStart: ({ resolvedConcurrency }) => {
+ concurrency = resolvedConcurrency;
+ },
+ timeoutInMilliseconds: config.timeout,
+ logLevel: "error",
+ };
+ const warmup = path.join(config.directory, "warmup.mp4");
+ await renderMedia({
+ ...options,
+ frameRange: [0, config.warmup - 1],
+ outputLocation: warmup,
+ });
+ encodingCommands.length = 0;
+ const start = performance.now();
+ await renderMedia({
+ ...options,
+ frameRange: [config.warmup, config.warmup + config.frames - 1],
+ outputLocation: path.join(config.directory, "export.mp4"),
+ onProgress: ({ renderedFrames, encodedFrames }) => {
+ fs.writeFile(
+ path.join(config.directory, "progress.log"),
+ JSON.stringify({ renderedFrames, encodedFrames })
+ ).catch(() => {});
+ },
+ });
+ const export_ms = performance.now() - start;
+ await fs.unlink(warmup);
+ return {
+ export_ms,
+ encoder,
+ hardware_encoding: hardwareEncoding,
+ encoding_commands: encodingCommands,
+ renderer: "@remotion/renderer renderMedia",
+ concurrency,
+ browser: execFileSync(chrome, ["--version"], {
+ encoding: "utf8",
+ }).trim(),
+ chromium_options: chromiumOptions,
+ };
+ } finally {
+ await browser.close({ silent: true });
+ }
+}
diff --git a/render-bench/vs-remotion/measurements/m5-max-4k-circles.json b/render-bench/vs-remotion/measurements/m5-max-4k-circles.json
new file mode 100644
index 00000000..7b16be1d
--- /dev/null
+++ b/render-bench/vs-remotion/measurements/m5-max-4k-circles.json
@@ -0,0 +1,202 @@
+{
+ "measured_at": "2026-10-02",
+ "machine": {
+ "model": "Apple M5 Max",
+ "logical_cpus": 18,
+ "memory_gib": 128
+ },
+ "workload": {
+ "nodes": 100000,
+ "circles": 99000,
+ "text": 1000,
+ "width": 3840,
+ "height": 2160,
+ "frames": 300,
+ "fps": 30,
+ "filters": 0,
+ "animated_radii": 10000,
+ "source_sha256": {
+ "run.mjs": "668124daafccd402aa972f8da831ddc888959dd3efa0e95962d1b7e017fd65d2",
+ "web.mjs": "de0fa5d65e1cfa6c840dab0d7f96b6f047972fc3263f1b7cdfe14dd5c7e78985",
+ "ffmpeg.mjs": "a9d9f053f1bf8722df28a50353886352af34b19a12761d9ef846e451385ce27a",
+ "browser.jsx": "6e8184feaf37b3d092fff9da262d51c627c4220bfbada778c57e56ba587bf65b",
+ "process.mjs": "b53dd8865bc7d0f124e764e55361cefad92ec11821ceb23264b6d6ee3e490d43",
+ "scene.jsx": "cf278fd1af9195d146c707c76035f63c7e6f2a2b7a73e642ab0f1972e3ed4b5b",
+ "report.mjs": "66b37f3c091d799caa492ceeb36c8a92d518e71bc926d0c891564e974cb59781",
+ "package.json": "e83f1eb8f0bfb174fa72f596150f83c7a62b770a92a6313473d8c9a6add79b91",
+ "server.jsx": "fffe47a1df4ed8df7414b5c925b9d091abf4053d266f9822d29d4200bac0089f",
+ "main.rs": "528327d57167ec47016861ee11b9a348146727de8410d641c12ae6aaefd94580"
+ }
+ },
+ "measurement": "One complete 300-frame H.264 MP4 export per pipeline after three warm-up frames; no audio. Build, media preparation, bundling, browser launch, warm-up and MediaBunny OPFS-to-host copy excluded.",
+ "source": {
+ "fframes_base_commit": "68ef9722d54443d4058cf2d2e051159cfe684b8e",
+ "usvgr_base_commit": "8657f976ce221dcffaf28c2a5de5103e922b30eb",
+ "usvgr_commit": "1c2a088217eb3365e965fd8dbd62acf265a07d33",
+ "fframes_renderer_commit": "04865260b13f66fa5004b472b95877990882de9a",
+ "benchmark_note": "Source hashes describe the measured scene before identifier, formatting and metadata cleanup. The circle animation math is unchanged."
+ },
+ "versions": {
+ "remotion": "4.0.529",
+ "react": "19.2.0",
+ "mediabunny": "1.56.1"
+ },
+ "browser_graphics": {
+ "remotion-ffmpeg": "Default headless Chrome: software rasterization; VideoToolbox hardware encoding.",
+ "remotion-mediabunny": "Chrome reported ANGLE Metal on Apple M5 Max; WebCodecs prefer-hardware."
+ },
+ "records": [
+ {
+ "engine": "fframes-gpu",
+ "status": "ok",
+ "load_before": [6.36572265625, 11.033203125, 9.80810546875],
+ "load_after": [7.29248046875, 11.080078125, 9.8388671875],
+ "audio": false,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "concurrency": {
+ "encoder_threads": 18,
+ "policy": "MaxPerformance"
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 7225.018333,
+ "ffmpeg": "46d8f46",
+ "fps": 30,
+ "frames": 300,
+ "hardware_encoding": true,
+ "nodes": 100000,
+ "video": {
+ "codec_name": "h264",
+ "width": 3840,
+ "height": 2160,
+ "avg_frame_rate": "30/1",
+ "duration": "10.000000",
+ "nb_frames": "300"
+ }
+ },
+ {
+ "engine": "remotion-ffmpeg",
+ "status": "ok",
+ "load_before": [7.29248046875, 11.080078125, 9.8388671875],
+ "load_after": [252.47412109375, 94.68212890625, 42.4697265625],
+ "export_ms": 109227.19979099999,
+ "encoder": "h264_videotoolbox",
+ "hardware_encoding": true,
+ "renderer": "@remotion/renderer renderMedia",
+ "concurrency": 18,
+ "browser": "Google Chrome for Testing 149.0.7790.0",
+ "chromium_options": {
+ "disableWebSecurity": false
+ },
+ "video": {
+ "codec_name": "h264",
+ "width": 3840,
+ "height": 2160,
+ "avg_frame_rate": "30/1",
+ "duration": "10.000000",
+ "nb_frames": "300",
+ "side_data_list": [{}]
+ },
+ "fframes_gpu_speedup": 15.117913167376871
+ },
+ {
+ "engine": "remotion-mediabunny",
+ "status": "ok",
+ "load_before": [7.0947265625, 26.22314453125, 29.8193359375],
+ "load_after": [4.73095703125, 18.8232421875, 26.37890625],
+ "export_ms": 121132.09999999404,
+ "bytes": 66626599,
+ "encoder": "webcodecs-h264",
+ "audio": false,
+ "hardware_acceleration_preference": "prefer-hardware",
+ "codec_configuration": {
+ "alpha": "discard",
+ "bitrate": 8000000,
+ "bitrateMode": "variable",
+ "codec": "avc1.640033",
+ "contentHint": "",
+ "framerate": 30,
+ "hardwareAcceleration": "prefer-hardware",
+ "height": 2160,
+ "latencyMode": "quality",
+ "width": 3840
+ },
+ "renderer": "@remotion/web-renderer renderMediaOnWeb",
+ "browser": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",
+ "gpu": "ANGLE (Apple, ANGLE Metal Renderer: Apple M5 Max, Unspecified Version)",
+ "output": "OPFS MP4; validation copy excluded",
+ "explicit_frame_duration": true,
+ "warmup_ms": 1370.800000011921,
+ "concurrency": 1,
+ "video": {
+ "codec_name": "h264",
+ "width": 3840,
+ "height": 2160,
+ "avg_frame_rate": "30/1",
+ "duration": "10.000000",
+ "nb_frames": "300"
+ },
+ "fframes_gpu_speedup": 16.76564603950245
+ },
+ {
+ "engine": "fframes",
+ "status": "ok",
+ "load_before": [4.5869140625, 5.21435546875, 10.197265625],
+ "load_after": [41.6064453125, 17.11474609375, 14.341796875],
+ "audio": false,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "concurrency": {
+ "render_threads": 18
+ },
+ "encoder": "libx264",
+ "export_ms": 69740.38620899999,
+ "ffmpeg": "46d8f46",
+ "fps": 30,
+ "frames": 300,
+ "hardware_encoding": false,
+ "nodes": 100000,
+ "video": {
+ "codec_name": "h264",
+ "width": 3840,
+ "height": 2160,
+ "avg_frame_rate": "30/1",
+ "duration": "10.000000",
+ "nb_frames": "300"
+ },
+ "fframes_gpu_speedup": 9.652624117293017
+ }
+ ],
+ "concurrency_check": {
+ "engine": "remotion-ffmpeg",
+ "status": "ok",
+ "load_before": [155.59375, 86.3046875, 41.24365234375],
+ "load_after": [73.6611328125, 78.32763671875, 43.3857421875],
+ "export_ms": 98759.18274999999,
+ "encoder": "h264_videotoolbox",
+ "hardware_encoding": true,
+ "renderer": "@remotion/renderer renderMedia",
+ "concurrency": 8,
+ "browser": "Google Chrome for Testing 149.0.7790.0",
+ "chromium_options": {
+ "disableWebSecurity": false
+ },
+ "video": {
+ "codec_name": "h264",
+ "width": 3840,
+ "height": 2160,
+ "avg_frame_rate": "30/1",
+ "duration": "10.000000",
+ "nb_frames": "300",
+ "side_data_list": [{}]
+ },
+ "fframes_gpu_speedup": 13.669056353659496
+ }
+}
diff --git a/render-bench/vs-remotion/measurements/m5-max-ffmpeg.json b/render-bench/vs-remotion/measurements/m5-max-ffmpeg.json
new file mode 100644
index 00000000..92175744
--- /dev/null
+++ b/render-bench/vs-remotion/measurements/m5-max-ffmpeg.json
@@ -0,0 +1,480 @@
+{
+ "schema_version": 9,
+ "comparison": "Remotion vs fframes CPU and Skia GPU: complete H.264 MP4 export",
+ "encoding": {
+ "codec": "h264",
+ "target_bitrate": 8000000,
+ "cpu_encoder": "libx264 medium",
+ "macos_gpu_encoder": "h264_videotoolbox",
+ "macos_remotion_encoder": "h264_videotoolbox",
+ "gop": 30,
+ "pixel_format": "yuv420p",
+ "codec_threads": 1,
+ "fps": 30,
+ "audio": false
+ },
+ "workload": "20 animated panels: 99,000 overlapping 16–28px rectangles, 8px blurred saturated glows, 12px drop shadows, and 1,000 changing DM Sans text digits painted last",
+ "plan": {
+ "nodes": 100000,
+ "effect_passes": 12,
+ "rounds": 3,
+ "frames": 30,
+ "warmup": 3,
+ "timeout": 600000,
+ "backends": ["cpu", "skia-gpu-if-available"],
+ "chrome": "/Users/dkovalenko/dev/fframes-m5-main/render-bench/vs-remotion/node_modules/.remotion/chrome-headless-shell/mac-arm64/chrome-headless-shell-mac-arm64/chrome-headless-shell"
+ },
+ "environment": {
+ "platform": "darwin",
+ "arch": "arm64",
+ "cpus": "Apple M5 Max",
+ "logical_cpus": 18,
+ "memory_bytes": 137438953472,
+ "node": "v26.10.0",
+ "remotion": "4.0.529",
+ "react": "19.2.0",
+ "git": "4ffb052d3430e0672b4f3647450c181606ddf418",
+ "dirty": true,
+ "command": [
+ "/opt/homebrew/Cellar/node/26.10.0_1/bin/node",
+ "/Users/dkovalenko/dev/fframes-m5-main/render-bench/vs-remotion/run.mjs",
+ "--binary",
+ "/Users/dkovalenko/.cache/fframes-m5-bench-target/release/vs-remotion-bench",
+ "--chrome",
+ "/Users/dkovalenko/dev/fframes-m5-main/render-bench/vs-remotion/node_modules/.remotion/chrome-headless-shell/mac-arm64/chrome-headless-shell-mac-arm64/chrome-headless-shell",
+ "--out",
+ "/Users/dkovalenko/.cache/fframes-cpu-backend-m5-verified"
+ ],
+ "font_sha256": "9ae2da663d64342031e59b5fa680dd355171d021b7ebf83774efc7c0330ae7b5",
+ "binary_sha256": "0d65b1c0700178caf86d165272605b630eff804ac94d16ee66ab12b15c4251d7",
+ "browser_bundle_sha256": "f8e7279795be49c3b15e72d37590680912bcedde6a5265bfe1cc94e316152886"
+ },
+ "records": [
+ {
+ "nodes": 100000,
+ "engine": "fframes",
+ "round": 0,
+ "status": "ok",
+ "load_before": [5.01123046875, 16.681640625, 26.8349609375],
+ "load_after": [4.84912109375, 16.26318359375, 26.5673828125],
+ "code": 0,
+ "signal": null,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "encoder": "libx264",
+ "export_ms": 8372.913792000001,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": false,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 1653807
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes-gpu",
+ "round": 0,
+ "status": "ok",
+ "load_before": [4.84912109375, 16.26318359375, 26.5673828125],
+ "load_after": [4.86083984375, 16.076171875, 26.44091796875],
+ "code": 0,
+ "signal": null,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 1435.3076250000001,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": true,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2435570
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "remotion",
+ "round": 0,
+ "status": "ok",
+ "load_before": [4.86083984375, 16.076171875, 26.44091796875],
+ "load_after": [7.52490234375, 13.38134765625, 24.0498046875],
+ "code": 0,
+ "signal": null,
+ "export_ms": 103501.581042,
+ "encoder": "h264_videotoolbox",
+ "hardware_encoding": true,
+ "encoding_commands": [
+ [
+ "-r",
+ 30,
+ "-f",
+ "image2pipe",
+ "-s",
+ "1000x1000",
+ "-vcodec",
+ "mjpeg",
+ "-i",
+ "-",
+ "-c:v",
+ "h264_videotoolbox",
+ "-pix_fmt",
+ "yuv420p",
+ "-g",
+ "30",
+ "-video_track_timescale",
+ "90000",
+ "-b:v",
+ "8M",
+ "-y",
+ "-threads",
+ "1",
+ "-allow_sw",
+ "0",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/react-motion-render2JPZuf/pre-encode.mp4"
+ ],
+ [
+ "-i",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/react-motion-render2JPZuf/pre-encode.mp4",
+ "-an",
+ "-c:v",
+ "copy",
+ "-map_metadata",
+ "-1",
+ "-metadata",
+ "comment=Made with Remotion 4.0.529",
+ "-y",
+ "-f",
+ "mp4",
+ "-threads",
+ "1",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/remotion-v4.0.529-assetsnzfwoo27vh/remotion-stitch-temp-dir/fast-start-intermediate.remotion-in-progress"
+ ]
+ ],
+ "renderer": "@remotion/renderer renderMedia",
+ "concurrency": 1,
+ "browser": "Google Chrome for Testing 149.0.7790.0",
+ "chromium_options": {
+ "disableWebSecurity": false
+ },
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuvj420p",
+ "color_range": "pc",
+ "bytes": 2730815
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes-gpu",
+ "round": 1,
+ "status": "ok",
+ "load_before": [7.52490234375, 13.38134765625, 24.0498046875],
+ "load_after": [7.52490234375, 13.38134765625, 24.0498046875],
+ "code": 0,
+ "signal": null,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 1535.576042,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": true,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2435570
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "remotion",
+ "round": 1,
+ "status": "ok",
+ "load_before": [7.52490234375, 13.38134765625, 24.0498046875],
+ "load_after": [7.66015625, 11.5771484375, 21.98291015625],
+ "code": 0,
+ "signal": null,
+ "export_ms": 102802.527041,
+ "encoder": "h264_videotoolbox",
+ "hardware_encoding": true,
+ "encoding_commands": [
+ [
+ "-r",
+ 30,
+ "-f",
+ "image2pipe",
+ "-s",
+ "1000x1000",
+ "-vcodec",
+ "mjpeg",
+ "-i",
+ "-",
+ "-c:v",
+ "h264_videotoolbox",
+ "-pix_fmt",
+ "yuv420p",
+ "-g",
+ "30",
+ "-video_track_timescale",
+ "90000",
+ "-b:v",
+ "8M",
+ "-y",
+ "-threads",
+ "1",
+ "-allow_sw",
+ "0",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/react-motion-renderHQcd77/pre-encode.mp4"
+ ],
+ [
+ "-i",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/react-motion-renderHQcd77/pre-encode.mp4",
+ "-an",
+ "-c:v",
+ "copy",
+ "-map_metadata",
+ "-1",
+ "-metadata",
+ "comment=Made with Remotion 4.0.529",
+ "-y",
+ "-f",
+ "mp4",
+ "-threads",
+ "1",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/remotion-v4.0.529-assetscy564epzqv/remotion-stitch-temp-dir/fast-start-intermediate.remotion-in-progress"
+ ]
+ ],
+ "renderer": "@remotion/renderer renderMedia",
+ "concurrency": 1,
+ "browser": "Google Chrome for Testing 149.0.7790.0",
+ "chromium_options": {
+ "disableWebSecurity": false
+ },
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuvj420p",
+ "color_range": "pc",
+ "bytes": 2730815
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes",
+ "round": 1,
+ "status": "ok",
+ "load_before": [7.66015625, 11.5771484375, 21.98291015625],
+ "load_after": [7.0966796875, 11.3271484375, 21.7724609375],
+ "code": 0,
+ "signal": null,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "encoder": "libx264",
+ "export_ms": 8667.137042,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": false,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 1653807
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "remotion",
+ "round": 2,
+ "status": "ok",
+ "load_before": [7.0966796875, 11.3271484375, 21.7724609375],
+ "load_after": [5.6767578125, 9.58447265625, 19.8779296875],
+ "code": 0,
+ "signal": null,
+ "export_ms": 97089.24375,
+ "encoder": "h264_videotoolbox",
+ "hardware_encoding": true,
+ "encoding_commands": [
+ [
+ "-r",
+ 30,
+ "-f",
+ "image2pipe",
+ "-s",
+ "1000x1000",
+ "-vcodec",
+ "mjpeg",
+ "-i",
+ "-",
+ "-c:v",
+ "h264_videotoolbox",
+ "-pix_fmt",
+ "yuv420p",
+ "-g",
+ "30",
+ "-video_track_timescale",
+ "90000",
+ "-b:v",
+ "8M",
+ "-y",
+ "-threads",
+ "1",
+ "-allow_sw",
+ "0",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/react-motion-renderb5hwul/pre-encode.mp4"
+ ],
+ [
+ "-i",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/react-motion-renderb5hwul/pre-encode.mp4",
+ "-an",
+ "-c:v",
+ "copy",
+ "-map_metadata",
+ "-1",
+ "-metadata",
+ "comment=Made with Remotion 4.0.529",
+ "-y",
+ "-f",
+ "mp4",
+ "-threads",
+ "1",
+ "/var/folders/3n/m0mym_ms2jjfg_hwzlmsp8rh0000gn/T/remotion-v4.0.529-assetscftwjec2fu/remotion-stitch-temp-dir/fast-start-intermediate.remotion-in-progress"
+ ]
+ ],
+ "renderer": "@remotion/renderer renderMedia",
+ "concurrency": 1,
+ "browser": "Google Chrome for Testing 149.0.7790.0",
+ "chromium_options": {
+ "disableWebSecurity": false
+ },
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuvj420p",
+ "color_range": "pc",
+ "bytes": 2730815
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes",
+ "round": 2,
+ "status": "ok",
+ "load_before": [5.6767578125, 9.58447265625, 19.8779296875],
+ "load_after": [5.111328125, 9.33447265625, 19.66845703125],
+ "code": 0,
+ "signal": null,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "encoder": "libx264",
+ "export_ms": 8349.115625,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": false,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 1653807
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes-gpu",
+ "round": 2,
+ "status": "ok",
+ "load_before": [5.111328125, 9.33447265625, 19.66845703125],
+ "load_after": [4.94189453125, 9.22900390625, 19.5703125],
+ "code": 0,
+ "signal": null,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 1419.415083,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": true,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2435570
+ }
+ }
+ ],
+ "summary": {
+ "status": "complete",
+ "export_median_ms": {
+ "cpu": 8372.913792000001,
+ "gpu": 1435.3076250000001,
+ "remotion": 102802.527041
+ },
+ "speedup": 12.277987041885451,
+ "gpu_speedup": 71.62403741915604,
+ "gpu_status": "complete",
+ "gpu_skip_reason": null
+ }
+}
diff --git a/render-bench/vs-remotion/measurements/m5-max-mediabunny.json b/render-bench/vs-remotion/measurements/m5-max-mediabunny.json
new file mode 100644
index 00000000..3c6ea504
--- /dev/null
+++ b/render-bench/vs-remotion/measurements/m5-max-mediabunny.json
@@ -0,0 +1,380 @@
+{
+ "schema_version": 10,
+ "comparison": "Remotion + MediaBunny vs fframes CPU and Skia GPU: complete H.264 MP4 export",
+ "encoding": {
+ "codec": "h264",
+ "target_bitrate": 8000000,
+ "cpu_encoder": "libx264 medium",
+ "macos_gpu_encoder": "h264_videotoolbox",
+ "remotion_encoder": "WebCodecs H.264, prefer-hardware",
+ "gop": 30,
+ "pixel_format": "yuv420p",
+ "native_codec_threads": 1,
+ "fps": 30,
+ "audio": false
+ },
+ "workload": "20 animated panels: 99,000 overlapping 16–28px rectangles, 8px blurred saturated glows, 12px drop shadows, and 1,000 changing DM Sans text digits painted last",
+ "plan": {
+ "nodes": 100000,
+ "effect_passes": 12,
+ "rounds": 3,
+ "frames": 30,
+ "warmup": 3,
+ "timeout": 600000,
+ "backends": ["cpu", "skia-gpu-if-available"],
+ "chrome": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
+ },
+ "environment": {
+ "platform": "darwin",
+ "arch": "arm64",
+ "cpus": "Apple M5 Max",
+ "logical_cpus": 18,
+ "memory_bytes": 137438953472,
+ "node": "v26.10.0",
+ "remotion": "4.0.529",
+ "mediabunny": "1.56.1",
+ "react": "19.2.0",
+ "git": "4ffb052d3430e0672b4f3647450c181606ddf418",
+ "dirty": true,
+ "command": [
+ "/opt/homebrew/Cellar/node/26.10.0_1/bin/node",
+ "/Users/dkovalenko/dev/fframes-m5-main/render-bench/vs-remotion/run.mjs",
+ "--binary",
+ "/Users/dkovalenko/.cache/fframes-m5-bench-target/release/vs-remotion-bench",
+ "--out",
+ "/Users/dkovalenko/.cache/fframes-mediabunny-m5-final"
+ ],
+ "font_sha256": "9ae2da663d64342031e59b5fa680dd355171d021b7ebf83774efc7c0330ae7b5",
+ "binary_sha256": "0d65b1c0700178caf86d165272605b630eff804ac94d16ee66ab12b15c4251d7",
+ "browser_bundle_sha256": "c44b41e93daa25642de45851a9fc859233c89b484155d2c931afc3a01a338cb7"
+ },
+ "records": [
+ {
+ "nodes": 100000,
+ "engine": "fframes",
+ "round": 0,
+ "status": "ok",
+ "load_before": [10.86865234375, 6.97607421875, 6.13818359375],
+ "load_after": [9.8984375, 6.89453125, 6.11865234375],
+ "code": 0,
+ "signal": null,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "encoder": "libx264",
+ "export_ms": 8820.673375,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": false,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 1653807
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes-gpu",
+ "round": 0,
+ "status": "ok",
+ "load_before": [9.8984375, 6.89453125, 6.11865234375],
+ "load_after": [9.8984375, 6.89453125, 6.11865234375],
+ "code": 0,
+ "signal": null,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 1514.4243749999998,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": true,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2435570
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "remotion",
+ "round": 0,
+ "status": "ok",
+ "load_before": [9.8984375, 6.89453125, 6.11865234375],
+ "load_after": [9.1259765625, 7.2080078125, 6.32666015625],
+ "code": 0,
+ "signal": null,
+ "export_ms": 112273.70000000298,
+ "bytes": 2371038,
+ "encoder": "webcodecs-h264",
+ "hardware_acceleration_preference": "prefer-hardware",
+ "codec_configuration": {
+ "alpha": "discard",
+ "bitrate": 8000000,
+ "bitrateMode": "variable",
+ "codec": "avc1.640020",
+ "contentHint": "",
+ "framerate": 30,
+ "hardwareAcceleration": "prefer-hardware",
+ "height": 1000,
+ "latencyMode": "quality",
+ "width": 1000
+ },
+ "renderer": "@remotion/web-renderer renderMediaOnWeb",
+ "browser": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",
+ "gpu": "ANGLE (Apple, ANGLE Metal Renderer: Apple M5 Max, Unspecified Version)",
+ "output": "OPFS MP4; validation copy excluded",
+ "explicit_frame_duration": true,
+ "warmup_ms": 10872.79999999702,
+ "concurrency": 1,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2371038
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes-gpu",
+ "round": 1,
+ "status": "ok",
+ "load_before": [9.1259765625, 7.2080078125, 6.32666015625],
+ "load_after": [9.1259765625, 7.2080078125, 6.32666015625],
+ "code": 0,
+ "signal": null,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 1568.629209,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": true,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2435570
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "remotion",
+ "round": 1,
+ "status": "ok",
+ "load_before": [9.1259765625, 7.2080078125, 6.32666015625],
+ "load_after": [7.80859375, 7.27783203125, 6.46630859375],
+ "code": 0,
+ "signal": null,
+ "export_ms": 110644.69999998808,
+ "bytes": 2371038,
+ "encoder": "webcodecs-h264",
+ "hardware_acceleration_preference": "prefer-hardware",
+ "codec_configuration": {
+ "alpha": "discard",
+ "bitrate": 8000000,
+ "bitrateMode": "variable",
+ "codec": "avc1.640020",
+ "contentHint": "",
+ "framerate": 30,
+ "hardwareAcceleration": "prefer-hardware",
+ "height": 1000,
+ "latencyMode": "quality",
+ "width": 1000
+ },
+ "renderer": "@remotion/web-renderer renderMediaOnWeb",
+ "browser": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",
+ "gpu": "ANGLE (Apple, ANGLE Metal Renderer: Apple M5 Max, Unspecified Version)",
+ "output": "OPFS MP4; validation copy excluded",
+ "explicit_frame_duration": true,
+ "warmup_ms": 10790.60000000894,
+ "concurrency": 1,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2371038
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes",
+ "round": 1,
+ "status": "ok",
+ "load_before": [7.80859375, 7.27783203125, 6.46630859375],
+ "load_after": [7.30908203125, 7.18603515625, 6.44287109375],
+ "code": 0,
+ "signal": null,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "encoder": "libx264",
+ "export_ms": 8361.135958,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": false,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 1653807
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "remotion",
+ "round": 2,
+ "status": "ok",
+ "load_before": [7.30908203125, 7.18603515625, 6.44287109375],
+ "load_after": [8.8330078125, 7.56201171875, 6.67529296875],
+ "code": 0,
+ "signal": null,
+ "export_ms": 112594.09999999404,
+ "bytes": 2371038,
+ "encoder": "webcodecs-h264",
+ "hardware_acceleration_preference": "prefer-hardware",
+ "codec_configuration": {
+ "alpha": "discard",
+ "bitrate": 8000000,
+ "bitrateMode": "variable",
+ "codec": "avc1.640020",
+ "contentHint": "",
+ "framerate": 30,
+ "hardwareAcceleration": "prefer-hardware",
+ "height": 1000,
+ "latencyMode": "quality",
+ "width": 1000
+ },
+ "renderer": "@remotion/web-renderer renderMediaOnWeb",
+ "browser": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",
+ "gpu": "ANGLE (Apple, ANGLE Metal Renderer: Apple M5 Max, Unspecified Version)",
+ "output": "OPFS MP4; validation copy excluded",
+ "explicit_frame_duration": true,
+ "warmup_ms": 10506.70000000298,
+ "concurrency": 1,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2371038
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes",
+ "round": 2,
+ "status": "ok",
+ "load_before": [8.8330078125, 7.56201171875, 6.67529296875],
+ "load_after": [8.16943359375, 7.46044921875, 6.6494140625],
+ "code": 0,
+ "signal": null,
+ "backend": "cpu",
+ "cache": {
+ "layer_capacity": 20,
+ "text_capacity": 100000
+ },
+ "encoder": "libx264",
+ "export_ms": 8435.747334,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": false,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 1653807
+ }
+ },
+ {
+ "nodes": 100000,
+ "engine": "fframes-gpu",
+ "round": 2,
+ "status": "ok",
+ "load_before": [8.16943359375, 7.46044921875, 6.6494140625],
+ "load_after": [8.16943359375, 7.46044921875, 6.6494140625],
+ "code": 0,
+ "signal": null,
+ "backend": "skia-metal",
+ "cache": {
+ "geometry_bytes": 51200000,
+ "geometry_capacity": 100000,
+ "text_capacity": 100000
+ },
+ "encoder": "h264_videotoolbox",
+ "export_ms": 1435.0492909999998,
+ "ffmpeg": "46d8f46",
+ "hardware_encoding": true,
+ "video": {
+ "frames": 30,
+ "fps": 30,
+ "duration_s": 1,
+ "width": 1000,
+ "height": 1000,
+ "codec": "h264",
+ "pixel_format": "yuv420p",
+ "color_range": "tv",
+ "bytes": 2435570
+ }
+ }
+ ],
+ "summary": {
+ "status": "complete",
+ "export_median_ms": {
+ "cpu": 8435.747334,
+ "gpu": 1514.4243749999998,
+ "remotion": 112273.70000000298
+ },
+ "speedup": 13.309277240617147,
+ "gpu_speedup": 74.13622089911422,
+ "gpu_status": "complete",
+ "gpu_skip_reason": null
+ }
+}
diff --git a/render-bench/vs-remotion/package.json b/render-bench/vs-remotion/package.json
index 5dda2b71..5e2cb17e 100644
--- a/render-bench/vs-remotion/package.json
+++ b/render-bench/vs-remotion/package.json
@@ -5,6 +5,7 @@
"dependencies": {
"@remotion/bundler": "4.0.529",
"@remotion/renderer": "4.0.529",
+ "@remotion/web-renderer": "4.0.529",
"react": "19.2.0",
"react-dom": "19.2.0",
"remotion": "4.0.529"
diff --git a/render-bench/vs-remotion/report.mjs b/render-bench/vs-remotion/report.mjs
index 23c00cb6..c3bbb746 100644
--- a/render-bench/vs-remotion/report.mjs
+++ b/render-bench/vs-remotion/report.mjs
@@ -1,62 +1,89 @@
-function median(values) {
- const sorted = [...values].sort((a, b) => a - b);
- return sorted[Math.floor(sorted.length / 2)];
-}
+export const engines = [
+ "fframes",
+ "fframes-gpu",
+ "remotion-ffmpeg",
+ "remotion-mediabunny",
+];
+const labels = {
+ fframes: "fframes CPU (tiny-skia)",
+ "fframes-gpu": "fframes + Skia GPU",
+ "remotion-ffmpeg": "Remotion + FFmpeg",
+ "remotion-mediabunny": "Remotion + MediaBunny",
+};
+
export function summarize(records, plan) {
- const native = records.filter(r => r.engine === "fframes");
- const browser = records.filter(r => r.engine === "remotion");
- const gpu = records.filter(r => r.engine === "fframes-gpu");
- const valid = runs =>
- runs.length === plan.rounds &&
- new Set(runs.map(r => r.round)).size === plan.rounds &&
- runs.every(
- r =>
- r.status === "ok" &&
- r.samples?.length === plan.frames &&
- r.samples.every(
- (s, i) =>
- s.frame === plan.warmup + i &&
- Number.isFinite(s.total_ms) &&
- s.total_ms > 0
- )
- );
- const complete = valid(native) && valid(browser);
- const gpuComplete = valid(gpu);
- const gpuSkipped =
- gpu.length === plan.rounds && gpu.every(r => r.status === "skipped");
- const total = r => r.samples.reduce((n, s) => n + s.total_ms, 0);
- const fframes = complete ? median(native.map(total)) : null;
- const remotion = complete ? median(browser.map(total)) : null;
- const gpuMs = gpuComplete ? median(gpu.map(total)) : null;
+ const results = Object.fromEntries(
+ engines.map(engine => {
+ const runs = records.filter(r => r.engine === engine);
+ const complete =
+ runs.length === plan.rounds &&
+ new Set(runs.map(r => r.round)).size === plan.rounds;
+ const skipped =
+ engine === "fframes-gpu" &&
+ complete &&
+ runs.every(r => r.status === "skipped");
+ const valid =
+ complete &&
+ runs.every(
+ r =>
+ r.status === "ok" &&
+ r.video?.frames === plan.frames &&
+ Number.isFinite(r.export_ms) &&
+ r.export_ms > 0 &&
+ (engine === "remotion-mediabunny"
+ ? r.encoder === "webcodecs-h264"
+ : ["libx264", "h264_videotoolbox"].includes(r.encoder))
+ );
+ return [
+ engine,
+ {
+ status: skipped ? "skipped" : valid ? "complete" : "incomplete",
+ export_ms: valid ? runs[0].export_ms : null,
+ ...(skipped ? { reason: runs[0].reason } : {}),
+ },
+ ];
+ })
+ );
return {
- status: complete && (gpuComplete || gpuSkipped) ? "complete" : "incomplete",
- fframes_median_ms: fframes,
- remotion_median_ms: remotion,
- speedup: complete ? remotion / fframes : null,
- gpu_median_ms: gpuMs,
- gpu_speedup: complete && gpuComplete ? remotion / gpuMs : null,
- gpu_status: gpuSkipped
- ? "skipped"
- : gpuComplete
- ? "complete"
- : "incomplete",
- gpu_skip_reason: gpuSkipped ? gpu[0].reason : null,
+ status: Object.values(results).every(r => r.status !== "incomplete")
+ ? "complete"
+ : "incomplete",
+ pipelines: results,
};
}
+
export function markdown(report) {
- const result = report.summary;
+ const result = report.summary.pipelines;
+ const speedup = (engine, baseline) => {
+ const time = result[engine].export_ms;
+ const reference = result[baseline].export_ms;
+ return time && reference ? `${(reference / time).toFixed(2)}×` : "n/a";
+ };
+ const rows = engines.map(engine => {
+ const run = result[engine];
+ const encoder =
+ report.records.find(r => r.engine === engine && r.status === "ok")
+ ?.encoder ?? "n/a";
+ const time =
+ run.status === "skipped"
+ ? `skipped: ${run.reason}`
+ : run.export_ms == null
+ ? "incomplete"
+ : `${(run.export_ms / 1000).toFixed(3)} s`;
+ return `| ${labels[engine]} | ${encoder} | ${time} | ${speedup(engine, "remotion-ffmpeg")} | ${speedup(engine, "remotion-mediabunny")} |`;
+ });
return [
- "# fframes + Skia vs Remotion",
+ "# fframes vs Remotion + FFmpeg and Remotion + MediaBunny",
+ "",
+ report.workload,
"",
- "100,000 elements: 99,000 rectangles and 1,000 changing text digits. Remotion uses an unkeyed list with 12 dependent effect/state updates per element. All render the same 1000×1000 scene serially, without a video encoder.",
+ "One complete 300-frame (10-second) H.264 MP4 export per pipeline, after a three-frame MP4 warm-up. No audio. Includes rendering, pixel conversion, encoder setup, encoding, draining, muxing and file writes. Compilation, media preparation, browser launch, bundling and warm-up are excluded. MediaBunny writes to the browser’s origin-private file system; copying the completed file to the host for validation is excluded. Output frame counts and durations are checked after timing.",
"",
- "Median of 3 rounds, each with 3 warm-up and 30 measured frames. PNG compression is included; startup, warm-up and disk writes are excluded.",
+ "| Pipeline | Encoder | Complete MP4 export | Speedup vs Remotion + FFmpeg | Speedup vs Remotion + MediaBunny |",
+ "|---|---|---:|---:|---:|",
+ ...rows,
"",
- "| Renderer | Median for 30 frames | Speedup vs Remotion |",
- "|---|---:|---:|",
- `| fframes + Skia CPU | ${result.fframes_median_ms?.toFixed(2) ?? "incomplete"} ms | ${result.speedup?.toFixed(2) ?? "n/a"}× |`,
- `| fframes + Skia GPU | ${result.gpu_status === "skipped" ? `skipped: ${result.gpu_skip_reason}` : `${result.gpu_median_ms?.toFixed(2) ?? "incomplete"} ms`} | ${result.gpu_speedup?.toFixed(2) ?? "n/a"}× |`,
- `| Remotion | ${result.remotion_median_ms?.toFixed(2) ?? "incomplete"} ms | — |`,
+ "30 fps, 8 Mbps target, GOP 30, no audio. fframes CPU uses all available logical cores; Skia uses MaxPerformance with the default worker pool. Remotion + FFmpeg uses 18 browser tabs, capped by the available logical cores, with its default browser graphics settings. CPU uses x264 medium. Skia GPU and Remotion + FFmpeg require hardware VideoToolbox on macOS and use x264 elsewhere; native encoders use one codec thread per segment. MediaBunny uses WebCodecs H.264 with prefer-hardware; Chrome controls encoder selection and threading. Hardware preference does not prove which encoder Chrome selected. Equal bitrate targets do not guarantee equal image quality. Browser executables and versions are recorded separately for each Remotion path.",
"",
].join("\n");
}
diff --git a/render-bench/vs-remotion/run.mjs b/render-bench/vs-remotion/run.mjs
index 342f8fbb..aed9fa0e 100644
--- a/render-bench/vs-remotion/run.mjs
+++ b/render-bench/vs-remotion/run.mjs
@@ -2,19 +2,29 @@ import fs from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import { fileURLToPath } from "node:url";
-import { execFileSync } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import { isolated } from "./process.mjs";
import { createHash } from "node:crypto";
import { bundle } from "@remotion/bundler";
-import {
- openBrowser,
- selectComposition,
- renderFrames,
-} from "@remotion/renderer";
-import { summarize, markdown } from "./report.mjs";
+import { remotionWorker } from "./web.mjs";
+import { ffmpegWorker } from "./ffmpeg.mjs";
+import { engines, summarize, markdown } from "./report.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "../..");
const args = process.argv.slice(2);
+if (process.platform === "darwin") {
+ const awake = spawn(
+ "/usr/bin/caffeinate",
+ ["-i", "-w", String(process.pid)],
+ {
+ stdio: "ignore",
+ }
+ );
+ awake.on("error", error =>
+ console.error(`Preventing idle sleep failed: ${error}`)
+ );
+ awake.unref();
+}
const option = (name, fallback) => {
const i = args.indexOf(`--${name}`);
return i < 0 ? fallback : args[i + 1];
@@ -22,75 +32,52 @@ const option = (name, fallback) => {
const git = (...a) =>
execFileSync("git", ["-C", root, ...a], { encoding: "utf8" }).trim();
-async function remotionWorker(config) {
- const chromiumOptions = { disableWebSecurity: false };
- const browser = await openBrowser("chrome", {
- browserExecutable: config.chrome,
- chromiumOptions,
- logLevel: "error",
- });
- try {
- const composition = await selectComposition({
- serveUrl: config.bundle,
- id: "MixedGrid",
- puppeteerInstance: browser,
- timeoutInMilliseconds: config.timeout,
- logLevel: "error",
- });
- const samples = [];
- const images = new Map();
- let dom;
- await renderFrames({
- composition,
- serveUrl: config.bundle,
- puppeteerInstance: browser,
- concurrency: 1,
- frameRange: [0, config.warmup + config.frames - 1],
- imageFormat: "png",
- outputDir: null,
- timeoutInMilliseconds: config.timeout,
- logLevel: "error",
- onStart: ({ parallelEncoding, resolvedConcurrency }) => {
- if (parallelEncoding || resolvedConcurrency !== 1)
- throw new Error("unexpected Remotion rendering pipeline");
- },
- onFrameBuffer: async (buffer, frame) => {
- if (frame >= config.warmup) images.set(frame, buffer);
- // Inspect the real Remotion page during warm-up, outside measured frames.
- if (frame === config.warmup - 1) {
- for (const page of await browser.pages()) {
- const counts = await page.evaluate(() => ({
- rectangles: document.querySelectorAll("svg rect").length,
- texts: document.querySelectorAll("svg text").length,
- }));
- if (counts.rectangles + counts.texts === config.nodes) dom = counts;
- }
- if (!dom || dom.texts !== Math.ceil(config.nodes / 100))
- throw new Error("incorrect Remotion DOM element count");
- }
- },
- onFrameUpdate: (_count, frame, total_ms) => {
- if (frame >= config.warmup) samples.push({ frame, total_ms });
- },
- });
- samples.sort((a, b) => a.frame - b.frame);
- // Remotion's per-frame timing covers seek, effects, raster and PNG capture.
- // Save captured buffers only after rendering has finished.
- for (const [frame, buffer] of images)
- await fs.writeFile(path.join(config.directory, `${frame}.png`), buffer);
- return {
- samples,
- renderer: "@remotion/renderer renderFrames",
- concurrency: 1,
- browser: execFileSync(config.chrome, ["--version"], {
- encoding: "utf8",
- }).trim(),
- chromium_options: chromiumOptions,
- dom,
- };
- } finally {
- await browser.close({ silent: true });
- }
+function inspectVideo(file, plan) {
+ const probe = JSON.parse(
+ execFileSync(
+ "ffprobe",
+ [
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-count_frames",
+ "-show_entries",
+ "stream=codec_name,width,height,pix_fmt,color_range,avg_frame_rate,nb_read_frames,duration:format=size",
+ "-of",
+ "json",
+ file,
+ ],
+ { encoding: "utf8" }
+ )
+ );
+ const video = probe.streams[0];
+ const [numerator, denominator] = video.avg_frame_rate.split("/").map(Number);
+ const fps = numerator / denominator;
+ const frames = Number(video.nb_read_frames);
+ const duration = Number(video.duration);
+ if (
+ video.codec_name !== "h264" ||
+ video.width !== plan.width ||
+ video.height !== plan.height ||
+ !["yuv420p", "yuvj420p"].includes(video.pix_fmt) ||
+ fps !== 30 ||
+ frames !== plan.frames ||
+ !Number.isFinite(duration) ||
+ Math.abs(duration - plan.frames / fps) > 0.001
+ )
+ throw new Error(`incorrect MP4 output: ${JSON.stringify(video)}`);
+ return {
+ frames,
+ fps,
+ duration_s: duration,
+ width: video.width,
+ height: video.height,
+ codec: video.codec_name,
+ pixel_format: video.pix_fmt,
+ color_range: video.color_range,
+ bytes: Number(probe.format.size),
+ };
}
async function directoryHash(directory) {
const hash = createHash("sha256");
@@ -105,21 +92,38 @@ async function directoryHash(directory) {
}
if (args[0] === "--worker") {
const config = JSON.parse(await fs.readFile(args[1], "utf8"));
- console.log(JSON.stringify(await remotionWorker(config)));
+ const worker =
+ config.engine === "remotion-ffmpeg" ? ffmpegWorker : remotionWorker;
+ console.log(JSON.stringify(await worker(config)));
} else {
for (let i = 0; i < args.length; i += 2) {
- if (!["--chrome", "--out", "--binary"].includes(args[i]) || !args[i + 1])
+ if (
+ !["--chrome", "--ffmpeg-chrome", "--out", "--binary"].includes(args[i]) ||
+ !args[i + 1]
+ )
throw new Error(`unknown or incomplete option: ${args[i]}`);
}
const plan = {
nodes: 100000,
- effect_passes: 12,
- rounds: 3,
- frames: 30,
+ width: 3840,
+ height: 2160,
+ rounds: 1,
+ frames: 300,
warmup: 3,
- timeout: 300000,
- backends: ["skia-cpu", "skia-gpu-if-available"],
- chrome: option("chrome", process.env.CHROME_PATH ?? "/usr/bin/chromium"),
+ timeout: 600000,
+ backends: ["cpu", "skia-gpu-if-available"],
+ engines,
+ ffmpeg_chrome: option(
+ "ffmpeg-chrome",
+ process.env.FFMPEG_CHROME_PATH ?? null
+ ),
+ chrome: option(
+ "chrome",
+ process.env.CHROME_PATH ??
+ (process.platform === "darwin"
+ ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
+ : "/usr/bin/google-chrome")
+ ),
};
const binary = path.resolve(
option("binary", path.join(root, "target/release/vs-remotion-bench"))
@@ -140,10 +144,26 @@ if (args[0] === "--worker") {
if (err.code !== "ENOENT") throw err;
}
const report = {
- schema_version: 5,
- comparison: "Remotion renderFrames vs fframes Previewer + Skia",
+ schema_version: 15,
+ comparison:
+ "fframes CPU and Skia GPU vs Remotion + FFmpeg and Remotion + MediaBunny: complete H.264 MP4 export",
+ encoding: {
+ codec: "h264",
+ target_bitrate: 8000000,
+ cpu_encoder: "libx264 medium",
+ macos_gpu_encoder: "h264_videotoolbox",
+ remotion_ffmpeg_encoder:
+ process.platform === "darwin" ? "h264_videotoolbox" : "libx264 medium",
+ remotion_mediabunny_encoder: "WebCodecs H.264, prefer-hardware",
+ gop: 30,
+ pixel_format: "yuv420p",
+ native_codec_threads: 1,
+ fps: 30,
+ audio: false,
+ },
+ workload_revision: "100k-4k-circles-300-frames-v1",
workload:
- "99% rectangles, 1% changing DM Sans text digits; text painted last",
+ "4K (3840×2160), 99,000 overlapping circles and 1,000 changing DM Sans text digits in 20 panels. Every circle moves and changes color; 10,000 radii animate between 16 and 28 SVG units. A 1000×1000 viewBox stretches to the output. No filters. Remotion uses 100,000 keyed components with useCurrentFrame and a memoized parent tree.",
plan,
environment: {
platform: os.platform(),
@@ -155,6 +175,11 @@ if (args[0] === "--worker") {
remotion: JSON.parse(
await fs.readFile(path.join(here, "node_modules/remotion/package.json"))
).version,
+ mediabunny: JSON.parse(
+ await fs.readFile(
+ path.join(here, "node_modules/mediabunny/package.json")
+ )
+ ).version,
react: JSON.parse(
await fs.readFile(path.join(here, "node_modules/react/package.json"))
).version,
@@ -170,13 +195,25 @@ if (args[0] === "--worker") {
},
records: [],
};
- const serveUrl = await bundle({
+ const webBundle = await bundle({
entryPoint: path.join(here, "browser.jsx"),
outDir: path.join(out, "remotion-bundle"),
publicDir: path.join(here, "media"),
enableCaching: false,
+ ignoreRegisterRootWarning: true,
+ webpackOverride: config => ({
+ ...config,
+ entry: path.join(here, "browser.jsx"),
+ }),
+ });
+ const serverBundle = await bundle({
+ entryPoint: path.join(here, "server.jsx"),
+ outDir: path.join(out, "remotion-ffmpeg-bundle"),
+ publicDir: path.join(here, "media"),
+ enableCaching: false,
});
- report.environment.browser_bundle_sha256 = await directoryHash(serveUrl);
+ report.environment.mediabunny_bundle_sha256 = await directoryHash(webBundle);
+ report.environment.ffmpeg_bundle_sha256 = await directoryHash(serverBundle);
const persist = async () => {
report.summary = summarize(report.records, plan);
await fs.writeFile(
@@ -187,7 +224,6 @@ if (args[0] === "--worker") {
};
for (let round = 0; round < plan.rounds; round++) {
const nodes = plan.nodes;
- const engines = ["fframes", "fframes-gpu", "remotion"];
const order = engines.map((_, i) => engines[(i + round) % engines.length]);
for (const engine of order) {
const directory = path.join(out, `${nodes}-${engine}-${round}`);
@@ -198,32 +234,33 @@ if (args[0] === "--worker") {
engine,
round,
directory,
- bundle: serveUrl,
+ bundle: engine === "remotion-ffmpeg" ? serverBundle : webBundle,
};
const configPath = path.join(directory, "config.json");
await fs.writeFile(configPath, JSON.stringify(config));
console.error(
`round ${round + 1}/${plan.rounds}: ${nodes} nodes, ${engine}`
);
- const result =
- engine !== "remotion"
- ? await isolated(
- binary,
- [engine === "fframes" ? "cpu" : "gpu", directory],
- plan.timeout,
- path.join(directory, "process.log")
- )
- : await isolated(
- process.execPath,
- [fileURLToPath(import.meta.url), "--worker", configPath],
- plan.timeout,
- path.join(directory, "process.log")
- );
+ const loadBefore = os.loadavg();
+ const result = engine.startsWith("fframes")
+ ? await isolated(
+ binary,
+ [engine === "fframes" ? "cpu" : "gpu", directory],
+ plan.timeout,
+ path.join(directory, "process.log")
+ )
+ : await isolated(
+ process.execPath,
+ [fileURLToPath(import.meta.url), "--worker", configPath],
+ plan.timeout,
+ path.join(directory, "process.log")
+ );
const record = {
nodes,
engine,
round,
status: result.status,
+ load_before: loadBefore,
load_after: os.loadavg(),
code: result.code,
signal: result.signal,
@@ -232,6 +269,9 @@ if (args[0] === "--worker") {
if (result.status !== "ok")
throw new Error(result.error || result.status);
Object.assign(record, JSON.parse(result.stdout));
+ // Verify the completed file after the timer has stopped.
+ if (record.status === "ok")
+ record.video = inspectVideo(path.join(directory, "export.mp4"), plan);
} catch (err) {
record.status =
result.status === "ok" ? "invalid-output" : result.status;
diff --git a/render-bench/vs-remotion/run.sh b/render-bench/vs-remotion/run.sh
index df2a5ea3..e0bfeb0a 100755
--- a/render-bench/vs-remotion/run.sh
+++ b/render-bench/vs-remotion/run.sh
@@ -4,8 +4,10 @@ bench=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$bench/../.." && pwd)
invocation_dir=$PWD
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
- echo "Usage: $0 [--chrome PATH] [--out DIR]"
- echo "Runs the fixed 100,000-element benchmark: 30 frames, 3 warm-up frames, 3 rounds."
+ echo "Usage: $0 [--chrome PATH] [--ffmpeg-chrome PATH] [--out DIR]"
+ echo "Runs 4K, 99,000 circles and 1,000 text nodes: 300 frames, 3 warm-up frames, 1 round."
+ echo "Measures wall-clock time to render and finish a complete H.264 MP4."
+ echo "Compares fframes CPU, Skia GPU, Remotion + FFmpeg, and Remotion + MediaBunny."
exit 0
fi
cd "$root"
diff --git a/render-bench/vs-remotion/scene.jsx b/render-bench/vs-remotion/scene.jsx
new file mode 100644
index 00000000..a1ea3fd4
--- /dev/null
+++ b/render-bench/vs-remotion/scene.jsx
@@ -0,0 +1,109 @@
+import React, { useEffect, useMemo, useState } from "react";
+import {
+ interpolate,
+ staticFile,
+ useCurrentFrame,
+ useDelayRender,
+} from "remotion";
+
+export const WIDTH = 3840;
+export const HEIGHT = 2160;
+
+const circles = 99000;
+const textNodes = 1000;
+const nodes = circles + textNodes;
+const panels = 20;
+const perPanel = nodes / panels;
+const textStep = nodes / textNodes;
+const color = (id, frame) =>
+ `rgb(${(id * 13 + frame * 17) % 256},${(id * 7 + frame * 29) % 256},${(id * 3 + frame * 43) % 256})`;
+function circleRadius(slot, frame) {
+ if (slot % 10 !== 1) return 16 + (slot % 4) * 4;
+ return interpolate((slot + frame) % 60, [0, 30, 60], [16, 28, 16], {
+ easing: t => t * t * (3 - 2 * t),
+ });
+}
+function Cell({ slot }) {
+ const frame = useCurrentFrame();
+ const id = (slot + frame * 37) % nodes;
+ if (slot % textStep === 0) {
+ const panel = Math.floor(slot / perPanel);
+ const index = (slot % perPanel) / textStep;
+ return (
+ <text
+ key={slot}
+ x={(panel % 5) * 200 + 24 + (index % 10) * 16}
+ y={Math.floor(panel / 5) * 250 + 40 + Math.floor(index / 10) * 40}
+ fontFamily="DM Sans"
+ fontSize="16"
+ fill="#fff"
+ >
+ {(id + frame) % 10}
+ </text>
+ );
+ }
+ const radius = circleRadius(slot, frame);
+ return (
+ <circle
+ key={slot}
+ cx={32 + ((slot * 13 + frame * 3) % 128)}
+ cy={32 + ((slot * 17 + frame * 5) % 176)}
+ r={radius}
+ fill={color(id, frame)}
+ />
+ );
+}
+export function GridVideo({ fontCss = "" }) {
+ const { delayRender, continueRender, cancelRender } = useDelayRender();
+ const [fontHandle] = useState(() =>
+ delayRender("benchmark font", { retries: 0 })
+ );
+ useEffect(() => {
+ const font = new FontFace(
+ "DM Sans",
+ `url(${staticFile("DMSans-Regular.ttf")})`
+ );
+ font
+ .load()
+ .then(loaded => {
+ document.fonts.add(loaded);
+ continueRender(fontHandle);
+ })
+ .catch(cancelRender);
+ }, [fontHandle, continueRender, cancelRender]);
+ const { layers, texts } = useMemo(() => {
+ const layers = [];
+ for (let panel = 0; panel < panels; panel++) {
+ const cells = [];
+ for (let slot = panel * perPanel; slot < (panel + 1) * perPanel; slot++)
+ if (slot % textStep !== 0) cells.push(<Cell key={slot} slot={slot} />);
+ layers.push(
+ <g
+ key={panel}
+ transform={`translate(${(panel % 5) * 200} ${Math.floor(panel / 5) * 250})`}
+ >
+ {cells}
+ </g>
+ );
+ }
+ const texts = [];
+ for (let slot = 0; slot < nodes; slot += textStep)
+ texts.push(<Cell key={slot} slot={slot} />);
+ return { layers, texts };
+ }, []);
+ return (
+ <svg
+ width={WIDTH}
+ height={HEIGHT}
+ viewBox="0 0 1000 1000"
+ preserveAspectRatio="none"
+ style={{ display: "block", background: "#18202c" }}
+ >
+ <defs>
+ <style>{fontCss}</style>
+ </defs>
+ {layers}
+ {texts}
+ </svg>
+ );
+}
diff --git a/render-bench/vs-remotion/server.jsx b/render-bench/vs-remotion/server.jsx
new file mode 100644
index 00000000..b4c788ac
--- /dev/null
+++ b/render-bench/vs-remotion/server.jsx
@@ -0,0 +1,15 @@
+import React from "react";
+import { Composition, registerRoot } from "remotion";
+import { GridVideo, WIDTH, HEIGHT } from "./scene.jsx";
+
+registerRoot(() => (
+ <Composition
+ id="MixedGrid"
+ component={GridVideo}
+ width={WIDTH}
+ height={HEIGHT}
+ fps={30}
+ durationInFrames={303}
+ defaultProps={{ fontCss: "" }}
+ />
+));
diff --git a/render-bench/vs-remotion/src/main.rs b/render-bench/vs-remotion/src/main.rs
index e7d20e37..bf3c9582 100644
--- a/render-bench/vs-remotion/src/main.rs
+++ b/render-bench/vs-remotion/src/main.rs
@@ -1,25 +1,64 @@
-//! Render-only twin of browser.jsx. No video encoder is instantiated.
-use std::{hint::black_box, path::Path, time::Instant};
+//! Fixed scene benchmark: wall-clock time to render a complete H.264 MP4.
+use std::{path::Path, time::Instant};
use fframes::{
- AudioMap, Duration, FFramesContext, Frame, Previewer, RenderOptions, StaticMediaProvider, Svgr,
- Video,
+ AudioMap, Color, Duration, EncoderOptions, FFramesContext, FFramesLoggerVariant,
+ FFramesRenderBackend, Frame, RenderOptions, StaticMediaProvider, Svgr, Transform, Video,
+ cpu::CpuRenderingBackend,
+};
+use fframes_skia_renderer::{
+ SkiaBackend, SkiaCacheConfig, SkiaFFramesRenderer, SkiaPipelineConcurrencyPolicy,
+ SkiaPipelineConfig,
};
-use fframes_skia_renderer::{SkiaBackend, SkiaCpuCtx, SkiaFrameRenderer};
fframes::include_media_dir!(struct BenchMedia, "render-bench/vs-remotion/media");
-const SIDE: usize = 1000;
-const NODES: usize = 100_000;
-const FRAMES: usize = 30;
+const VIDEO_WIDTH: usize = 3840;
+const VIDEO_HEIGHT: usize = 2160;
+const CIRCLES: usize = 99_000;
+const TEXTS: usize = 1000;
+const NODES: usize = CIRCLES + TEXTS;
+const PANELS: usize = 20;
+const PER_PANEL: usize = NODES / PANELS;
+const TEXT_STEP: usize = NODES / TEXTS;
+const CACHE_CAPACITY: usize = 100_000;
+const FRAMES: usize = 300;
const WARMUP: usize = 3;
+const CACHE: SkiaCacheConfig = SkiaCacheConfig {
+ text_capacity: CACHE_CAPACITY,
+ geometry_capacity: CACHE_CAPACITY,
+ geometry_bytes: CACHE_CAPACITY * 512,
+};
+
+fn cpu_backend() -> CpuRenderingBackend {
+ CpuRenderingBackend {
+ concurrency: fframes::get_thread_count(),
+ text_cache_capacity: CACHE_CAPACITY,
+ ..Default::default()
+ }
+}
+
+fn circle_radius(slot: usize, frame: usize) -> f64 {
+ if slot % 10 != 1 {
+ return (16 + slot % 4 * 4) as f64;
+ }
+ let phase = ((slot + frame) % 60) as f64;
+ let (progress, from, to) = if phase <= 30. {
+ (phase / 30., 16., 28.)
+ } else {
+ ((phase - 30.) / 30., 28., 16.)
+ };
+ let amount = progress * progress * (3. - 2. * progress);
+ amount * (to - from) + from
+}
struct Grid;
impl Video for Grid {
const FPS: usize = 30;
- const WIDTH: usize = SIDE;
- const HEIGHT: usize = SIDE;
+ const WIDTH: usize = VIDEO_WIDTH;
+ const HEIGHT: usize = VIDEO_HEIGHT;
+ const BACKGROUND_COLOR: Color = Color::hex("#18202c");
fn duration(&self) -> Duration<'_> {
Duration::Frames(FRAMES + WARMUP)
}
@@ -27,28 +66,53 @@ impl Video for Grid {
AudioMap::none()
}
fn render_frame<'a>(&'a self, frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
- let nodes: Vec<_> = (0..NODES).filter(|slot| slot % 100 != 0)
- .chain((0..NODES).step_by(100)).map(|slot| {
+ let panels: Vec<_> = (0..PANELS)
+ .map(|panel| {
+ let circles: Vec<_> = (panel * PER_PANEL..(panel + 1) * PER_PANEL)
+ .filter(|slot| slot % TEXT_STEP != 0)
+ .map(|slot| {
+ let id = (slot + frame.index * 37) % NODES;
+ let radius = circle_radius(slot, frame.index);
+ let fill = Color::rgba(
+ ((id * 13 + frame.index * 17) % 256) as u8,
+ ((id * 7 + frame.index * 29) % 256) as u8,
+ ((id * 3 + frame.index * 43) % 256) as u8,
+ 255,
+ );
+ fframes::svgr!(<circle cx={32 + (slot * 13 + frame.index * 3) % 128}
+ cy={32 + (slot * 17 + frame.index * 5) % 176}
+ r={radius} fill={fill} />)
+ })
+ .collect();
+ let transform =
+ Transform::translate((panel % 5 * 200) as f64, (panel / 5 * 250) as f64);
+ fframes::svgr!(<g transform={transform}>{circles}</g>)
+ })
+ .collect();
+ let texts: Vec<_> = (0..NODES).step_by(TEXT_STEP).map(|slot| {
+ let panel = slot / PER_PANEL;
+ let index = slot % PER_PANEL / TEXT_STEP;
let id = (slot + frame.index * 37) % NODES;
- let r = (id * 13 + frame.index * 17) % 256;
- let g = (id * 7 + frame.index * 29) % 256;
- let b = (id * 3 + frame.index * 43) % 256;
- let fill = format!("#{r:02x}{g:02x}{b:02x}");
- if slot % 100 == 0 {
- let index = slot / 100;
- fframes::svgr!(<text x={(index % 100) * 10 + 1} y={(index / 100) * 10 + 7}
- font-family="DM Sans" font-size="10" fill={fill}>{((id + frame.index) % 10).to_string()}</text>)
- } else {
- fframes::svgr!(<rect x={slot % SIDE} y={slot / SIDE} width="1" height="1" fill={fill} />)
- }
+ fframes::svgr!(<text x={panel % 5 * 200 + 24 + index % 10 * 16}
+ y={panel / 5 * 250 + 40 + index / 10 * 40}
+ font-family="DM Sans" font-size="16" fill="#fff">{((id + frame.index) % 10).to_string()}</text>)
}).collect();
- fframes::svgr!(<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000">{nodes}</svg>)
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width={VIDEO_WIDTH} height={VIDEO_HEIGHT}
+ viewBox="0 0 1000 1000" preserveAspectRatio="none">
+ {panels}
+ {texts}
+ </svg>
+ )
}
}
#[cfg(target_os = "macos")]
fn gpu_backend() -> Result<fframes_skia_renderer::metal::SkiaMetalCtx, Box<dyn std::error::Error>> {
- Ok(fframes_skia_renderer::metal::SkiaMetalCtx::new(SIDE, SIDE)?)
+ Ok(fframes_skia_renderer::metal::SkiaMetalCtx::new(
+ VIDEO_WIDTH,
+ VIDEO_HEIGHT,
+ )?)
}
#[cfg(not(target_os = "macos"))]
@@ -76,7 +140,11 @@ fn gpu_backend() -> Result<fframes_skia_renderer::vulkan::SkiaVulkanCtx, Box<dyn
};
Ok(
fframes_skia_renderer::vulkan::SkiaVulkanCtx::new_with_device(
- entry, instance, device, SIDE, SIDE,
+ entry,
+ instance,
+ device,
+ VIDEO_WIDTH,
+ VIDEO_HEIGHT,
)?,
)
}
@@ -87,13 +155,22 @@ fn main() {
let out = Path::new(&args[2]);
std::fs::create_dir_all(out).expect("output directory");
match args[1].as_str() {
- "cpu" => run(&SkiaCpuCtx::new(SIDE, SIDE), "skia-cpu", out),
+ "cpu" => run(cpu_backend, "cpu", out),
"gpu" => match gpu_backend().and_then(|backend| {
backend.create_skia_surface()?;
Ok(backend)
}) {
Ok(backend) => run(
- &backend,
+ || {
+ SkiaFFramesRenderer::new(
+ SkiaPipelineConfig {
+ concurrency_policy: SkiaPipelineConcurrencyPolicy::MaxPerformance,
+ cache: CACHE,
+ ..Default::default()
+ },
+ &backend,
+ )
+ },
if cfg!(target_os = "macos") {
"skia-metal"
} else {
@@ -110,47 +187,76 @@ fn main() {
}
}
-fn run(backend: &impl SkiaBackend, name: &str, out: &Path) {
+fn run<B: FFramesRenderBackend>(pipeline: impl Fn() -> B, name: &str, out: &Path) {
let video = Grid;
let media = BenchMedia::prepare().expect("benchmark font");
+ let hardware_encoding = name == "skia-metal";
+ let encoder_name = if hardware_encoding {
+ "h264_videotoolbox"
+ } else {
+ "libx264"
+ };
+ // Fail instead of silently benchmarking a different encoder.
+ let codec_name = std::ffi::CString::new(encoder_name).expect("encoder name");
+ assert!(
+ !unsafe { fframes::ffmpeg_sys_fframes::avcodec_find_encoder_by_name(codec_name.as_ptr()) }
+ .is_null(),
+ "required encoder {encoder_name} unavailable"
+ );
+ let codec_params: &[(&str, &str)] = if hardware_encoding {
+ &[("allow_sw", "0"), ("threads", "1")]
+ } else {
+ &[("preset", "medium"), ("threads", "1")]
+ };
let options = RenderOptions {
media: Some(&media),
load_system_fonts: false,
+ logger: FFramesLoggerVariant::Silent,
+ frame_range: Some(0..WARMUP),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some(encoder_name),
+ codec_params: Some(codec_params),
+ bitrate: Some(8_000_000),
+ gop_size: 30,
+ qmin: 0,
+ qmax: 69,
+ ..Default::default()
+ },
..Default::default()
};
- let mut preview = Previewer::new(&video, &options).expect("preview initialization");
- let mut renderer = SkiaFrameRenderer::new(backend);
- let mut samples = Vec::new();
- for frame in 0..FRAMES + WARMUP {
- let start = Instant::now();
- // Includes scene generation, SVG conversion, and rasterization.
- let image = preview.render(frame, &mut renderer).expect("render frame");
- let render_ms = start.elapsed().as_secs_f64() * 1000.;
- // Chrome exposes screenshots as PNGs. Produce the same artifact in memory;
- // record image compression separately and include it in the comparable total.
- let mut bytes = Vec::new();
- {
- let mut encoder = png::Encoder::new(&mut bytes, SIDE as u32, SIDE as u32);
- encoder.set_color(png::ColorType::Rgba);
- encoder.set_depth(png::BitDepth::Eight);
- encoder.set_compression(png::Compression::Fast);
- encoder
- .write_header()
- .expect("PNG header")
- .write_image_data(&image.pixels)
- .expect("PNG pixels");
- }
- let total_ms = start.elapsed().as_secs_f64() * 1000.;
- black_box(&bytes);
- if frame >= WARMUP {
- samples.push(serde_json::json!({"frame": frame, "render_ms": render_ms, "png_ms": total_ms-render_ms, "total_ms": total_ms}));
- // Disk writes and correctness checks are excluded on both sides.
- std::fs::write(out.join(format!("{frame}.png")), &bytes)
- .expect("save verification PNG");
- }
- }
+ let warmup = out.join("warmup.mp4");
+ fframes::render(&warmup, &video, pipeline(), &options).expect("warm-up MP4");
+ let options = RenderOptions {
+ frame_range: Some(WARMUP..WARMUP + FRAMES),
+ ..options
+ };
+ let start = Instant::now();
+ fframes::render(out.join("export.mp4"), &video, pipeline(), &options)
+ .expect("complete MP4 export");
+ let export_ms = start.elapsed().as_secs_f64() * 1000.;
+ std::fs::remove_file(warmup).expect("remove warm-up MP4");
+ let ffmpeg =
+ unsafe { std::ffi::CStr::from_ptr(fframes::ffmpeg_sys_fframes::av_version_info()) }
+ .to_string_lossy();
+ let cache = if name == "cpu" {
+ serde_json::json!({"text_capacity": cpu_backend().text_cache_capacity,
+ "layer_capacity": cpu_backend().cache_capacity})
+ } else {
+ serde_json::json!({"text_capacity": CACHE.text_capacity,
+ "geometry_capacity": CACHE.geometry_capacity, "geometry_bytes": CACHE.geometry_bytes})
+ };
+ let concurrency = if name == "cpu" {
+ serde_json::json!({"render_threads": cpu_backend().concurrency})
+ } else {
+ serde_json::json!({"policy": "MaxPerformance",
+ "encoder_threads": fframes::get_thread_count()})
+ };
println!(
"{}",
- serde_json::json!({"backend": name, "nodes": NODES, "samples": samples})
+ serde_json::json!({"backend": name, "nodes": NODES, "cache": cache,
+ "concurrency": concurrency, "frames": FRAMES, "fps": Grid::FPS,
+ "audio": false, "width": VIDEO_WIDTH, "height": VIDEO_HEIGHT,
+ "export_ms": export_ms, "ffmpeg": ffmpeg,
+ "encoder": encoder_name, "hardware_encoding": hardware_encoding})
);
}
diff --git a/render-bench/vs-remotion/web.mjs b/render-bench/vs-remotion/web.mjs
new file mode 100644
index 00000000..9cdddc23
--- /dev/null
+++ b/render-bench/vs-remotion/web.mjs
@@ -0,0 +1,132 @@
+import fs from "node:fs/promises";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { spawn } from "node:child_process";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+export async function remotionWorker(config) {
+ const font = await fs.readFile(path.join(here, "media/DMSans-Regular.ttf"));
+ const fontCss = `@font-face{font-family:"DM Sans";font-style:normal;font-weight:400;src:url(data:font/ttf;base64,${font.toString("base64")}) format("truetype");}`;
+ let finish;
+ const complete = new Promise(resolve => {
+ finish = resolve;
+ });
+ const server = http.createServer(async (req, res) => {
+ try {
+ if (req.method === "POST" && req.url === "/result") {
+ const parts = [];
+ for await (const part of req) parts.push(part);
+ const result = JSON.parse(Buffer.concat(parts).toString());
+ res.end("ok");
+ finish(result);
+ return;
+ }
+ if (req.method === "POST" && req.url === "/progress") {
+ const parts = [];
+ for await (const part of req) parts.push(part);
+ await fs.appendFile(
+ path.join(config.directory, "progress.log"),
+ `${Buffer.concat(parts)}\n`
+ );
+ res.end("ok");
+ return;
+ }
+ if (
+ req.method === "POST" &&
+ ["/save/warmup.mp4", "/save/export.mp4"].includes(req.url)
+ ) {
+ const file = await fs.open(
+ path.join(config.directory, path.basename(req.url)),
+ "w"
+ );
+ try {
+ for await (const part of req) await file.writeFile(part);
+ } finally {
+ await file.close();
+ }
+ res.end("saved");
+ return;
+ }
+ if (req.url === "/") {
+ res.setHeader("Content-Type", "text/html");
+ res.end(
+ '<!doctype html><html><head></head><body style="margin:0"><script src="/bundle.js"></script></body></html>'
+ );
+ return;
+ }
+ if (req.url === "/config") {
+ res.setHeader("Content-Type", "application/json");
+ res.end(
+ JSON.stringify({
+ frames: config.frames,
+ warmup: config.warmup,
+ timeout: config.timeout,
+ })
+ );
+ return;
+ }
+ if (req.url === "/font.css") {
+ res.setHeader("Content-Type", "text/css");
+ res.end(fontCss);
+ return;
+ }
+ if (req.url === "/DMSans-Regular.ttf") {
+ res.setHeader("Content-Type", "font/ttf");
+ res.end(font);
+ return;
+ }
+ const name = decodeURIComponent(req.url.split("?")[0]).slice(1);
+ if (!name || name.includes("..")) throw new Error("invalid path");
+ res.setHeader(
+ "Content-Type",
+ name.endsWith(".js") ? "text/javascript" : "application/octet-stream"
+ );
+ res.end(await fs.readFile(path.join(config.bundle, name)));
+ } catch (error) {
+ res.statusCode = 404;
+ res.end(String(error));
+ }
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ const profile = await fs.mkdtemp(
+ path.join(os.tmpdir(), "fframes-mediabunny-")
+ );
+ const browserLog = await fs.open(
+ path.join(config.directory, "browser.log"),
+ "w"
+ );
+ const browser = spawn(
+ config.chrome,
+ [
+ `--user-data-dir=${profile}`,
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--new-window",
+ `http://127.0.0.1:${server.address().port}`,
+ ],
+ { stdio: ["ignore", "ignore", browserLog.fd] }
+ );
+ await browserLog.close();
+ browser.on("error", error => finish({ error: String(error) }));
+ const exited = new Promise(resolve => browser.once("close", resolve));
+ const timer = setTimeout(
+ () => finish({ error: "browser export timed out" }),
+ config.timeout
+ );
+ try {
+ const result = await complete;
+ if (result.error) throw new Error(result.error);
+ await fs.unlink(path.join(config.directory, "warmup.mp4"));
+ return result;
+ } finally {
+ clearTimeout(timer);
+ browser.kill("SIGTERM");
+ await exited;
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+ await fs.rm(profile, { recursive: true, force: true });
+ }
+}