Skip to content

programmatic video rendering framework that is actually fast

perf(player): draw the frames into the window swapchain instead of reading them back (#224)

Dmitriy Kovalenko3f188aaa8783
diff --git a/Cargo.lock b/Cargo.lock
index d4c2b0a9..2b58666e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1211,10 +1211,12 @@ dependencies = [
name = "fframes_native_player"
version = "1.2.0"
dependencies = [
+ "core-graphics-types 0.2.0",
"cpal",
"fframes",
"fframes_skia_renderer",
"hello-world-example",
+ "raw-window-metal",
"softbuffer",
"winit",
]
@@ -2414,7 +2416,7 @@ dependencies = [
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
- "objc2-metal",
+ "objc2-metal 0.2.2",
]
[[package]]
@@ -2496,6 +2498,17 @@ dependencies = [
"objc2-foundation 0.2.2",
]
+[[package]]
+name = "objc2-metal"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.4",
+ "objc2-foundation 0.3.2",
+]
+
[[package]]
name = "objc2-quartz-core"
version = "0.2.2"
@@ -2506,7 +2519,7 @@ dependencies = [
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
- "objc2-metal",
+ "objc2-metal 0.2.2",
]
[[package]]
@@ -2519,6 +2532,7 @@ dependencies = [
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
]
[[package]]
@@ -3025,6 +3039,18 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "raw-window-metal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
+dependencies = [
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
+]
+
[[package]]
name = "rayon"
version = "1.10.0"
diff --git a/fframes-native-player/Cargo.toml b/fframes-native-player/Cargo.toml
index 8dbbb6f6..c7c27169 100644
--- a/fframes-native-player/Cargo.toml
+++ b/fframes-native-player/Cargo.toml
@@ -18,6 +18,11 @@ winit = "0.30"
softbuffer = "0.4"
cpal = { version = "0.18", optional = true }
+# The CAMetalLayer of the window, presented to by Metal and by Vulkan (MoltenVK).
+[target.'cfg(target_os = "macos")'.dependencies]
+raw-window-metal = { version = "1.1", optional = true }
+core-graphics-types = { version = "0.2", optional = true, default-features = false }
+
[dev-dependencies]
fframes = { workspace = true, features = ["compile-time-svgtree"] }
hello-world-example = { path = "../examples/hello-world" }
@@ -27,8 +32,8 @@ default = ["vulkan", "audio"]
audio = ["cpal"]
# At least one GPU backend is required to build Skia with Ganesh. The player falls back
# to the Skia CPU raster backend at runtime if the GPU backend can not be initialized.
-vulkan = ["fframes_skia_renderer/vulkan"]
-metal = ["fframes_skia_renderer/metal"]
+vulkan = ["fframes_skia_renderer/vulkan", "dep:raw-window-metal"]
+metal = ["fframes_skia_renderer/metal", "dep:raw-window-metal", "dep:core-graphics-types"]
# See fframes-media/Cargo.toml: docs.rs cannot build FFmpeg from source.
[package.metadata.docs.rs]
diff --git a/fframes-native-player/src/app.rs b/fframes-native-player/src/app.rs
index 95e8bb8f..94ddc630 100644
--- a/fframes-native-player/src/app.rs
+++ b/fframes-native-player/src/app.rs
@@ -64,6 +64,7 @@ pub(crate) struct AppConfig<'a> {
pub title: &'a str,
pub window_size: LogicalSize<u32>,
pub backend: PlayerBackend,
+ pub vsync: bool,
pub fps: usize,
pub duration_in_frames: usize,
pub background: fframes::Color,
@@ -97,7 +98,11 @@ pub(crate) struct App<'s> {
seeking_with_mouse: bool,
stats_since: Instant,
+ /// New frames drawn into the window since `stats_since`. Frames taken from the
+ /// scheduler can be replaced before a redraw, so they are not counted.
frames_shown: usize,
+ /// The position of the frame last drawn into the window.
+ presented: Option<u64>,
shown_fps: f64,
title_updated_at: Instant,
}
@@ -135,6 +140,7 @@ impl<'s> App<'s> {
seeking_with_mouse: false,
stats_since: now,
frames_shown: 0,
+ presented: None,
shown_fps: 0.,
title_updated_at: now,
config,
@@ -198,7 +204,6 @@ impl<'s> App<'s> {
if let Some(frame) = self.scheduler.take(position) {
self.current = Some(frame);
- self.frames_shown += 1;
self.needs_redraw = true;
}
@@ -426,6 +431,12 @@ impl<'s> App<'s> {
if let Some(presenter) = self.presenter.as_mut() {
presenter.present(self.current.as_ref().map(|(_, tree)| tree), &controls)?;
+
+ let position = self.current.as_ref().map(|(position, _)| *position);
+ if position.is_some() && position != self.presented {
+ self.frames_shown += 1;
+ }
+ self.presented = position;
}
Ok(())
@@ -456,6 +467,7 @@ impl ApplicationHandler<FrameReady> for App<'_> {
match Presenter::new(
window.clone(),
self.config.backend,
+ self.config.vsync,
self.config.background,
duration_label,
) {
diff --git a/fframes-native-player/src/error.rs b/fframes-native-player/src/error.rs
index 5ba7ed77..5061bb99 100644
--- a/fframes-native-player/src/error.rs
+++ b/fframes-native-player/src/error.rs
@@ -45,6 +45,12 @@ impl From<winit::error::OsError> for PlayerError {
}
}
+impl From<winit::raw_window_handle::HandleError> for PlayerError {
+ fn from(err: winit::raw_window_handle::HandleError) -> Self {
+ PlayerError::Window(err.to_string())
+ }
+}
+
impl From<softbuffer::SoftBufferError> for PlayerError {
fn from(err: softbuffer::SoftBufferError) -> Self {
PlayerError::Surface(err.to_string())
diff --git a/fframes-native-player/src/lib.rs b/fframes-native-player/src/lib.rs
index 7439ddc1..74043852 100644
--- a/fframes-native-player/src/lib.rs
+++ b/fframes-native-player/src/lib.rs
@@ -1,5 +1,6 @@
//! Real-time native preview of an fframes [`Video`] in a desktop window, rendered by the
-//! Skia backend.
+//! Skia backend. The GPU backends draw into the swapchain of the window (a `CAMetalLayer`
+//! drawable or a Vulkan swapchain image) and no frame is read back.
//!
//! ```rust,ignore
//! fn main() {
@@ -139,6 +140,7 @@ pub fn play<'a, 'media: 'a, TVideo: Video + Sync>(
title: options.title,
window_size: initial_window_size::<TVideo>(options),
backend: options.backend,
+ vsync: options.vsync,
fps: TVideo::FPS,
duration_in_frames: timeline.duration_in_frames,
background: TVideo::BACKGROUND_COLOR,
diff --git a/fframes-native-player/src/options.rs b/fframes-native-player/src/options.rs
index a4d62278..3f3d4b81 100644
--- a/fframes-native-player/src/options.rs
+++ b/fframes-native-player/src/options.rs
@@ -29,6 +29,10 @@ pub struct PlayerOptions<'a, 'media> {
/// fit 1280x720.
pub window_size: Option<(u32, u32)>,
pub backend: PlayerBackend,
+ /// Wait for the display refresh to show a frame. With `false` a frame is shown as soon
+ /// as it is drawn, up to the frame rate of the video: the picture can tear and the GPU
+ /// stays busy. Only the GPU backends wait for the display.
+ pub vsync: bool,
/// Start playing right away instead of paused on `start_frame`.
pub autoplay: bool,
/// Restart from the first frame after the last one (toggle with `r`).
@@ -54,6 +58,7 @@ impl Default for PlayerOptions<'_, '_> {
title: "fframes",
window_size: None,
backend: PlayerBackend::Auto,
+ vsync: true,
autoplay: true,
looping: true,
start_frame: 0,
diff --git a/fframes-native-player/src/presenter.rs b/fframes-native-player/src/presenter.rs
deleted file mode 100644
index 57b4ad95..00000000
--- a/fframes-native-player/src/presenter.rs
+++ /dev/null
@@ -1,237 +0,0 @@
-use std::num::NonZeroU32;
-use std::rc::Rc;
-
-use fframes::usvgr;
-use fframes_skia_renderer::render::RenderCache;
-use fframes_skia_renderer::skia_safe::{
- self, AlphaType, Color, ColorType, ImageInfo, Rect, Surface, gpu,
-};
-use fframes_skia_renderer::{SkiaBackend, SkiaCpuCtx};
-use winit::window::Window;
-
-use crate::controls::{Controls, ControlsLayout, ControlsState};
-use crate::error::{PlayerError, PlayerResult};
-use crate::options::PlayerBackend;
-
-// Fields drop in declaration order: skia resources first, then the context, then the
-// backend that owns the device.
-pub(crate) struct Presenter {
- surface: Option<Surface>,
- render_cache: RenderCache,
- gpu_context: Option<gpu::DirectContext>,
- _backend: Box<dyn SkiaBackend>,
- window_surface: softbuffer::Surface<Rc<Window>, Rc<Window>>,
- window: Rc<Window>,
- background: Color,
- controls: Controls,
- layout: ControlsLayout,
- /// The longest time label, sizes the time slots of the control bar.
- duration_label: String,
-}
-
-impl Presenter {
- pub(crate) fn new(
- window: Rc<Window>,
- backend: PlayerBackend,
- background: fframes::Color,
- duration_label: String,
- ) -> PlayerResult<Self> {
- let context = softbuffer::Context::new(window.clone())?;
- let window_surface = softbuffer::Surface::new(&context, window.clone())?;
- let (backend, gpu_context) = create_backend(backend)?;
- let controls = Controls::new();
- let size = window.inner_size();
- let layout = ControlsLayout::new(
- &controls,
- &duration_label,
- size.width as f32,
- size.height as f32,
- window.scale_factor() as f32,
- );
-
- let mut presenter = Self {
- surface: None,
- render_cache: RenderCache::new(),
- gpu_context,
- _backend: backend,
- window_surface,
- window,
- background: Color::from_argb(background.a, background.r, background.g, background.b),
- controls,
- layout,
- duration_label,
- };
-
- presenter.resize()?;
- Ok(presenter)
- }
-
- pub(crate) fn is_gpu(&self) -> bool {
- self.gpu_context.is_some()
- }
-
- /// Where the control bar is for the current window size, in physical pixels.
- pub(crate) fn controls_layout(&self) -> &ControlsLayout {
- &self.layout
- }
-
- /// Recreates the surfaces for the current window size.
- pub(crate) fn resize(&mut self) -> PlayerResult<()> {
- let size = self.window.inner_size();
- let (Some(width), Some(height)) =
- (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
- else {
- // Minimized, keep the old surface around until the window is visible again.
- return Ok(());
- };
-
- self.window_surface.resize(width, height)?;
- self.layout = ControlsLayout::new(
- &self.controls,
- &self.duration_label,
- size.width as f32,
- size.height as f32,
- self.window.scale_factor() as f32,
- );
-
- let info = surface_image_info(size.width, size.height);
- let surface = match self.gpu_context.as_mut() {
- Some(context) => gpu::surfaces::render_target(
- context,
- gpu::Budgeted::Yes,
- &info,
- None,
- gpu::SurfaceOrigin::TopLeft,
- None,
- false,
- None,
- ),
- None => skia_safe::surfaces::raster(&info, None, None),
- };
-
- self.surface = Some(surface.ok_or_else(|| {
- PlayerError::Skia(format!(
- "failed to create a {}x{} surface",
- size.width, size.height
- ))
- })?);
-
- Ok(())
- }
-
- /// Renders `tree` letterboxed into the window with the controls on top and presents it.
- pub(crate) fn present(
- &mut self,
- tree: Option<&usvgr::Tree>,
- controls: &ControlsState,
- ) -> PlayerResult<()> {
- let Some(surface) = self.surface.as_mut() else {
- return Ok(());
- };
-
- let (width, height) = (surface.width(), surface.height());
- let canvas = surface.canvas();
- canvas.clear(Color::BLACK);
-
- if let Some(tree) = tree {
- let video = tree.size();
- let scale = (width as f32 / video.width()).min(height as f32 / video.height());
- let offset_x = (width as f32 - video.width() * scale) / 2.;
- let offset_y = (height as f32 - video.height() * scale) / 2.;
-
- canvas.save();
- canvas.translate((offset_x, offset_y));
- canvas.scale((scale, scale));
- canvas.clip_rect(
- Rect::from_wh(video.width(), video.height()),
- None,
- Some(true),
- );
- canvas.draw_color(self.background, None);
- fframes_skia_renderer::render::render_tree(tree, canvas, &mut self.render_cache);
- canvas.restore();
- }
-
- self.controls.draw(canvas, &self.layout, controls);
-
- // Video frame images point into the tree's pixel buffers: wait for the GPU so the
- // tree can be dropped as soon as the next frame replaces it.
- if let Some(context) = self.gpu_context.as_mut() {
- context.flush_submit_and_sync_cpu();
- }
-
- let mut buffer = self.window_surface.buffer_mut()?;
- // The window surface might still have the previous size if the resize event
- // has not been processed yet: skip this frame, a redraw follows the resize.
- if buffer.len() != (width * height) as usize {
- return Ok(());
- }
-
- let info = surface_image_info(width as u32, height as u32);
- let pixels = fframes::bytemuck::cast_slice_mut::<u32, u8>(&mut buffer);
- if !surface.read_pixels(&info, pixels, width as usize * 4, (0, 0)) {
- return Err(PlayerError::Skia(
- "failed to read back the frame".to_string(),
- ));
- }
-
- buffer.present()?;
- Ok(())
- }
-}
-
-fn surface_image_info(width: u32, height: u32) -> ImageInfo {
- // BGRA in memory is `0xAARRGGBB` as a little-endian `u32`, which is what softbuffer
- // expects (it ignores the alpha byte).
- ImageInfo::new(
- (width as i32, height as i32),
- ColorType::BGRA8888,
- AlphaType::Premul,
- None,
- )
-}
-
-type Backend = (Box<dyn SkiaBackend>, Option<gpu::DirectContext>);
-
-fn create_backend(backend: PlayerBackend) -> PlayerResult<Backend> {
- match backend {
- PlayerBackend::Auto => {
- #[cfg(feature = "metal")]
- match create_backend(PlayerBackend::Metal) {
- Ok(backend) => return Ok(backend),
- Err(err) => eprintln!("fframes player: metal is not available ({err})"),
- }
-
- #[cfg(feature = "vulkan")]
- match create_backend(PlayerBackend::Vulkan) {
- Ok(backend) => return Ok(backend),
- Err(err) => eprintln!("fframes player: vulkan is not available ({err})"),
- }
-
- eprintln!("fframes player: falling back to the Skia CPU renderer");
- create_backend(PlayerBackend::Cpu)
- }
- #[cfg(feature = "metal")]
- PlayerBackend::Metal => {
- gpu_backend(fframes_skia_renderer::metal::SkiaMetalCtx::new(16, 16))
- }
- #[cfg(feature = "vulkan")]
- PlayerBackend::Vulkan => {
- gpu_backend(fframes_skia_renderer::vulkan::SkiaVulkanCtx::new(16, 16))
- }
- PlayerBackend::Cpu => Ok((Box::new(SkiaCpuCtx::new(16, 16)), None)),
- }
-}
-
-/// The backend contexts create a fixed-size surface: only its GPU context is kept, the
-/// player creates its own window-sized surfaces on it.
-#[cfg(any(feature = "metal", feature = "vulkan"))]
-fn gpu_backend<T: SkiaBackend + 'static>(
- backend: fframes::FFramesRendererResult<T>,
-) -> PlayerResult<Backend> {
- let backend = backend?;
- let (_surface, context) = backend.create_skia_surface()?;
- let context = context.ok_or_else(|| PlayerError::Skia("no GPU context".to_string()))?;
-
- Ok((Box::new(backend), Some(context)))
-}
diff --git a/fframes-native-player/src/presenter/cpu.rs b/fframes-native-player/src/presenter/cpu.rs
new file mode 100644
index 00000000..827bed65
--- /dev/null
+++ b/fframes-native-player/src/presenter/cpu.rs
@@ -0,0 +1,74 @@
+use std::num::NonZeroU32;
+use std::rc::Rc;
+
+use fframes_skia_renderer::skia_safe::{AlphaType, Canvas, ColorType, ImageInfo, surfaces};
+use winit::window::Window;
+
+use super::WindowTarget;
+use crate::error::{PlayerError, PlayerResult};
+
+/// Skia draws on the CPU into the pixel buffer of the window.
+pub(super) struct CpuTarget {
+ surface: softbuffer::Surface<Rc<Window>, Rc<Window>>,
+ size: (u32, u32),
+}
+
+impl CpuTarget {
+ pub(super) fn new(window: Rc<Window>) -> PlayerResult<Self> {
+ let context = softbuffer::Context::new(window.clone())?;
+ let surface = softbuffer::Surface::new(&context, window)?;
+
+ Ok(Self {
+ surface,
+ size: (0, 0),
+ })
+ }
+}
+
+impl WindowTarget for CpuTarget {
+ fn is_gpu(&self) -> bool {
+ false
+ }
+
+ fn resize(&mut self, width: u32, height: u32) -> PlayerResult<()> {
+ let (Some(nonzero_width), Some(nonzero_height)) =
+ (NonZeroU32::new(width), NonZeroU32::new(height))
+ else {
+ return Ok(());
+ };
+
+ self.surface.resize(nonzero_width, nonzero_height)?;
+ self.size = (width, height);
+ Ok(())
+ }
+
+ fn present(&mut self, draw: &mut dyn FnMut(&Canvas)) -> PlayerResult<()> {
+ let (width, height) = self.size;
+ if width == 0 || height == 0 {
+ return Ok(());
+ }
+
+ let mut buffer = self.surface.buffer_mut()?;
+ // BGRA in memory is `0xAARRGGBB` as a little-endian `u32`, which is what softbuffer
+ // expects (it ignores the alpha byte).
+ let info = ImageInfo::new(
+ (width as i32, height as i32),
+ ColorType::BGRA8888,
+ AlphaType::Premul,
+ None,
+ );
+ let pixels = fframes::bytemuck::cast_slice_mut::<u32, u8>(&mut buffer);
+ let mut surface = surfaces::wrap_pixels(&info, pixels, width as usize * 4, None)
+ .ok_or_else(|| {
+ PlayerError::Skia(format!(
+ "can not draw into the {width}x{height} window buffer"
+ ))
+ })?;
+
+ draw(surface.canvas());
+ drop(surface);
+
+ buffer.present()?;
+ Ok(())
+ }
+}
diff --git a/fframes-native-player/src/presenter/metal.rs b/fframes-native-player/src/presenter/metal.rs
new file mode 100644
index 00000000..66e4dcaf
--- /dev/null
+++ b/fframes-native-player/src/presenter/metal.rs
@@ -0,0 +1,130 @@
+use std::ffi::c_void;
+
+use core_graphics_types::geometry::CGSize;
+use fframes_skia_renderer::metal::SkiaMetalCtx;
+use fframes_skia_renderer::metal::metal_rs::foreign_types::{ForeignType, ForeignTypeRef};
+use fframes_skia_renderer::metal::metal_rs::objc::Message;
+use fframes_skia_renderer::metal::metal_rs::objc::rc::autoreleasepool;
+use fframes_skia_renderer::metal::metal_rs::objc::runtime::Sel;
+use fframes_skia_renderer::metal::metal_rs::{MTLPixelFormat, MetalLayer, MetalLayerRef};
+use fframes_skia_renderer::skia_safe::gpu::{
+ self, DirectContext, SurfaceOrigin, SyncCpu, backend_render_targets, mtl,
+};
+use fframes_skia_renderer::skia_safe::{Canvas, ColorType};
+use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
+use winit::window::Window;
+
+use super::WindowTarget;
+use crate::error::{PlayerError, PlayerResult};
+
+/// Skia draws into the drawables of a `CAMetalLayer` of the window.
+pub(super) struct MetalTarget {
+ gpu: DirectContext,
+ layer: MetalLayer,
+ backend: SkiaMetalCtx,
+}
+
+impl MetalTarget {
+ pub(super) fn new(window: &Window, vsync: bool) -> PlayerResult<Self> {
+ // The size is for the backend's own surfaces, which the player does not use.
+ let backend = SkiaMetalCtx::new(16, 16)?;
+ let gpu = backend.create_context()?;
+
+ let RawWindowHandle::AppKit(handle) = window.window_handle()?.as_raw() else {
+ return Err(PlayerError::Window(
+ "metal can only present to an AppKit window".to_owned(),
+ ));
+ };
+ // SAFETY: the view of a live window, `Presenter::new` runs on the main thread.
+ let layer = unsafe { raw_window_metal::Layer::from_ns_view(handle.ns_view) };
+ // SAFETY: `into_raw` hands over a retained `CAMetalLayer`.
+ let layer = unsafe { MetalLayer::from_ptr(layer.into_raw().as_ptr().cast()) };
+
+ layer.set_device(backend.device());
+ layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
+ // Skia copies the drawable for blend modes that read the destination.
+ layer.set_framebuffer_only(false);
+ layer.set_presents_with_transaction(false);
+ layer.set_display_sync_enabled(vsync);
+ set_srgb_colorspace(&layer);
+
+ Ok(Self {
+ gpu,
+ layer,
+ backend,
+ })
+ }
+}
+
+impl WindowTarget for MetalTarget {
+ fn is_gpu(&self) -> bool {
+ true
+ }
+
+ fn resize(&mut self, width: u32, height: u32) -> PlayerResult<()> {
+ self.layer
+ .set_drawable_size(CGSize::new(f64::from(width), f64::from(height)));
+ Ok(())
+ }
+
+ fn present(&mut self, draw: &mut dyn FnMut(&Canvas)) -> PlayerResult<()> {
+ // The drawable is autoreleased.
+ autoreleasepool(|| {
+ // Waits while every drawable of the layer is on screen or queued for it.
+ let Some(drawable) = self.layer.next_drawable() else {
+ return Ok(());
+ };
+
+ let texture = drawable.texture();
+ // SAFETY: the texture lives as long as the drawable, which outlives the surface.
+ let texture_info = unsafe { mtl::TextureInfo::new(texture.as_ptr() as mtl::Handle) };
+ let render_target = backend_render_targets::make_mtl(
+ (texture.width() as i32, texture.height() as i32),
+ &texture_info,
+ );
+ let mut surface = gpu::surfaces::wrap_backend_render_target(
+ &mut self.gpu,
+ &render_target,
+ SurfaceOrigin::TopLeft,
+ ColorType::BGRA8888,
+ None,
+ None,
+ )
+ .ok_or_else(|| PlayerError::Skia("can not draw into the drawable".to_owned()))?;
+
+ draw(surface.canvas());
+ self.gpu
+ .flush_and_submit_surface(&mut surface, SyncCpu::Yes);
+ drop(surface);
+
+ // Skia submitted to the same queue, the drawable is presented after its work.
+ let commands = self.backend.command_queue().new_command_buffer();
+ commands.present_drawable(drawable);
+ commands.commit();
+
+ Ok(())
+ })
+ }
+}
+
+/// Skia draws sRGB. Tagging the layer makes macOS convert it to the color space of the
+/// display, an untagged layer is shown as is (oversaturated on wide gamut displays).
+fn set_srgb_colorspace(layer: &MetalLayerRef) {
+ #[link(name = "CoreGraphics", kind = "framework")]
+ unsafe extern "C" {
+ static kCGColorSpaceSRGB: *const c_void;
+ fn CGColorSpaceCreateWithName(name: *const c_void) -> *mut c_void;
+ fn CGColorSpaceRelease(space: *mut c_void);
+ }
+
+ // SAFETY: `-[CAMetalLayer setColorspace:]` takes a `CGColorSpaceRef` and retains it.
+ unsafe {
+ let space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ if space.is_null() {
+ return;
+ }
+
+ let _: Result<(), _> = layer.send_message(Sel::register("setColorspace:"), (space,));
+ CGColorSpaceRelease(space);
+ }
+}
diff --git a/fframes-native-player/src/presenter/mod.rs b/fframes-native-player/src/presenter/mod.rs
new file mode 100644
index 00000000..95ce3727
--- /dev/null
+++ b/fframes-native-player/src/presenter/mod.rs
@@ -0,0 +1,182 @@
+//! Draws the frames into the window. The GPU backends render into the images the window
+//! shows (a `CAMetalLayer` drawable or a Vulkan swapchain image) and the CPU backend into
+//! the pixel buffer of the window, so no frame is read back from the GPU.
+
+mod cpu;
+#[cfg(feature = "metal")]
+mod metal;
+#[cfg(feature = "vulkan")]
+mod vulkan;
+
+use std::rc::Rc;
+
+use fframes::usvgr;
+use fframes_skia_renderer::render::RenderCache;
+use fframes_skia_renderer::skia_safe::{Canvas, Color, Rect};
+use winit::window::Window;
+
+use crate::controls::{Controls, ControlsLayout, ControlsState};
+use crate::error::PlayerResult;
+use crate::options::PlayerBackend;
+
+/// The images of the window that Skia draws into.
+trait WindowTarget {
+ fn is_gpu(&self) -> bool;
+
+ /// The window has a new size in physical pixels, neither is zero.
+ fn resize(&mut self, width: u32, height: u32) -> PlayerResult<()>;
+
+ /// Draws the next image of the window with `draw` and shows it. Returns once the GPU is
+ /// done: video frame images point into the pixel buffers of the tree, which is dropped
+ /// as soon as the next frame replaces it.
+ fn present(&mut self, draw: &mut dyn FnMut(&Canvas)) -> PlayerResult<()>;
+}
+
+// Fields drop in declaration order: the cached Skia objects before the target that owns
+// the context and the device.
+pub(crate) struct Presenter {
+ render_cache: RenderCache,
+ target: Box<dyn WindowTarget>,
+ window: Rc<Window>,
+ background: Color,
+ controls: Controls,
+ layout: ControlsLayout,
+ /// The longest time label, sizes the time slots of the control bar.
+ duration_label: String,
+}
+
+impl Presenter {
+ pub(crate) fn new(
+ window: Rc<Window>,
+ backend: PlayerBackend,
+ vsync: bool,
+ background: fframes::Color,
+ duration_label: String,
+ ) -> PlayerResult<Self> {
+ let target = create_target(&window, backend, vsync)?;
+ let controls = Controls::new();
+ let size = window.inner_size();
+ let layout = ControlsLayout::new(
+ &controls,
+ &duration_label,
+ size.width as f32,
+ size.height as f32,
+ window.scale_factor() as f32,
+ );
+
+ let mut presenter = Self {
+ render_cache: RenderCache::new(),
+ target,
+ window,
+ background: Color::from_argb(background.a, background.r, background.g, background.b),
+ controls,
+ layout,
+ duration_label,
+ };
+
+ presenter.resize()?;
+ Ok(presenter)
+ }
+
+ pub(crate) fn is_gpu(&self) -> bool {
+ self.target.is_gpu()
+ }
+
+ /// Where the control bar is for the current window size, in physical pixels.
+ pub(crate) fn controls_layout(&self) -> &ControlsLayout {
+ &self.layout
+ }
+
+ /// Resizes the window images to the current window size.
+ pub(crate) fn resize(&mut self) -> PlayerResult<()> {
+ let size = self.window.inner_size();
+ if size.width == 0 || size.height == 0 {
+ // Minimized, keep the old images around until the window is visible again.
+ return Ok(());
+ }
+
+ self.target.resize(size.width, size.height)?;
+ self.layout = ControlsLayout::new(
+ &self.controls,
+ &self.duration_label,
+ size.width as f32,
+ size.height as f32,
+ self.window.scale_factor() as f32,
+ );
+
+ Ok(())
+ }
+
+ /// Renders `tree` letterboxed into the window with the controls on top and presents it.
+ pub(crate) fn present(
+ &mut self,
+ tree: Option<&usvgr::Tree>,
+ controls: &ControlsState,
+ ) -> PlayerResult<()> {
+ let Self {
+ render_cache,
+ target,
+ background,
+ controls: bar,
+ layout,
+ ..
+ } = self;
+
+ target.present(&mut |canvas| {
+ let size = canvas.base_layer_size();
+ let (width, height) = (size.width as f32, size.height as f32);
+ canvas.clear(Color::BLACK);
+
+ if let Some(tree) = tree {
+ let video = tree.size();
+ let scale = (width / video.width()).min(height / video.height());
+ let offset_x = (width - video.width() * scale) / 2.;
+ let offset_y = (height - video.height() * scale) / 2.;
+
+ canvas.save();
+ canvas.translate((offset_x, offset_y));
+ canvas.scale((scale, scale));
+ canvas.clip_rect(
+ Rect::from_wh(video.width(), video.height()),
+ None,
+ Some(true),
+ );
+ canvas.draw_color(*background, None);
+ fframes_skia_renderer::render::render_tree(tree, canvas, render_cache);
+ canvas.restore();
+ }
+
+ bar.draw(canvas, layout, controls);
+ })
+ }
+}
+
+fn create_target(
+ window: &Rc<Window>,
+ backend: PlayerBackend,
+ vsync: bool,
+) -> PlayerResult<Box<dyn WindowTarget>> {
+ match backend {
+ PlayerBackend::Auto => {
+ #[cfg(feature = "metal")]
+ match create_target(window, PlayerBackend::Metal, vsync) {
+ Ok(target) => return Ok(target),
+ Err(err) => eprintln!("fframes player: metal is not available ({err})"),
+ }
+
+ #[cfg(feature = "vulkan")]
+ match create_target(window, PlayerBackend::Vulkan, vsync) {
+ Ok(target) => return Ok(target),
+ Err(err) => eprintln!("fframes player: vulkan is not available ({err})"),
+ }
+
+ eprintln!("fframes player: falling back to the Skia CPU renderer");
+ create_target(window, PlayerBackend::Cpu, vsync)
+ }
+ #[cfg(feature = "metal")]
+ PlayerBackend::Metal => Ok(Box::new(metal::MetalTarget::new(window, vsync)?)),
+ #[cfg(feature = "vulkan")]
+ PlayerBackend::Vulkan => Ok(Box::new(vulkan::VulkanTarget::new(window.clone(), vsync)?)),
+ PlayerBackend::Cpu => Ok(Box::new(cpu::CpuTarget::new(window.clone())?)),
+ }
+}
diff --git a/fframes-native-player/src/presenter/vulkan.rs b/fframes-native-player/src/presenter/vulkan.rs
new file mode 100644
index 00000000..8785d3ea
--- /dev/null
+++ b/fframes-native-player/src/presenter/vulkan.rs
@@ -0,0 +1,550 @@
+use std::ffi::CStr;
+use std::mem::ManuallyDrop;
+use std::rc::Rc;
+
+use fframes_skia_renderer::skia_safe::gpu::ganesh::vk::backend_render_targets;
+use fframes_skia_renderer::skia_safe::gpu::{
+ self, DirectContext, FlushInfo, SurfaceOrigin, SyncCpu,
+};
+use fframes_skia_renderer::skia_safe::{Canvas, ColorType, Surface};
+use fframes_skia_renderer::vulkan::ash::{
+ self,
+ vk::{self, Handle},
+};
+use fframes_skia_renderer::vulkan::{SkiaVulkanCtx, VulkanContext};
+use fframes_skia_renderer::{QueueLock, lock_queue};
+use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle};
+use winit::window::Window;
+
+use super::WindowTarget;
+use crate::error::{PlayerError, PlayerResult};
+
+/// What has to outlive the Vulkan surface besides the window: on macOS the `CAMetalLayer`
+/// that `MoltenVK` presents to.
+#[cfg(target_os = "macos")]
+type SurfaceLayer = raw_window_metal::Layer;
+#[cfg(not(target_os = "macos"))]
+type SurfaceLayer = ();
+
+/// Skia draws into the images of a swapchain of the window.
+pub(super) struct VulkanTarget {
+ swapchain: Option<Swapchain>,
+ // Dropped in `drop`, after the swapchain images it draws into.
+ gpu: ManuallyDrop<DirectContext>,
+ queue: vk::Queue,
+ queue_lock: QueueLock,
+ surface: vk::SurfaceKHR,
+ surface_fn: ash::khr::surface::Instance,
+ swapchain_fn: ash::khr::swapchain::Device,
+ /// Signaled once an acquired image can be drawn into.
+ acquired: vk::Fence,
+ present_mode: vk::PresentModeKHR,
+ /// The window size in physical pixels.
+ size: (u32, u32),
+ _layer: SurfaceLayer,
+ backend: SkiaVulkanCtx,
+ _window: Rc<Window>,
+}
+
+struct Swapchain {
+ handle: vk::SwapchainKHR,
+ /// A Skia surface on every image of the swapchain.
+ images: Vec<Surface>,
+ /// The swapchain no longer matches the window and is recreated before the next frame.
+ outdated: bool,
+}
+
+impl Swapchain {
+ fn destroy(self, swapchain_fn: &ash::khr::swapchain::Device) {
+ // Skia's views of the images go first.
+ drop(self.images);
+ unsafe { swapchain_fn.destroy_swapchain(self.handle, None) };
+ }
+}
+
+/// Formats Skia draws into as they are shown: 8 bit, sRGB encoded.
+const FORMATS: [(vk::Format, gpu::vk::Format, ColorType); 2] = [
+ (
+ vk::Format::B8G8R8A8_UNORM,
+ gpu::vk::Format::B8G8R8A8_UNORM,
+ ColorType::BGRA8888,
+ ),
+ (
+ vk::Format::R8G8B8A8_UNORM,
+ gpu::vk::Format::R8G8B8A8_UNORM,
+ ColorType::RGBA8888,
+ ),
+];
+
+impl VulkanTarget {
+ pub(super) fn new(window: Rc<Window>, vsync: bool) -> PlayerResult<Self> {
+ let extension = surface_extension(window.display_handle()?.as_raw())?;
+ // The size is for the backend's own surfaces, which the player does not use.
+ let backend = SkiaVulkanCtx::new_with_instance_extensions(16, 16, &[extension])?;
+ let VulkanContext {
+ gpu,
+ queue_lock,
+ queue,
+ ..
+ } = backend.create_context()?;
+ let surface_fn = ash::khr::surface::Instance::new(backend.entry(), backend.instance());
+ let swapchain_fn = ash::khr::swapchain::Device::new(backend.instance(), backend.device());
+ let (surface, layer) = create_surface(&backend, &window)?;
+ let size = window.inner_size();
+
+ // From here on `drop` releases what was created.
+ let mut target = Self {
+ swapchain: None,
+ gpu: ManuallyDrop::new(gpu),
+ queue,
+ queue_lock,
+ surface,
+ surface_fn,
+ swapchain_fn,
+ acquired: vk::Fence::null(),
+ // vsync, the only mode every driver has
+ present_mode: vk::PresentModeKHR::FIFO,
+ size: (size.width, size.height),
+ _layer: layer,
+ backend,
+ _window: window,
+ };
+
+ let can_present = unsafe {
+ target.surface_fn.get_physical_device_surface_support(
+ target.backend.physical_device(),
+ target.backend.queue_family_index(),
+ target.surface,
+ )
+ }
+ .map_err(vulkan_error("can not query the window surface"))?;
+ if !can_present {
+ return Err(PlayerError::Surface(
+ "the graphics queue of the GPU can not present to the window".to_owned(),
+ ));
+ }
+
+ if !vsync {
+ let modes = unsafe {
+ target.surface_fn.get_physical_device_surface_present_modes(
+ target.backend.physical_device(),
+ target.surface,
+ )
+ }
+ .map_err(vulkan_error("can not query the window surface"))?;
+ // `MAILBOX` replaces the queued image instead of showing it right away.
+ if let Some(mode) = [vk::PresentModeKHR::IMMEDIATE, vk::PresentModeKHR::MAILBOX]
+ .into_iter()
+ .find(|mode| modes.contains(mode))
+ {
+ target.present_mode = mode;
+ }
+ }
+
+ target.acquired = unsafe {
+ target
+ .backend
+ .device()
+ .create_fence(&vk::FenceCreateInfo::default(), None)
+ }
+ .map_err(vulkan_error("can not create a fence"))?;
+
+ // Fails here rather than on the first frame, so the CPU backend can take over.
+ target.recreate_swapchain()?;
+ Ok(target)
+ }
+
+ /// Replaces the swapchain with one for the current window size. Leaves none while the
+ /// window has no area.
+ fn recreate_swapchain(&mut self) -> PlayerResult<()> {
+ let device = self.backend.device();
+ let physical_device = self.backend.physical_device();
+ let queue_family_index = self.backend.queue_family_index();
+
+ let old = self.swapchain.take();
+ if old.is_some() {
+ // The images of the old swapchain may still be presented. Every context that
+ // submits to the device shares the queue and the lock of the player's context.
+ let _queue = lock_queue(Some(&self.queue_lock));
+ unsafe { device.device_wait_idle() }
+ .map_err(vulkan_error("can not wait for the GPU"))?;
+ }
+
+ let (capabilities, formats) = unsafe {
+ (
+ self.surface_fn
+ .get_physical_device_surface_capabilities(physical_device, self.surface),
+ self.surface_fn
+ .get_physical_device_surface_formats(physical_device, self.surface),
+ )
+ };
+ let capabilities =
+ capabilities.map_err(vulkan_error("can not query the window surface"))?;
+ let formats = formats.map_err(vulkan_error("can not query the window surface"))?;
+
+ // `u32::MAX`: the surface takes the size of the swapchain (Wayland).
+ let extent = if capabilities.current_extent.width == u32::MAX {
+ vk::Extent2D {
+ width: self.size.0.clamp(
+ capabilities.min_image_extent.width,
+ capabilities.max_image_extent.width,
+ ),
+ height: self.size.1.clamp(
+ capabilities.min_image_extent.height,
+ capabilities.max_image_extent.height,
+ ),
+ }
+ } else {
+ capabilities.current_extent
+ };
+ if extent.width == 0 || extent.height == 0 {
+ if let Some(old) = old {
+ old.destroy(&self.swapchain_fn);
+ }
+ return Ok(());
+ }
+
+ let Some((format, skia_format, color_type)) = FORMATS.into_iter().find(|(format, ..)| {
+ formats.iter().any(|supported| {
+ supported.format == *format
+ && supported.color_space == vk::ColorSpaceKHR::SRGB_NONLINEAR
+ })
+ }) else {
+ return Err(PlayerError::Surface(format!(
+ "the window supports none of the formats Skia draws into: {formats:?}"
+ )));
+ };
+
+ // Skia copies to and from render targets it wraps.
+ let required_usage = vk::ImageUsageFlags::COLOR_ATTACHMENT
+ | vk::ImageUsageFlags::TRANSFER_SRC
+ | vk::ImageUsageFlags::TRANSFER_DST;
+ if !capabilities.supported_usage_flags.contains(required_usage) {
+ return Err(PlayerError::Surface(format!(
+ "the window images can not be used as {required_usage:?}"
+ )));
+ }
+ // Lets Skia read the destination for blend modes without copying it.
+ let usage = required_usage
+ | (capabilities.supported_usage_flags & vk::ImageUsageFlags::INPUT_ATTACHMENT);
+
+ let mut image_count = capabilities.min_image_count + 1;
+ if capabilities.max_image_count > 0 {
+ image_count = image_count.min(capabilities.max_image_count);
+ }
+ let composite_alpha = [
+ vk::CompositeAlphaFlagsKHR::OPAQUE,
+ vk::CompositeAlphaFlagsKHR::INHERIT,
+ vk::CompositeAlphaFlagsKHR::PRE_MULTIPLIED,
+ vk::CompositeAlphaFlagsKHR::POST_MULTIPLIED,
+ ]
+ .into_iter()
+ .find(|mode| capabilities.supported_composite_alpha.contains(*mode))
+ .unwrap_or(vk::CompositeAlphaFlagsKHR::OPAQUE);
+
+ let create_info = vk::SwapchainCreateInfoKHR::default()
+ .surface(self.surface)
+ .min_image_count(image_count)
+ .image_format(format)
+ .image_color_space(vk::ColorSpaceKHR::SRGB_NONLINEAR)
+ .image_extent(extent)
+ .image_array_layers(1)
+ .image_usage(usage)
+ .image_sharing_mode(vk::SharingMode::EXCLUSIVE)
+ .pre_transform(capabilities.current_transform)
+ .composite_alpha(composite_alpha)
+ .present_mode(self.present_mode)
+ .clipped(true)
+ .old_swapchain(
+ old.as_ref()
+ .map_or(vk::SwapchainKHR::null(), |old| old.handle),
+ );
+ let handle = unsafe { self.swapchain_fn.create_swapchain(&create_info, None) };
+
+ // Retired by the new swapchain, or of no use if it could not be created.
+ if let Some(old) = old {
+ old.destroy(&self.swapchain_fn);
+ }
+ let handle = handle.map_err(vulkan_error("can not create the swapchain"))?;
+
+ let images = unsafe { self.swapchain_fn.get_swapchain_images(handle) }
+ .map_err(vulkan_error("can not get the swapchain images"));
+ let images = images.and_then(|images| {
+ images
+ .into_iter()
+ .map(|image| {
+ // SAFETY: the image lives as long as the swapchain, which outlives the
+ // surface (`Swapchain::destroy`).
+ let mut image_info = unsafe {
+ gpu::vk::ImageInfo::new(
+ image.as_raw() as _,
+ gpu::vk::Alloc::default(),
+ gpu::vk::ImageTiling::OPTIMAL,
+ gpu::vk::ImageLayout::UNDEFINED,
+ skia_format,
+ 1,
+ queue_family_index,
+ None,
+ None,
+ None,
+ )
+ };
+ image_info.image_usage_flags = usage.as_raw();
+
+ let render_target = backend_render_targets::make_vk(
+ (extent.width as i32, extent.height as i32),
+ &image_info,
+ );
+ gpu::surfaces::wrap_backend_render_target(
+ &mut self.gpu,
+ &render_target,
+ SurfaceOrigin::TopLeft,
+ color_type,
+ None,
+ None,
+ )
+ .ok_or_else(|| {
+ PlayerError::Skia("can not draw into the swapchain images".to_owned())
+ })
+ })
+ .collect::<PlayerResult<Vec<_>>>()
+ });
+
+ match images {
+ Ok(images) => {
+ self.swapchain = Some(Swapchain {
+ handle,
+ images,
+ outdated: false,
+ });
+ Ok(())
+ }
+ Err(err) => {
+ unsafe { self.swapchain_fn.destroy_swapchain(handle, None) };
+ Err(err)
+ }
+ }
+ }
+
+ /// The index of the next swapchain image, once it can be drawn into. `None` while the
+ /// window has no area.
+ fn acquire(&mut self) -> PlayerResult<Option<u32>> {
+ // A swapchain that turns out to be out of date is recreated once.
+ for _ in 0..2 {
+ let Some(swapchain) = self.swapchain.as_mut() else {
+ return Ok(None);
+ };
+
+ let acquired = unsafe {
+ self.swapchain_fn.acquire_next_image(
+ swapchain.handle,
+ u64::MAX,
+ vk::Semaphore::null(),
+ self.acquired,
+ )
+ };
+
+ match acquired {
+ Ok((index, suboptimal)) => {
+ swapchain.outdated |= suboptimal;
+
+ let device = self.backend.device();
+ unsafe {
+ device
+ .wait_for_fences(&[self.acquired], true, u64::MAX)
+ .and_then(|()| device.reset_fences(&[self.acquired]))
+ }
+ .map_err(vulkan_error("can not wait for the swapchain image"))?;
+
+ return Ok(Some(index));
+ }
+ Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => self.recreate_swapchain()?,
+ Err(err) => return Err(vulkan_error("can not acquire a swapchain image")(err)),
+ }
+ }
+
+ Ok(None)
+ }
+}
+
+impl WindowTarget for VulkanTarget {
+ fn is_gpu(&self) -> bool {
+ true
+ }
+
+ fn resize(&mut self, width: u32, height: u32) -> PlayerResult<()> {
+ self.size = (width, height);
+ if let Some(swapchain) = self.swapchain.as_mut() {
+ swapchain.outdated = true;
+ }
+ Ok(())
+ }
+
+ fn present(&mut self, draw: &mut dyn FnMut(&Canvas)) -> PlayerResult<()> {
+ if self
+ .swapchain
+ .as_ref()
+ .is_none_or(|swapchain| swapchain.outdated)
+ {
+ self.recreate_swapchain()?;
+ }
+
+ let Some(index) = self.acquire()? else {
+ return Ok(());
+ };
+ let Some(swapchain) = self.swapchain.as_mut() else {
+ return Ok(());
+ };
+ let surface = &mut swapchain.images[index as usize];
+
+ draw(surface.canvas());
+
+ let _queue = lock_queue(Some(&self.queue_lock));
+ // Ask Skia for the layout the presentation engine reads. `BackendSurfaceAccess::Present`
+ // changes the layout only when Skia's context lists `VK_KHR_swapchain`, and the
+ // contexts of `SkiaVulkanCtx` do not.
+ let present_layout = gpu::vk::mutable_texture_states::new_vulkan(
+ gpu::vk::ImageLayout::PRESENT_SRC_KHR,
+ self.backend.queue_family_index(),
+ );
+ self.gpu.flush_surface_with_texture_state(
+ surface,
+ &FlushInfo::default(),
+ Some(&present_layout),
+ );
+ self.gpu.submit(SyncCpu::Yes);
+
+ let presented = unsafe {
+ self.swapchain_fn.queue_present(
+ self.queue,
+ &vk::PresentInfoKHR::default()
+ .swapchains(&[swapchain.handle])
+ .image_indices(&[index]),
+ )
+ };
+
+ match presented {
+ Ok(suboptimal) => swapchain.outdated |= suboptimal,
+ Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => swapchain.outdated = true,
+ Err(err) => return Err(vulkan_error("can not present")(err)),
+ }
+
+ Ok(())
+ }
+}
+
+impl Drop for VulkanTarget {
+ fn drop(&mut self) {
+ let device = self.backend.device();
+ // Waiting for the GPU and dropping the context reach the queue.
+ let _queue = lock_queue(Some(&self.queue_lock));
+ unsafe {
+ let _ = device.device_wait_idle();
+ }
+
+ if let Some(swapchain) = self.swapchain.take() {
+ swapchain.destroy(&self.swapchain_fn);
+ }
+
+ unsafe {
+ // SAFETY: not used after this
+ ManuallyDrop::drop(&mut self.gpu);
+ device.destroy_fence(self.acquired, None);
+ self.surface_fn.destroy_surface(self.surface, None);
+ }
+ }
+}
+
+/// The instance extension that creates surfaces for windows of `display`.
+fn surface_extension(display: RawDisplayHandle) -> PlayerResult<&'static CStr> {
+ match display {
+ RawDisplayHandle::AppKit(_) => Ok(ash::ext::metal_surface::NAME),
+ RawDisplayHandle::Xlib(_) => Ok(ash::khr::xlib_surface::NAME),
+ RawDisplayHandle::Xcb(_) => Ok(ash::khr::xcb_surface::NAME),
+ RawDisplayHandle::Wayland(_) => Ok(ash::khr::wayland_surface::NAME),
+ RawDisplayHandle::Windows(_) => Ok(ash::khr::win32_surface::NAME),
+ other => Err(PlayerError::Window(format!(
+ "vulkan can not present to {other:?}"
+ ))),
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn create_surface(
+ backend: &SkiaVulkanCtx,
+ window: &Window,
+) -> PlayerResult<(vk::SurfaceKHR, SurfaceLayer)> {
+ use winit::raw_window_handle::RawWindowHandle;
+
+ let RawWindowHandle::AppKit(handle) = window.window_handle()?.as_raw() else {
+ return Err(PlayerError::Window(
+ "vulkan can only present to an AppKit window on macOS".to_owned(),
+ ));
+ };
+
+ // SAFETY: the view of a live window, `Presenter::new` runs on the main thread.
+ let layer = unsafe { raw_window_metal::Layer::from_ns_view(handle.ns_view) };
+ let create_info = vk::MetalSurfaceCreateInfoEXT::default().layer(layer.as_ptr().as_ptr());
+ let surface = unsafe {
+ ash::ext::metal_surface::Instance::new(backend.entry(), backend.instance())
+ .create_metal_surface(&create_info, None)
+ }
+ .map_err(vulkan_error("can not create the window surface"))?;
+
+ Ok((surface, layer))
+}
+
+#[cfg(not(target_os = "macos"))]
+fn create_surface(
+ backend: &SkiaVulkanCtx,
+ window: &Window,
+) -> PlayerResult<(vk::SurfaceKHR, SurfaceLayer)> {
+ use winit::raw_window_handle::RawWindowHandle;
+
+ let (entry, instance) = (backend.entry(), backend.instance());
+ let display = window.display_handle()?.as_raw();
+ let handle = window.window_handle()?.as_raw();
+ let unsupported = || PlayerError::Window(format!("vulkan can not present to {handle:?}"));
+
+ // SAFETY: the handles are of a live window, which outlives the surface.
+ let surface = unsafe {
+ match (display, handle) {
+ (RawDisplayHandle::Xlib(display), RawWindowHandle::Xlib(window)) => {
+ let create_info = vk::XlibSurfaceCreateInfoKHR::default()
+ .dpy(display.display.ok_or_else(unsupported)?.as_ptr())
+ .window(window.window);
+ ash::khr::xlib_surface::Instance::new(entry, instance)
+ .create_xlib_surface(&create_info, None)
+ }
+ (RawDisplayHandle::Xcb(display), RawWindowHandle::Xcb(window)) => {
+ let create_info = vk::XcbSurfaceCreateInfoKHR::default()
+ .connection(display.connection.ok_or_else(unsupported)?.as_ptr())
+ .window(window.window.get());
+ ash::khr::xcb_surface::Instance::new(entry, instance)
+ .create_xcb_surface(&create_info, None)
+ }
+ (RawDisplayHandle::Wayland(display), RawWindowHandle::Wayland(window)) => {
+ let create_info = vk::WaylandSurfaceCreateInfoKHR::default()
+ .display(display.display.as_ptr())
+ .surface(window.surface.as_ptr());
+ ash::khr::wayland_surface::Instance::new(entry, instance)
+ .create_wayland_surface(&create_info, None)
+ }
+ (RawDisplayHandle::Windows(_), RawWindowHandle::Win32(window)) => {
+ let create_info = vk::Win32SurfaceCreateInfoKHR::default()
+ .hinstance(window.hinstance.map_or(0, std::num::NonZeroIsize::get))
+ .hwnd(window.hwnd.get());
+ ash::khr::win32_surface::Instance::new(entry, instance)
+ .create_win32_surface(&create_info, None)
+ }
+ _ => return Err(unsupported()),
+ }
+ }
+ .map_err(vulkan_error("can not create the window surface"))?;
+
+ Ok((surface, ()))
+}
+
+fn vulkan_error(what: &str) -> impl FnOnce(vk::Result) -> PlayerError + '_ {
+ move |err| PlayerError::Surface(format!("{what}: {err}"))
+}
diff --git a/fframes-skia-renderer/src/backends/metal.rs b/fframes-skia-renderer/src/backends/metal.rs
index ba07523a..9961c5a6 100644
--- a/fframes-skia-renderer/src/backends/metal.rs
+++ b/fframes-skia-renderer/src/backends/metal.rs
@@ -130,12 +130,21 @@ fn gpu_context_options() -> gpu::ContextOptions {
}
impl SkiaMetalCtx {
- /// A new Skia context on the device.
- pub(crate) fn create_context(&self) -> FFramesRendererResult<DirectContext> {
+ /// A new Skia context on the device. It submits to [`Self::command_queue`].
+ pub fn create_context(&self) -> FFramesRendererResult<DirectContext> {
gpu::direct_contexts::make_metal(&self.backend, Some(&gpu_context_options()))
.ok_or_else(|| FFramesRendererError::Skia("Failed to create GPU context".to_string()))
}
+ pub fn device(&self) -> &metal_rs::DeviceRef {
+ &self.device
+ }
+
+ /// The queue the Skia contexts of this backend submit to.
+ pub fn command_queue(&self) -> &metal_rs::CommandQueueRef {
+ &self.command_queue
+ }
+
/// The `id<MTLDevice>` of the context.
#[cfg(target_os = "macos")]
pub(crate) fn device_ptr(&self) -> *mut std::ffi::c_void {
diff --git a/fframes-skia-renderer/src/backends/vulkan.rs b/fframes-skia-renderer/src/backends/vulkan.rs
index cb004862..9fd69ca9 100644
--- a/fframes-skia-renderer/src/backends/vulkan.rs
+++ b/fframes-skia-renderer/src/backends/vulkan.rs
@@ -1,5 +1,6 @@
use super::SkiaBackend;
use crate::skia_backend::{SkiaFFramesRenderer, SkiaPipelineConfig};
+pub use ash;
use ash::vk::{self, Handle};
use ash::{Entry, Instance};
use fframes::{FFramesRendererError, FFramesRendererResult};
@@ -8,7 +9,7 @@ use skia_safe::gpu::ganesh::context_options::{Enable, ShaderCacheStrategy};
use skia_safe::gpu::ganesh::vk::backend_render_targets;
use skia_safe::gpu::{self, DirectContext};
use skia_safe::{Surface, gpu::SurfaceOrigin};
-use std::ffi::{CString, c_void};
+use std::ffi::{CStr, CString, c_void};
use std::os::raw::c_char;
#[allow(dead_code)]
@@ -42,12 +43,13 @@ struct ForeignDevice {
}
/// A Skia GPU context and the queue it submits to.
-pub(crate) struct VulkanContext {
- pub(crate) gpu: DirectContext,
- pub(crate) queue_lock: super::QueueLock,
- pub(crate) queue: vk::Queue,
- #[cfg_attr(not(feature = "vulkan-video"), allow(dead_code))]
- pub(crate) queue_index: u32,
+pub struct VulkanContext {
+ pub gpu: DirectContext,
+ /// Held around everything that reaches [`Self::queue`]: Skia's submits, presents, readbacks.
+ pub queue_lock: super::QueueLock,
+ pub queue: vk::Queue,
+ /// The index of [`Self::queue`] in the queue family of the backend.
+ pub queue_index: u32,
}
unsafe impl Send for SkiaVulkanCtx {}
@@ -55,29 +57,43 @@ unsafe impl Sync for SkiaVulkanCtx {}
impl SkiaVulkanCtx {
pub fn new(width: usize, height: usize) -> FFramesRendererResult<Self> {
+ Self::new_with_instance_extensions(width, height, &[])
+ }
+
+ /// Like [`Self::new`], with more instance extensions enabled. Presenting to a window
+ /// needs the surface extension of its window system (`VK_KHR_xlib_surface`,
+ /// `VK_KHR_wayland_surface`, `VK_KHR_win32_surface`, `VK_EXT_metal_surface`, ...).
+ pub fn new_with_instance_extensions(
+ width: usize,
+ height: usize,
+ instance_extensions: &[&'static CStr],
+ ) -> FFramesRendererResult<Self> {
unsafe {
let entry = Entry::load().map_err(|e| {
FFramesRendererError::Skia(format!("Failed to load Vulkan entry: {e}"))
})?;
+ let api_version = vulkan_version(&entry)?.map_or_else(
+ || vk::make_api_version(0, 1, 1, 0),
+ |(major, minor, patch)| {
+ vk::make_api_version(0, major as u32, minor as u32, patch as u32)
+ },
+ );
+ let mut extension_names = vec![
+ vk::KHR_GET_PHYSICAL_DEVICE_PROPERTIES2_NAME,
+ vk::KHR_SURFACE_NAME,
+ vk::KHR_PORTABILITY_ENUMERATION_NAME,
+ ];
+ for name in instance_extensions {
+ if !extension_names.contains(name) {
+ extension_names.push(*name);
+ }
+ }
let instance: Instance = {
- let api_version = vulkan_version(&entry)?.map_or_else(
- || vk::make_api_version(0, 1, 1, 0),
- |(major, minor, patch)| {
- vk::make_api_version(0, major as u32, minor as u32, patch as u32)
- },
- );
-
let app_name = CString::new("fframes_skia_renderer").map_err(|e| {
FFramesRendererError::Skia(format!("Failed to create CString: {e}"))
})?;
- let extension_names = [
- vk::KHR_GET_PHYSICAL_DEVICE_PROPERTIES2_NAME,
- vk::KHR_SURFACE_NAME,
- vk::KHR_PORTABILITY_ENUMERATION_NAME,
- ];
-
let extension_name_ptrs: Vec<*const c_char> =
extension_names.iter().map(|name| name.as_ptr()).collect();
@@ -282,18 +298,29 @@ impl SkiaVulkanCtx {
self.encoder_device.as_ref()
}
- #[cfg(feature = "vulkan-video")]
- pub(crate) fn device(&self) -> &ash::Device {
+ pub fn entry(&self) -> &Entry {
+ &self.entry
+ }
+
+ pub fn instance(&self) -> &Instance {
+ &self.instance
+ }
+
+ pub fn physical_device(&self) -> vk::PhysicalDevice {
+ self.physical_device
+ }
+
+ pub fn device(&self) -> &ash::Device {
&self.device
}
- #[cfg(feature = "vulkan-video")]
- pub(crate) fn queue_family_index(&self) -> u32 {
+ /// The graphics queue family every context of this backend submits to.
+ pub fn queue_family_index(&self) -> u32 {
self.queue_family_index
}
/// A new Skia context on the next queue of the device.
- pub(crate) fn create_context(&self) -> FFramesRendererResult<VulkanContext> {
+ pub fn create_context(&self) -> FFramesRendererResult<VulkanContext> {
unsafe {
let get_proc = |of| {
let proc_ptr = match of {