Skip to content

programmatic video rendering framework that is actually fast

feat(fframes): ctx.render_svgr renders svgr trees into images

Dmitriy Kovalenko26f7524475bc
diff --git a/fframes/src/fframes_context.rs b/fframes/src/fframes_context.rs
index 919a6dcd..4e97242c 100644
--- a/fframes/src/fframes_context.rs
+++ b/fframes/src/fframes_context.rs
@@ -138,6 +138,49 @@ 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
+ /// fill the image, over a transparent background. So `svgr` is a whole `<svg>` document
+ /// with a `width` and a `height`.
+ ///
+ /// The images nest: an svgr image can show a 3D render that shows another svgr image.
+ ///
+ /// - The CPU backend and the Skia CPU backend return pixels. The Skia GPU backends
+ /// return pixels or, on Vulkan with the `wgpu` feature, a texture that stays on the GPU.
+ /// - An svgr tree without `{}` renders once per render and size. Later calls return the
+ /// same image.
+ /// - `None` in the editor, and when the tree does not convert (the problem is logged).
+ /// - `<image href>` of the image needs the `compile-time-svgtree` feature.
+ ///
+ /// To show a [`Scene`](crate::Scene) at its own time, render it into an `<svg>`.
+ /// `start_frame` is the frame of the video where the scene starts:
+ ///
+ /// ```rust,ignore
+ /// let local = Frame::clone_with_scene_offset(&frame, start_frame);
+ /// let screen = ctx.render_svgr(
+ /// svgr!(<svg viewBox="0 0 1920 1080" width="1920" height="1080">
+ /// {self.intro.render_frame(local, ctx)}
+ /// </svg>),
+ /// 1024,
+ /// 576,
+ /// );
+ /// ```
+ pub fn render_svgr(
+ &self,
+ svgr: Svgr<'_>,
+ width: u32,
+ height: u32,
+ ) -> Option<ImageData<'static>> {
+ #[cfg(not(target_arch = "wasm32"))]
+ return crate::svgr_image::render_svgr(svgr, width, height);
+ #[cfg(target_arch = "wasm32")]
+ {
+ let _ = (svgr, width, height);
+ None
+ }
+ }
+
/// Finds the scene layout and duration information based on the layout of defined in `define_scenes` of the `Video`.
pub fn get_scene_info<T: crate::Scene>(&self, scene: &T) -> Option<&crate::SceneInfo> {
let scenes = self.scenes.as_ref()?;
diff --git a/fframes/src/lib.rs b/fframes/src/lib.rs
index 720f913f..a68c9f5a 100644
--- a/fframes/src/lib.rs
+++ b/fframes/src/lib.rs
@@ -122,6 +122,8 @@ mod named_range;
mod scenes;
mod shader;
mod svgr;
+#[cfg(not(target_arch = "wasm32"))]
+mod svgr_image;
mod text;
mod time_spec;
mod video;
@@ -164,6 +166,8 @@ pub use named_range::*;
pub use scenes::*;
pub use shader::*;
pub use svgr::*;
+#[cfg(not(target_arch = "wasm32"))]
+pub use svgr_image::*;
pub use svgr_macro::*;
pub use text::*;
pub use time_spec::*;
diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rs
index b95627cf..29b64a5e 100644
--- a/fframes/src/renderer/cli.rs
+++ b/fframes/src/renderer/cli.rs
@@ -561,6 +561,7 @@ impl<'r, 'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend, A: Arg
&mut fallback
};
Previewer::new(video, &options)
+ .map(|previewer| previewer.with_svgr_rasterizer(backend.svgr_rasterizer()))
.map_err(err)
.and_then(|mut previewer| match command {
Command::Frame(args) => frame(json, &mut previewer, frame_renderer, args),
@@ -592,7 +593,6 @@ impl<'r, 'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend, A: Arg
audio: !args.mute,
backend: args.backend,
};
- let options = previewer.options().clone();
// Fonts and caches of the previewer are not needed by the player.
drop(previewer);
play(video, &options, &request).map(|()| ExitCode::SUCCESS)
diff --git a/fframes/src/renderer/cpu.rs b/fframes/src/renderer/cpu.rs
index 8f4a3f67..724aeb34 100644
--- a/fframes/src/renderer/cpu.rs
+++ b/fframes/src/renderer/cpu.rs
@@ -4,8 +4,8 @@ use super::{
renderer_error::RenderEncodingError,
};
use crate::{
- AbortSignal, AudioTimelineSamples, Frame, RenderOptions, ResolvedRenderingTimeline, TextCache,
- Video, VideoDecodersWorker, usvgr,
+ AbortSignal, AudioTimelineSamples, Frame, RenderOptions, ResolvedRenderingTimeline, SvgrImages,
+ TextCache, Video, VideoDecodersWorker, usvgr,
};
use std::{
path::Path,
@@ -117,6 +117,32 @@ impl EncoderFrameRenderer for CpuEncoderFrameRenderer {
}
}
+/// Renders the trees of `FFramesContext::render_svgr` with tiny-skia, the rasterizer of the
+/// CPU backend. The default [`FFramesRenderBackend::svgr_rasterizer`].
+#[derive(Debug, Clone, Copy, Default)]
+pub struct CpuSvgrRasterizer;
+
+impl crate::SvgrRasterizer for CpuSvgrRasterizer {
+ fn rasterize(
+ &self,
+ tree: &usvgr::Tree,
+ width: u32,
+ height: u32,
+ ) -> Option<crate::media::ImageData<'static>> {
+ let mut pixmap = svgr::tiny_skia::Pixmap::new(width, height)?;
+ let context = svgr::Context::new_from_pixmap_unsafe(&pixmap);
+ svgr::render(
+ tree,
+ super::fit_transform(tree, width, height),
+ &mut pixmap.as_mut(),
+ &mut SvgrCache::new(0),
+ &PixmapPool::new(),
+ &context,
+ );
+ Some(crate::rendered_image(width, height, pixmap.take()))
+ }
+}
+
impl FFramesRenderBackend for CpuRenderingBackend {
fn frame_renderer(&self) -> Option<impl FrameRenderer + '_> {
Some(super::CpuFrameRenderer::new(self.cache_capacity))
@@ -185,6 +211,7 @@ impl FFramesRenderBackend for CpuRenderingBackend {
.map_err(|err| FFramesRendererError::RenderChunkError(0, err))?;
let writer = writer.with_encoder_input(encoder_input);
let failed = AtomicBool::new(false);
+ let svgr_images = SvgrImages::new(self.svgr_rasterizer());
let render_worker = |worker: usize| -> FFramesRendererResult<()> {
let worker_local_decoders = VideoDecodersWorker::new(1);
@@ -235,10 +262,11 @@ impl FFramesRenderBackend for CpuRenderingBackend {
std::thread::scope(|scope| {
let workers: Vec<_> = (0..scheduler.workers())
.map(|worker| {
- let render_worker = &render_worker;
- let failed = &failed;
+ let (render_worker, failed, svgr_images) =
+ (&render_worker, &failed, &svgr_images);
scope.spawn(move || {
- let result = render_worker(worker);
+ let result =
+ svgr_images.enter(usvg_options, font_db, || render_worker(worker));
if result.is_err() {
failed.store(true, Ordering::Relaxed);
}
@@ -286,11 +314,11 @@ impl FFramesRenderBackend for CpuRenderingBackend {
ctx: crate::FFramesContext<'a, 'media>,
) -> FFramesRendererResult<Vec<u8>> {
let mut converter_cache = usvgr::Cache::default();
- let rtree = super::render_frame_guarded(video, frame, &ctx)?.into_svg_tree(
- usvg_options,
- &mut converter_cache,
- font_db,
- )?;
+ let svgr_images = SvgrImages::new(self.svgr_rasterizer());
+ let svgr = svgr_images.enter(usvg_options, font_db, || {
+ super::render_frame_guarded(video, frame, &ctx)
+ })?;
+ let rtree = svgr.into_svg_tree(usvg_options, &mut converter_cache, font_db)?;
let frame = super::CpuFrameRenderer::new(0).render_tree(
&rtree,
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index fd1f5634..37fc45c9 100644
--- a/fframes/src/renderer/preview.rs
+++ b/fframes/src/renderer/preview.rs
@@ -294,6 +294,7 @@ pub struct Previewer<'a, 'media, TVideo: Video> {
timeline_index: TimelineIndex,
worker: Worker,
converter_text_cache_capacity: usize,
+ svgr_images: crate::SvgrImages<'a>,
}
impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
@@ -336,9 +337,21 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
timeline_index,
worker: Worker::new(10),
converter_text_cache_capacity: 10,
+ svgr_images: crate::SvgrImages::new(default_svgr_rasterizer()),
})
}
+ /// Renders the trees of [`FFramesContext::render_svgr`] with `rasterizer`, usually
+ /// what [`super::FFramesRenderBackend::svgr_rasterizer`] of the backend returns. The
+ /// default is the CPU rasterizer.
+ pub fn with_svgr_rasterizer(
+ mut self,
+ rasterizer: Option<Box<dyn crate::SvgrRasterizer + 'a>>,
+ ) -> Self {
+ self.svgr_images = crate::SvgrImages::new(rasterizer);
+ self
+ }
+
/// Scenes and duration for resolving time specs like `[email protected]`.
pub fn timeline(&self) -> &TimelineIndex {
&self.timeline_index
@@ -431,6 +444,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
&self.options,
&self.image_source,
&self.size,
+ &self.svgr_images,
fast_shapes,
)
.convert(&mut self.worker, frame)
@@ -458,6 +472,7 @@ impl<'a, 'media: 'a, TVideo: Video> Previewer<'a, 'media, TVideo> {
&self.options,
&self.image_source,
&self.size,
+ &self.svgr_images,
batch.fast_shapes,
);
let convert = |worker: &mut Worker, frame: usize| {
@@ -692,6 +707,7 @@ struct Conversion<'p, 'media, TVideo> {
ctx: FFramesContext<'p, 'media>,
options: usvgr::Options<'p>,
font_db: &'p usvgr::fontdb::Database,
+ svgr_images: &'p crate::SvgrImages<'p>,
}
impl<'p, 'media: 'p, TVideo: Video> Conversion<'p, 'media, TVideo> {
@@ -701,6 +717,7 @@ impl<'p, 'media: 'p, TVideo: Video> Conversion<'p, 'media, TVideo> {
options: &RenderOptions<'_, 'media>,
image_source: &'p HashMap<String, Arc<usvgr::PreloadedImageData>>,
size: &VideoSize,
+ svgr_images: &'p crate::SvgrImages<'p>,
fast_shapes: bool,
) -> Self {
Self {
@@ -722,6 +739,7 @@ impl<'p, 'media: 'p, TVideo: Video> Conversion<'p, 'media, TVideo> {
..Default::default()
},
font_db: runtime.font_source.as_db_ref(),
+ svgr_images,
}
}
@@ -733,21 +751,32 @@ impl<'p, 'media: 'p, TVideo: Video> Conversion<'p, 'media, TVideo> {
self.ctx.duration_in_frames
)));
}
- let svgr = super::render_frame_guarded(
- self.video,
- Frame::__internal_make_for_renderer(
- frame,
- frame,
- TVideo::FPS,
- worker.text_cache.clone(),
- worker.decoders.clone(),
- ),
- &self.ctx,
- )?;
+ let svgr = self.svgr_images.enter(&self.options, self.font_db, || {
+ super::render_frame_guarded(
+ self.video,
+ Frame::__internal_make_for_renderer(
+ frame,
+ frame,
+ TVideo::FPS,
+ worker.text_cache.clone(),
+ worker.decoders.clone(),
+ ),
+ &self.ctx,
+ )
+ })?;
Ok(svgr.into_svg_tree(&self.options, &mut worker.converter_cache, self.font_db)?)
}
}
+/// The CPU rasterizer when the crate has it.
+#[cfg_attr(feature = "cpu_renderer", allow(clippy::unnecessary_wraps))]
+pub(super) fn default_svgr_rasterizer() -> Option<Box<dyn crate::SvgrRasterizer + 'static>> {
+ #[cfg(feature = "cpu_renderer")]
+ return Some(Box::new(super::cpu::CpuSvgrRasterizer));
+ #[cfg(not(feature = "cpu_renderer"))]
+ None
+}
+
/// How [`Previewer::convert_each`] converts frames.
#[derive(Clone, Copy)]
struct Batch {
diff --git a/fframes/src/renderer/render_backend.rs b/fframes/src/renderer/render_backend.rs
index 8a7ee068..d30a1c49 100644
--- a/fframes/src/renderer/render_backend.rs
+++ b/fframes/src/renderer/render_backend.rs
@@ -60,6 +60,13 @@ pub trait FFramesRenderBackend {
.map_err(|err| FFramesRendererError::from_chunk(0, err))
}
+ /// Renders svgr trees inside `Video::render_frame` for
+ /// [`crate::FFramesContext::render_svgr`] during the renders and previews of this
+ /// backend. The default renders on the CPU with tiny-skia (feature `cpu_renderer`).
+ fn svgr_rasterizer(&self) -> Option<Box<dyn crate::SvgrRasterizer + '_>> {
+ super::default_svgr_rasterizer()
+ }
+
fn render_frame<'a, 'media: 'a, TVideo: Video + Sync + Sized + Send>(
self,
frame: crate::Frame,
diff --git a/fframes/src/renderer/tests/mod.rs b/fframes/src/renderer/tests/mod.rs
index 22147d33..c64a852f 100644
--- a/fframes/src/renderer/tests/mod.rs
+++ b/fframes/src/renderer/tests/mod.rs
@@ -1,4 +1,6 @@
mod preview_tests;
+#[cfg(feature = "cpu_renderer")]
+mod svgr_image_tests;
mod yuv420_conversion_tests;
#[cfg(all(feature = "h264", feature = "cpu_renderer"))]
mod yuv_matrix_render_tests;
diff --git a/fframes/src/renderer/tests/svgr_image_tests.rs b/fframes/src/renderer/tests/svgr_image_tests.rs
new file mode 100644
index 00000000..1cc86d6b
--- /dev/null
+++ b/fframes/src/renderer/tests/svgr_image_tests.rs
@@ -0,0 +1,100 @@
+use std::sync::Mutex;
+
+use crate::media::ImageData;
+use crate::{
+ AudioMap, Color, CpuFrameRenderer, FFramesContext, Frame, Previewer, RenderOptions, Svgr, Video,
+};
+
+/// Renders a red square into an svgr image, puts that image into a second svgr image, and
+/// the second one into the frame.
+#[derive(Default)]
+struct Nested {
+ images: Mutex<Vec<ImageData<'static>>>,
+}
+
+impl Video for Nested {
+ const FPS: usize = 10;
+ const WIDTH: usize = 40;
+ const HEIGHT: usize = 40;
+ const BACKGROUND_COLOR: Color = Color::rgb(0, 0, 255);
+
+ fn duration(&self) -> crate::Duration<'_> {
+ crate::Duration::Frames(2)
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+
+ fn render_frame<'a>(&'a self, _: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let Some(red) = ctx.render_svgr(
+ crate::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10">
+ <rect x="0" y="0" width="10" height="10" fill="#ff0000" />
+ </svg>
+ ),
+ 8,
+ 8,
+ ) else {
+ return crate::svgr!(<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"></svg>);
+ };
+ let Some(outer) = ctx.render_svgr(
+ crate::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
+ <rect x="0" y="0" width="20" height="20" fill="#00ff00" />
+ <image href={red.href()} x="0" y="0" width="10" height="10" />
+ </svg>
+ ),
+ 20,
+ 20,
+ ) else {
+ return crate::svgr!(<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"></svg>);
+ };
+ self.images.lock().unwrap().push(red);
+ crate::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">
+ <image href={outer.href()} x="0" y="0" width="40" height="40" />
+ </svg>
+ )
+ }
+}
+
+// The images of `<image href>` resolve in trees made at compile time.
+#[cfg(feature = "compile-time-svgtree")]
+#[test]
+fn svgr_images_nest_and_render_with_the_backend() {
+ let video = Nested::default();
+ let mut previewer = Previewer::new(&video, &RenderOptions::default()).unwrap();
+ let mut renderer = CpuFrameRenderer::default();
+ let frame = previewer.render(0, &mut renderer).unwrap();
+ let pixel = |x: usize, y: usize| &frame.pixels[(y * 40 + x) * 4..][..4];
+ // the red image fills the top left quarter of the green image, which fills the frame
+ assert_eq!(pixel(10, 10), [255, 0, 0, 255]);
+ assert_eq!(pixel(30, 30), [0, 255, 0, 255]);
+
+ previewer.render(1, &mut renderer).unwrap();
+ let images = video.images.lock().unwrap();
+ assert_eq!(images.len(), 2);
+ // a tree without `{}` renders once
+ assert!(std::sync::Arc::ptr_eq(&images[0].href(), &images[1].href()));
+ assert_eq!(&images[0].image.data[..4], &[255, 0, 0, 255]);
+}
+
+#[test]
+fn svgr_images_need_a_render() {
+ let svgr = crate::svgr!(<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"></svg>);
+ assert!(crate::svgr_image::render_svgr(svgr, 4, 4).is_none());
+}
+
+#[test]
+fn a_backend_without_a_rasterizer_gives_no_images() {
+ let video = Nested::default();
+ let mut previewer = Previewer::new(&video, &RenderOptions::default())
+ .unwrap()
+ .with_svgr_rasterizer(None);
+ let frame = previewer
+ .render(0, &mut CpuFrameRenderer::default())
+ .unwrap();
+ // `render_frame` falls back to an empty frame: the background
+ assert_eq!(&frame.pixels[..4], &[0, 0, 255, 255]);
+}
diff --git a/fframes/src/svgr_image.rs b/fframes/src/svgr_image.rs
new file mode 100644
index 00000000..e467c4a8
--- /dev/null
+++ b/fframes/src/svgr_image.rs
@@ -0,0 +1,180 @@
+//! Svgr trees rendered into images while a frame renders, see
+//! [`FFramesContext::render_svgr`](crate::FFramesContext::render_svgr).
+//!
+//! A rendering backend gives an [`SvgrRasterizer`]
+//! ([`FFramesRenderBackend::svgr_rasterizer`](crate::FFramesRenderBackend::svgr_rasterizer)).
+//! The render puts it into an [`SvgrImages`] and enters it on each thread that calls
+//! `Video::render_frame` ([`SvgrImages::enter`]). `render_svgr` uses the images that the
+//! thread entered.
+
+use std::borrow::Cow;
+use std::cell::Cell;
+use std::num::NonZeroUsize;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, PoisonError};
+
+use crate::media::{ImageData, ImageMetadata};
+use crate::{Svgr, usvgr};
+
+/// The number of images of static trees that one render keeps.
+const STATIC_IMAGES: NonZeroUsize = NonZeroUsize::new(64).unwrap();
+
+/// Renders converted svgr trees into images for
+/// [`FFramesContext::render_svgr`](crate::FFramesContext::render_svgr). A backend shares
+/// one rasterizer between all threads of a render.
+pub trait SvgrRasterizer: Sync {
+ /// Renders `tree` scaled to `width` x `height` pixels over a transparent background.
+ /// Returns premultiplied RGBA pixels ([`rendered_image`]) or a texture on the GPU of
+ /// the backend (`fframes::wgpu_layer`). `None` when the backend cannot render it.
+ fn rasterize(&self, tree: &usvgr::Tree, width: u32, height: u32) -> Option<ImageData<'static>>;
+}
+
+/// The svgr images of one render: the rasterizer of the backend and the images of static
+/// trees, which render once.
+pub struct SvgrImages<'a> {
+ rasterizer: Option<Box<dyn SvgrRasterizer + 'a>>,
+ static_images: Mutex<lru::LruCache<(u64, u32, u32), ImageData<'static>>>,
+}
+
+/// What [`SvgrImages::enter`] makes available to the thread.
+struct Scope<'s> {
+ images: &'s SvgrImages<'s>,
+ options: &'s usvgr::Options<'s>,
+ font_db: &'s usvgr::fontdb::Database,
+}
+
+thread_local! {
+ /// The [`Scope`] of the innermost [`SvgrImages::enter`] on this thread, or null.
+ static ACTIVE: Cell<*const ()> = const { Cell::new(std::ptr::null()) };
+}
+
+impl<'a> SvgrImages<'a> {
+ /// `rasterizer` is what [`FFramesRenderBackend::svgr_rasterizer`](crate::FFramesRenderBackend::svgr_rasterizer)
+ /// returns. Without one `render_svgr` returns `None`.
+ pub fn new(rasterizer: Option<Box<dyn SvgrRasterizer + 'a>>) -> Self {
+ Self {
+ rasterizer,
+ static_images: Mutex::new(lru::LruCache::new(STATIC_IMAGES)),
+ }
+ }
+
+ /// Runs `f` with these images as the images of `render_svgr` on this thread. Call
+ /// `Video::render_frame` in `f`. `options` and `font_db` convert the trees. Give the
+ /// ones that convert the frames.
+ pub fn enter<R>(
+ &self,
+ options: &usvgr::Options,
+ font_db: &usvgr::fontdb::Database,
+ f: impl FnOnce() -> R,
+ ) -> R {
+ /// Puts the previous scope back, also when `f` panics.
+ struct Restore(*const ());
+ impl Drop for Restore {
+ fn drop(&mut self) {
+ ACTIVE.set(self.0);
+ }
+ }
+
+ let scope = Scope {
+ images: self,
+ options,
+ font_db,
+ };
+ let _restore = Restore(ACTIVE.replace(std::ptr::from_ref(&scope).cast()));
+ f()
+ }
+}
+
+impl Scope<'_> {
+ fn render(&self, svgr: Svgr<'_>, width: u32, height: u32) -> Option<ImageData<'static>> {
+ let images = self.images;
+ let rasterizer = images.rasterizer.as_deref()?;
+ let key = static_hash(&svgr).map(|hash| (hash, width, height));
+ let cached = |key| {
+ images
+ .static_images
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .get(&key)
+ .cloned()
+ };
+ if let Some(image) = key.and_then(cached) {
+ return Some(image);
+ }
+
+ let tree = svgr
+ .into_svg_tree(self.options, &mut usvgr::Cache::default(), self.font_db)
+ .inspect_err(|e| log::warn!("fframes: render_svgr can not convert the tree: {e}"))
+ .ok()?;
+ let image = rasterizer.rasterize(&tree, width, height)?;
+ if let Some(key) = key {
+ images
+ .static_images
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .put(key, image.clone());
+ }
+ Some(image)
+ }
+}
+
+impl std::fmt::Debug for SvgrImages<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SvgrImages").finish_non_exhaustive()
+ }
+}
+
+/// Renders `svgr` with the images that this thread entered. `None` when it entered none.
+pub(crate) fn render_svgr(svgr: Svgr<'_>, width: u32, height: u32) -> Option<ImageData<'static>> {
+ if width == 0 || height == 0 {
+ return None;
+ }
+ let scope = ACTIVE.get();
+ if scope.is_null() {
+ return None;
+ }
+ // SAFETY: `SvgrImages::enter` sets the pointer to a scope on its stack and puts the
+ // previous value back before that scope ends. The reference does not leave this call.
+ let scope = unsafe { &*scope.cast::<Scope<'_>>() };
+ scope.render(svgr, width, height)
+}
+
+/// The hash of `svgr` when its whole tree is static (has no `{}`). The same hash means the
+/// same tree.
+fn static_hash(svgr: &Svgr<'_>) -> Option<u64> {
+ #[cfg(feature = "compile-time-svgtree")]
+ if let [Some(root)] = svgr.svg_tree.nodes.as_slice() {
+ return root.static_hash;
+ }
+ let _ = svgr;
+ None
+}
+
+/// An image of premultiplied RGBA pixels, `width * 4` bytes per row. Each image gets a new
+/// id, so a cache keyed by the id never returns an old image.
+pub fn rendered_image(width: u32, height: u32, rgba: Vec<u8>) -> ImageData<'static> {
+ static NEXT_ID: AtomicU64 = AtomicU64::new(0);
+ let id = format!("fframes-svgr:{}", NEXT_ID.fetch_add(1, Ordering::Relaxed));
+ ImageData::new_from_raw_data(
+ Arc::new(usvgr::PreloadedImageData {
+ data: Cow::Owned(rgba),
+ width,
+ height,
+ id: id.clone(),
+ }),
+ id,
+ ImageMetadata { width, height },
+ )
+}
+
+/// The pixels of `image`. An image on the GPU (`fframes::wgpu_layer`) is read back, which
+/// waits for the GPU. `None` when that fails. Other images are their own pixels.
+pub fn image_pixels(
+ image: &Arc<usvgr::PreloadedImageData>,
+) -> Option<Arc<usvgr::PreloadedImageData>> {
+ #[cfg(feature = "wgpu")]
+ if let Some(layer) = crate::resolve_wgpu_layer(image) {
+ return layer.pixels();
+ }
+ Some(Arc::clone(image))
+}