programmatic video rendering framework that is actually fast
feat(examples): svg-in-3d, svgr and 3D nested four levels
Dmitriy Kovalenko51d78c257e17
diff --git a/Cargo.lock b/Cargo.lockindex f5a2c909..f7454ab0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3915,6 +3915,14 @@ version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]+name = "svg-in-3d-example"+version = "1.2.0"+dependencies = [+ "fframes",+ "fframes_skia_renderer",+]+[[package]]name = "svgr"version = "0.50.2"diff --git a/Cargo.toml b/Cargo.tomlindex a49cbde3..9f1ffaf1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -53,6 +53,7 @@ members = ["examples/made-of-motion","examples/shader-mode","examples/lottie-launch",+ "examples/svg-in-3d",][workspace.lints.rust]diff --git a/examples/svg-in-3d/Cargo.toml b/examples/svg-in-3d/Cargo.tomlnew file mode 100644index 00000000..2a9a228e--- /dev/null+++ b/examples/svg-in-3d/Cargo.toml@@ -0,0 +1,34 @@+[package]+name = "svg-in-3d-example"+version = "1.2.0"+edition = "2024"+publish = false++[dependencies]+# `3d`: `fframes::three_d`; `wgpu`: the 3D renders on the GPU+fframes = { workspace = true, features = ["3d", "wgpu"] }++# Skia on Metal on macOS, on Vulkan everywhere else.+[target.'cfg(target_os = "macos")'.dependencies]+fframes_skia_renderer = { workspace = true, features = ["metal"] }++[target.'cfg(not(any(target_os = "macos", target_arch = "wasm32")))'.dependencies]+# `wgpu`: the svgr images and the 3D render on the Vulkan device of Skia and stay on the GPU+fframes_skia_renderer = { workspace = true, features = ["vulkan", "wgpu"] }++[features]+default = ["renderer"]+renderer = ["fframes/compile-time-svgtree", "fframes/cli"]++[lib]+name = "svg_in_3d_example"+path = "src/lib.rs"+doctest = false++[[bin]]+name = "svg-in-3d"+path = "src/main.rs"+required-features = ["renderer"]++[lints]+workspace = truediff --git a/examples/svg-in-3d/media/DMSans-Medium.ttf b/examples/svg-in-3d/media/DMSans-Medium.ttfnew file mode 100644index 00000000..fc8a5ebdBinary files /dev/null and b/examples/svg-in-3d/media/DMSans-Medium.ttf differdiff --git a/examples/svg-in-3d/media/JetBrainsMono-Regular.ttf b/examples/svg-in-3d/media/JetBrainsMono-Regular.ttfnew file mode 100644index 00000000..7d26f5a5Binary files /dev/null and b/examples/svg-in-3d/media/JetBrainsMono-Regular.ttf differdiff --git a/examples/svg-in-3d/src/lib.rs b/examples/svg-in-3d/src/lib.rsnew file mode 100644index 00000000..d1feae0c--- /dev/null+++ b/examples/svg-in-3d/src/lib.rs@@ -0,0 +1,240 @@+//! An svgr UI on the screen of a turning 3D monitor. The UI shows a 3D render of its own:+//! a cube with an svgr logo on its faces. So the frame nests four levels:+//!+//! ```text+//! logo svgr -> cube (3D) -> UI svgr -> monitor (3D) -> frame svgr+//! ```+//!+//! `ctx.render_svgr` renders each svgr level with the backend of the video. On the Skia+//! Vulkan backend with the `wgpu` feature, no level leaves the GPU.++// Colors are hex numbers, as in three.js: `0xff4a00`.+#![allow(clippy::unreadable_literal)]++use std::f32::consts::TAU;++use fframes::three_d::*;+use fframes::{AudioMap, Color, Duration, FFramesContext, Frame, Svgr, Video, svgr};++fframes::include_media_dir!(pub struct SvgIn3dMedia, "examples/svg-in-3d/media");++pub const WIDTH: usize = 1920;+pub const HEIGHT: usize = 1080;+pub const FPS: usize = 30;+const SECONDS: f32 = 8.0;++/// The size of the UI texture: the 16:10 screen at 1280 x 800.+const UI: (u32, u32) = (1280, 800);+/// The size of the cube render in the UI.+const CUBE: u32 = 480;++/// The monitor, the cube and their renderers. Built once, posed in each frame.+pub struct Monitor {+ scene: Scene,+ body: NodeId,+ screen: NodeId,+ renderer: Renderer,+ cube_scene: Scene,+ cube: NodeId,+ cube_renderer: Renderer,+}++impl std::fmt::Debug for Monitor {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Monitor").finish_non_exhaustive()+ }+}++impl Default for Monitor {+ fn default() -> Self {+ Self::new()+ }+}++impl Monitor {+ pub fn new() -> Self {+ let mut scene = Scene::new().environment(Environment::studio());+ let frame = Material::metal(0x2a2d33, 0.35).clearcoat(0.6);+ let body = scene.add(+ Node::mesh(+ Geometry::rounded_box(1.84, 1.2, 0.09, 0.035, 4),+ frame.clone(),+ )+ .at(0.0, 1.32, 0.0),+ );+ // The UI shows as it is: an unlit screen with the UI texture, set in each frame.+ let screen = scene.add_to(+ body,+ Node::mesh(Geometry::plane(1.68, 1.05), Material::unlit(0xffffff)).at(0.0, 0.0, 0.0455),+ );+ scene.add(+ Node::mesh(Geometry::cylinder(0.05, 0.06, 0.62, 24), frame.clone()).at(0.0, 0.5, -0.06),+ );+ scene.add(+ Node::mesh(Geometry::rounded_box(0.8, 0.04, 0.42, 0.02, 3), frame).at(0.0, 0.2, -0.06),+ );+ scene.add(+ Node::mesh(Geometry::floor(20.0, 20.0), Material::shadow_catcher(0.55))+ .at(0.0, 0.18, 0.0)+ .shadows(false, true),+ );+ scene.add(Node::light(Light::sun(+ Rgb::WHITE,+ 2.5,+ vec3(2.5, 6.0, 4.0),+ )));++ let mut cube_scene = Scene::new().environment(Environment::studio());+ let cube = cube_scene.add(Node::mesh(+ Geometry::cuboid(1.0, 1.0, 1.0),+ Material::standard(0xffffff).roughness(0.35),+ ));+ cube_scene.add(Node::light(Light::sun(+ Rgb::WHITE,+ 2.0,+ vec3(2.0, 3.0, 4.0),+ )));++ Self {+ scene,+ body,+ screen,+ renderer: Renderer::new(WIDTH as u32, HEIGHT as u32).tone_mapping(ToneMapping::Neutral),+ cube_scene,+ cube,+ cube_renderer: Renderer::new(CUBE, CUBE).tone_mapping(ToneMapping::Neutral),+ }+ }++ /// Renders the 3D on the CPU, also with a GPU.+ pub fn on_cpu(mut self) -> Self {+ self.renderer = self.renderer.cpu();+ self.cube_renderer = self.cube_renderer.cpu();+ self+ }++ /// The cube with `logo` on its faces at `t` seconds.+ fn cube(+ &self,+ logo: &fframes::media::ImageData<'_>,+ t: f32,+ ) -> fframes::media::ImageData<'static> {+ let mut scene = self.cube_scene.clone();+ scene[self.cube].rotation = euler(t * 0.7, t * 1.1, 0.25);+ if let Some(material) = scene[self.cube].material_mut() {+ material.map = Some(Texture::from_image(logo).into());+ }+ let camera = Camera::perspective(35.0).at(0.0, 0.0, 3.4);+ self.cube_renderer.render(&scene, &camera)+ }++ /// The monitor with `ui` on its screen at `t` seconds.+ fn monitor(+ &self,+ ui: &fframes::media::ImageData<'_>,+ t: f32,+ ) -> fframes::media::ImageData<'static> {+ let mut scene = self.scene.clone();+ // turns far enough that the text on the screen is seen at a low angle+ scene[self.body].rotation = euler(0.0, (t / SECONDS * TAU).sin() * deg(52.0), 0.0);+ if let Some(material) = scene[self.screen].material_mut() {+ material.map = Some(Texture::from_image(ui).into());+ }+ let camera =+ Camera::perspective(30.0).orbit(vec3(0.0, 1.1, 0.0), 4.6, 12.0 * (t * 0.4).sin(), 9.0);+ self.renderer.render(&scene, &camera)+ }+}++/// `m:ss.cc` of `t` seconds.+fn timer(t: f32) -> String {+ let centis = (t * 100.0).round() as u32;+ format!(+ "{}:{:02}.{:02}",+ centis / 6000,+ centis / 100 % 60,+ centis % 100+ )+}++impl Video for Monitor {+ const FPS: usize = FPS;+ const WIDTH: usize = WIDTH;+ const HEIGHT: usize = HEIGHT;+ const BACKGROUND_COLOR: Color = Color::BLACK;++ fn duration(&self) -> Duration<'_> {+ Duration::Seconds(SECONDS)+ }++ fn audio(&self) -> AudioMap<'_> {+ AudioMap::none()+ }++ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ let t = frame.seconds();++ // level 1: a static svgr logo. It renders once, later frames get the same image.+ let Some(logo) = ctx.render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">+ <rect x="0" y="0" width="256" height="256" fill="#2f81f7" />+ <rect x="14" y="14" width="228" height="228" rx="28" fill="none" stroke="#ffffff" stroke-width="10" />+ <text x="128" y="168" text-anchor="middle" font-family="DM Sans" font-size="116" fill="#ffffff">"ff"</text>+ </svg>+ ),+ 256,+ 256,+ ) else {+ return Svgr::empty();+ };++ // level 2: the logo on a turning cube+ let cube = self.cube(&logo, t);++ // level 3: the UI with a live timer and the cube render+ let progress = t / SECONDS;+ let Some(ui) = ctx.render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 800" width="1280" height="800">+ <rect x="0" y="0" width="1280" height="800" fill="#0d1117" />+ <rect x="0" y="0" width="1280" height="96" fill="#161b22" />+ <circle cx="52" cy="48" r="12" fill="#ff5f56" />+ <circle cx="88" cy="48" r="12" fill="#ffbd2e" />+ <circle cx="124" cy="48" r="12" fill="#27c93f" />+ <text x="168" y="62" font-family="DM Sans" font-size="38" fill="#e6edf3">"ctx.render_svgr"</text>+ <text x="1232" y="64" text-anchor="end" font-family="JetBrains Mono" font-size="40" fill="#ff7b72">{timer(t)}</text>+ <rect x="64" y="148" width="528" height="528" rx="24" fill="#161b22" />+ <image href={cube.href()} x="88" y="172" width="480" height="480" />+ <text x="660" y="236" font-family="JetBrains Mono" font-size="34" fill="#7ee787">"svg -> 3D"</text>+ <text x="660" y="296" font-family="JetBrains Mono" font-size="34" fill="#79c0ff">"3D -> svg"</text>+ <text x="660" y="356" font-family="JetBrains Mono" font-size="34" fill="#d2a8ff">"svg -> 3D"</text>+ <text x="660" y="416" font-family="JetBrains Mono" font-size="34" fill="#ffa657">"3D -> frame"</text>+ <text x="660" y="520" font-family="DM Sans" font-size="30" fill="#8b949e">"frame " {frame.index.to_string()}</text>+ <rect x="660" y="600" width="540" height="18" rx="9" fill="#30363d" />+ <rect x="660" y="600" width={18.0 + 522.0 * progress} height="18" rx="9" fill="#2f81f7" />+ </svg>+ ),+ UI.0,+ UI.1,+ ) else {+ return Svgr::empty();+ };++ // level 4: the UI on the screen of the monitor, in the frame+ let monitor = self.monitor(&ui, t);+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1920 1080" width={WIDTH} height={HEIGHT}>+ <defs>+ <radialGradient id="room" cx="50%" cy="38%" r="75%">+ <stop offset="0%" stop-color="#3a4150" />+ <stop offset="100%" stop-color="#0b0d12" />+ </radialGradient>+ </defs>+ <rect x="0" y="0" width="1920" height="1080" fill="url(#room)" />+ <image href={monitor.href()} x="0" y="0" width="1920" height="1080" />+ <text x="96" y="1010" font-family="DM Sans" font-size="34" fill="#8b949e">"An svgr UI on a 3D screen. The UI holds a 3D render with an svgr logo."</text>+ </svg>+ )+ }+}diff --git a/examples/svg-in-3d/src/main.rs b/examples/svg-in-3d/src/main.rsnew file mode 100644index 00000000..642a3d70--- /dev/null+++ b/examples/svg-in-3d/src/main.rs@@ -0,0 +1,53 @@+use std::process::ExitCode;++use fframes::cli::{self, clap};+use fframes::{RenderOptions, StaticMediaProvider};+use fframes_skia_renderer::{+ SkiaFFramesRenderer, SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig,+};+use svg_in_3d_example::{HEIGHT, Monitor, SvgIn3dMedia, WIDTH};++#[derive(Debug, clap::Args)]+struct Args {+ /// Render everything on the CPU: the 3D with the software rasterizer, the svgr images+ /// and the frame with the tiny-skia backend.+ #[arg(long, global = true)]+ cpu: bool,+}++fn main() -> ExitCode {+ let args = cli::parse::<Args>();+ let media = SvgIn3dMedia::prepare().expect("media");+ let cpu = args.app.cpu;+ let video = if cpu {+ Monitor::new().on_cpu()+ } else {+ Monitor::new()+ };+ let options = RenderOptions {+ media: Some(&media),+ ..Default::default()+ };++ let command = cli::new(&video, options)+ .args(args)+ .default_output("out.mp4");+ if cpu {+ return command.run();+ }++ #[cfg(target_os = "macos")]+ let gpu = fframes_skia_renderer::metal::SkiaMetalCtx::new(WIDTH, HEIGHT).expect("GPU context");+ #[cfg(not(target_os = "macos"))]+ let gpu =+ fframes_skia_renderer::vulkan::SkiaVulkanCtx::new(WIDTH, HEIGHT).expect("GPU context");+ let pipeline = SkiaPipelineConfig {+ concurrency_policy: SkiaPipelineConcurrencyPolicy::MaxPerformance,+ ..Default::default()+ };+ #[cfg(target_os = "macos")]+ let backend = SkiaFFramesRenderer::new_metal(&gpu, pipeline);+ #[cfg(not(target_os = "macos"))]+ let backend = SkiaFFramesRenderer::new_vulkan(&gpu, pipeline);+ command.backend(backend.expect("skia renderer")).run()+}diff --git a/examples/svg-in-3d/tests/recursion.rs b/examples/svg-in-3d/tests/recursion.rsnew file mode 100644index 00000000..0fb3ac01--- /dev/null+++ b/examples/svg-in-3d/tests/recursion.rs@@ -0,0 +1,287 @@+//! svg -> 3D -> svg -> 3D -> frame. An svgr image on a quad (scene A), the render of A in a+//! second svgr image (B), B on a quad (scene C), the render of C in the frame. The pixels+//! of the frame land where the projections of the cameras put them, on every backend.+#![allow(clippy::unreadable_literal)]++use std::sync::atomic::{AtomicBool, Ordering};++use fframes::media::ImageData;+use fframes::three_d::*;+use fframes::{+ AudioMap, Color, Duration, FFramesContext, Frame, RenderOptions, StaticMediaProvider, Svgr,+ Video, svgr,+};+use fframes_skia_renderer::{SkiaCpuCtx, SkiaFFramesRenderer, SkiaPipelineConfig};+use svg_in_3d_example::SvgIn3dMedia;++const FRAME: u32 = 640;+/// The size of the innermost image and of the render of A.+const INNER: u32 = 256;+/// The size of B and of the render of C.+const OUTER: u32 = 512;+/// Where A is in B, and where C is in the frame.+const A_IN_B: f32 = 128.0;+const C_IN_FRAME: f32 = 64.0;++#[derive(Debug)]+struct Nested {+ gpu_3d: bool,+ /// Set when B is a texture on the GPU (`fframes::wgpu_layer`).+ b_on_gpu: AtomicBool,+}++impl Nested {+ fn new(gpu_3d: bool) -> Self {+ Self {+ gpu_3d,+ b_on_gpu: AtomicBool::new(false),+ }+ }++ /// `image` on a quad that the camera sees head on, rendered at `size` x `size`.+ fn quad(&self, image: &ImageData<'_>, size: u32) -> ImageData<'static> {+ let mut scene = Scene::new();+ scene.add(Node::mesh(+ Geometry::plane(2.0, 2.0),+ Material::unlit(0xffffff).map(Texture::from_image(image)),+ ));+ let renderer = Renderer::new(size, size).tone_mapping(ToneMapping::Linear);+ let renderer = if self.gpu_3d {+ renderer.gpu()+ } else {+ renderer.cpu()+ };+ renderer.render(&scene, &camera())+ }+}++fn camera() -> Camera {+ Camera::perspective(40.0)+ .at(0.0, 0.0, 3.0)+ .look_at(Vec3::ZERO)+}++/// The pixel of a quad render of `size` that shows texture coordinate `uv`.+fn on_quad(uv: Vec2, size: u32) -> Vec2 {+ // `Geometry::plane` has UV (0, 0) at the top left corner (-1, 1)+ let world = vec3(-1.0 + 2.0 * uv.x, 1.0 - 2.0 * uv.y, 0.0);+ camera()+ .project(world, size as f32, size as f32)+ .expect("the quad is in front of the camera")+ .truncate()+}++/// The pixel of the frame that shows pixel `p` of B.+fn b_in_frame(p: Vec2) -> Vec2 {+ on_quad(p / OUTER as f32, OUTER) + C_IN_FRAME+}++/// The pixel of the frame that shows pixel `p` of the innermost image.+fn inner_in_frame(p: Vec2) -> Vec2 {+ b_in_frame(on_quad(p / INNER as f32, INNER) + A_IN_B)+}++impl Video for Nested {+ const FPS: usize = 30;+ const WIDTH: usize = FRAME as usize;+ const HEIGHT: usize = FRAME as usize;+ const BACKGROUND_COLOR: Color = Color::BLACK;++ fn duration(&self) -> Duration<'_> {+ Duration::Frames(1)+ }++ fn audio(&self) -> AudioMap<'_> {+ AudioMap::none()+ }++ fn render_frame<'a>(&'a self, _frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ let inner = ctx+ .render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">+ <rect x="0" y="0" width="256" height="256" fill="#ffffff" />+ <rect x="64" y="64" width="64" height="64" fill="#ff0000" />+ <text x="140" y="236" font-family="DM Sans" font-size="110" fill="#000000">"F"</text>+ </svg>+ ),+ INNER,+ INNER,+ )+ .expect("the innermost image renders");+ let a = self.quad(&inner, INNER);+ let b = ctx+ .render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">+ <rect x="0" y="0" width="512" height="512" fill="#808080" />+ <image href={a.href()} x="128" y="128" width="256" height="256" />+ <rect x="16" y="16" width="64" height="64" fill="#00ff00" />+ </svg>+ ),+ OUTER,+ OUTER,+ )+ .expect("B renders");+ #[cfg(not(target_os = "macos"))]+ self.b_on_gpu.store(+ fframes::resolve_wgpu_layer(&b.href()).is_some(),+ Ordering::Relaxed,+ );+ let c = self.quad(&b, OUTER);+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" width="640" height="640">+ <image href={c.href()} x="64" y="64" width="512" height="512" />+ </svg>+ )+ }+}++/// Straight RGBA pixels of a rendered frame.+struct Pixels(Vec<u8>);++impl Pixels {+ fn at(&self, p: Vec2) -> [u8; 3] {+ let i = ((p.y as usize) * FRAME as usize + p.x as usize) * 4;+ [self.0[i], self.0[i + 1], self.0[i + 2]]+ }++ /// The darkest channel sum in a box around `p`.+ fn darkest_near(&self, p: Vec2, radius: f32) -> u32 {+ let mut darkest = u32::MAX;+ for dy in -(radius as i32)..=radius as i32 {+ for dx in -(radius as i32)..=radius as i32 {+ let [r, g, b] = self.at(p + Vec2::new(dx as f32, dy as f32));+ darkest = darkest.min(u32::from(r) + u32::from(g) + u32::from(b));+ }+ }+ darkest+ }++ fn mean_difference(&self, other: &Pixels) -> f64 {+ let sum: u64 = (self.0.iter().zip(&other.0))+ .map(|(a, b)| u64::from(a.abs_diff(*b)))+ .sum();+ sum as f64 / self.0.len() as f64+ }+}++fn assert_color(pixels: &Pixels, p: Vec2, expected: [u8; 3], what: &str, backend: &str) {+ let actual = pixels.at(p);+ let close = actual.iter().zip(expected).all(|(a, e)| a.abs_diff(e) <= 4);+ assert!(+ close,+ "{backend}: {what} at {p}: expected {expected:?}, got {actual:?}"+ );+}++/// Checks the landmarks of the frame: the red square and the black text of the innermost+/// image, the white around them, and the green marker and the gray of B.+fn assert_landmarks(pixels: &Pixels, backend: &str) {+ let red = inner_in_frame(Vec2::splat(96.0));+ assert_color(pixels, red, [255, 0, 0], "the red square", backend);+ let white = inner_in_frame(Vec2::new(40.0, 200.0));+ assert_color(+ pixels,+ white,+ [255, 255, 255],+ "the white of the innermost image",+ backend,+ );+ let green = b_in_frame(Vec2::splat(48.0));+ assert_color(pixels, green, [0, 255, 0], "the marker of B", backend);+ let gray = b_in_frame(Vec2::new(460.0, 460.0));+ assert_color(pixels, gray, [128, 128, 128], "the gray of B", backend);+ // The "F" covers the box from (150, 160) to (200, 236) of the innermost image. Its stem+ // is near x 160.+ let text = inner_in_frame(Vec2::new(162.0, 200.0));+ assert!(+ pixels.darkest_near(text, 4.0) < 60,+ "{backend}: no black text near {text}"+ );+ // outside C the frame is black+ assert_color(pixels, Vec2::splat(20.0), [0, 0, 0], "the frame", backend);+}++fn render(video: &Nested, backend: impl fframes::FFramesRenderBackend) -> Pixels {+ let media = SvgIn3dMedia::prepare().expect("media");+ let options = RenderOptions {+ media: Some(&media),+ ..Default::default()+ };+ Pixels(fframes::render_frame(0, video, backend, &options).expect("the frame renders"))+}++fn save(pixels: &Pixels, name: &str) {+ let Ok(dir) = std::env::var("SVG_IN_3D_TEST_OUTPUT") else {+ return;+ };+ image_save(&format!("{dir}/{name}.png"), &pixels.0);+}++fn image_save(path: &str, rgba: &[u8]) {+ fframes::RgbaFrame {+ width: FRAME,+ height: FRAME,+ pixels: rgba.to_vec(),+ }+ .save_png(path)+ .expect("png");+}++#[test]+fn nested_images_land_where_the_projections_put_them() {+ let cpu = render(+ &Nested::new(false),+ fframes::cpu::CpuRenderingBackend::default(),+ );+ save(&cpu, "cpu");+ assert_landmarks(&cpu, "CPU backend");++ let skia_cpu_ctx = SkiaCpuCtx::new(FRAME as usize, FRAME as usize);+ let skia_cpu = render(+ &Nested::new(false),+ SkiaFFramesRenderer::new_cpu(&skia_cpu_ctx, SkiaPipelineConfig::default()).unwrap(),+ );+ save(&skia_cpu, "skia-cpu");+ assert_landmarks(&skia_cpu, "Skia CPU backend");+ let difference = skia_cpu.mean_difference(&cpu);+ assert!(+ difference < 1.0,+ "Skia CPU differs from CPU by {difference} on average"+ );++ #[cfg(not(target_os = "macos"))]+ {+ let Ok(vulkan) =+ fframes_skia_renderer::vulkan::SkiaVulkanCtx::new(FRAME as usize, FRAME as usize)+ else {+ eprintln!("no Vulkan device, the GPU part is skipped");+ return;+ };+ assert!(+ vulkan.shared_gpu().is_some(),+ "wgpu shares the Vulkan device"+ );+ let video = Nested::new(true);+ let gpu = render(+ &video,+ SkiaFFramesRenderer::new_vulkan(&vulkan, SkiaPipelineConfig::default()).unwrap(),+ );+ save(&gpu, "skia-vulkan");+ assert!(+ video.b_on_gpu.load(Ordering::Relaxed),+ "B stays on the GPU on Skia Vulkan with wgpu"+ );+ assert_landmarks(&gpu, "Skia Vulkan backend");+ let difference = gpu.mean_difference(&cpu);+ assert!(+ difference < 1.0,+ "the GPU differs from the CPU by {difference} on average"+ );+ eprintln!(+ "mean difference to the CPU backend: Skia CPU {:.3}, Skia Vulkan {difference:.3}",+ skia_cpu.mean_difference(&cpu)+ );+ }+}diff --git a/examples/svg-in-3d/tests/stress.rs b/examples/svg-in-3d/tests/stress.rsnew file mode 100644index 00000000..bd0c2af6--- /dev/null+++ b/examples/svg-in-3d/tests/stress.rs@@ -0,0 +1,164 @@+//! Many frames with nested svgr images and 3D render at the same time on the Skia Vulkan+//! backend: no deadlock, and the same video on every run.+#![cfg(not(target_os = "macos"))]+#![allow(clippy::unreadable_literal)]++use std::hash::{Hash, Hasher};+use std::path::Path;++use fframes::media::{FFmpegDecoder, ImageData};+use fframes::three_d::*;+use fframes::{+ AudioMap, Color, Duration, FFramesContext, Frame, RenderOptions, StaticMediaProvider, Svgr,+ Video, svgr,+};+use fframes_skia_renderer::vulkan::SkiaVulkanCtx;+use fframes_skia_renderer::{+ SkiaFFramesRenderer, SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig,+};+use svg_in_3d_example::SvgIn3dMedia;++const SIZE: usize = 320;+const FPS: usize = 30;+const FRAMES: usize = 200;++#[derive(Debug)]+struct Busy;++/// `image` on a quad turned by `angle` radians, rendered at `size` x `size`.+fn quad(image: &ImageData<'_>, size: u32, angle: f32) -> ImageData<'static> {+ let mut scene = Scene::new().environment(Environment::studio());+ scene.add(+ Node::mesh(+ Geometry::plane(2.0, 2.0),+ Material::standard(0xffffff).map(Texture::from_image(image)),+ )+ .rotate_y(angle),+ );+ let camera = Camera::perspective(40.0).at(0.0, 0.0, 3.0);+ Renderer::new(size, size).gpu().render(&scene, &camera)+}++impl Video for Busy {+ const FPS: usize = FPS;+ const WIDTH: usize = SIZE;+ const HEIGHT: usize = SIZE;+ const BACKGROUND_COLOR: Color = Color::BLACK;++ fn duration(&self) -> Duration<'_> {+ Duration::Frames(FRAMES)+ }++ fn audio(&self) -> AudioMap<'_> {+ AudioMap::none()+ }++ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ let n = frame.index as f32;+ // a static image (rendered once) and a new one in every frame+ let Some(logo) = ctx.render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">+ <rect x="0" y="0" width="128" height="128" fill="#2f81f7" />+ <text x="64" y="88" text-anchor="middle" font-family="DM Sans" font-size="64" fill="#ffffff">"ff"</text>+ </svg>+ ),+ 128,+ 128,+ ) else {+ return Svgr::empty();+ };+ let Some(inner) = ctx.render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">+ <rect x="0" y="0" width="256" height="256" fill="#ffffff" />+ <rect x={(n * 3.0) % 192.0} y="40" width="64" height="64" fill="#ff0000" />+ <image href={logo.href()} x="16" y="120" width="96" height="96" />+ <text x="128" y="200" font-family="JetBrains Mono" font-size="40" fill="#000000">{frame.index.to_string()}</text>+ </svg>+ ),+ 256,+ 256,+ ) else {+ return Svgr::empty();+ };+ let a = quad(&inner, 256, (n * 0.05).sin() * 0.7);+ let Some(b) = ctx.render_svgr(+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" width="320" height="320">+ <rect x="0" y="0" width="320" height="320" fill="#202830" />+ <image href={a.href()} x="32" y="32" width="256" height="256" />+ <circle cx={20.0 + (n * 2.0) % 280.0} cy="300" r="12" fill="#00ff00" />+ </svg>+ ),+ 320,+ 320,+ ) else {+ return Svgr::empty();+ };+ let c = quad(&b, 320, (n * 0.02).cos() * 0.5);+ svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" width="320" height="320">+ <image href={c.href()} x="0" y="0" width="320" height="320" />+ </svg>+ )+ }+}++/// Renders the video and returns the hash of every decoded frame.+fn render(gpu: &SkiaVulkanCtx, output: &Path) -> u64 {+ let media = SvgIn3dMedia::prepare().expect("media");+ let chunks = output.with_extension("chunks");+ let options = RenderOptions {+ media: Some(&media),+ logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,+ tmp_files_directory: Some(&chunks),+ ..Default::default()+ };+ let backend = SkiaFFramesRenderer::new_vulkan(+ gpu,+ SkiaPipelineConfig {+ concurrency_policy: SkiaPipelineConcurrencyPolicy::MaxPerformance,+ ..Default::default()+ },+ )+ .unwrap();+ fframes::render(output, &Busy, backend, &options).expect("the video renders");++ let mut hasher = std::hash::DefaultHasher::new();+ let mut decoder = unsafe { FFmpegDecoder::new(output, FPS, 1) }.unwrap();+ for frame in 0..FRAMES {+ unsafe {+ assert!(+ decoder.decode_up_to(frame as i64).unwrap(),+ "frame {frame} is missing"+ );+ let image = decoder+ .get_raw_frame()+ .convert_last_decoded_frame_into_svg_image(None)+ .unwrap();+ image.data.hash(&mut hasher);+ }+ }+ hasher.finish()+}++#[test]+fn many_parallel_frames_with_nested_images_are_deterministic() {+ let Ok(gpu) = SkiaVulkanCtx::new(SIZE, SIZE) else {+ eprintln!("no Vulkan device, skipped");+ return;+ };+ assert!(gpu.shared_gpu().is_some(), "wgpu shares the Vulkan device");+ let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("svg-in-3d-stress");+ std::fs::create_dir_all(&dir).unwrap();++ let first = render(&gpu, &dir.join("first.mp4"));+ let second = render(&gpu, &dir.join("second.mp4"));+ eprintln!("frame hash: {first:016x}");+ assert_eq!(first, second, "two renders of the same video differ");+ if let Ok(keep) = std::env::var("SVG_IN_3D_TEST_OUTPUT") {+ std::fs::copy(dir.join("first.mp4"), Path::new(&keep).join("stress.mp4")).unwrap();+ }+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/fframes/src/fframes_context.rs b/fframes/src/fframes_context.rsindex 4e97242c..a6788acc 100644--- a/fframes/src/fframes_context.rs+++ b/fframes/src/fframes_context.rs@@ -140,7 +140,7 @@ impl<'a, 'media: 'a> FFramesContext<'a, 'media> {/// Renders `svgr` into an image of `width` x `height` pixels with the backend that/// renders the video. Use the image as `<image href={image.href()} .../>`, or as the- /// texture of a 3D material (`fframes_3d::Texture::from_image`). The tree is scaled to+ /// texture of a 3D material (`three_d::Texture::from_image`). The tree is scaled to/// fill the image, over a transparent background. So `svgr` is a whole `<svg>` document/// with a `width` and a `height`.///