Skip to content

programmatic video rendering framework that is actually fast

perf(skia): draw circles, ellipses and rounded rects as native shapes

Dmitriy Kovalenko00c2afb9181d
diff --git a/Cargo.lock b/Cargo.lock
index 63418c91..cd3a8d95 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3562,9 +3562,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "svgr"
-version = "0.46.0"
+version = "0.46.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fac2e661050721c00a3ea807bf2855a54f27ad726166b1ce881280b9bb6a2182"
+checksum = "b7693be4358db6d2b20e039a8b9ff93b3736e481ad36ab435ccdb489da104214"
dependencies = [
"gif 0.12.0",
"jpeg-decoder",
@@ -3593,9 +3593,9 @@ dependencies = [
[[package]]
name = "svgrtypes"
-version = "0.46.0"
+version = "0.46.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f28c9992491123c065bc90c089e4ead6a951dfde8273f2fa2c26a3efa7baa10d"
+checksum = "5bbca5efc5d159da4ce7ef452d7a65dfd58ed6c71b5454304fd2d9ae9786c6c4"
dependencies = [
"kurbo 0.8.3",
"proc-macro2",
@@ -4014,9 +4014,9 @@ checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
[[package]]
name = "usvgr"
-version = "0.46.0"
+version = "0.46.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0161ea03cdcccf46f6581868223f38f7e619e4eb9f40457c2cb7c9a1be709654"
+checksum = "cd6aeccea458c5a0ca94be0f1a5eabf44d4b754316101569f3cae399c53debb5"
dependencies = [
"ahash",
"base64 0.21.7",
diff --git a/Cargo.toml b/Cargo.toml
index f10186b5..9ef6dc9a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -98,8 +98,8 @@ float_cmp = "allow"
# into the parent directory of fframes (as a sibling) and uncomment the following lines:
# svgr = { path = "../svgr/crates/svgr" }
# usvgr = { path = "../svgr/crates/usvgr" }
-svgr = "0.46.0"
-usvgr = "0.46.0"
+svgr = "0.46.1"
+usvgr = "0.46.1"
# ffmpeg-sys-next with prebuilt FFmpeg binaries: https://github.com/dmtrKovalenko/rust-ffmpeg-sys
ffmpeg-sys-fframes = "9.0.0"
wasm-bindgen = "0.2.100"
diff --git a/fframes-native-player/src/lib.rs b/fframes-native-player/src/lib.rs
index 66f61513..7439ddc1 100644
--- a/fframes-native-player/src/lib.rs
+++ b/fframes-native-player/src/lib.rs
@@ -99,9 +99,11 @@ pub fn play<'a, 'media: 'a, TVideo: Video + Sync>(
media.populate_image_source(&mut image_source);
}
+ // The player draws with the Skia renderer, which draws `FastShape`s natively.
let usvg_options = usvgr::Options {
image_data: Some(&image_source),
font_family: options.default_font.to_string(),
+ fast_shapes: true,
..Default::default()
};
diff --git a/fframes-skia-renderer/src/frame_renderer.rs b/fframes-skia-renderer/src/frame_renderer.rs
index ca5d4f83..f4371379 100644
--- a/fframes-skia-renderer/src/frame_renderer.rs
+++ b/fframes-skia-renderer/src/frame_renderer.rs
@@ -115,6 +115,10 @@ impl<'a, TBackend: SkiaBackend> SkiaFrameRenderer<'a, TBackend> {
}
impl<TBackend: SkiaBackend> FrameRenderer for SkiaFrameRenderer<'_, TBackend> {
+ fn fast_shapes(&self) -> bool {
+ true
+ }
+
fn svg_text_cache_capacity(&self) -> Option<usize> {
Some(self.cache_config.text_capacity)
}
diff --git a/fframes-skia-renderer/src/instant_rendering.rs b/fframes-skia-renderer/src/instant_rendering.rs
index 326905f1..f9e7e944 100644
--- a/fframes-skia-renderer/src/instant_rendering.rs
+++ b/fframes-skia-renderer/src/instant_rendering.rs
@@ -89,6 +89,7 @@ impl InstantRenderingVideoCtx<'_> {
let usvg_options = usvgr::Options {
font_family: "Arial".to_string(),
+ fast_shapes: true,
..Default::default()
};
diff --git a/fframes-skia-renderer/src/render/fingerprint.rs b/fframes-skia-renderer/src/render/fingerprint.rs
index bb51678b..ee86f2a9 100644
--- a/fframes-skia-renderer/src/render/fingerprint.rs
+++ b/fframes-skia-renderer/src/render/fingerprint.rs
@@ -177,8 +177,19 @@ fn hash_exact_group(
h.write_u8(3);
hash_exact_group(h, text.flattened(), points_budget, true)?;
}
- usvgr::Node::Path(path) => {
- h.write_u8(1);
+ usvgr::Node::Path(_) | usvgr::Node::FastShape(_) => {
+ let path = match child {
+ usvgr::Node::FastShape(fast_shape) => {
+ h.write_u8(4);
+ hash_fast_shape_kind(h, fast_shape.kind());
+ fast_shape.path()
+ }
+ usvgr::Node::Path(path) => {
+ h.write_u8(1);
+ &**path
+ }
+ _ => unreachable!(),
+ };
let has_pattern = [
path.fill().map(fframes::usvgr::Fill::paint),
path.stroke().map(fframes::usvgr::Stroke::paint),
@@ -302,6 +313,11 @@ fn hash_node(h: &mut FxHasher, node: &usvgr::Node) {
h.write_u8(1);
hash_path(h, path);
}
+ usvgr::Node::FastShape(fast_shape) => {
+ h.write_u8(4);
+ hash_fast_shape_kind(h, fast_shape.kind());
+ hash_path(h, fast_shape.path());
+ }
usvgr::Node::Image(image) => {
h.write_u8(2);
hash_image(h, image);
@@ -313,6 +329,22 @@ fn hash_node(h: &mut FxHasher, node: &usvgr::Node) {
}
}
+/// A fast shape's path data is only its bounding rectangle; the kind is its geometry.
+fn hash_fast_shape_kind(h: &mut FxHasher, kind: usvgr::FastShapeKind) {
+ match kind {
+ usvgr::FastShapeKind::Ellipse(rect) => {
+ h.write_u8(0);
+ h.rect(rect);
+ }
+ usvgr::FastShapeKind::RoundRect { rect, rx, ry } => {
+ h.write_u8(1);
+ h.rect(rect);
+ h.f32(rx);
+ h.f32(ry);
+ }
+ }
+}
+
fn hash_clip_path(h: &mut FxHasher, clip_path: &usvgr::ClipPath) {
h.transform(clip_path.transform());
hash_group(h, clip_path.root());
diff --git a/fframes-skia-renderer/src/render/mod.rs b/fframes-skia-renderer/src/render/mod.rs
index 01b8126d..7b7b80a7 100644
--- a/fframes-skia-renderer/src/render/mod.rs
+++ b/fframes-skia-renderer/src/render/mod.rs
@@ -272,7 +272,16 @@ fn render_node(node: &usvgr::Node, canvas: &Canvas, cache: &mut RenderCache) {
render_group(group, canvas, cache);
}
usvgr::Node::Path(path) => {
- render_path(path, canvas, cache);
+ render_path_with_alpha(path, None, canvas, cache, 1.0);
+ }
+ usvgr::Node::FastShape(fast_shape) => {
+ render_path_with_alpha(
+ fast_shape.path(),
+ Some(fast_shape.kind()),
+ canvas,
+ cache,
+ 1.0,
+ );
}
usvgr::Node::Image(image) => {
render_image(image, canvas, cache);
@@ -620,7 +629,19 @@ fn render_folded_opacity(
match child {
usvgr::Node::Path(path) if path.fill().is_none() || path.stroke().is_none() => {
- render_path_with_alpha(path, canvas, cache, alpha);
+ render_path_with_alpha(path, None, canvas, cache, alpha);
+ true
+ }
+ usvgr::Node::FastShape(fast_shape)
+ if fast_shape.path().fill().is_none() || fast_shape.path().stroke().is_none() =>
+ {
+ render_path_with_alpha(
+ fast_shape.path(),
+ Some(fast_shape.kind()),
+ canvas,
+ cache,
+ alpha,
+ );
true
}
usvgr::Node::Image(image) => match image.kind() {
@@ -722,7 +743,14 @@ fn build_clip_group(
for child in group.children() {
let contribution = match child {
- usvgr::Node::Path(path) => {
+ usvgr::Node::Path(_) | usvgr::Node::FastShape(_) => {
+ let (path, fast_shape) = match child {
+ usvgr::Node::FastShape(fast_shape) => {
+ (fast_shape.path(), Some(fast_shape.kind()))
+ }
+ usvgr::Node::Path(path) => (&**path, None),
+ _ => unreachable!(),
+ };
if path.visibility() != usvgr::Visibility::Visible {
continue;
}
@@ -733,7 +761,7 @@ fn build_clip_group(
usvgr::FillRule::EvenOdd => skia_safe::PathFillType::EvenOdd,
});
- let mut sk_path = cache.convert_path(path);
+ let mut sk_path = geometry_path(path, fast_shape, cache);
sk_path.set_fill_type(fill_type);
Some(sk_path.make_transform(transform))
}
@@ -810,14 +838,14 @@ fn apply_mask(mask: &usvgr::Mask, canvas: &Canvas, cache: &mut RenderCache) {
}
}
-fn render_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache) {
- render_path_with_alpha(path, canvas, cache, 1.0);
-}
-
/// Renders a path with its paints faded by `alpha`, which is how an opacity group
/// holding only this path looks when the path does not overlap itself.
+///
+/// `fast_shape` is set for [`usvgr::FastShape`] nodes: Skia then draws the oval or rounded rect
+/// analytically instead of tessellating `path`'s cubics on the CPU.
fn render_path_with_alpha(
path: &usvgr::Path,
+ fast_shape: Option<usvgr::FastShapeKind>,
canvas: &Canvas,
cache: &mut RenderCache,
alpha: f32,
@@ -827,30 +855,98 @@ fn render_path_with_alpha(
}
if path.paint_order() == usvgr::PaintOrder::FillAndStroke {
- fill_path(path, canvas, cache, alpha);
- stroke_path(path, canvas, cache, alpha);
+ fill_path(path, fast_shape, canvas, cache, alpha);
+ stroke_path(path, fast_shape, canvas, cache, alpha);
} else {
- stroke_path(path, canvas, cache, alpha);
- fill_path(path, canvas, cache, alpha);
+ stroke_path(path, fast_shape, canvas, cache, alpha);
+ fill_path(path, fast_shape, canvas, cache, alpha);
}
}
fn draw_path_with_alpha(
canvas: &Canvas,
- path: &skia_safe::Path,
+ geometry: &Geometry,
paint: &skia_safe::Paint,
alpha: f32,
) {
if alpha < 1.0 {
let mut paint = paint.clone();
paint.set_alpha_f(paint.alpha_f() * alpha);
- canvas.draw_path(path, &paint);
+ geometry.draw(canvas, &paint);
} else {
- canvas.draw_path(path, paint);
+ geometry.draw(canvas, paint);
+ }
+}
+
+/// What a path node draws. A fast shape's oval or rounded rect is drawn directly, without
+/// building a Skia path.
+enum Geometry {
+ Path(skia_safe::Path),
+ Oval(skia_safe::Rect),
+ RRect(skia_safe::RRect),
+}
+
+impl Geometry {
+ fn draw(&self, canvas: &Canvas, paint: &skia_safe::Paint) {
+ match self {
+ Geometry::Path(path) => canvas.draw_path(path, paint),
+ Geometry::Oval(rect) => canvas.draw_oval(rect, paint),
+ Geometry::RRect(rrect) => canvas.draw_rrect(rrect, paint),
+ };
+ }
+}
+
+/// [`geometry_path`] for drawing. Dashed strokes keep the path: Skia dashes an oval or rounded
+/// rect drawn directly along its default path, which for a rounded rect starts on the left edge
+/// instead of where SVG's starts.
+fn geometry(
+ path: &usvgr::Path,
+ fast_shape: Option<usvgr::FastShapeKind>,
+ dashed: bool,
+ cache: &mut RenderCache,
+) -> Geometry {
+ match fast_shape {
+ Some(usvgr::FastShapeKind::Ellipse(rect)) if !dashed => Geometry::Oval(to_rect(rect)),
+ Some(usvgr::FastShapeKind::RoundRect { rect, rx, ry }) if !dashed => {
+ Geometry::RRect(skia_safe::RRect::new_rect_xy(to_rect(rect), rx, ry))
+ }
+ _ => Geometry::Path(geometry_path(path, fast_shape, cache)),
}
}
-fn fill_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alpha: f32) {
+/// Skia path of a path, or of the shape a [`usvgr::FastShape`] keeps.
+fn geometry_path(
+ path: &usvgr::Path,
+ fast_shape: Option<usvgr::FastShapeKind>,
+ cache: &mut RenderCache,
+) -> skia_safe::Path {
+ match fast_shape {
+ // Skia's default oval starts at the rightmost point and goes clockwise, like SVG's.
+ Some(usvgr::FastShapeKind::Ellipse(rect)) => skia_safe::Path::oval(to_rect(rect), None),
+ // Index 0 starts at the end of the top-left corner, where the SVG spec's `rect` path
+ // starts, so dashes line up (the default starts on the left edge).
+ Some(usvgr::FastShapeKind::RoundRect { rect, rx, ry }) => {
+ skia_safe::Path::rrect_with_start_index(
+ skia_safe::RRect::new_rect_xy(to_rect(rect), rx, ry),
+ skia_safe::PathDirection::CW,
+ 0,
+ )
+ }
+ None => cache.convert_path(path),
+ }
+}
+
+fn to_rect(rect: usvgr::NonZeroRect) -> skia_safe::Rect {
+ skia_safe::Rect::from_ltrb(rect.left(), rect.top(), rect.right(), rect.bottom())
+}
+
+fn fill_path(
+ path: &usvgr::Path,
+ fast_shape: Option<usvgr::FastShapeKind>,
+ canvas: &Canvas,
+ cache: &mut RenderCache,
+ alpha: f32,
+) {
let Some(fill) = path.fill() else { return };
let bounds = path.data().bounds();
@@ -863,8 +959,11 @@ fn fill_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alpha
usvgr::FillRule::EvenOdd => skia_safe::PathFillType::EvenOdd,
};
- let mut sk_path = cache.convert_path(path);
- sk_path.set_fill_type(fill_type);
+ let mut sk_path = geometry(path, fast_shape, false, cache);
+ // Ovals and rounded rects do not overlap themselves, so the fill rule does not matter.
+ if let Geometry::Path(sk_path) = &mut sk_path {
+ sk_path.set_fill_type(fill_type);
+ }
let anti_alias = path.rendering_mode().use_shape_antialiasing();
let cache_key = path
@@ -909,10 +1008,16 @@ fn fill_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alpha
}
}
-fn stroke_path(path: &usvgr::Path, canvas: &Canvas, cache: &mut RenderCache, alpha: f32) {
+fn stroke_path(
+ path: &usvgr::Path,
+ fast_shape: Option<usvgr::FastShapeKind>,
+ canvas: &Canvas,
+ cache: &mut RenderCache,
+ alpha: f32,
+) {
let Some(stroke) = path.stroke() else { return };
- let sk_path = cache.convert_path(path);
+ let sk_path = geometry(path, fast_shape, stroke.dasharray().is_some(), cache);
let anti_alias = path.rendering_mode().use_shape_antialiasing();
let cache_key = path
diff --git a/fframes-skia-renderer/src/render/occlusion.rs b/fframes-skia-renderer/src/render/occlusion.rs
index f1b0c846..ff2269af 100644
--- a/fframes-skia-renderer/src/render/occlusion.rs
+++ b/fframes-skia-renderer/src/render/occlusion.rs
@@ -43,11 +43,15 @@ pub(super) fn visible_nodes(
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;
+ let (path, fast_shape) = match node {
+ usvgr::Node::Path(path) => (&**path, None),
+ usvgr::Node::FastShape(fast_shape) => (fast_shape.path(), Some(fast_shape.kind())),
+ _ => {
+ // 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;
@@ -80,7 +84,13 @@ pub(super) fn visible_nodes(
if fill.opacity().get() != 1. || !matches!(fill.paint(), usvgr::Paint::Color(_)) {
continue;
}
- let mut shape = cache.convert_path(path).make_transform(&matrix);
+ if let Some(kind) = fast_shape
+ && matrix.is_scale_translate()
+ {
+ covered.add(inscribed_rect(kind, &matrix).with_inset((1., 1.)));
+ continue;
+ }
+ let mut shape = super::geometry_path(path, fast_shape, cache).make_transform(&matrix);
shape.set_fill_type(match fill.rule() {
usvgr::FillRule::NonZero => PathFillType::Winding,
usvgr::FillRule::EvenOdd => PathFillType::EvenOdd,
@@ -98,6 +108,19 @@ pub(super) fn visible_nodes(
Some(visible)
}
+/// A rectangle inside a fast shape, in device space: inset by where the corner arcs (the whole
+/// outline of an ellipse) pass 45 degrees. Only valid for a scale-translate `matrix`.
+fn inscribed_rect(kind: usvgr::FastShapeKind, matrix: &skia_safe::Matrix) -> Rect {
+ let (rect, rx, ry) = match kind {
+ usvgr::FastShapeKind::Ellipse(rect) => (rect, rect.width() / 2., rect.height() / 2.),
+ usvgr::FastShapeKind::RoundRect { rect, rx, ry } => (rect, rx, ry),
+ };
+ let inset = 1. - std::f32::consts::FRAC_1_SQRT_2;
+ let inner = Rect::from_ltrb(rect.left(), rect.top(), rect.right(), rect.bottom())
+ .with_inset((rx * inset, ry * inset));
+ matrix.map_rect(inner).0
+}
+
struct Coverage {
rows: [u64; 64],
overlaps: bool,
diff --git a/fframes-skia-renderer/src/skia_backend.rs b/fframes-skia-renderer/src/skia_backend.rs
index 071ed87a..4f909ef8 100644
--- a/fframes-skia-renderer/src/skia_backend.rs
+++ b/fframes-skia-renderer/src/skia_backend.rs
@@ -43,6 +43,11 @@ impl<'a, TSkiaBackend: SkiaBackend> SkiaFFramesRenderer<'a, TSkiaBackend> {
}
impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBackend> {
+ /// Ovals and rounded rects are drawn analytically, see [`crate::render::render_tree`].
+ fn fast_shapes(&self) -> bool {
+ true
+ }
+
/// Skia previews on the same GPU context: shaders and filters look like in the video.
fn frame_renderer(&self) -> Option<impl FrameRenderer + '_> {
Some(
diff --git a/fframes-skia-renderer/tests/fast_shapes.rs b/fframes-skia-renderer/tests/fast_shapes.rs
new file mode 100644
index 00000000..85ad0a15
--- /dev/null
+++ b/fframes-skia-renderer/tests/fast_shapes.rs
@@ -0,0 +1,259 @@
+//! `usvgr::Options::fast_shapes` keeps `circle`, `ellipse` and rounded `rect` as
+//! `Node::FastShape`, which this renderer draws with Skia's analytic ovals and rounded rects
+//! instead of the generic path. Both must look the same: same coverage, and dashes starting
+//! where the SVG spec's path decomposition starts.
+
+use fframes::usvgr;
+use fframes_skia_renderer::render::{RenderCache, render_tree};
+use skia_safe::{AlphaType, ColorType, ImageInfo};
+
+const SIZE: i32 = 200;
+
+fn tree(svg: &str, fast_shapes: bool) -> usvgr::Tree {
+ let options = usvgr::Options {
+ fast_shapes,
+ ..Default::default()
+ };
+ usvgr::Tree::from_str(svg, &options, &usvgr::fontdb::Database::new()).expect("valid svg")
+}
+
+fn render(tree: &usvgr::Tree) -> Vec<u8> {
+ let info = ImageInfo::new(
+ (SIZE, SIZE),
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ skia_safe::ColorSpace::new_srgb(),
+ );
+ let mut surface = skia_safe::surfaces::raster(&info, None, None).expect("raster surface");
+ surface.canvas().clear(skia_safe::Color::WHITE);
+ render_tree(tree, surface.canvas(), &mut RenderCache::new());
+
+ let mut pixels = vec![0u8; (SIZE * SIZE * 4) as usize];
+ assert!(surface.read_pixels(&info, &mut pixels, (SIZE * 4) as usize, (0, 0)));
+ pixels
+}
+
+fn count_fast_shapes(group: &usvgr::Group) -> usize {
+ group
+ .children()
+ .iter()
+ .map(|node| match node {
+ usvgr::Node::FastShape(_) => 1,
+ usvgr::Node::Group(group) => count_fast_shapes(group),
+ _ => 0,
+ })
+ .sum()
+}
+
+fn svg(body: &str) -> String {
+ format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="{SIZE}" height="{SIZE}" viewBox="0 0 200 200">{body}</svg>"#
+ )
+}
+
+/// Renders `body` as paths and as fast shapes; returns how many pixels differ by more than
+/// anti-aliasing does. Native ovals are antialiased a little differently (up to ~45 levels on
+/// edge pixels), and dashes are measured along Skia's exact oval instead of our cubics (448.13
+/// vs 448.46 around a 90x50 ellipse), which moves dash ends by up to a third of a pixel. A dash
+/// pattern that starts elsewhere changes hundreds of pixels completely.
+fn differing_pixels(body: &str) -> usize {
+ let svg = svg(body);
+ let paths = render(&tree(&svg, false));
+ let shapes = render(&tree(&svg, true));
+ paths
+ .chunks_exact(4)
+ .zip(shapes.chunks_exact(4))
+ .filter(|(a, b)| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 96))
+ .count()
+}
+
+#[test]
+fn only_round_shapes_become_fast_shapes() {
+ let svg = svg(r#"
+ <circle cx="50" cy="50" r="20"/>
+ <ellipse cx="100" cy="50" rx="30" ry="10"/>
+ <rect x="10" y="100" width="50" height="30" rx="8"/>
+ <rect x="70" y="100" width="50" height="30"/>
+ <polygon points="150,100 190,100 170,130"/>
+ <line x1="10" y1="190" x2="190" y2="190" stroke="black"/>
+ "#);
+
+ assert_eq!(count_fast_shapes(tree(&svg, false).root()), 0);
+ assert_eq!(count_fast_shapes(tree(&svg, true).root()), 3);
+}
+
+#[test]
+fn fast_shapes_render_like_paths() {
+ let cases = [
+ (
+ "filled circle",
+ r#"<circle cx="100" cy="100" r="70" fill="teal"/>"#,
+ ),
+ (
+ "filled ellipse",
+ r#"<ellipse cx="100" cy="100" rx="90" ry="40" fill="teal"/>"#,
+ ),
+ (
+ "stroked circle",
+ r#"<circle cx="100" cy="100" r="70" fill="none" stroke="navy" stroke-width="9"/>"#,
+ ),
+ (
+ "dashed circle",
+ r#"<circle cx="100" cy="100" r="70" fill="none" stroke="navy" stroke-width="10" stroke-dasharray="40 20"/>"#,
+ ),
+ (
+ "dashed ellipse",
+ r#"<ellipse cx="100" cy="100" rx="90" ry="50" fill="none" stroke="navy" stroke-width="8" stroke-dasharray="30 15" stroke-dashoffset="7"/>"#,
+ ),
+ (
+ "rounded rect",
+ r#"<rect x="20" y="40" width="160" height="120" rx="24" ry="16" fill="orange" stroke="black" stroke-width="4"/>"#,
+ ),
+ (
+ "dashed rounded rect",
+ r#"<rect x="20" y="40" width="160" height="120" rx="30" fill="none" stroke="black" stroke-width="6" stroke-dasharray="25 10"/>"#,
+ ),
+ (
+ "pill",
+ r#"<rect x="20" y="70" width="160" height="60" rx="100" fill="orange" stroke="black" stroke-width="4" stroke-dasharray="20 8"/>"#,
+ ),
+ (
+ "non-uniform scale",
+ r#"<g transform="scale(1.8 0.6)"><circle cx="55" cy="160" r="40" fill="purple" stroke="black" stroke-width="5"/></g>"#,
+ ),
+ (
+ "skewed rounded rect",
+ r#"<g transform="skewX(20)"><rect x="10" y="40" width="120" height="100" rx="20" fill="olive" stroke="black" stroke-width="6" stroke-dasharray="12 6"/></g>"#,
+ ),
+ (
+ "gradient and opacity",
+ r#"<defs><linearGradient id="g"><stop offset="0" stop-color="red"/><stop offset="1" stop-color="blue"/></linearGradient></defs>
+ <circle cx="100" cy="100" r="80" fill="url(#g)" opacity="0.6"/>"#,
+ ),
+ ];
+
+ // Occlusion culling only runs for groups of 64 or more children; fast shapes certify the
+ // area they cover analytically, so overlapping stacks check that nothing visible is culled.
+ let stack = |transform: &str| {
+ let shapes: String = (0..150)
+ .map(|i| {
+ let (x, y) = (80 + (i * 7) % 40, 80 + (i * 11) % 40);
+ let color = format!(
+ "rgb({},{},{})",
+ (i * 41) % 256,
+ (i * 97) % 256,
+ (i * 13) % 256
+ );
+ if i % 3 == 0 {
+ format!(
+ r#"<rect x="{}" y="{}" width="70" height="60" rx="18" fill="{color}"/>"#,
+ x - 35,
+ y - 30
+ )
+ } else {
+ format!(
+ r#"<ellipse cx="{x}" cy="{y}" rx="{}" ry="32" fill="{color}"/>"#,
+ 30 + i % 15
+ )
+ }
+ })
+ .collect();
+ format!(r#"<g transform="{transform}">{shapes}</g>"#)
+ };
+ let stacks = [
+ ("overlapping stack", stack("translate(0 0)")),
+ ("scaled stack", stack("translate(10 0) scale(0.9 1.1)")),
+ ("rotated stack", stack("rotate(12 100 100)")),
+ ];
+
+ let failures: Vec<_> = cases
+ .iter()
+ .map(|(name, body)| (*name, body.to_string()))
+ .chain(stacks.iter().map(|(name, body)| (*name, body.clone())))
+ .map(|(name, body)| (name, differing_pixels(&body)))
+ .filter(|(_, differing)| *differing > 24)
+ .collect();
+ assert!(
+ failures.is_empty(),
+ "fast shapes render differently from paths (case, differing pixels): {failures:?}"
+ );
+}
+
+fn leaves(group: &usvgr::Group, out: &mut Vec<usvgr::Node>) {
+ for node in group.children() {
+ match node {
+ usvgr::Node::Group(group) => leaves(group, out),
+ node => out.push(node.clone()),
+ }
+ }
+}
+
+/// Fast shapes skip building and measuring the outline; their bounding boxes come from the
+/// rectangle and stroke width and must equal what measuring the outline gives.
+#[test]
+fn fast_shape_bounding_boxes_match_paths() {
+ let svg = svg(r#"
+ <circle cx="50" cy="50" r="20" fill="red"/>
+ <circle cx="50" cy="50" r="20" fill="none" stroke="red" stroke-width="7"/>
+ <ellipse cx="120" cy="60" rx="40" ry="15" stroke="red" stroke-width="3" stroke-linejoin="miter"/>
+ <rect x="10" y="100" width="80" height="40" rx="10" ry="6" stroke="red" stroke-width="5"/>
+ <rect x="110" y="110" width="80" height="40" rx="90" stroke="red" stroke-width="2"/>
+ <g transform="rotate(30 100 100) skewX(15)">
+ <ellipse cx="100" cy="150" rx="40" ry="20" stroke="red" stroke-width="4"/>
+ </g>
+ "#);
+ let (mut paths, mut shapes) = (Vec::new(), Vec::new());
+ leaves(tree(&svg, false).root(), &mut paths);
+ leaves(tree(&svg, true).root(), &mut shapes);
+ assert_eq!(paths.len(), shapes.len());
+
+ let near = |a: usvgr::Rect, b: usvgr::Rect| {
+ [
+ (a.left(), b.left()),
+ (a.top(), b.top()),
+ (a.right(), b.right()),
+ (a.bottom(), b.bottom()),
+ ]
+ .iter()
+ .all(|(a, b)| (a - b).abs() < 0.05)
+ };
+ for (path, shape) in paths.iter().zip(&shapes) {
+ let usvgr::Node::FastShape(fast_shape) = shape else {
+ panic!("not a fast shape: {shape:?}");
+ };
+ for (what, a, b) in [
+ ("bbox", path.bounding_box(), shape.bounding_box()),
+ (
+ "stroke bbox",
+ path.stroke_bounding_box(),
+ shape.stroke_bounding_box(),
+ ),
+ (
+ "abs bbox",
+ path.abs_bounding_box(),
+ shape.abs_bounding_box(),
+ ),
+ (
+ "abs stroke bbox",
+ path.abs_stroke_bounding_box(),
+ shape.abs_stroke_bounding_box(),
+ ),
+ ] {
+ assert!(
+ near(a, b),
+ "{what} of {:?}: path {a:?}, fast shape {b:?}",
+ fast_shape.kind()
+ );
+ }
+
+ // The outline built on demand is the one the regular conversion would build.
+ let usvgr::Node::Path(path) = path else {
+ unreachable!()
+ };
+ let outline = fast_shape.to_path().expect("outline");
+ assert!(near(
+ path.data().compute_tight_bounds().unwrap(),
+ outline.data().compute_tight_bounds().unwrap()
+ ));
+ }
+}
diff --git a/fframes-skia-renderer/tests/static_cache.rs b/fframes-skia-renderer/tests/static_cache.rs
index aacecd01..3ae042fa 100644
--- a/fframes-skia-renderer/tests/static_cache.rs
+++ b/fframes-skia-renderer/tests/static_cache.rs
@@ -63,6 +63,7 @@ fn first_child_static_hash(tree: &usvgr::Tree) -> Option<u64> {
match tree.root().children().first().expect("root has a child") {
usvgr::Node::Group(g) => g.static_hash(),
usvgr::Node::Path(p) => p.static_hash(),
+ usvgr::Node::FastShape(e) => e.path().static_hash(),
_ => None,
}
}
diff --git a/fframes-test-utils/src/static_hash_spec.rs b/fframes-test-utils/src/static_hash_spec.rs
index 29b9c59c..fd1321eb 100644
--- a/fframes-test-utils/src/static_hash_spec.rs
+++ b/fframes-test-utils/src/static_hash_spec.rs
@@ -160,6 +160,9 @@ fn collect(group: &usvgr::Group, out: &mut HashMap<String, Option<u64>>) {
usvgr::Node::Path(p) if !p.id().is_empty() => {
out.insert(p.id().to_owned(), p.static_hash());
}
+ usvgr::Node::FastShape(e) if !e.path().id().is_empty() => {
+ out.insert(e.path().id().to_owned(), e.path().static_hash());
+ }
_ => {}
}
}
diff --git a/fframes/src/diagnostics.rs b/fframes/src/diagnostics.rs
index 5442bdfe..ae097c2d 100644
--- a/fframes/src/diagnostics.rs
+++ b/fframes/src/diagnostics.rs
@@ -284,10 +284,10 @@ fn inspect_group(group: &usvgr::Group, width: f32, height: f32, out: &mut Vec<Di
});
}
}
- usvgr::Node::Path(path) => {
- if !path.abs_transform().is_finite() {
+ usvgr::Node::Path(_) | usvgr::Node::FastShape(_) => {
+ if !node.abs_transform().is_finite() {
out.push(Diagnostic::InvalidTransform {
- id: path.id().to_owned(),
+ id: node.id().to_owned(),
});
}
}
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index ff212ae3..5415fa2e 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 {
+ /// Whether this renderer draws [`usvgr::Node::FastShape`] natively, see
+ /// [`super::FFramesRenderBackend::fast_shapes`].
+ fn fast_shapes(&self) -> bool {
+ false
+ }
+
/// 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> {
@@ -406,6 +412,15 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
/// Calls `Video::render_frame` and converts the result.
pub fn svg_tree(&mut self, frame: usize) -> FFramesRendererResult<usvgr::Tree> {
+ self.convert_frame(frame, false)
+ }
+
+ /// [`Self::svg_tree`] for a renderer, which may draw [`usvgr::Node::FastShape`] natively.
+ fn convert_frame(
+ &mut self,
+ frame: usize,
+ fast_shapes: bool,
+ ) -> FFramesRendererResult<usvgr::Tree> {
self.check_frame(frame)?;
let ctx = FFramesContext {
@@ -434,6 +449,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
let usvg_options = usvgr::Options {
image_data: Some(&self.image_source),
font_family: self.options.default_font.to_string(),
+ fast_shapes,
..Default::default()
};
@@ -459,7 +475,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
renderer: &mut dyn FrameRenderer,
) -> FFramesRendererResult<RgbaFrame> {
self.configure_renderer_cache(renderer);
- let tree = self.svg_tree(frame)?;
+ let tree = self.convert_frame(frame, renderer.fast_shapes())?;
let (width, height) = self.size();
renderer.render_tree(&tree, TVideo::BACKGROUND_COLOR, width, height)
}
@@ -482,7 +498,8 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
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 fast_shapes = renderer.fast_shapes();
+ let (tree, mut found) = diagnostics::collect(|| self.convert_frame(frame, fast_shapes));
let tree = tree?;
found.extend(diagnostics::inspect_tree(
&tree,
diff --git a/fframes/src/renderer/render_backend.rs b/fframes/src/renderer/render_backend.rs
index 27f79819..812c99d0 100644
--- a/fframes/src/renderer/render_backend.rs
+++ b/fframes/src/renderer/render_backend.rs
@@ -9,6 +9,15 @@ use usvgr::fontdb;
#[allow(clippy::too_many_arguments)]
pub trait FFramesRenderBackend {
+ /// Whether this backend draws [`usvgr::Node::FastShape`] natively. When `true`, frames are
+ /// converted with [`usvgr::Options::fast_shapes`]: `circle`, `ellipse` and rounded `rect`
+ /// stay shapes instead of becoming generic paths.
+ ///
+ /// The default (`false`) keeps the exact path geometry the CPU backend is tested against.
+ fn fast_shapes(&self) -> bool {
+ false
+ }
+
/// Renders single frames (`fframes::Previewer`, the CLI's `frame`, `strip`, `onion` and
/// `snapshot`) the way this backend renders the video, so previews match the output.
/// `None` uses the built-in CPU renderer.
diff --git a/fframes/src/renderer/renderer.rs b/fframes/src/renderer/renderer.rs
index fa8a3989..1219bf30 100644
--- a/fframes/src/renderer/renderer.rs
+++ b/fframes/src/renderer/renderer.rs
@@ -198,6 +198,7 @@ pub fn render<
let usvg_options = usvgr::Options {
image_data: Some(&image_source),
font_family: options.default_font.to_string(),
+ fast_shapes: render_backend.fast_shapes(),
..Default::default()
};
@@ -314,6 +315,7 @@ pub fn render_frame<
};
let decoders = VideoDecodersWorker::new(1);
+ let fast_shapes = render_backend.fast_shapes();
render_backend.render_frame(
crate::Frame::__internal_make_for_renderer(
frame_index,
@@ -326,6 +328,7 @@ pub fn render_frame<
&crate::usvgr::Options {
image_data: Some(&image_source),
font_family: options.default_font.to_string(),
+ fast_shapes,
..Default::default()
},
font_source.as_db_ref(),