programmatic video rendering framework that is actually fast
feat(skia): render_svgr with Skia, on the shared GPU with wgpu
Dmitriy Kovalenko61cda3a7b800
diff --git a/fframes-native-player/src/lib.rs b/fframes-native-player/src/lib.rsindex 74043852..9de36745 100644--- a/fframes-native-player/src/lib.rs+++ b/fframes-native-player/src/lib.rs@@ -122,6 +122,9 @@ pub fn play<'a, 'media: 'a, TVideo: Video + Sync>(},};+ // The window owns the Skia context, so the trees of `render_svgr` render on the CPU.+ let svgr_images = fframes::SvgrImages::new(Some(Box::new(fframes::cpu::CpuSvgrRasterizer)));+let scheduler = Scheduler::new(timeline.duration_in_frames,options.prefetch_frames,@@ -156,16 +159,19 @@ pub fn play<'a, 'media: 'a, TVideo: Video + Sync>(let result = std::thread::scope(|scope| {for _ in 0..options.render_threads() {scope.spawn(|| {- scheduler.run_worker(- video,- &ctx,- &usvg_options,- font_source.as_db_ref(),- // Decoders hand out their current frame buffer, which is recycled by the- // next decode, so they must not be shared between threads.- VideoDecodersWorker::new(options.prefetch_frames.max(1) * 2),- ¬ify_frame_ready,- );+ let db = font_source.as_db_ref();+ svgr_images.enter(&usvg_options, db, || {+ scheduler.run_worker(+ video,+ &ctx,+ &usvg_options,+ db,+ // Decoders hand out their current frame buffer, which is recycled by+ // the next decode, so they must not be shared between threads.+ VideoDecodersWorker::new(options.prefetch_frames.max(1) * 2),+ ¬ify_frame_ready,+ );+ });});}diff --git a/fframes-skia-renderer/src/backends/mod.rs b/fframes-skia-renderer/src/backends/mod.rsindex fb4a845c..f7ebb4ff 100644--- a/fframes-skia-renderer/src/backends/mod.rs+++ b/fframes-skia-renderer/src/backends/mod.rs@@ -76,6 +76,16 @@ pub trait SkiaBackend: Sync + Send {})}+ /// A GPU context without a surface, and the lock of its queue. Code that draws into+ /// surfaces of its own size uses it (`FFramesContext::render_svgr`). The default makes+ /// a whole context with [`Self::create_skia_context`] and drops the surface.+ fn create_offscreen_context(+ &self,+ ) -> FFramesRendererResult<(Option<DirectContext>, Option<QueueLock>)> {+ let context = self.create_skia_context()?;+ Ok((context.gpu, context.queue_lock))+ }+/// Offers hardware frames to the video encoder of a render: textures Skia draws into and/// the encoder reads, so the pixels never leave the GPU. Called once per render before/// the encoders are opened.diff --git a/fframes-skia-renderer/src/backends/vulkan.rs b/fframes-skia-renderer/src/backends/vulkan.rsindex 1312b0ed..5c5851bf 100644--- a/fframes-skia-renderer/src/backends/vulkan.rs+++ b/fframes-skia-renderer/src/backends/vulkan.rs@@ -506,6 +506,13 @@ impl SkiaBackend for SkiaVulkanCtx {Ok((context.surface, context.gpu))}+ fn create_offscreen_context(+ &self,+ ) -> FFramesRendererResult<(Option<DirectContext>, Option<super::QueueLock>)> {+ let context = self.create_context()?;+ Ok((Some(context.gpu), Some(context.queue_lock)))+ }+fn create_skia_context(&self) -> FFramesRendererResult<super::SkiaContext> {let context = self.create_context()?;let lock = context.queue_lock.clone();diff --git a/fframes-skia-renderer/src/lib.rs b/fframes-skia-renderer/src/lib.rsindex 70c930a9..fe4f39a2 100644--- a/fframes-skia-renderer/src/lib.rs+++ b/fframes-skia-renderer/src/lib.rs@@ -18,6 +18,9 @@ pub use instant_rendering::*;mod frame_renderer;pub use frame_renderer::*;+mod svgr_rasterizer;+pub use svgr_rasterizer::SkiaSvgrRasterizer;+mod frame_export;pub use frame_export::{FrameExportPath, HardwareFrameTarget, SkiaEncoderFrameRenderer, SkiaFrameExport,diff --git a/fframes-skia-renderer/src/render/mod.rs b/fframes-skia-renderer/src/render/mod.rsindex 2cabeb88..5c5575e4 100644--- a/fframes-skia-renderer/src/render/mod.rs+++ b/fframes-skia-renderer/src/render/mod.rs@@ -15,7 +15,7 @@ mod occlusion;mod resources;mod shader;#[cfg(feature = "wgpu")]-mod wgpu_layer;+pub(crate) mod wgpu_layer;pub use shader::compile_shader;diff --git a/fframes-skia-renderer/src/render/wgpu_layer.rs b/fframes-skia-renderer/src/render/wgpu_layer.rsindex ac71d9d5..cea07d3a 100644--- a/fframes-skia-renderer/src/render/wgpu_layer.rs+++ b/fframes-skia-renderer/src/render/wgpu_layer.rs@@ -20,7 +20,25 @@ pub(super) fn image(return None;}let mut context = canvas.recording_context()?;- let texture = layer.texture();+ let backend_texture = backend_texture(+ layer.texture(),+ gpu::vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,+ )?;+ gpu::images::borrow_texture_from(+ &mut context,+ &backend_texture,+ SurfaceOrigin::TopLeft,+ ColorType::RGBA8888,+ AlphaType::Premul,+ None,+ )+}++/// `texture` as a Skia texture in `layout`. `None` when the texture is not a Vulkan texture.+pub(crate) fn backend_texture(+ texture: &wgpu::Texture,+ layout: gpu::vk::ImageLayout,+) -> Option<gpu::BackendTexture> {let raw = {let hal = unsafe { texture.as_hal::<wgpu::hal::api::Vulkan>() }?;unsafe { hal.raw_handle() }@@ -30,7 +48,7 @@ pub(super) fn image(raw.as_raw() as _,gpu::vk::Alloc::default(),gpu::vk::ImageTiling::OPTIMAL,- gpu::vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,+ layout,gpu::vk::Format::R8G8B8A8_UNORM,1,None,@@ -41,21 +59,13 @@ pub(super) fn image(};info.image_usage_flags = usage_flags(texture.usage()).as_raw();info.sample_count = 1;- let backend_texture = unsafe {+ Some(unsafe {backend_textures::make_vk((texture.width() as i32, texture.height() as i32),&info,- "fframes wgpu layer",+ "fframes wgpu texture",)- };- gpu::images::borrow_texture_from(- &mut context,- &backend_texture,- SurfaceOrigin::TopLeft,- ColorType::RGBA8888,- AlphaType::Premul,- None,- )+ })}fn usage_flags(usage: wgpu::TextureUsages) -> vk::ImageUsageFlags {diff --git a/fframes-skia-renderer/src/skia_backend.rs b/fframes-skia-renderer/src/skia_backend.rsindex 4f909ef8..0f8539b7 100644--- a/fframes-skia-renderer/src/skia_backend.rs+++ b/fframes-skia-renderer/src/skia_backend.rs@@ -34,6 +34,15 @@ impl<'a, TSkiaBackend: SkiaBackend> SkiaFFramesRenderer<'a, TSkiaBackend> {}}+ /// The rasterizer of `FFramesContext::render_svgr` for renders with this backend.+ pub(crate) fn svgr_rasterizer_impl(&self) -> crate::SkiaSvgrRasterizer<'a, TSkiaBackend> {+ crate::SkiaSvgrRasterizer::new(+ self.backend,+ self.pipeline_config.cache,+ self.pipeline_config.gpu_contexts().max(2),+ )+ }+/// How rendered frames are handed to the video encoder. By default the fastest way the/// backend and the encoder support is used, see [`SkiaFrameExport`].pub fn frame_export(mut self, frame_export: SkiaFrameExport) -> Self {@@ -56,6 +65,11 @@ impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBa)}+ /// Skia renders the trees of `FFramesContext::render_svgr`, see [`crate::SkiaSvgrRasterizer`].+ fn svgr_rasterizer(&self) -> Option<Box<dyn fframes::SvgrRasterizer + '_>> {+ Some(Box::new(self.svgr_rasterizer_impl()))+ }+fn negotiate_encoder_input(&self,encoder: &VideoEncoderInfo<'_>,@@ -85,11 +99,11 @@ impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBa) -> FFramesRendererResult<Vec<u8>> {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 svgr_images = fframes::SvgrImages::new(self.svgr_rasterizer());+ let svgr = svgr_images.enter(usvg_options, font_db, || {+ fframes::render_frame_guarded(video, frame, &ctx)+ })?;+ let rtree = svgr.into_svg_tree(usvg_options, &mut converter_cache, font_db)?;let frame = crate::SkiaFrameRenderer::new(self.backend).with_cache_config(self.pipeline_config.cache)diff --git a/fframes-skia-renderer/src/skia_pipeline.rs b/fframes-skia-renderer/src/skia_pipeline.rsindex 1eae3832..dff99f91 100644--- a/fframes-skia-renderer/src/skia_pipeline.rs+++ b/fframes-skia-renderer/src/skia_pipeline.rs@@ -207,6 +207,12 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:let failed = AtomicBool::new(false);let buffers = BufferPool::default();+ // The generators share the images of `FFramesContext::render_svgr`.+ let svgr_images = fframes::SvgrImages::new(Some(Box::new(crate::SkiaSvgrRasterizer::new(+ skia,+ pipeline_config.cache,+ gpu_contexts.max(2),+ ))));let (tree_sender, tree_receiver) = mpsc::sync_channel::<(FrameClaim, usvgr::Tree)>(queue_size);let (frame_sender, frame_receiver) = mpsc::sync_channel::<RenderedFrame>(queue_size);// Every stage owns its end of the queues, so a stage that stops (all of its threads@@ -226,25 +232,27 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:let mut handles = Vec::new();for worker in 0..scheduler.workers() {let tree_sender = tree_sender.clone();- let (scheduler, failed) = (&scheduler, &failed);+ let (scheduler, failed, svgr_images) = (&scheduler, &failed, &svgr_images);#[cfg(feature = "debug")]let metrics = metrics.generator_metrics.clone();handles.push(scope.spawn(move || {- mark_failed(generate_frames(- worker,- video,- scheduler,- frame_offset,- usvg_options,- font_db,- tree_sender,- queue_size,- pipeline_config.cache.text_capacity,- ctx,- failed,- #[cfg(feature = "debug")]- metrics,- ))+ mark_failed(svgr_images.enter(usvg_options, font_db, || {+ generate_frames(+ worker,+ video,+ scheduler,+ frame_offset,+ usvg_options,+ font_db,+ tree_sender,+ queue_size,+ pipeline_config.cache.text_capacity,+ ctx,+ failed,+ #[cfg(feature = "debug")]+ metrics,+ )+ }))}));}drop(tree_sender);diff --git a/fframes-skia-renderer/src/svgr_rasterizer.rs b/fframes-skia-renderer/src/svgr_rasterizer.rsnew file mode 100644index 00000000..9cd4fefb--- /dev/null+++ b/fframes-skia-renderer/src/svgr_rasterizer.rs@@ -0,0 +1,316 @@+//! The trees of `FFramesContext::render_svgr` rendered with Skia, see [`SkiaSvgrRasterizer`].++use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};++use fframes::media::ImageData;+use fframes::usvgr;+use skia_safe::gpu::{self, DirectContext};+use skia_safe::{AlphaType, Canvas, ColorType, ImageInfo, surfaces};++use crate::render::RenderCache;+use crate::{QueueLock, SkiaBackend, SkiaCacheConfig, lock_queue};++/// Renders the svgr trees of `FFramesContext::render_svgr` with Skia, on the GPU or the+/// CPU of a backend. The threads of a render share it.+///+/// On a backend that shares its GPU with wgpu (the Vulkan backend with the `wgpu` feature)+/// the image is a texture on that GPU (`fframes::wgpu_layer`). Skia draws the tree into+/// it, and 3D materials and frames sample it in place. On every other backend the image+/// holds the pixels.+///+/// Each call takes a Skia context from a pool of at most `contexts` contexts. A call waits+/// while all of them are in use. A context is never held while user code runs, so a+/// waiting call always gets one.+pub struct SkiaSvgrRasterizer<'a, B: SkiaBackend> {+ backend: &'a B,+ cache_config: SkiaCacheConfig,+ pool: Mutex<Pool>,+ /// Signals that a context is free again.+ available: Condvar,+ #[cfg(feature = "wgpu")]+ targets: Mutex<Vec<Target>>,+}++#[derive(Default)]+struct Pool {+ free: Vec<Context>,+ /// The contexts that exist, free or in use.+ created: usize,+ max: usize,+}++/// A Skia context of the pool with its caches.+struct Context {+ gpu: Option<DirectContext>,+ queue_lock: Option<QueueLock>,+ cache: RenderCache,+}++// SAFETY: the pool gives a context to one thread at a time. A Skia context and the Skia+// objects of its cache are not bound to the thread that made them.+unsafe impl Send for Context {}++impl Drop for Context {+ fn drop(&mut self) {+ // what lives on the context goes first, and destroying a context waits for its queue+ self.cache = RenderCache::new();+ let _queue = lock_queue(self.queue_lock.as_ref());+ self.gpu = None;+ }+}++/// A texture that Skia draws an svgr tree into. It is free again when its image is+/// dropped. At that time the frames that sample it are submitted.+#[cfg(feature = "wgpu")]+struct Target {+ texture: fframes::wgpu::Texture,+ image: std::sync::Weak<usvgr::PreloadedImageData>,+}++fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {+ mutex.lock().unwrap_or_else(PoisonError::into_inner)+}++impl<'a, B: SkiaBackend> SkiaSvgrRasterizer<'a, B> {+ /// `contexts` is the maximum number of Skia contexts that render trees at the same+ /// time (at least one).+ pub fn new(backend: &'a B, cache_config: SkiaCacheConfig, contexts: usize) -> Self {+ Self {+ backend,+ cache_config,+ pool: Mutex::new(Pool {+ max: contexts.max(1),+ ..Pool::default()+ }),+ available: Condvar::new(),+ #[cfg(feature = "wgpu")]+ targets: Mutex::new(Vec::new()),+ }+ }++ /// A free context, or a new one. Waits while all contexts are in use.+ fn take(&self) -> Option<Context> {+ let mut pool = lock(&self.pool);+ loop {+ if let Some(context) = pool.free.pop() {+ return Some(context);+ }+ if pool.created < pool.max {+ pool.created += 1;+ break;+ }+ pool = self+ .available+ .wait(pool)+ .unwrap_or_else(PoisonError::into_inner);+ }+ drop(pool);+ match self.backend.create_offscreen_context() {+ Ok((gpu, queue_lock)) => Some(Context {+ gpu,+ queue_lock,+ cache: RenderCache::with_config(self.cache_config).for_backend(self.backend),+ }),+ Err(e) => {+ eprintln!("fframes: render_svgr can not create a Skia context: {e}");+ lock(&self.pool).created -= 1;+ self.available.notify_one();+ None+ }+ }+ }++ fn give_back(&self, context: Context) {+ lock(&self.pool).free.push(context);+ self.available.notify_one();+ }++ /// Renders into a new surface and reads the pixels back.+ fn pixels(+ &self,+ context: &mut Context,+ tree: &usvgr::Tree,+ width: u32,+ height: u32,+ ) -> Option<ImageData<'static>> {+ let info = ImageInfo::new(+ (width as i32, height as i32),+ ColorType::RGBA8888,+ AlphaType::Premul,+ None,+ );+ let mut surface = match context.gpu.as_mut() {+ Some(gpu) => gpu::surfaces::render_target(+ gpu,+ gpu::Budgeted::Yes,+ &info,+ None,+ gpu::SurfaceOrigin::TopLeft,+ None,+ false,+ None,+ ),+ None => surfaces::raster(&info, None, None),+ }?;+ draw(surface.canvas(), tree, width, height, &mut context.cache);+ let mut pixels = vec![0; width as usize * height as usize * 4];+ // the readback submits the drawing to the queue and waits for it+ let read = {+ let _queue = lock_queue(context.queue_lock.as_ref());+ surface.read_pixels(&info, &mut pixels, width as usize * 4, (0, 0))+ };+ read.then(|| fframes::rendered_image(width, height, pixels))+ }+}++/// Clears the canvas and draws `tree` scaled to `width` x `height`.+fn draw(canvas: &Canvas, tree: &usvgr::Tree, width: u32, height: u32, cache: &mut RenderCache) {+ canvas.clear(skia_safe::Color::TRANSPARENT);+ canvas.save();+ crate::apply_fit(canvas, tree, width as i32, height as i32);+ crate::render::render_tree(tree, canvas, cache);+ canvas.restore();+}++impl<B: SkiaBackend> fframes::SvgrRasterizer for SkiaSvgrRasterizer<'_, B> {+ fn rasterize(&self, tree: &usvgr::Tree, width: u32, height: u32) -> Option<ImageData<'static>> {+ let mut context = self.take()?;+ #[cfg(feature = "wgpu")]+ let image = match self.shared_gpu() {+ Some(shared) if context.gpu.is_some() => {+ self.texture(&shared, &mut context, tree, width, height)+ }+ _ => self.pixels(&mut context, tree, width, height),+ };+ #[cfg(not(feature = "wgpu"))]+ let image = self.pixels(&mut context, tree, width, height);+ self.give_back(context);+ image+ }+}++#[cfg(feature = "wgpu")]+impl<B: SkiaBackend> SkiaSvgrRasterizer<'_, B> {+ /// The GPU that the contexts of the backend draw on, when it is shared with wgpu.+ fn shared_gpu(&self) -> Option<fframes::SharedGpu> {+ let id = self.backend.shared_gpu_id()?;+ fframes::shared_gpu().filter(|gpu| gpu.id() == id)+ }++ /// A free texture of this size with a new image of it, or a new texture.+ fn target(+ &self,+ shared: &fframes::SharedGpu,+ width: u32,+ height: u32,+ ) -> (fframes::wgpu::Texture, ImageData<'static>) {+ use fframes::wgpu;++ let mut targets = lock(&self.targets);+ let free = |t: &Target| t.image.strong_count() == 0;+ let found = targets+ .iter()+ .position(|t| free(t) && t.texture.width() == width && t.texture.height() == height);+ let slot = found.unwrap_or_else(|| {+ // free textures of other sizes are not used again soon+ targets.retain(|t| !free(t));+ targets.push(Target {+ texture: shared.device().create_texture(&wgpu::TextureDescriptor {+ label: Some("fframes svgr image"),+ size: wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: fframes::WGPU_LAYER_FORMAT,+ usage: fframes::WGPU_LAYER_USAGE | wgpu::TextureUsages::RENDER_ATTACHMENT,+ view_formats: &[],+ }),+ image: std::sync::Weak::new(),+ });+ targets.len() - 1+ });+ let texture = targets[slot].texture.clone();+ let image = fframes::wgpu_layer(shared, &texture);+ targets[slot].image = std::sync::Arc::downgrade(&image.href());+ (texture, image)+ }++ /// Draws `tree` into a texture on the shared GPU. The pixels stay on the GPU.+ ///+ /// wgpu tracks the state of the texture, so wgpu makes every transition: a clear pass+ /// leaves the texture as a color target, Skia draws and leaves it in that layout, and+ /// [`fframes::finish_wgpu_layer`] makes it sampled. Each step is a submission to the+ /// one queue of the shared GPU, so the queue orders them.+ fn texture(+ &self,+ shared: &fframes::SharedGpu,+ context: &mut Context,+ tree: &usvgr::Tree,+ width: u32,+ height: u32,+ ) -> Option<ImageData<'static>> {+ use fframes::wgpu;+ use skia_safe::gpu::vk::ImageLayout;++ let (texture, image) = self.target(shared, width, height);+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ let mut encoder = shared+ .device()+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());+ encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("fframes svgr image clear"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ store: wgpu::StoreOp::Store,+ },+ })],+ ..Default::default()+ });+ shared.submit([encoder.finish()]);++ let gpu_context = context.gpu.as_mut()?;+ let backend_texture = crate::render::wgpu_layer::backend_texture(+ &texture,+ ImageLayout::COLOR_ATTACHMENT_OPTIMAL,+ )?;+ let mut surface = gpu::surfaces::wrap_backend_texture(+ gpu_context,+ &backend_texture,+ gpu::SurfaceOrigin::TopLeft,+ None,+ ColorType::RGBA8888,+ None,+ None,+ )?;+ draw(surface.canvas(), tree, width, height, &mut context.cache);+ let state = gpu::vk::mutable_texture_states::new_vulkan(+ ImageLayout::COLOR_ATTACHMENT_OPTIMAL,+ ash::vk::QUEUE_FAMILY_IGNORED,+ );+ {+ let _queue = lock_queue(context.queue_lock.as_ref());+ gpu_context.flush_surface_with_texture_state(+ &mut surface,+ &gpu::FlushInfo::default(),+ Some(&state),+ );+ gpu_context.submit(gpu::SyncCpu::No);+ }+ drop(surface);++ let mut encoder = shared+ .device()+ .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());+ fframes::finish_wgpu_layer(&mut encoder, &texture);+ shared.submit([encoder.finish()]);+ Some(image)+ }+}