Skip to content

programmatic video rendering framework that is actually fast

feat(skia): hand frames to the encoder on the GPU (#173)

Dmitriy Kovalenko7bbec1278c76
diff --git a/AGENTS.md b/AGENTS.md
index 902d8d3f..9d00d33b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -617,6 +617,22 @@ Global flags: `--json` (one JSON document on stdout, JSON progress events on std
(`features = ["vulkan"]`; `new_metal` with `metal`). The Skia backend walks the `svgr!` tree
directly and caches static subtrees as pictures; it is roughly 10x faster than the CPU
backend on 1080p (see `cargo run --release -p fframes_skia_renderer --features vulkan --example svgr_vs_skia`).
+- The Skia backend hands frames to the encoder the fastest way both support
+ (`SkiaFFramesRenderer::frame_export(SkiaFrameExport::Auto)`, the default):
+ 1. hardware frames, the encoder reads the texture Skia drew and nothing is read back:
+ `h264_videotoolbox`/`hevc_videotoolbox` with `new_metal`, and `h264_vulkan`/`hevc_vulkan`
+ with `SkiaVulkanCtx::new_shared_with_encoder(W, H)` and
+ `fframes_skia_renderer = { features = ["vulkan-video"] }` (the driver needs Vulkan Video
+ encode). Only when the requested `pixel_format` is `yuv420p` (the default) or `nv12`;
+ 2. conversion on the GPU for `yuv420p`, `nv12`, `nv21`, `yuva420p`, `yuv422p` and `yuv444p`: only
+ the converted planes are read back;
+ 3. RGBA readback and conversion on the CPU for every other pixel format
+ (`SkiaFrameExport::CpuConversion` forces it). The CPU backend always converts this way.
+
+ A backend of your own implements
+ `FFramesRenderBackend::negotiate_encoder_input` (a software format or
+ `EncoderInput::hardware_frames`) and `encoder_frame_renderer`, which returns libav frames
+ (`fframes::VideoFrame`) for `SegmentWriter::submit_frame`.
- macOS: request `hevc_videotoolbox` only with `fframes = { features = ["videotoolbox"] }`
(see `examples/teej-podcast/Cargo.toml`), otherwise the encoder silently falls back.
- In code: `fframes::Previewer::new(&video, &options)` keeps fonts, images and caches between
diff --git a/Cargo.lock b/Cargo.lock
index 4d98473e..c0313e98 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1211,6 +1211,7 @@ name = "fframes_skia_renderer"
version = "1.1.0"
dependencies = [
"ash",
+ "core-foundation 0.10.0",
"fframes",
"foreign-types-shared",
"low-poly-art-example",
diff --git a/examples/pixel-memory/src/scenes/fibonnaci_gallery.rs b/examples/pixel-memory/src/scenes/fibonnaci_gallery.rs
index 424c091d..543484a5 100644
--- a/examples/pixel-memory/src/scenes/fibonnaci_gallery.rs
+++ b/examples/pixel-memory/src/scenes/fibonnaci_gallery.rs
@@ -6,7 +6,7 @@ use rand::Rng;
use std::f32::consts::PI;
/// The golden ratio (φ = (1 + √5) / 2)
-const PHI: f32 = 1.618_034;
+const PHI: f32 = std::f32::consts::GOLDEN_RATIO;
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::sync::atomic::AtomicBool;
diff --git a/examples/pixel-memory/src/scenes/spiral_gallery.rs b/examples/pixel-memory/src/scenes/spiral_gallery.rs
index ff92e580..1a42e642 100644
--- a/examples/pixel-memory/src/scenes/spiral_gallery.rs
+++ b/examples/pixel-memory/src/scenes/spiral_gallery.rs
@@ -7,7 +7,7 @@ use rand::Rng;
use std::f32::consts::PI;
use std::fmt::{Debug, Formatter, Result as FmtResult};
-const GOLDEN_RATIO: f32 = 1.618_034; // Golden ratio (φ)
+const GOLDEN_RATIO: f32 = std::f32::consts::GOLDEN_RATIO; // Golden ratio (φ)
const BASE_PHOTO_SIZE: f32 = 1000.0; // Base size for photos in pixels
const SPIRAL_BASE_RADIUS: f32 = 60.0; // Starting radius for spiral
const SPIRAL_ANGLE_INCREMENT: f32 = 0.5; // Angle increment in PI units
diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rs
index 41f9a66e..71e99a4f 100644
--- a/fframes-media/src/video_decoder.rs
+++ b/fframes-media/src/video_decoder.rs
@@ -704,6 +704,12 @@ impl FFmpegDecoder {
av_frame_copy_props(self.frame_buf.latest_av_frame, self.hw_frame);
}
+ // The decoder fell back to software decoding: the frame it returned already
+ // holds the pixels.
+ _ if target_frame != self.frame_buf.latest_av_frame => {
+ av_frame_unref(self.frame_buf.latest_av_frame);
+ av_frame_move_ref(self.frame_buf.latest_av_frame, target_frame);
+ }
_ => (),
}
@@ -892,7 +898,18 @@ unsafe extern "C" fn get_hw_format(
p = p.add(1);
}
+ // The device has no decoder for this stream (a driver without the codec, an
+ // unsupported profile). The formats that are left decode in software.
eprintln!("Failed to get HW surface format, falling back to software decoding");
+ let mut p = pix_fmts;
+ while !p.is_null() && *p != AVPixelFormat::AV_PIX_FMT_NONE {
+ let desc = av_pix_fmt_desc_get(*p);
+ if !desc.is_null() && (*desc).flags & AV_PIX_FMT_FLAG_HWACCEL as u64 == 0 {
+ return *p;
+ }
+ p = p.add(1);
+ }
+
AVPixelFormat::AV_PIX_FMT_NONE
}
}
diff --git a/fframes-skia-renderer/Cargo.toml b/fframes-skia-renderer/Cargo.toml
index 103a6ab8..180f8efe 100644
--- a/fframes-skia-renderer/Cargo.toml
+++ b/fframes-skia-renderer/Cargo.toml
@@ -27,6 +27,8 @@ foreign-types-shared = "0.3.1"
# Cargo merges these features into the skia-safe dependency above.
[target.'cfg(target_os = "macos")'.dependencies]
skia-safe = { version = "0.153.3", features = ["svg", "gl"] }
+# CoreVideo attributes of the VideoToolbox frames rendered with Metal
+core-foundation = { version = "0.10", optional = true }
[target.'cfg(not(target_os = "macos"))'.dependencies]
skia-safe = { version = "0.153.3", features = ["svg", "webp"] }
@@ -41,8 +43,11 @@ low-poly-art-example = { path = "../examples/low-poly-art" }
default = ["gpu", "binary-cache"]
binary-cache = ["skia-safe/binary-cache"]
gpu = ["skia-safe/ganesh"]
-metal = ["gpu", "skia-safe/metal", "metal-rs"]
+metal = ["gpu", "skia-safe/metal", "metal-rs", "dep:core-foundation"]
vulkan = ["gpu", "skia-safe/vulkan", "ash"]
+# Share the Vulkan device with FFmpeg, so Vulkan Video encoders (h264_vulkan, hevc_vulkan)
+# read the frames on the GPU. Builds FFmpeg with Vulkan support.
+vulkan-video = ["vulkan", "fframes/vulkan"]
d3d = ["skia-safe/d3d"]
gl = ["skia-safe/gl"]
x11 = ["skia-safe/x11"]
diff --git a/fframes-skia-renderer/src/backends/metal.rs b/fframes-skia-renderer/src/backends/metal.rs
index 6014fb15..ba07523a 100644
--- a/fframes-skia-renderer/src/backends/metal.rs
+++ b/fframes-skia-renderer/src/backends/metal.rs
@@ -129,10 +129,44 @@ fn gpu_context_options() -> gpu::ContextOptions {
gpu_context_opts
}
+impl SkiaMetalCtx {
+ /// A new Skia context on the device.
+ pub(crate) 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()))
+ }
+
+ /// The `id<MTLDevice>` of the context.
+ #[cfg(target_os = "macos")]
+ pub(crate) fn device_ptr(&self) -> *mut std::ffi::c_void {
+ self.device.as_ptr().cast()
+ }
+}
+
impl SkiaBackend for SkiaMetalCtx {
+ #[cfg(target_os = "macos")]
+ fn negotiate_hardware_frames(
+ &self,
+ encoder: &fframes::VideoEncoderInfo<'_>,
+ ) -> Option<fframes::EncoderInput> {
+ crate::frame_export::videotoolbox::negotiate(self, encoder)
+ }
+
+ #[cfg(target_os = "macos")]
+ fn hardware_frame_target(
+ &self,
+ input: &fframes::EncoderInput,
+ width: i32,
+ height: i32,
+ ) -> FFramesRendererResult<(DirectContext, Box<dyn crate::HardwareFrameTarget>)> {
+ let (gpu, target) = crate::frame_export::videotoolbox::VideoToolboxFrameTarget::new(
+ self, input, width, height,
+ )?;
+ Ok((gpu, Box::new(target)))
+ }
+
fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)> {
- let mut gpu_context =
- gpu::direct_contexts::make_metal(&self.backend, Some(&gpu_context_options())).unwrap();
+ let mut gpu_context = self.create_context()?;
let texture_descriptor = TextureDescriptor::new();
texture_descriptor.set_width(self.width as u64);
diff --git a/fframes-skia-renderer/src/backends/mod.rs b/fframes-skia-renderer/src/backends/mod.rs
index b38e7a9f..b982bd12 100644
--- a/fframes-skia-renderer/src/backends/mod.rs
+++ b/fframes-skia-renderer/src/backends/mod.rs
@@ -2,14 +2,95 @@
pub mod metal;
#[cfg(feature = "vulkan")]
pub mod vulkan;
+#[cfg(feature = "vulkan")]
+pub(crate) mod vulkan_readback;
-use fframes::FFramesRendererResult;
+use fframes::{EncoderInput, FFramesRendererError, FFramesRendererResult, VideoEncoderInfo};
use skia_safe::{Surface, gpu::DirectContext, surfaces};
-use crate::SkiaFFramesRenderer;
+use crate::{HardwareFrameTarget, SkiaFFramesRenderer};
+
+/// The lock of the GPU queue a context submits to, see [`SkiaContext::queue_lock`].
+pub type QueueLock = std::sync::Arc<std::sync::Mutex<()>>;
+
+/// Holds `lock` (when there is one) until the guard is dropped.
+pub fn lock_queue(lock: Option<&QueueLock>) -> Option<std::sync::MutexGuard<'_, ()>> {
+ lock.map(|lock| {
+ lock.lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ })
+}
+
+/// Reads the pixels of a GPU surface without keeping the queue of its context busy, see
+/// [`SkiaContext::reader`].
+pub trait SurfaceReader {
+ /// Submits everything drawn with `gpu` followed by a copy of `surface`, waits for the
+ /// copy and writes it to `pixels`: rows of `width * 4` bytes without padding, in the
+ /// byte order of the surface (which has to be RGBA or BGRA 8888).
+ ///
+ /// The queue is only held while submitting, not while the GPU works.
+ fn read(
+ &mut self,
+ gpu: &mut DirectContext,
+ surface: &mut Surface,
+ pixels: &mut [u8],
+ ) -> FFramesRendererResult<()>;
+}
+
+/// A GPU context of a backend with a surface to draw into.
+pub struct SkiaContext {
+ pub surface: Surface,
+ /// `None` for backends that render on the CPU.
+ pub gpu: Option<DirectContext>,
+ /// A Vulkan queue must not be used from two threads at once, and a device can have
+ /// fewer queues than a render has GPU contexts (integrated GPUs expose a single one).
+ /// Contexts that share a queue share this lock; whoever drives a context holds it
+ /// around every call that reaches the queue: a flush that submits, a pixel readback,
+ /// dropping the context. `None` when the backend needs no such lock.
+ pub queue_lock: Option<QueueLock>,
+ /// The fast way to read surfaces of this context back when the queue is shared.
+ /// Without it Skia's own readback is used under [`Self::queue_lock`].
+ pub reader: Option<Box<dyn SurfaceReader>>,
+}
pub trait SkiaBackend: Sync + Send {
fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)>;
+
+ /// Like [`Self::create_skia_surface`], with what the context needs to share its GPU
+ /// queue with other contexts of the backend.
+ fn create_skia_context(&self) -> FFramesRendererResult<SkiaContext> {
+ let (surface, gpu) = self.create_skia_surface()?;
+ Ok(SkiaContext {
+ surface,
+ gpu,
+ queue_lock: None,
+ reader: None,
+ })
+ }
+
+ /// 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.
+ ///
+ /// `None` (the default) when the backend has no such frames for this encoder; the
+ /// frames are converted to its pixel format and read back then.
+ fn negotiate_hardware_frames(&self, _encoder: &VideoEncoderInfo<'_>) -> Option<EncoderInput> {
+ None
+ }
+
+ /// A new GPU context together with the frames negotiated by
+ /// [`Self::negotiate_hardware_frames`] that are rendered on it. Called on every GPU
+ /// thread of a render.
+ fn hardware_frame_target(
+ &self,
+ _input: &EncoderInput,
+ _width: i32,
+ _height: i32,
+ ) -> FFramesRendererResult<(DirectContext, Box<dyn HardwareFrameTarget>)> {
+ Err(FFramesRendererError::Skia(
+ "this Skia backend has no hardware frames".to_owned(),
+ ))
+ }
}
#[derive(Clone, Copy)]
diff --git a/fframes-skia-renderer/src/backends/vulkan.rs b/fframes-skia-renderer/src/backends/vulkan.rs
index ab7ed165..cb004862 100644
--- a/fframes-skia-renderer/src/backends/vulkan.rs
+++ b/fframes-skia-renderer/src/backends/vulkan.rs
@@ -21,9 +21,33 @@ pub struct SkiaVulkanCtx {
/// Every Skia context gets its own queue (round robin when there are more contexts),
/// because a queue must not be submitted to from several threads at once.
queues: Vec<vk::Queue>,
+ /// One lock per queue: contexts that end up on the same queue submit one at a time.
+ queue_locks: Vec<super::QueueLock>,
next_queue: std::sync::atomic::AtomicUsize,
width: usize,
height: usize,
+ /// What Skia has to know about a device it did not see being created: the API version
+ /// of the instance and the enabled instance and device extensions.
+ foreign_device: Option<ForeignDevice>,
+ /// The libav device this context renders on when the device is shared with `FFmpeg`
+ /// ([`Self::new_shared_with_encoder`]). The device belongs to `FFmpeg` then.
+ #[cfg(feature = "vulkan-video")]
+ encoder_device: Option<fframes::AvBuffer>,
+}
+
+struct ForeignDevice {
+ api_version: gpu::vk::Version,
+ instance_extensions: Vec<String>,
+ device_extensions: Vec<String>,
+}
+
+/// 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,
}
unsafe impl Send for SkiaVulkanCtx {}
@@ -138,7 +162,7 @@ impl SkiaVulkanCtx {
})?
};
- let queues = (0..queue_count)
+ let queues: Vec<_> = (0..queue_count)
.map(|index| device.get_device_queue(queue_family_index, index))
.collect();
@@ -148,35 +172,128 @@ impl SkiaVulkanCtx {
device,
physical_device,
queue_family_index,
+ queue_locks: queue_locks(&queues),
queues,
next_queue: std::sync::atomic::AtomicUsize::new(0),
width,
height,
+ foreign_device: None,
+ #[cfg(feature = "vulkan-video")]
+ encoder_device: None,
})
}
}
- fn find_memory_type_index(
- &self,
- type_filter: u32,
- properties: vk::MemoryPropertyFlags,
- ) -> Option<u32> {
- let mem_properties = unsafe {
- self.instance
- .get_physical_device_memory_properties(self.physical_device)
+ /// Renders on the Vulkan device of `FFmpeg` (`av_hwdevice_ctx_create`) instead of an own
+ /// one. Sharing the device is what lets Vulkan Video encoders (`h264_vulkan`,
+ /// `hevc_vulkan`) take the rendered frames as GPU images: with such an encoder the
+ /// frames are converted to NV12 on the GPU and never read back. Every other encoder
+ /// works as with [`Self::new`].
+ ///
+ /// Fails when `FFmpeg` can not open a Vulkan device (Vulkan 1.3 is required).
+ #[cfg(feature = "vulkan-video")]
+ pub fn new_shared_with_encoder(width: usize, height: usize) -> FFramesRendererResult<Self> {
+ use fframes::ffmpeg_sys_fframes::{
+ AVHWDeviceContext, AVHWDeviceType, AVVulkanDeviceContext,
};
- (0..mem_properties.memory_type_count).find(|&i| {
- (type_filter & (1 << i)) != 0
- && mem_properties.memory_types[i as usize]
- .property_flags
- .contains(properties)
- })
+ let encoder_device = fframes::hardware_device(AVHWDeviceType::AV_HWDEVICE_TYPE_VULKAN)
+ .map_err(|err| {
+ FFramesRendererError::Skia(format!("FFmpeg can not open a Vulkan device: {err}"))
+ })?;
+
+ unsafe {
+ let hwctx = &*(*encoder_device.data::<AVHWDeviceContext>())
+ .hwctx
+ .cast::<AVVulkanDeviceContext>();
+
+ let entry = Entry::load().map_err(|e| {
+ FFramesRendererError::Skia(format!("Failed to load Vulkan entry: {e}"))
+ })?;
+ let instance = Instance::load(
+ entry.static_fn(),
+ vk::Instance::from_raw(hwctx.inst as usize as u64),
+ );
+ let device = ash::Device::load(
+ instance.fp_v1_0(),
+ vk::Device::from_raw(hwctx.act_dev as usize as u64),
+ );
+
+ let family = hwctx.qf[..hwctx.nb_qf.max(0) as usize]
+ .iter()
+ .find(|family| {
+ family.num > 0 && family.flags & vk::QueueFlags::GRAPHICS.as_raw() != 0
+ })
+ .ok_or_else(|| {
+ FFramesRendererError::Skia(
+ "FFmpeg's Vulkan device has no graphics queue".to_string(),
+ )
+ })?;
+ let queue_family_index = family.idx as u32;
+ let queue_flags = vk::DeviceQueueCreateFlags::from_raw(hwctx.queue_flags);
+ let queues: Vec<_> = (0..family.num.clamp(1, 16) as u32)
+ .map(|queue_index| {
+ if queue_flags.is_empty() {
+ device.get_device_queue(queue_family_index, queue_index)
+ } else {
+ // queues created with flags are only reachable with them
+ device.get_device_queue2(
+ &vk::DeviceQueueInfo2::default()
+ .flags(queue_flags)
+ .queue_family_index(queue_family_index)
+ .queue_index(queue_index),
+ )
+ }
+ })
+ .collect();
+
+ Ok(SkiaVulkanCtx {
+ entry,
+ instance,
+ device,
+ physical_device: vk::PhysicalDevice::from_raw(hwctx.phys_dev as usize as u64),
+ queue_family_index,
+ queue_locks: queue_locks(&queues),
+ queues,
+ next_queue: std::sync::atomic::AtomicUsize::new(0),
+ width,
+ height,
+ foreign_device: Some(ForeignDevice {
+ // what libav creates its instance with
+ api_version: gpu::vk::Version::new(1, 3, 0),
+ instance_extensions: extension_names(
+ hwctx.enabled_inst_extensions,
+ hwctx.nb_enabled_inst_extensions,
+ ),
+ device_extensions: extension_names(
+ hwctx.enabled_dev_extensions,
+ hwctx.nb_enabled_dev_extensions,
+ ),
+ }),
+ encoder_device: Some(encoder_device),
+ })
+ }
}
-}
-impl SkiaBackend for SkiaVulkanCtx {
- fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)> {
+ /// The libav hardware device of a context created with
+ /// [`Self::new_shared_with_encoder`].
+ #[cfg(feature = "vulkan-video")]
+ pub fn encoder_device(&self) -> Option<&fframes::AvBuffer> {
+ self.encoder_device.as_ref()
+ }
+
+ #[cfg(feature = "vulkan-video")]
+ pub(crate) fn device(&self) -> &ash::Device {
+ &self.device
+ }
+
+ #[cfg(feature = "vulkan-video")]
+ pub(crate) 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> {
unsafe {
let get_proc = |of| {
let proc_ptr = match of {
@@ -195,21 +312,38 @@ impl SkiaBackend for SkiaVulkanCtx {
}
};
- let queue = self.queues[self
+ let queue_index = self
.next_queue
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
- % self.queues.len()];
+ % self.queues.len();
+ let queue = self.queues[queue_index];
// Initialize Skia Vulkan backend context
- let backend_context = gpu::vk::BackendContext::new_builder(
+ let mut backend_context = gpu::vk::BackendContext::new_builder(
self.instance.handle().as_raw() as _,
self.physical_device.as_raw() as _,
self.device.handle().as_raw() as _,
(queue.as_raw() as _, self.queue_family_index as usize),
&get_proc,
- None,
- )
- .build();
+ self.foreign_device
+ .as_ref()
+ .map(|device| device.api_version),
+ );
+ if let Some(device) = &self.foreign_device {
+ let instance_extensions: Vec<&str> = device
+ .instance_extensions
+ .iter()
+ .map(String::as_str)
+ .collect();
+ let device_extensions: Vec<&str> = device
+ .device_extensions
+ .iter()
+ .map(String::as_str)
+ .collect();
+ backend_context =
+ backend_context.with_extensions(&instance_extensions, &device_extensions);
+ }
+ let backend_context = backend_context.build();
// Configure context options (same as in Metal implementation)
let mut gpu_context_opts = gpu::ContextOptions::new();
@@ -233,12 +367,62 @@ impl SkiaBackend for SkiaVulkanCtx {
// Batch processing
gpu_context_opts.reduce_ops_task_splitting = Enable::Yes;
- // Create GPU context
- let mut gpu_context =
- gpu::direct_contexts::make_vulkan(&backend_context, Some(&gpu_context_opts))
- .ok_or_else(|| {
- FFramesRendererError::Skia("Failed to create GPU context".to_string())
- })?;
+ let gpu = gpu::direct_contexts::make_vulkan(&backend_context, Some(&gpu_context_opts))
+ .ok_or_else(|| {
+ FFramesRendererError::Skia("Failed to create GPU context".to_string())
+ })?;
+
+ Ok(VulkanContext {
+ gpu,
+ queue_lock: self.queue_locks[queue_index].clone(),
+ queue,
+ queue_index: queue_index as u32,
+ })
+ }
+ }
+
+ fn find_memory_type_index(
+ &self,
+ type_filter: u32,
+ properties: vk::MemoryPropertyFlags,
+ ) -> Option<u32> {
+ let mem_properties = unsafe {
+ self.instance
+ .get_physical_device_memory_properties(self.physical_device)
+ };
+
+ (0..mem_properties.memory_type_count).find(|&i| {
+ (type_filter & (1 << i)) != 0
+ && mem_properties.memory_types[i as usize]
+ .property_flags
+ .contains(properties)
+ })
+ }
+}
+
+impl SkiaBackend for SkiaVulkanCtx {
+ fn create_skia_surface(&self) -> FFramesRendererResult<(Surface, Option<DirectContext>)> {
+ let context = self.create_skia_context()?;
+ Ok((context.surface, context.gpu))
+ }
+
+ fn create_skia_context(&self) -> FFramesRendererResult<super::SkiaContext> {
+ unsafe {
+ let VulkanContext {
+ gpu: mut gpu_context,
+ queue_lock,
+ queue,
+ ..
+ } = self.create_context()?;
+ let reader = super::vulkan_readback::VulkanSurfaceReader::new(
+ &self.device,
+ &self
+ .instance
+ .get_physical_device_memory_properties(self.physical_device),
+ self.queue_family_index,
+ queue,
+ queue_lock.clone(),
+ )?;
let image_create_info = vk::ImageCreateInfo::default()
.image_type(vk::ImageType::TYPE_2D)
@@ -333,13 +517,44 @@ impl SkiaBackend for SkiaVulkanCtx {
FFramesRendererError::Skia("Failed to wrap backend render target".to_string())
})?;
- Ok((surface, Some(gpu_context)))
+ Ok(super::SkiaContext {
+ surface,
+ gpu: Some(gpu_context),
+ queue_lock: Some(queue_lock),
+ reader: Some(Box::new(reader)),
+ })
}
}
+
+ #[cfg(feature = "vulkan-video")]
+ fn negotiate_hardware_frames(
+ &self,
+ encoder: &fframes::VideoEncoderInfo<'_>,
+ ) -> Option<fframes::EncoderInput> {
+ crate::frame_export::vulkan_frames::negotiate(self, encoder)
+ }
+
+ #[cfg(feature = "vulkan-video")]
+ fn hardware_frame_target(
+ &self,
+ input: &fframes::EncoderInput,
+ width: i32,
+ height: i32,
+ ) -> FFramesRendererResult<(DirectContext, Box<dyn crate::HardwareFrameTarget>)> {
+ let (gpu, target) =
+ crate::frame_export::vulkan_frames::VulkanFrameTarget::new(self, input, width, height)?;
+ Ok((gpu, Box::new(target)))
+ }
}
impl Drop for SkiaVulkanCtx {
fn drop(&mut self) {
+ // a device shared with FFmpeg is destroyed with its last reference
+ #[cfg(feature = "vulkan-video")]
+ if self.encoder_device.is_some() {
+ return;
+ }
+
unsafe {
self.device.destroy_device(None);
// Instance and entry are managed by Arc, so they'll be cleaned up
@@ -360,6 +575,28 @@ impl<'a> SkiaFFramesRenderer<'a, SkiaVulkanCtx> {
}
}
+/// Copies a C array of extension names.
+#[cfg(feature = "vulkan-video")]
+unsafe fn extension_names(names: *const *const c_char, count: i32) -> Vec<String> {
+ if names.is_null() {
+ return Vec::new();
+ }
+
+ unsafe { std::slice::from_raw_parts(names, count.max(0) as usize) }
+ .iter()
+ .filter(|name| !name.is_null())
+ .map(|name| {
+ unsafe { std::ffi::CStr::from_ptr(*name) }
+ .to_string_lossy()
+ .into_owned()
+ })
+ .collect()
+}
+
+fn queue_locks(queues: &[vk::Queue]) -> Vec<super::QueueLock> {
+ queues.iter().map(|_| super::QueueLock::default()).collect()
+}
+
fn vulkan_version(entry: &Entry) -> FFramesRendererResult<Option<(usize, usize, usize)>> {
let detected_version = unsafe {
entry.try_enumerate_instance_version().map_err(|e| {
diff --git a/fframes-skia-renderer/src/backends/vulkan_readback.rs b/fframes-skia-renderer/src/backends/vulkan_readback.rs
new file mode 100644
index 00000000..81421b61
--- /dev/null
+++ b/fframes-skia-renderer/src/backends/vulkan_readback.rs
@@ -0,0 +1,302 @@
+use super::{QueueLock, SurfaceReader, lock_queue};
+use ash::vk::{self, Handle};
+use fframes::{FFramesRendererError, FFramesRendererResult};
+use skia_safe::gpu::{self, DirectContext};
+use skia_safe::surface::BackendHandleAccess;
+use skia_safe::{ColorType, Surface};
+
+fn vulkan_error(what: &str, result: vk::Result) -> FFramesRendererError {
+ FFramesRendererError::Skia(format!("{what}: {result}"))
+}
+
+/// The Vulkan image behind a GPU surface.
+pub(crate) fn backing_image(surface: &mut Surface) -> Option<vk::Image> {
+ let info = gpu::surfaces::get_backend_texture(surface, BackendHandleAccess::FlushRead)
+ .and_then(|texture| texture.vulkan_image_info())
+ .or_else(|| {
+ gpu::surfaces::get_backend_render_target(surface, BackendHandleAccess::FlushRead)
+ .and_then(|target| target.vulkan_image_info())
+ })?;
+
+ Some(vk::Image::from_raw(*info.image() as usize as u64))
+}
+
+/// Host memory the GPU copies a surface into.
+struct Staging {
+ buffer: vk::Buffer,
+ memory: vk::DeviceMemory,
+ mapped: *const u8,
+ size: usize,
+}
+
+pub(crate) struct VulkanSurfaceReader {
+ device: ash::Device,
+ queue: vk::Queue,
+ queue_lock: QueueLock,
+ memory_properties: vk::PhysicalDeviceMemoryProperties,
+ command_pool: vk::CommandPool,
+ commands: vk::CommandBuffer,
+ fence: vk::Fence,
+ staging: Option<Staging>,
+}
+
+impl VulkanSurfaceReader {
+ pub(crate) fn new(
+ device: &ash::Device,
+ memory_properties: &vk::PhysicalDeviceMemoryProperties,
+ queue_family_index: u32,
+ queue: vk::Queue,
+ queue_lock: QueueLock,
+ ) -> FFramesRendererResult<Self> {
+ unsafe {
+ let command_pool = device
+ .create_command_pool(
+ &vk::CommandPoolCreateInfo::default()
+ .queue_family_index(queue_family_index)
+ .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER),
+ None,
+ )
+ .map_err(|err| vulkan_error("can not create a command pool", err))?;
+
+ let created = device
+ .allocate_command_buffers(
+ &vk::CommandBufferAllocateInfo::default()
+ .command_pool(command_pool)
+ .level(vk::CommandBufferLevel::PRIMARY)
+ .command_buffer_count(1),
+ )
+ .and_then(|buffers| {
+ let fence = device.create_fence(&vk::FenceCreateInfo::default(), None)?;
+ Ok((buffers[0], fence))
+ });
+
+ match created {
+ Ok((commands, fence)) => Ok(Self {
+ device: device.clone(),
+ queue,
+ queue_lock,
+ memory_properties: *memory_properties,
+ command_pool,
+ commands,
+ fence,
+ staging: None,
+ }),
+ Err(err) => {
+ device.destroy_command_pool(command_pool, None);
+ Err(vulkan_error("can not allocate a command buffer", err))
+ }
+ }
+ }
+ }
+
+ fn free_staging(&mut self) {
+ if let Some(staging) = self.staging.take() {
+ unsafe {
+ self.device.unmap_memory(staging.memory);
+ self.device.destroy_buffer(staging.buffer, None);
+ self.device.free_memory(staging.memory, None);
+ }
+ }
+ }
+
+ /// Mapped memory of at least `size` bytes the GPU can copy into. Kept between frames.
+ fn staging(&mut self, size: usize) -> FFramesRendererResult<&Staging> {
+ if self
+ .staging
+ .as_ref()
+ .is_none_or(|staging| staging.size < size)
+ {
+ self.free_staging();
+
+ unsafe {
+ let buffer = self
+ .device
+ .create_buffer(
+ &vk::BufferCreateInfo::default()
+ .size(size as u64)
+ .usage(vk::BufferUsageFlags::TRANSFER_DST)
+ .sharing_mode(vk::SharingMode::EXCLUSIVE),
+ None,
+ )
+ .map_err(|err| vulkan_error("can not create a readback buffer", err))?;
+ let requirements = self.device.get_buffer_memory_requirements(buffer);
+
+ // Cached memory is read at the speed of ordinary memory; fall back to what
+ // every device has.
+ let visible =
+ vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
+ let memory_type = [visible | vk::MemoryPropertyFlags::HOST_CACHED, visible]
+ .into_iter()
+ .find_map(|wanted| {
+ (0..self.memory_properties.memory_type_count).find(|&index| {
+ requirements.memory_type_bits & (1 << index) != 0
+ && self.memory_properties.memory_types[index as usize]
+ .property_flags
+ .contains(wanted)
+ })
+ });
+
+ let mapped = memory_type
+ .ok_or(vk::Result::ERROR_FEATURE_NOT_PRESENT)
+ .and_then(|memory_type| {
+ self.device.allocate_memory(
+ &vk::MemoryAllocateInfo::default()
+ .allocation_size(requirements.size)
+ .memory_type_index(memory_type),
+ None,
+ )
+ })
+ .and_then(|memory| {
+ let mapped =
+ self.device
+ .bind_buffer_memory(buffer, memory, 0)
+ .and_then(|()| {
+ self.device.map_memory(
+ memory,
+ 0,
+ vk::WHOLE_SIZE,
+ vk::MemoryMapFlags::empty(),
+ )
+ });
+ if mapped.is_err() {
+ self.device.free_memory(memory, None);
+ }
+ mapped.map(|mapped| (memory, mapped))
+ });
+
+ match mapped {
+ Ok((memory, mapped)) => {
+ self.staging = Some(Staging {
+ buffer,
+ memory,
+ mapped: mapped.cast::<u8>().cast_const(),
+ size,
+ });
+ }
+ Err(err) => {
+ self.device.destroy_buffer(buffer, None);
+ return Err(vulkan_error("can not allocate readback memory", err));
+ }
+ }
+ }
+ }
+
+ Ok(self
+ .staging
+ .as_ref()
+ .expect("the staging buffer was just created"))
+ }
+}
+
+impl SurfaceReader for VulkanSurfaceReader {
+ fn read(
+ &mut self,
+ gpu: &mut DirectContext,
+ surface: &mut Surface,
+ pixels: &mut [u8],
+ ) -> FFramesRendererResult<()> {
+ let (width, height) = (surface.width() as u32, surface.height() as u32);
+ let size = width as usize * height as usize * 4;
+ if !matches!(
+ surface.image_info().color_type(),
+ ColorType::RGBA8888 | ColorType::BGRA8888
+ ) || pixels.len() < size
+ {
+ return Err(FFramesRendererError::Skia(
+ "the surface reader copies four byte pixels into a buffer of their size".to_owned(),
+ ));
+ }
+
+ let image = backing_image(surface).ok_or_else(|| {
+ FFramesRendererError::Skia("the surface has no Vulkan image".to_owned())
+ })?;
+ let (buffer, mapped) = {
+ let staging = self.staging(size)?;
+ (staging.buffer, staging.mapped)
+ };
+
+ // Skia records what was drawn (this is the expensive part and needs no queue) and
+ // leaves the image in the layout it is copied from.
+ gpu.flush_surface_with_texture_state(
+ surface,
+ &gpu::FlushInfo::default(),
+ Some(&gpu::vk::mutable_texture_states::new_vulkan(
+ gpu::vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
+ vk::QUEUE_FAMILY_IGNORED,
+ )),
+ );
+
+ unsafe {
+ let device = &self.device;
+ let record = || -> Result<(), vk::Result> {
+ device.reset_fences(&[self.fence])?;
+ device.reset_command_buffer(self.commands, vk::CommandBufferResetFlags::empty())?;
+ device.begin_command_buffer(
+ self.commands,
+ &vk::CommandBufferBeginInfo::default()
+ .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
+ )?;
+ device.cmd_copy_image_to_buffer(
+ self.commands,
+ image,
+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
+ buffer,
+ &[vk::BufferImageCopy {
+ buffer_offset: 0,
+ // rows without padding
+ buffer_row_length: 0,
+ buffer_image_height: 0,
+ image_subresource: vk::ImageSubresourceLayers {
+ aspect_mask: vk::ImageAspectFlags::COLOR,
+ mip_level: 0,
+ base_array_layer: 0,
+ layer_count: 1,
+ },
+ image_offset: vk::Offset3D::default(),
+ image_extent: vk::Extent3D {
+ width,
+ height,
+ depth: 1,
+ },
+ }],
+ );
+ device.end_command_buffer(self.commands)
+ };
+ record().map_err(|err| vulkan_error("can not record the readback", err))?;
+
+ // The queue runs what it is given in order: the draws, then the copy.
+ let submitted = {
+ let _queue = lock_queue(Some(&self.queue_lock));
+ if gpu.submit(gpu::SyncCpu::No) {
+ let commands = [self.commands];
+ device.queue_submit(
+ self.queue,
+ &[vk::SubmitInfo::default().command_buffers(&commands)],
+ self.fence,
+ )
+ } else {
+ Err(vk::Result::ERROR_UNKNOWN)
+ }
+ };
+ submitted.map_err(|err| vulkan_error("can not submit the frame to the GPU", err))?;
+
+ device
+ .wait_for_fences(&[self.fence], true, u64::MAX)
+ .map_err(|err| vulkan_error("waiting for the readback failed", err))?;
+ std::ptr::copy_nonoverlapping(mapped, pixels.as_mut_ptr(), size);
+ }
+
+ Ok(())
+ }
+}
+
+impl Drop for VulkanSurfaceReader {
+ fn drop(&mut self) {
+ // `read` waits for its copy, so nothing of ours is in flight here
+ self.free_staging();
+ unsafe {
+ self.device.destroy_fence(self.fence, None);
+ self.device.destroy_command_pool(self.command_pool, None);
+ }
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_export/mod.rs b/fframes-skia-renderer/src/frame_export/mod.rs
new file mode 100644
index 00000000..b1a12fb1
--- /dev/null
+++ b/fframes-skia-renderer/src/frame_export/mod.rs
@@ -0,0 +1,391 @@
+use crate::{QueueLock, SkiaBackend, SkiaContext, SurfaceReader, lock_queue};
+use fframes::{
+ Color, EncoderFrameRenderer, EncoderInput, FFramesRendererError, FFramesRendererResult,
+ RenderEncodingResult, RgbaFrameConverter, VideoEncoderInfo, VideoFrame, usvgr,
+};
+use skia_safe::{AlphaType, ColorType, ImageInfo, Surface, gpu};
+
+mod planes;
+#[cfg(all(target_os = "macos", feature = "metal"))]
+pub(crate) mod videotoolbox;
+#[cfg(feature = "vulkan-video")]
+pub(crate) mod vulkan_frames;
+
+/// How the frames Skia renders are handed to the video encoder.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum SkiaFrameExport {
+ /// The fastest way the backend and the encoder support: hardware frames, then
+ /// conversion on the GPU, then conversion on the CPU.
+ #[default]
+ Auto,
+ /// Convert to the encoder's pixel format on the GPU and read the planes back, never
+ /// hardware frames. Formats without a GPU conversion are converted on the CPU.
+ GpuConversion,
+ /// Read RGBA back and convert it on the CPU.
+ CpuConversion,
+}
+
+/// The way frames of a render take, see [`SkiaEncoderFrameRenderer::path`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FrameExportPath {
+ /// The encoder reads the texture Skia rendered.
+ HardwareFrames,
+ /// Converted on the GPU, planes read back.
+ GpuConversion,
+ /// RGBA read back and converted on the CPU.
+ CpuConversion,
+}
+
+/// Hardware frames of one GPU context: the textures the encoder reads.
+/// Created by [`SkiaBackend::hardware_frame_target`] together with the context.
+pub trait HardwareFrameTarget {
+ /// The surface the next frame has to be drawn into.
+ fn begin_frame(&mut self, gpu: &mut gpu::DirectContext) -> FFramesRendererResult<&mut Surface>;
+
+ /// Submits what was drawn since [`Self::begin_frame`] and returns it as a frame of the
+ /// encoder.
+ fn finish_frame(&mut self, gpu: &mut gpu::DirectContext) -> FFramesRendererResult<VideoFrame>;
+
+ /// Ends the target and then the GPU context it was created with, in that order: the
+ /// surfaces of the target live on the context. Destroying a context submits to its
+ /// queue, so a target that shares the queue with the encoder does it under the lock
+ /// of the queue.
+ fn retire(self: Box<Self>, gpu: gpu::DirectContext) {
+ drop(self);
+ drop(gpu);
+ }
+}
+
+/// `true` when the pixel format requested for the video is what hardware frames of
+/// `hardware_format` deliver: 8 bit 4:2:0 without alpha (the default), or the hardware
+/// format itself. A request for 10 bit, 4:4:4 or alpha describes the stream the user wants,
+/// and hardware frames would encode 8 bit 4:2:0 in its place.
+#[allow(dead_code)] // only backends with hardware frames ask
+pub(crate) fn accepts_hardware_frames(
+ encoder: &VideoEncoderInfo<'_>,
+ hardware_format: fframes::ffmpeg_sys_fframes::AVPixelFormat,
+) -> bool {
+ use fframes::ffmpeg_sys_fframes::AVPixelFormat::{AV_PIX_FMT_NV12, AV_PIX_FMT_YUV420P};
+
+ let requested = encoder.requested_pixel_format();
+ encoder.lists(hardware_format)
+ && (requested == hardware_format
+ || requested == AV_PIX_FMT_YUV420P
+ || requested == AV_PIX_FMT_NV12)
+}
+
+/// Draws an empty frame through `target`, the whole way a frame of the render takes, and
+/// ends the target and its context.
+#[allow(dead_code)] // only backends with hardware frames try them out
+pub(crate) fn trial_frame(
+ mut target: Box<dyn HardwareFrameTarget>,
+ mut gpu: gpu::DirectContext,
+) -> FFramesRendererResult<()> {
+ let frame = target
+ .begin_frame(&mut gpu)
+ .map(|surface| {
+ surface.canvas().clear(skia_safe::Color::BLACK);
+ })
+ .and_then(|()| target.finish_frame(&mut gpu));
+ target.retire(gpu);
+
+ frame.map(drop)
+}
+
+pub(crate) fn negotiate<TBackend: SkiaBackend + ?Sized>(
+ backend: &TBackend,
+ mode: SkiaFrameExport,
+ encoder: &VideoEncoderInfo<'_>,
+) -> RenderEncodingResult<EncoderInput> {
+ let mut hardware_error = None;
+ if mode == SkiaFrameExport::Auto
+ && let Some(input) = backend.negotiate_hardware_frames(encoder)
+ {
+ match encoder.try_open(&input) {
+ Ok(()) => return Ok(input),
+ Err(err) => hardware_error = Some(err),
+ }
+ }
+
+ // An encoder that takes nothing but hardware frames fails here too. The error from
+ // its hardware frames says why.
+ EncoderInput::requested(encoder).map_err(|err| hardware_error.unwrap_or(err))
+}
+
+/// Writes the uniforms of a runtime effect by name, wherever its layout puts them.
+pub(crate) fn pack_uniforms(
+ effect: &skia_safe::RuntimeEffect,
+ values: &[(&str, &[f32])],
+) -> FFramesRendererResult<skia_safe::Data> {
+ let mut data = vec![0_u8; effect.uniform_size()];
+ for (name, value) in values {
+ let uniform = effect
+ .uniforms()
+ .iter()
+ .find(|uniform| uniform.name() == *name)
+ .filter(|uniform| uniform.size_in_bytes() == size_of_val(*value))
+ .ok_or_else(|| {
+ FFramesRendererError::Skia(format!("conversion shader has no uniform `{name}`"))
+ })?;
+
+ let bytes: Vec<u8> = value.iter().flat_map(|v| v.to_ne_bytes()).collect();
+ data[uniform.offset()..uniform.offset() + bytes.len()].copy_from_slice(&bytes);
+ }
+
+ Ok(skia_safe::Data::new_copy(&data))
+}
+
+/// The queue side of a GPU context: how its surfaces are read back.
+struct ContextQueue {
+ /// Held around everything that submits to the queue of the context.
+ lock: Option<QueueLock>,
+ reader: Option<Box<dyn SurfaceReader>>,
+}
+
+impl ContextQueue {
+ /// Submits what was drawn and reads `surface` back into `pixels` as rows of `info`
+ /// without padding.
+ fn read(
+ &mut self,
+ gpu: Option<&mut gpu::DirectContext>,
+ surface: &mut Surface,
+ info: &ImageInfo,
+ pixels: &mut [u8],
+ ) -> FFramesRendererResult<()> {
+ // A reader copies the bytes of the surface as they are.
+ if let (Some(reader), Some(gpu)) = (self.reader.as_mut(), gpu)
+ && surface.image_info().color_type() == info.color_type()
+ {
+ return reader.read(gpu, surface, pixels);
+ }
+
+ // Skia submits and waits for the GPU in one call, the queue is busy for all of it.
+ let _queue = lock_queue(self.lock.as_ref());
+ if surface.read_pixels(info, pixels, info.min_row_bytes(), (0, 0)) {
+ Ok(())
+ } else {
+ Err(FFramesRendererError::Skia(
+ "failed to read pixels from the Skia surface".to_owned(),
+ ))
+ }
+ }
+}
+
+enum Target {
+ Hardware(Box<dyn HardwareFrameTarget>),
+ Planes {
+ surface: Surface,
+ exporter: planes::PlaneExporter,
+ },
+ Rgba {
+ surface: Surface,
+ info: ImageInfo,
+ },
+}
+
+/// A frame as it leaves the GPU thread.
+pub(crate) enum Rendered {
+ Frame(VideoFrame),
+ /// Premultiplied RGBA that still has to be converted, which the encoder threads do.
+ Rgba(Vec<u8>),
+}
+
+/// Skia as a `fframes::EncoderFrameRenderer`: draws frames on one GPU context and returns
+/// them the way [`fframes::FFramesRenderBackend::negotiate_encoder_input`] negotiated.
+/// Keeps the surfaces, GPU context and render cache between frames.
+pub struct SkiaEncoderFrameRenderer<'b> {
+ /// Only taken when the renderer is dropped.
+ target: Option<Target>,
+ render_cache: crate::render::RenderCache,
+ /// Only used when RGBA is converted on the calling thread.
+ converter: Option<RgbaFrameConverter>,
+ input: EncoderInput,
+ width: i32,
+ height: i32,
+ // dropped after the surfaces that were created on it
+ gpu: Option<gpu::DirectContext>,
+ /// Hardware targets deal with their queue themselves.
+ queue: ContextQueue,
+ /// The GPU context lives on the device of the backend.
+ backend: std::marker::PhantomData<&'b ()>,
+}
+
+impl<'b> SkiaEncoderFrameRenderer<'b> {
+ pub fn new<TBackend: SkiaBackend + ?Sized>(
+ backend: &'b TBackend,
+ mode: SkiaFrameExport,
+ input: &EncoderInput,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<Self> {
+ let (width, height) = (width as i32, height as i32);
+
+ let (target, gpu, queue) = if input.is_hardware() {
+ // hardware frames bring their own surfaces
+ let (gpu, target) = backend.hardware_frame_target(input, width, height)?;
+ let queue = ContextQueue {
+ lock: None,
+ reader: None,
+ };
+ (Target::Hardware(target), Some(gpu), queue)
+ } else {
+ // Scaled renders (`scale_resolution`) need a surface of the output size, not
+ // the one the backend was created with.
+ let SkiaContext {
+ surface,
+ mut gpu,
+ queue_lock,
+ reader,
+ } = crate::context_with_size(backend, width, height)?;
+ let exporter = match gpu.as_mut() {
+ Some(gpu) if mode != SkiaFrameExport::CpuConversion => {
+ planes::PlaneExporter::new(gpu, input.pixel_format, width, height)
+ .and_then(Result::ok)
+ }
+ _ => None,
+ };
+
+ let target = match exporter {
+ Some(exporter) => Target::Planes { surface, exporter },
+ None => Target::Rgba {
+ surface,
+ // Always read back as RGBA regardless of the surface's native (often
+ // BGRA) order.
+ info: ImageInfo::new(
+ (width, height),
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ None,
+ ),
+ },
+ };
+ let queue = ContextQueue {
+ lock: queue_lock,
+ reader,
+ };
+ (target, gpu, queue)
+ };
+
+ Ok(Self {
+ target: Some(target),
+ render_cache: crate::render::RenderCache::new(),
+ converter: None,
+ input: input.clone(),
+ width,
+ height,
+ gpu,
+ queue,
+ backend: std::marker::PhantomData,
+ })
+ }
+
+ /// The way the frames of this renderer take to the encoder.
+ pub fn path(&self) -> FrameExportPath {
+ match self.target {
+ Some(Target::Hardware(_)) => FrameExportPath::HardwareFrames,
+ Some(Target::Planes { .. }) => FrameExportPath::GpuConversion,
+ Some(Target::Rgba { .. }) | None => FrameExportPath::CpuConversion,
+ }
+ }
+
+ /// Draws `tree` and takes it off the GPU. `rgba_buffer` provides the buffer of the
+ /// given size for frames that leave as RGBA.
+ pub(crate) fn render(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: skia_safe::Color,
+ rgba_buffer: impl FnOnce(usize) -> Vec<u8>,
+ ) -> FFramesRendererResult<Rendered> {
+ let (width, height) = (self.width, self.height);
+ let render_cache = &mut self.render_cache;
+ let mut draw = |surface: &mut Surface| {
+ let canvas = surface.canvas();
+ canvas.clear(background);
+ canvas.save();
+ crate::apply_fit(canvas, tree, width, height);
+ crate::render::render_tree(tree, canvas, render_cache);
+ canvas.restore();
+ };
+
+ match self
+ .target
+ .as_mut()
+ .expect("the target is only taken on drop")
+ {
+ Target::Hardware(target) => {
+ let gpu = self
+ .gpu
+ .as_mut()
+ .expect("hardware targets are created on a GPU context");
+ draw(target.begin_frame(gpu)?);
+ target.finish_frame(gpu).map(Rendered::Frame)
+ }
+ Target::Planes { surface, exporter } => {
+ draw(surface);
+ exporter.convert(surface)?;
+
+ let (gpu, queue) = (self.gpu.as_mut(), &mut self.queue);
+ exporter
+ .read_back(|planes, info, pixels| queue.read(gpu, planes, info, pixels))
+ .map(Rendered::Frame)
+ }
+ Target::Rgba { surface, info } => {
+ draw(surface);
+
+ let mut pixels = rgba_buffer(info.compute_byte_size(info.min_row_bytes()));
+ self.queue
+ .read(self.gpu.as_mut(), surface, info, &mut pixels)?;
+ Ok(Rendered::Rgba(pixels))
+ }
+ }
+ }
+}
+
+impl Drop for SkiaEncoderFrameRenderer<'_> {
+ fn drop(&mut self) {
+ // Everything that lives on the GPU context goes before the context.
+ self.render_cache = crate::render::RenderCache::new();
+ let target = self.target.take();
+
+ match (target, self.gpu.take()) {
+ (Some(Target::Hardware(target)), Some(gpu)) => target.retire(gpu),
+ (target, gpu) => {
+ drop(target);
+ self.queue.reader = None;
+ // destroying a context waits for its queue
+ let _queue = lock_queue(self.queue.lock.as_ref());
+ drop(gpu);
+ }
+ }
+ }
+}
+
+impl EncoderFrameRenderer for SkiaEncoderFrameRenderer<'_> {
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: Color,
+ ) -> FFramesRendererResult<VideoFrame> {
+ let background =
+ skia_safe::Color::from_argb(background.a, background.r, background.g, background.b);
+
+ match self.render(tree, background, |size| vec![0; size])? {
+ Rendered::Frame(frame) => Ok(frame),
+ Rendered::Rgba(pixels) => {
+ let encoding_error = |err| FFramesRendererError::from_chunk(0, err);
+ if self.converter.is_none() {
+ self.converter = Some(
+ RgbaFrameConverter::for_input(&self.input, self.width, self.height)
+ .map_err(encoding_error)?,
+ );
+ }
+
+ self.converter
+ .as_mut()
+ .expect("the converter was just created")
+ .convert(&pixels)
+ .map_err(encoding_error)
+ }
+ }
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_export/planes.rs b/fframes-skia-renderer/src/frame_export/planes.rs
new file mode 100644
index 00000000..cd2e8260
--- /dev/null
+++ b/fframes-skia-renderer/src/frame_export/planes.rs
@@ -0,0 +1,380 @@
+use fframes::ffmpeg_sys_fframes::AVPixelFormat::{self, *};
+use fframes::pix_fmt::RGB_TO_YUV;
+use fframes::{
+ FFramesRendererError, FFramesRendererResult, FrameLayout, FramePool, RenderEncodingError,
+ VideoFrame,
+};
+use skia_safe::runtime_effect::ChildPtr;
+use skia_safe::{
+ AlphaType, BlendMode, ColorType, Data, FilterMode, ImageInfo, MipmapMode, Paint, Rect,
+ RuntimeEffect, SamplingOptions, Surface, TileMode, gpu,
+};
+
+/// A channel of the encoded picture as weights of the premultiplied RGBA the renderer draws.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) enum Channel {
+ Y,
+ U,
+ V,
+ A,
+}
+
+impl Channel {
+ /// `([r, g, b, a], offset)`
+ pub(crate) fn weights(self) -> ([f32; 4], f32) {
+ let yuv = |row: usize| {
+ let [r, g, b, offset] = RGB_TO_YUV[row];
+ ([r, g, b, 0.], offset)
+ };
+
+ match self {
+ Self::Y => yuv(0),
+ Self::U => yuv(1),
+ Self::V => yuv(2),
+ Self::A => ([0., 0., 0., 1.], 0.),
+ }
+ }
+}
+
+/// A plane of a pixel format: one channel per byte, or two alternating ones (NV12).
+#[derive(Debug, Clone, Copy)]
+struct PlaneSpec {
+ channels: (Channel, Option<Channel>),
+ /// Frame pixels per sample horizontally and vertically.
+ subsampling: (i32, i32),
+}
+
+const fn plane(channel: Channel, subsampling: (i32, i32)) -> PlaneSpec {
+ PlaneSpec {
+ channels: (channel, None),
+ subsampling,
+ }
+}
+
+const fn interleaved(first: Channel, second: Channel, subsampling: (i32, i32)) -> PlaneSpec {
+ PlaneSpec {
+ channels: (first, Some(second)),
+ subsampling,
+ }
+}
+
+/// The planes of the 8 bit YUV formats this converter produces, in libav plane order.
+fn plane_specs(format: AVPixelFormat) -> Option<&'static [PlaneSpec]> {
+ use Channel::{A, U, V, Y};
+
+ const FULL: (i32, i32) = (1, 1);
+ const HALF: (i32, i32) = (2, 2);
+ const HALF_WIDTH: (i32, i32) = (2, 1);
+
+ const YUV420P: &[PlaneSpec] = &[plane(Y, FULL), plane(U, HALF), plane(V, HALF)];
+ const YUVA420P: &[PlaneSpec] = &[
+ plane(Y, FULL),
+ plane(U, HALF),
+ plane(V, HALF),
+ plane(A, FULL),
+ ];
+ const NV12: &[PlaneSpec] = &[plane(Y, FULL), interleaved(U, V, HALF)];
+ const NV21: &[PlaneSpec] = &[plane(Y, FULL), interleaved(V, U, HALF)];
+ const YUV422P: &[PlaneSpec] = &[plane(Y, FULL), plane(U, HALF_WIDTH), plane(V, HALF_WIDTH)];
+ const YUV444P: &[PlaneSpec] = &[plane(Y, FULL), plane(U, FULL), plane(V, FULL)];
+
+ match format {
+ AV_PIX_FMT_YUV420P => Some(YUV420P),
+ AV_PIX_FMT_YUVA420P => Some(YUVA420P),
+ AV_PIX_FMT_NV12 => Some(NV12),
+ AV_PIX_FMT_NV21 => Some(NV21),
+ AV_PIX_FMT_YUV422P => Some(YUV422P),
+ AV_PIX_FMT_YUV444P => Some(YUV444P),
+ _ => None,
+ }
+}
+
+/// A plane placed inside the packed surface.
+#[derive(Debug, Clone, Copy)]
+struct PlacedPlane {
+ spec: PlaneSpec,
+ x: i32,
+ y: i32,
+ /// Size in bytes (= surface pixels) and rows.
+ width: i32,
+ height: i32,
+}
+
+/// Where the planes of a format go in the packed surface: shelves of planes, every plane
+/// starting at a column that keeps its lines aligned for the encoder.
+#[derive(Debug)]
+struct Packing {
+ width: i32,
+ height: i32,
+ planes: Vec<PlacedPlane>,
+}
+
+impl Packing {
+ const LINE_ALIGN: i32 = 64;
+ const PLANE_ALIGN: i32 = 32;
+ /// Lines the pixel buffer extends past the packed planes.
+ const BOTTOM_PADDING: i32 = 32;
+
+ fn new(specs: &[PlaneSpec], frame_width: i32, frame_height: i32) -> Self {
+ let width = (frame_width + Self::LINE_ALIGN - 1) & !(Self::LINE_ALIGN - 1);
+ let (mut x, mut y, mut shelf_height) = (0, 0, 0);
+
+ let planes = specs
+ .iter()
+ .map(|&spec| {
+ let samples = (frame_width + spec.subsampling.0 - 1) / spec.subsampling.0;
+ let plane_width = samples * if spec.channels.1.is_some() { 2 } else { 1 };
+ let plane_height = (frame_height + spec.subsampling.1 - 1) / spec.subsampling.1;
+
+ if x + plane_width > width {
+ x = 0;
+ y += shelf_height;
+ shelf_height = 0;
+ }
+
+ let placed = PlacedPlane {
+ spec,
+ x,
+ y,
+ width: plane_width,
+ height: plane_height,
+ };
+ x = (x + plane_width + Self::PLANE_ALIGN - 1) & !(Self::PLANE_ALIGN - 1);
+ shelf_height = shelf_height.max(plane_height);
+ placed
+ })
+ .collect();
+
+ Self {
+ width,
+ height: y + shelf_height,
+ planes,
+ }
+ }
+
+ /// Bytes of the planes one texel of the packed surface holds.
+ const TEXEL_BYTES: i32 = 4;
+
+ /// The packed surface as the pixel buffer of a frame: every plane is a window into it.
+ fn frame_layout(&self) -> FrameLayout {
+ let mut layout = FrameLayout {
+ // encoders may read whole macroblocks, past the last line of the last plane
+ size: (self.width * (self.height + Self::BOTTOM_PADDING) + Self::LINE_ALIGN) as usize,
+ ..Default::default()
+ };
+ for (index, plane) in self.planes.iter().enumerate() {
+ layout.planes[index] = Some(((plane.y * self.width + plane.x) as usize, self.width));
+ }
+ layout
+ }
+}
+
+const PLANE_SHADER: &str = "
+uniform shader frame;
+// top left texel of the plane in the packed surface
+uniform float2 origin;
+// frame pixels per sample of the plane
+uniform float2 subsampling;
+// 1 when two channels alternate along a line
+uniform float interleaved;
+uniform float4 evenWeights;
+uniform float4 oddWeights;
+uniform float2 offsets;
+
+// The center of a subsampled sample is the corner between the frame pixels it covers,
+// where bilinear filtering returns their average.
+float4 color(float index, float row) {
+ return float4(frame.eval(float2(index + 0.5, row) * subsampling));
+}
+
+half4 main(float2 coord) {
+ float2 position = coord - origin;
+ // a texel holds four consecutive bytes of the plane
+ float first = floor(position.x) * 4.0;
+ float row = position.y;
+
+ if (interleaved > 0.5) {
+ float4 left = color(first * 0.5, row);
+ float4 right = color(first * 0.5 + 1.0, row);
+ return half4(float4(
+ dot(left, evenWeights) + offsets.x,
+ dot(left, oddWeights) + offsets.y,
+ dot(right, evenWeights) + offsets.x,
+ dot(right, oddWeights) + offsets.y));
+ }
+
+ return half4(float4(
+ dot(color(first, row), evenWeights),
+ dot(color(first + 1.0, row), evenWeights),
+ dot(color(first + 2.0, row), evenWeights),
+ dot(color(first + 3.0, row), evenWeights)) + offsets.x);
+}
+";
+
+fn skia_error(message: &str) -> FFramesRendererError {
+ FFramesRendererError::Skia(message.to_owned())
+}
+
+fn encoding_error(err: RenderEncodingError) -> FFramesRendererError {
+ FFramesRendererError::from_chunk(0, err)
+}
+
+/// Converts rendered frames into planar YUV frames on the GPU, see the module docs.
+pub(crate) struct PlaneExporter {
+ surface: Surface,
+ info: ImageInfo,
+ effect: RuntimeEffect,
+ packing: Packing,
+ pool: FramePool,
+}
+
+impl PlaneExporter {
+ /// `None` when `format` has no GPU conversion.
+ pub(crate) fn new(
+ gpu: &mut gpu::DirectContext,
+ format: AVPixelFormat,
+ width: i32,
+ height: i32,
+ ) -> Option<FFramesRendererResult<Self>> {
+ let specs = plane_specs(format)?;
+ Some(Self::with_specs(gpu, format, specs, width, height))
+ }
+
+ fn with_specs(
+ gpu: &mut gpu::DirectContext,
+ format: AVPixelFormat,
+ specs: &[PlaneSpec],
+ width: i32,
+ height: i32,
+ ) -> FFramesRendererResult<Self> {
+ let packing = Packing::new(specs, width, height);
+
+ let info = ImageInfo::new(
+ (packing.width / Packing::TEXEL_BYTES, packing.height),
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ None,
+ );
+ let surface = gpu::surfaces::render_target(
+ gpu,
+ gpu::Budgeted::Yes,
+ &info,
+ None,
+ gpu::SurfaceOrigin::TopLeft,
+ None,
+ false,
+ None,
+ )
+ .ok_or_else(|| skia_error("can not create the GPU surface for the converted planes"))?;
+
+ let effect = RuntimeEffect::make_for_shader(PLANE_SHADER, None)
+ .map_err(|err| FFramesRendererError::Skia(format!("plane shader: {err}")))?;
+ let pool = FramePool::with_layout(format, width, height, packing.frame_layout())
+ .map_err(encoding_error)?;
+
+ Ok(Self {
+ surface,
+ info,
+ effect,
+ packing,
+ pool,
+ })
+ }
+
+ fn uniforms(&self, plane: &PlacedPlane) -> FFramesRendererResult<Data> {
+ let (even_weights, even_offset) = plane.spec.channels.0.weights();
+ let (odd_weights, odd_offset) = plane
+ .spec
+ .channels
+ .1
+ .map_or((even_weights, even_offset), Channel::weights);
+
+ super::pack_uniforms(
+ &self.effect,
+ &[
+ (
+ "origin",
+ &[(plane.x / Packing::TEXEL_BYTES) as f32, plane.y as f32],
+ ),
+ (
+ "subsampling",
+ &[
+ plane.spec.subsampling.0 as f32,
+ plane.spec.subsampling.1 as f32,
+ ],
+ ),
+ (
+ "interleaved",
+ &[f32::from(u8::from(plane.spec.channels.1.is_some()))],
+ ),
+ ("evenWeights", &even_weights),
+ ("oddWeights", &odd_weights),
+ ("offsets", &[even_offset, odd_offset]),
+ ],
+ )
+ }
+
+ /// Draws the planes of what was drawn into `source`. Nothing reaches the GPU before
+ /// the context is flushed or the planes are read back.
+ pub(crate) fn convert(&mut self, source: &mut Surface) -> FFramesRendererResult<()> {
+ let image = source.image_snapshot();
+ let shader_with = |filter: FilterMode| {
+ image
+ .to_shader(
+ (TileMode::Clamp, TileMode::Clamp),
+ SamplingOptions::new(filter, MipmapMode::None),
+ None,
+ )
+ .ok_or_else(|| skia_error("can not sample the rendered frame"))
+ };
+ let full_resolution = shader_with(FilterMode::Nearest)?;
+ let subsampled = shader_with(FilterMode::Linear)?;
+
+ for plane in &self.packing.planes {
+ let frame = if plane.spec.subsampling == (1, 1) {
+ full_resolution.clone()
+ } else {
+ subsampled.clone()
+ };
+ let shader = self
+ .effect
+ .make_shader(self.uniforms(plane)?, &[ChildPtr::Shader(frame)], None)
+ .ok_or_else(|| skia_error("can not instantiate the plane shader"))?;
+
+ let mut paint = Paint::default();
+ paint.set_shader(shader);
+ paint.set_blend_mode(BlendMode::Src);
+ // The last texel of a line may reach into the padding next to the plane.
+ self.surface.canvas().draw_rect(
+ Rect::from_xywh(
+ (plane.x / Packing::TEXEL_BYTES) as f32,
+ plane.y as f32,
+ ((plane.width + Packing::TEXEL_BYTES - 1) / Packing::TEXEL_BYTES) as f32,
+ plane.height as f32,
+ ),
+ &paint,
+ );
+ }
+
+ Ok(())
+ }
+
+ /// Reads the converted planes back into a frame. `read` submits what was drawn and
+ /// copies the packed surface into the buffer it is given (rows without padding).
+ pub(crate) fn read_back(
+ &mut self,
+ read: impl FnOnce(&mut Surface, &ImageInfo, &mut [u8]) -> FFramesRendererResult<()>,
+ ) -> FFramesRendererResult<VideoFrame> {
+ let frame = self.pool.get().map_err(encoding_error)?;
+ // The first plane starts at the beginning of the buffer the whole surface fits in.
+ let pixels = unsafe {
+ std::slice::from_raw_parts_mut(
+ frame.plane(0).0,
+ self.packing.width as usize * self.packing.height as usize,
+ )
+ };
+ read(&mut self.surface, &self.info, pixels)?;
+
+ Ok(frame)
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_export/videotoolbox.rs b/fframes-skia-renderer/src/frame_export/videotoolbox.rs
new file mode 100644
index 00000000..200b3a8f
--- /dev/null
+++ b/fframes-skia-renderer/src/frame_export/videotoolbox.rs
@@ -0,0 +1,413 @@
+use crate::HardwareFrameTarget;
+use crate::metal::SkiaMetalCtx;
+use core_foundation::base::{CFAllocatorRef, CFRelease, CFType, TCFType};
+use core_foundation::boolean::CFBoolean;
+use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
+use core_foundation::number::CFNumber;
+use core_foundation::string::{CFString, CFStringRef};
+use fframes::ffmpeg_sys_fframes::{AVHWDeviceType, AVPixelFormat, av_buffer_create};
+use fframes::{
+ AvBuffer, EncoderInput, FFramesRendererError, FFramesRendererResult, VideoEncoderInfo,
+ VideoFrame,
+};
+use skia_safe::gpu::{self, DirectContext, SurfaceOrigin, backend_render_targets, mtl};
+use skia_safe::{ColorType, Surface};
+use std::ffi::c_void;
+
+type CVPixelBufferPoolRef = *mut c_void;
+type CVPixelBufferRef = *mut c_void;
+type CVMetalTextureCacheRef = *mut c_void;
+type CVMetalTextureRef = *mut c_void;
+
+/// `kCVPixelFormatType_32BGRA` (`'BGRA'`)
+const CV_PIXEL_FORMAT_32_BGRA: i32 = 0x4247_5241;
+/// `MTLPixelFormatBGRA8Unorm`
+const MTL_PIXEL_FORMAT_BGRA8_UNORM: usize = 80;
+/// `MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget`
+const MTL_TEXTURE_USAGE_RENDER_TARGET: i64 = 0x1 | 0x4;
+
+#[link(name = "CoreVideo", kind = "framework")]
+unsafe extern "C" {
+ static kCVPixelBufferPixelFormatTypeKey: CFStringRef;
+ static kCVPixelBufferWidthKey: CFStringRef;
+ static kCVPixelBufferHeightKey: CFStringRef;
+ static kCVPixelBufferIOSurfacePropertiesKey: CFStringRef;
+ static kCVPixelBufferMetalCompatibilityKey: CFStringRef;
+ static kCVMetalTextureUsage: CFStringRef;
+ static kCVImageBufferYCbCrMatrixKey: CFStringRef;
+ static kCVImageBufferYCbCrMatrix_ITU_R_601_4: CFStringRef;
+
+ fn CVBufferSetAttachment(
+ buffer: CVPixelBufferRef,
+ key: CFStringRef,
+ value: core_foundation::base::CFTypeRef,
+ attachment_mode: u32,
+ );
+
+ fn CVPixelBufferPoolCreate(
+ allocator: CFAllocatorRef,
+ pool_attributes: CFDictionaryRef,
+ pixel_buffer_attributes: CFDictionaryRef,
+ pool_out: *mut CVPixelBufferPoolRef,
+ ) -> i32;
+
+ fn CVPixelBufferPoolCreatePixelBuffer(
+ allocator: CFAllocatorRef,
+ pool: CVPixelBufferPoolRef,
+ pixel_buffer_out: *mut CVPixelBufferRef,
+ ) -> i32;
+
+ fn CVPixelBufferRelease(pixel_buffer: CVPixelBufferRef);
+
+ fn CVMetalTextureCacheCreate(
+ allocator: CFAllocatorRef,
+ cache_attributes: CFDictionaryRef,
+ metal_device: *mut c_void,
+ texture_attributes: CFDictionaryRef,
+ cache_out: *mut CVMetalTextureCacheRef,
+ ) -> i32;
+
+ fn CVMetalTextureCacheCreateTextureFromImage(
+ allocator: CFAllocatorRef,
+ texture_cache: CVMetalTextureCacheRef,
+ source_image: CVPixelBufferRef,
+ texture_attributes: CFDictionaryRef,
+ pixel_format: usize,
+ width: usize,
+ height: usize,
+ plane_index: usize,
+ texture_out: *mut CVMetalTextureRef,
+ ) -> i32;
+
+ fn CVMetalTextureGetTexture(texture: CVMetalTextureRef) -> *mut c_void;
+
+ fn CVMetalTextureCacheFlush(texture_cache: CVMetalTextureCacheRef, options: u64);
+}
+
+fn skia_error(message: impl Into<String>) -> FFramesRendererError {
+ FFramesRendererError::Skia(message.into())
+}
+
+/// Offers BGRA pixel buffers to encoders that take `VideoToolbox` frames.
+pub(crate) fn negotiate(
+ backend: &SkiaMetalCtx,
+ encoder: &VideoEncoderInfo<'_>,
+) -> Option<EncoderInput> {
+ // ProRes derives its profile from the pixel format: BGRA would make it 4444.
+ if !matches!(encoder.name(), "h264_videotoolbox" | "hevc_videotoolbox")
+ || !super::accepts_hardware_frames(encoder, AVPixelFormat::AV_PIX_FMT_VIDEOTOOLBOX)
+ {
+ return None;
+ }
+
+ // Fails when FFmpeg was built without VideoToolbox (the `videotoolbox` feature).
+ let device = fframes::hardware_device(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX).ok()?;
+ // Tells the encoder what the pixel buffers hold. The buffers themselves come from
+ // the pool of the frame target.
+ let input = EncoderInput::hardware_frames(
+ &device,
+ AVPixelFormat::AV_PIX_FMT_VIDEOTOOLBOX,
+ AVPixelFormat::AV_PIX_FMT_BGRA,
+ (encoder.width, encoder.height),
+ |_| {},
+ )
+ .ok()?;
+
+ // Draw a frame the way the render will. When Metal can not render into the pixel
+ // buffers on this machine the frames take another way.
+ let (gpu, target) =
+ VideoToolboxFrameTarget::new(backend, &input, encoder.width, encoder.height).ok()?;
+ super::trial_frame(Box::new(target), gpu).ok()?;
+
+ Some(input)
+}
+
+/// Releases the pixel buffer of a frame once libav and the encoder are done with it.
+unsafe extern "C" fn release_pixel_buffer(_opaque: *mut c_void, data: *mut u8) {
+ unsafe { CVPixelBufferRelease(data.cast()) }
+}
+
+/// The Metal texture that views a pixel buffer.
+struct MetalTexture(CVMetalTextureRef);
+
+impl Drop for MetalTexture {
+ fn drop(&mut self) {
+ unsafe { CFRelease(self.0.cast_const()) }
+ }
+}
+
+/// The pixel buffer a frame is being drawn into.
+struct CurrentFrame {
+ // dropped before the texture it wraps
+ surface: Surface,
+ texture: MetalTexture,
+ frame: VideoFrame,
+}
+
+/// Renders frames into pixel buffers the encoder takes, see the module docs.
+pub(crate) struct VideoToolboxFrameTarget {
+ current: Option<CurrentFrame>,
+ pixel_buffers: CVPixelBufferPoolRef,
+ texture_cache: CVMetalTextureCacheRef,
+ frames: AvBuffer,
+ width: i32,
+ height: i32,
+}
+
+impl VideoToolboxFrameTarget {
+ pub(crate) fn new(
+ backend: &SkiaMetalCtx,
+ input: &EncoderInput,
+ width: i32,
+ height: i32,
+ ) -> FFramesRendererResult<(DirectContext, Self)> {
+ let Some(frames) = &input.hw_frames_ctx else {
+ return Err(skia_error(
+ "VideoToolbox frames need a hardware frames context",
+ ));
+ };
+ if input.software_format() != AVPixelFormat::AV_PIX_FMT_BGRA {
+ return Err(skia_error("only BGRA VideoToolbox frames are supported"));
+ }
+
+ let gpu = backend.create_context()?;
+ let key = |key: CFStringRef| unsafe { CFString::wrap_under_get_rule(key) };
+
+ // IOSurface backed buffers Metal can render into.
+ let buffer_attributes = unsafe {
+ CFDictionary::from_CFType_pairs(&[
+ (
+ key(kCVPixelBufferPixelFormatTypeKey),
+ CFNumber::from(CV_PIXEL_FORMAT_32_BGRA).as_CFType(),
+ ),
+ (
+ key(kCVPixelBufferWidthKey),
+ CFNumber::from(width).as_CFType(),
+ ),
+ (
+ key(kCVPixelBufferHeightKey),
+ CFNumber::from(height).as_CFType(),
+ ),
+ (
+ key(kCVPixelBufferIOSurfacePropertiesKey),
+ CFDictionary::<CFString, CFType>::from_CFType_pairs(&[]).as_CFType(),
+ ),
+ (
+ key(kCVPixelBufferMetalCompatibilityKey),
+ CFBoolean::true_value().as_CFType(),
+ ),
+ ])
+ };
+ let mut pixel_buffers = std::ptr::null_mut();
+ let status = unsafe {
+ CVPixelBufferPoolCreate(
+ std::ptr::null(),
+ std::ptr::null(),
+ buffer_attributes.as_concrete_TypeRef(),
+ &raw mut pixel_buffers,
+ )
+ };
+ if status != 0 || pixel_buffers.is_null() {
+ return Err(skia_error(format!(
+ "can not create a pixel buffer pool (CVReturn {status})"
+ )));
+ }
+
+ // Textures of the cache are only readable by default.
+ let texture_attributes = unsafe {
+ CFDictionary::from_CFType_pairs(&[(
+ key(kCVMetalTextureUsage),
+ CFNumber::from(MTL_TEXTURE_USAGE_RENDER_TARGET),
+ )])
+ };
+ let mut texture_cache = std::ptr::null_mut();
+ let status = unsafe {
+ CVMetalTextureCacheCreate(
+ std::ptr::null(),
+ std::ptr::null(),
+ backend.device_ptr(),
+ texture_attributes.as_concrete_TypeRef(),
+ &raw mut texture_cache,
+ )
+ };
+ if status != 0 || texture_cache.is_null() {
+ unsafe { CFRelease(pixel_buffers.cast_const()) };
+ return Err(skia_error(format!(
+ "can not create a Metal texture cache (CVReturn {status})"
+ )));
+ }
+
+ Ok((
+ gpu,
+ Self {
+ current: None,
+ pixel_buffers,
+ texture_cache,
+ frames: frames.clone(),
+ width,
+ height,
+ },
+ ))
+ }
+
+ /// A frame with a pixel buffer nobody uses: the pool does not recycle buffers the
+ /// encoder still reads.
+ fn new_frame(&self) -> FFramesRendererResult<(VideoFrame, CVPixelBufferRef)> {
+ let frame = VideoFrame::empty().map_err(|err| FFramesRendererError::from_chunk(0, err))?;
+
+ unsafe {
+ let mut pixel_buffer = std::ptr::null_mut();
+ let status = CVPixelBufferPoolCreatePixelBuffer(
+ std::ptr::null(),
+ self.pixel_buffers,
+ &raw mut pixel_buffer,
+ );
+ if status != 0 || pixel_buffer.is_null() {
+ return Err(skia_error(format!(
+ "can not allocate a pixel buffer (CVReturn {status})"
+ )));
+ }
+
+ // FFmpeg passes hardware pixel buffers through unchanged. The session's
+ // YCbCrMatrix property tags the stream, but does not choose the RGB input
+ // conversion matrix without this attachment. Match the BT.601 stream tag
+ // and the software/GPU YUV converters instead of VideoToolbox's HD default.
+ CVBufferSetAttachment(
+ pixel_buffer,
+ kCVImageBufferYCbCrMatrixKey,
+ kCVImageBufferYCbCrMatrix_ITU_R_601_4.cast(),
+ 1, // kCVAttachmentMode_ShouldPropagate
+ );
+
+ // What libav's own VideoToolbox frames look like: the pixel buffer in
+ // `data[3]`, kept alive by `buf[0]`.
+ let buffer = av_buffer_create(
+ pixel_buffer.cast(),
+ 1,
+ Some(release_pixel_buffer),
+ std::ptr::null_mut(),
+ 0,
+ );
+ if buffer.is_null() {
+ CVPixelBufferRelease(pixel_buffer);
+ return Err(skia_error("can not allocate a frame buffer"));
+ }
+
+ let raw = &mut *frame.as_ptr();
+ raw.buf[0] = buffer;
+ raw.data[3] = pixel_buffer.cast();
+ raw.format = AVPixelFormat::AV_PIX_FMT_VIDEOTOOLBOX as i32;
+ raw.width = self.width;
+ raw.height = self.height;
+ raw.hw_frames_ctx = self.frames.new_ref();
+
+ Ok((frame, pixel_buffer))
+ }
+ }
+}
+
+impl VideoToolboxFrameTarget {
+ /// Gives up a frame that was begun but never finished. What Skia recorded for it is
+ /// executed first, the texture of the frame can not be released before that.
+ fn abandon_frame(&mut self, gpu: &mut DirectContext) {
+ if self.current.is_some() {
+ gpu.flush_submit_and_sync_cpu();
+ self.current = None;
+ }
+ }
+}
+
+impl HardwareFrameTarget for VideoToolboxFrameTarget {
+ fn begin_frame(&mut self, gpu: &mut DirectContext) -> FFramesRendererResult<&mut Surface> {
+ self.abandon_frame(gpu);
+ let (frame, pixel_buffer) = self.new_frame()?;
+
+ let (texture, surface) = unsafe {
+ let mut texture = std::ptr::null_mut();
+ let status = CVMetalTextureCacheCreateTextureFromImage(
+ std::ptr::null(),
+ self.texture_cache,
+ pixel_buffer,
+ std::ptr::null(),
+ MTL_PIXEL_FORMAT_BGRA8_UNORM,
+ self.width as usize,
+ self.height as usize,
+ 0,
+ &raw mut texture,
+ );
+ if status != 0 || texture.is_null() {
+ return Err(skia_error(format!(
+ "can not map a pixel buffer into Metal (CVReturn {status})"
+ )));
+ }
+ let texture = MetalTexture(texture);
+
+ let texture_info =
+ mtl::TextureInfo::new(CVMetalTextureGetTexture(texture.0).cast_const());
+ let render_target =
+ backend_render_targets::make_mtl((self.width, self.height), &texture_info);
+ let surface = gpu::surfaces::wrap_backend_render_target(
+ gpu,
+ &render_target,
+ SurfaceOrigin::TopLeft,
+ ColorType::BGRA8888,
+ None,
+ None,
+ )
+ .ok_or_else(|| skia_error("can not render into a pixel buffer"))?;
+
+ (texture, surface)
+ };
+
+ let current = self.current.insert(CurrentFrame {
+ surface,
+ texture,
+ frame,
+ });
+ Ok(&mut current.surface)
+ }
+
+ fn retire(self: Box<Self>, gpu: DirectContext) {
+ self.retire_with(gpu);
+ }
+
+ fn finish_frame(&mut self, gpu: &mut DirectContext) -> FFramesRendererResult<VideoFrame> {
+ let CurrentFrame {
+ surface,
+ texture,
+ frame,
+ } = self
+ .current
+ .take()
+ .ok_or_else(|| skia_error("finish_frame without begin_frame"))?;
+
+ // The encoder reads the pixel buffer as soon as it gets the frame, the GPU has to
+ // be done with it by then.
+ gpu.flush_submit_and_sync_cpu();
+
+ drop(surface);
+ drop(texture);
+ unsafe { CVMetalTextureCacheFlush(self.texture_cache, 0) };
+
+ Ok(frame)
+ }
+}
+
+impl VideoToolboxFrameTarget {
+ /// See [`HardwareFrameTarget::retire`].
+ fn retire_with(mut self: Box<Self>, mut gpu: DirectContext) {
+ self.abandon_frame(&mut gpu);
+ drop(self);
+ drop(gpu);
+ }
+}
+
+impl Drop for VideoToolboxFrameTarget {
+ fn drop(&mut self) {
+ self.current = None;
+ unsafe {
+ CFRelease(self.texture_cache.cast_const());
+ CFRelease(self.pixel_buffers.cast_const());
+ }
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_export/vulkan_frames.rs b/fframes-skia-renderer/src/frame_export/vulkan_frames.rs
new file mode 100644
index 00000000..cba19e67
--- /dev/null
+++ b/fframes-skia-renderer/src/frame_export/vulkan_frames.rs
@@ -0,0 +1,589 @@
+use super::planes::Channel;
+use crate::HardwareFrameTarget;
+use crate::vulkan::SkiaVulkanCtx;
+use ash::vk::{self, Handle};
+use fframes::ffmpeg_sys_fframes::{
+ AVHWDeviceContext, AVHWFramesContext, AVPixelFormat, AVVkFrame, AVVulkanDeviceContext,
+ AVVulkanFramesContext,
+};
+use fframes::{
+ AvBuffer, EncoderInput, FFramesRendererError, FFramesRendererResult, VideoEncoderInfo,
+ VideoFrame,
+};
+use skia_safe::gpu::{self, DirectContext};
+use skia_safe::runtime_effect::ChildPtr;
+use skia_safe::{
+ AlphaType, BlendMode, ColorType, FilterMode, ImageInfo, MipmapMode, Paint, RuntimeEffect,
+ SamplingOptions, Surface, TileMode,
+};
+
+/// Copies that may be in flight on the GPU before the rendering thread waits for the oldest.
+const IN_FLIGHT_COPIES: usize = 4;
+
+const PLANE_SHADER: &str = "
+uniform shader frame;
+// frame pixels per sample of the plane
+uniform float2 subsampling;
+uniform float4 firstWeights;
+uniform float4 secondWeights;
+uniform float2 offsets;
+
+half4 main(float2 coord) {
+ // The center of a subsampled sample is the corner between the frame pixels it covers,
+ // where bilinear filtering returns their average.
+ float4 color = float4(frame.eval(coord * subsampling));
+ return half4(float4(
+ dot(color, firstWeights) + offsets.x,
+ dot(color, secondWeights) + offsets.y,
+ 0.0,
+ 1.0));
+}
+";
+
+fn skia_error(message: &str) -> FFramesRendererError {
+ FFramesRendererError::Skia(message.to_owned())
+}
+
+fn vulkan_error(what: &str, result: vk::Result) -> FFramesRendererError {
+ FFramesRendererError::Skia(format!("{what}: {result}"))
+}
+
+/// Offers NV12 Vulkan frames to encoders that take them, when the device is shared.
+pub(crate) fn negotiate(
+ backend: &SkiaVulkanCtx,
+ encoder: &VideoEncoderInfo<'_>,
+) -> Option<EncoderInput> {
+ let device = backend.encoder_device()?;
+ if !super::accepts_hardware_frames(encoder, AVPixelFormat::AV_PIX_FMT_VULKAN) {
+ return None;
+ }
+
+ // libav adds the usage flags the encoder needs to the images of the pool.
+ let input = EncoderInput::hardware_frames(
+ device,
+ AVPixelFormat::AV_PIX_FMT_VULKAN,
+ AVPixelFormat::AV_PIX_FMT_NV12,
+ (encoder.width, encoder.height),
+ |_| {},
+ )
+ .ok()?;
+
+ // Draw a frame the way the render will, so a device that can not do it is found out
+ // before the render depends on it.
+ let (gpu, target) =
+ VulkanFrameTarget::new(backend, &input, encoder.width, encoder.height).ok()?;
+ super::trial_frame(Box::new(target), gpu).ok()?;
+
+ Some(input)
+}
+
+/// A plane of the converted frame: the surface the shader draws it into and the image
+/// behind that surface.
+struct Plane {
+ surface: Surface,
+ image: vk::Image,
+ extent: vk::Extent3D,
+ channels: (Channel, Option<Channel>),
+ subsampling: f32,
+}
+
+impl Plane {
+ fn new(
+ gpu: &mut DirectContext,
+ color_type: ColorType,
+ (width, height): (i32, i32),
+ channels: (Channel, Option<Channel>),
+ subsampling: f32,
+ ) -> FFramesRendererResult<Self> {
+ let mut surface = gpu::surfaces::render_target(
+ gpu,
+ gpu::Budgeted::Yes,
+ &ImageInfo::new((width, height), color_type, AlphaType::Premul, None),
+ None,
+ gpu::SurfaceOrigin::TopLeft,
+ None,
+ false,
+ None,
+ )
+ .ok_or_else(|| skia_error("can not create a GPU surface for a plane of the frame"))?;
+
+ let image = crate::backends::vulkan_readback::backing_image(&mut surface)
+ .ok_or_else(|| skia_error("a plane surface has no Vulkan image"))?;
+
+ Ok(Self {
+ surface,
+ image,
+ extent: vk::Extent3D {
+ width: width as u32,
+ height: height as u32,
+ depth: 1,
+ },
+ channels,
+ subsampling,
+ })
+ }
+
+ fn draw(
+ &mut self,
+ effect: &RuntimeEffect,
+ frame: &skia_safe::Image,
+ ) -> FFramesRendererResult<()> {
+ let filter = if self.subsampling > 1. {
+ FilterMode::Linear
+ } else {
+ FilterMode::Nearest
+ };
+ let frame = frame
+ .to_shader(
+ (TileMode::Clamp, TileMode::Clamp),
+ SamplingOptions::new(filter, MipmapMode::None),
+ None,
+ )
+ .ok_or_else(|| skia_error("can not sample the rendered frame"))?;
+
+ let (first_weights, first_offset) = self.channels.0.weights();
+ let (second_weights, second_offset) =
+ self.channels.1.map_or(([0.; 4], 0.), Channel::weights);
+ let uniforms = super::pack_uniforms(
+ effect,
+ &[
+ ("subsampling", &[self.subsampling, self.subsampling]),
+ ("firstWeights", &first_weights),
+ ("secondWeights", &second_weights),
+ ("offsets", &[first_offset, second_offset]),
+ ],
+ )?;
+ let shader = effect
+ .make_shader(uniforms, &[ChildPtr::Shader(frame)], None)
+ .ok_or_else(|| skia_error("can not instantiate the plane shader"))?;
+
+ let mut paint = Paint::default();
+ paint.set_shader(shader);
+ paint.set_blend_mode(BlendMode::Src);
+ self.surface.canvas().draw_paint(&paint);
+ Ok(())
+ }
+}
+
+/// The lock of the queue a GPU context submits to. `FFmpeg` uses the queues of the shared
+/// device too and guards them with these locks, so everything Skia or we submit to the
+/// queue has to hold it.
+#[derive(Clone)]
+struct SharedQueueLock {
+ /// The lock other Skia contexts on the same queue take.
+ backend_lock: crate::QueueLock,
+ encoder_device: AvBuffer,
+ queue_family_index: u32,
+ queue_index: u32,
+}
+
+impl SharedQueueLock {
+ /// Runs `submit` while no other thread submits to the queue.
+ fn locked<T>(&self, submit: impl FnOnce() -> T) -> T {
+ let _backend = crate::lock_queue(Some(&self.backend_lock));
+ unsafe {
+ let device = self.encoder_device.data::<AVHWDeviceContext>();
+ let hwctx = &*(*device).hwctx.cast::<AVVulkanDeviceContext>();
+
+ if let Some(lock) = hwctx.lock_queue {
+ lock(device, self.queue_family_index, self.queue_index);
+ }
+ let result = submit();
+ if let Some(unlock) = hwctx.unlock_queue {
+ unlock(device, self.queue_family_index, self.queue_index);
+ }
+ result
+ }
+ }
+}
+
+/// A command buffer for one copy and the fence that tells when the GPU is done with it.
+struct CopySlot {
+ commands: vk::CommandBuffer,
+ fence: vk::Fence,
+ in_flight: bool,
+}
+
+/// Renders frames into the Vulkan images of the encoder's frame pool, see the module docs.
+pub(crate) struct VulkanFrameTarget {
+ scene: Surface,
+ luma: Plane,
+ chroma: Plane,
+ effect: RuntimeEffect,
+ device: ash::Device,
+ queue: vk::Queue,
+ queue_lock: SharedQueueLock,
+ command_pool: vk::CommandPool,
+ slots: Vec<CopySlot>,
+ next_slot: usize,
+ frames: AvBuffer,
+}
+
+impl VulkanFrameTarget {
+ pub(crate) fn new(
+ backend: &SkiaVulkanCtx,
+ input: &EncoderInput,
+ width: i32,
+ height: i32,
+ ) -> FFramesRendererResult<(DirectContext, Self)> {
+ let (Some(encoder_device), Some(frames)) = (backend.encoder_device(), &input.hw_frames_ctx)
+ else {
+ return Err(skia_error(
+ "Vulkan frames need a device shared with FFmpeg (SkiaVulkanCtx::new_shared_with_encoder)",
+ ));
+ };
+ if input.software_format() != AVPixelFormat::AV_PIX_FMT_NV12 {
+ return Err(skia_error("only NV12 Vulkan frames are supported"));
+ }
+ if width % 2 != 0 || height % 2 != 0 {
+ return Err(skia_error(
+ "NV12 Vulkan frames need an even width and height",
+ ));
+ }
+
+ let context = backend.create_context()?;
+ let mut gpu = context.gpu;
+
+ let scene = gpu::surfaces::render_target(
+ &mut gpu,
+ gpu::Budgeted::Yes,
+ &ImageInfo::new(
+ (width, height),
+ ColorType::RGBA8888,
+ AlphaType::Premul,
+ None,
+ ),
+ None,
+ gpu::SurfaceOrigin::TopLeft,
+ None,
+ false,
+ None,
+ )
+ .ok_or_else(|| skia_error("can not create the GPU surface for the frame"))?;
+ let luma = Plane::new(
+ &mut gpu,
+ ColorType::R8UNorm,
+ (width, height),
+ (Channel::Y, None),
+ 1.,
+ )?;
+ let chroma = Plane::new(
+ &mut gpu,
+ ColorType::R8G8UNorm,
+ (width / 2, height / 2),
+ (Channel::U, Some(Channel::V)),
+ 2.,
+ )?;
+ let effect = RuntimeEffect::make_for_shader(PLANE_SHADER, None)
+ .map_err(|err| FFramesRendererError::Skia(format!("plane shader: {err}")))?;
+
+ let device = backend.device().clone();
+ let queue_family_index = backend.queue_family_index();
+ let (command_pool, slots) = unsafe {
+ let command_pool = device
+ .create_command_pool(
+ &vk::CommandPoolCreateInfo::default()
+ .queue_family_index(queue_family_index)
+ .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER),
+ None,
+ )
+ .map_err(|err| vulkan_error("can not create a command pool", err))?;
+
+ let mut slots = Vec::with_capacity(IN_FLIGHT_COPIES);
+ let allocated = device
+ .allocate_command_buffers(
+ &vk::CommandBufferAllocateInfo::default()
+ .command_pool(command_pool)
+ .level(vk::CommandBufferLevel::PRIMARY)
+ .command_buffer_count(IN_FLIGHT_COPIES as u32),
+ )
+ .and_then(|buffers| {
+ for commands in buffers {
+ slots.push(CopySlot {
+ commands,
+ fence: device.create_fence(&vk::FenceCreateInfo::default(), None)?,
+ in_flight: false,
+ });
+ }
+ Ok(())
+ });
+
+ if let Err(err) = allocated {
+ for slot in &slots {
+ device.destroy_fence(slot.fence, None);
+ }
+ device.destroy_command_pool(command_pool, None);
+ return Err(vulkan_error("can not allocate command buffers", err));
+ }
+ (command_pool, slots)
+ };
+
+ Ok((
+ gpu,
+ Self {
+ scene,
+ luma,
+ chroma,
+ effect,
+ device,
+ queue: context.queue,
+ queue_lock: SharedQueueLock {
+ backend_lock: context.queue_lock,
+ encoder_device: encoder_device.clone(),
+ queue_family_index,
+ queue_index: context.queue_index,
+ },
+ command_pool,
+ slots,
+ next_slot: 0,
+ frames: frames.clone(),
+ },
+ ))
+ }
+
+ /// Waits until the copies that are still running on the GPU are done.
+ fn wait_for_copies(&mut self) {
+ for slot in &mut self.slots {
+ if std::mem::take(&mut slot.in_flight) {
+ unsafe {
+ let _ = self.device.wait_for_fences(&[slot.fence], true, u64::MAX);
+ }
+ }
+ }
+ }
+
+ /// Copies the converted planes into the images of `frame` and hands the images over to
+ /// the next user of the frame (the encoder), the way libav's own Vulkan code does.
+ // `data[0]` of a Vulkan frame is the `AVVkFrame` libav allocated.
+ #[allow(clippy::cast_ptr_alignment)]
+ unsafe fn copy_planes(&mut self, frame: &VideoFrame) -> FFramesRendererResult<()> {
+ unsafe {
+ let frames_context = self.frames.data::<AVHWFramesContext>();
+ let frames_hwctx = &*(*frames_context).hwctx.cast::<AVVulkanFramesContext>();
+ let vk_frame = (*frame.as_ptr()).data[0].cast::<AVVkFrame>();
+ if vk_frame.is_null() {
+ return Err(skia_error("the hardware frame has no Vulkan image"));
+ }
+
+ let slot_index = self.next_slot;
+ self.next_slot = (self.next_slot + 1) % self.slots.len();
+ let slot = &mut self.slots[slot_index];
+ if std::mem::take(&mut slot.in_flight) {
+ self.device
+ .wait_for_fences(&[slot.fence], true, u64::MAX)
+ .map_err(|err| vulkan_error("waiting for a frame copy failed", err))?;
+ }
+ self.device
+ .reset_fences(&[slot.fence])
+ .and_then(|()| {
+ self.device
+ .reset_command_buffer(slot.commands, vk::CommandBufferResetFlags::empty())
+ })
+ .map_err(|err| vulkan_error("can not reuse a command buffer", err))?;
+ let (commands, fence) = (slot.commands, slot.fence);
+
+ if let Some(lock) = frames_hwctx.lock_frame {
+ lock(frames_context, vk_frame);
+ }
+ let result = self.submit_copy(vk_frame, commands, fence);
+ if let Some(unlock) = frames_hwctx.unlock_frame {
+ unlock(frames_context, vk_frame);
+ }
+ result?;
+
+ self.slots[slot_index].in_flight = true;
+ Ok(())
+ }
+ }
+
+ /// Records and submits the copy. The frame has to be locked.
+ unsafe fn submit_copy(
+ &self,
+ vk_frame: *mut AVVkFrame,
+ commands: vk::CommandBuffer,
+ fence: vk::Fence,
+ ) -> FFramesRendererResult<()> {
+ unsafe {
+ let frame = &mut *vk_frame;
+ // NV12 is one image with two planes, or an image per plane on devices
+ // without multiplanar formats.
+ let images = frame.img.iter().take_while(|image| **image != 0).count();
+ if images == 0 || images > 2 {
+ return Err(skia_error("unexpected image layout of the hardware frame"));
+ }
+ let image = |index: usize| vk::Image::from_raw(frame.img[index]);
+ let (luma_target, chroma_target) = if images == 1 {
+ (
+ (image(0), vk::ImageAspectFlags::PLANE_0),
+ (image(0), vk::ImageAspectFlags::PLANE_1),
+ )
+ } else {
+ (
+ (image(0), vk::ImageAspectFlags::COLOR),
+ (image(1), vk::ImageAspectFlags::COLOR),
+ )
+ };
+
+ let device = &self.device;
+ let record = || -> Result<(), vk::Result> {
+ device.begin_command_buffer(
+ commands,
+ &vk::CommandBufferBeginInfo::default()
+ .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
+ )?;
+
+ // Every byte of the images is overwritten, so their old content (and
+ // layout) does not matter.
+ let barriers: Vec<_> = (0..images)
+ .map(|index| {
+ vk::ImageMemoryBarrier2::default()
+ .src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
+ .src_access_mask(vk::AccessFlags2::NONE)
+ .dst_stage_mask(vk::PipelineStageFlags2::ALL_TRANSFER)
+ .dst_access_mask(vk::AccessFlags2::TRANSFER_WRITE)
+ .old_layout(vk::ImageLayout::UNDEFINED)
+ .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
+ .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
+ .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
+ .image(image(index))
+ .subresource_range(vk::ImageSubresourceRange {
+ aspect_mask: vk::ImageAspectFlags::COLOR,
+ base_mip_level: 0,
+ level_count: 1,
+ base_array_layer: 0,
+ layer_count: 1,
+ })
+ })
+ .collect();
+ device.cmd_pipeline_barrier2(
+ commands,
+ &vk::DependencyInfo::default().image_memory_barriers(&barriers),
+ );
+
+ for (plane, (target, aspect)) in
+ [(&self.luma, luma_target), (&self.chroma, chroma_target)]
+ {
+ let layers = |aspect_mask| vk::ImageSubresourceLayers {
+ aspect_mask,
+ mip_level: 0,
+ base_array_layer: 0,
+ layer_count: 1,
+ };
+ device.cmd_copy_image(
+ commands,
+ plane.image,
+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
+ target,
+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
+ &[vk::ImageCopy {
+ src_subresource: layers(vk::ImageAspectFlags::COLOR),
+ src_offset: vk::Offset3D::default(),
+ dst_subresource: layers(aspect),
+ dst_offset: vk::Offset3D::default(),
+ extent: plane.extent,
+ }],
+ );
+ }
+
+ device.end_command_buffer(commands)
+ };
+ record().map_err(|err| vulkan_error("can not record the frame copy", err))?;
+
+ // The timeline semaphore of an image orders its users: wait for the previous
+ // one, signal the next value for the one after us.
+ let semaphore = |index: usize, value: u64| {
+ vk::SemaphoreSubmitInfo::default()
+ .semaphore(vk::Semaphore::from_raw(frame.sem[index]))
+ .value(value)
+ .stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
+ };
+ let waits: Vec<_> = (0..images)
+ .map(|index| semaphore(index, frame.sem_value[index]))
+ .collect();
+ let signals: Vec<_> = (0..images)
+ .map(|index| semaphore(index, frame.sem_value[index] + 1))
+ .collect();
+ let command_infos = [vk::CommandBufferSubmitInfo::default().command_buffer(commands)];
+ let submit = vk::SubmitInfo2::default()
+ .wait_semaphore_infos(&waits)
+ .command_buffer_infos(&command_infos)
+ .signal_semaphore_infos(&signals);
+
+ self.queue_lock
+ .locked(|| device.queue_submit2(self.queue, &[submit], fence))
+ .map_err(|err| vulkan_error("can not submit the frame copy", err))?;
+
+ for index in 0..images {
+ frame.sem_value[index] += 1;
+ frame.layout[index] = vk::ImageLayout::TRANSFER_DST_OPTIMAL.as_raw();
+ frame.access[index] = vk::AccessFlags2::TRANSFER_WRITE.as_raw();
+ }
+
+ Ok(())
+ }
+ }
+}
+
+impl HardwareFrameTarget for VulkanFrameTarget {
+ fn begin_frame(&mut self, _gpu: &mut DirectContext) -> FFramesRendererResult<&mut Surface> {
+ Ok(&mut self.scene)
+ }
+
+ fn retire(self: Box<Self>, gpu: DirectContext) {
+ self.retire_with(gpu);
+ }
+
+ fn finish_frame(&mut self, gpu: &mut DirectContext) -> FFramesRendererResult<VideoFrame> {
+ let frame = self.scene.image_snapshot();
+ self.luma.draw(&self.effect, &frame)?;
+ self.chroma.draw(&self.effect, &frame)?;
+ drop(frame);
+
+ // Skia leaves the planes ready to be copied from. Flushing them flushes the frame
+ // they sample too.
+ let copy_source = gpu::vk::mutable_texture_states::new_vulkan(
+ gpu::vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
+ vk::QUEUE_FAMILY_IGNORED,
+ );
+ for plane in [&mut self.luma, &mut self.chroma] {
+ gpu.flush_surface_with_texture_state(
+ &mut plane.surface,
+ &gpu::FlushInfo::default(),
+ Some(&copy_source),
+ );
+ }
+ if !self.queue_lock.locked(|| gpu.submit(gpu::SyncCpu::No)) {
+ return Err(skia_error("can not submit the frame to the GPU"));
+ }
+
+ let frame = VideoFrame::from_hw_frames(&self.frames)
+ .map_err(|err| FFramesRendererError::from_chunk(0, err))?;
+ // Goes to the queue Skia submitted the draws to, so the copy runs after them.
+ unsafe { self.copy_planes(&frame)? };
+
+ Ok(frame)
+ }
+}
+
+impl VulkanFrameTarget {
+ /// See [`HardwareFrameTarget::retire`].
+ fn retire_with(mut self: Box<Self>, gpu: DirectContext) {
+ self.wait_for_copies();
+ let queue_lock = self.queue_lock.clone();
+ drop(self);
+ // destroying the context waits for its queue
+ queue_lock.locked(|| drop(gpu));
+ }
+}
+
+impl Drop for VulkanFrameTarget {
+ fn drop(&mut self) {
+ self.wait_for_copies();
+ unsafe {
+ for slot in &self.slots {
+ self.device.destroy_fence(slot.fence, None);
+ }
+ self.device.destroy_command_pool(self.command_pool, None);
+ }
+ }
+}
diff --git a/fframes-skia-renderer/src/frame_renderer.rs b/fframes-skia-renderer/src/frame_renderer.rs
index 1e8c9c3f..f8deceb3 100644
--- a/fframes-skia-renderer/src/frame_renderer.rs
+++ b/fframes-skia-renderer/src/frame_renderer.rs
@@ -1,4 +1,4 @@
-use crate::SkiaBackend;
+use crate::{SkiaBackend, SkiaContext, lock_queue};
use fframes::{
Color, FFramesRendererError, FFramesRendererResult, FrameRenderer, RgbaFrame, usvgr,
};
@@ -11,9 +11,20 @@ pub fn surface_with_size<TBackend: SkiaBackend + ?Sized>(
width: i32,
height: i32,
) -> FFramesRendererResult<(Surface, Option<gpu::DirectContext>)> {
- let (surface, mut gpu_context) = backend.create_skia_surface()?;
- if surface.width() == width && surface.height() == height {
- return Ok((surface, gpu_context));
+ let context = context_with_size(backend, width, height)?;
+ Ok((context.surface, context.gpu))
+}
+
+/// [`surface_with_size`] with everything else of the new context, see
+/// [`SkiaBackend::create_skia_context`].
+pub fn context_with_size<TBackend: SkiaBackend + ?Sized>(
+ backend: &TBackend,
+ width: i32,
+ height: i32,
+) -> FFramesRendererResult<SkiaContext> {
+ let mut context = backend.create_skia_context()?;
+ if context.surface.width() == width && context.surface.height() == height {
+ return Ok(context);
}
let info = ImageInfo::new(
@@ -22,7 +33,7 @@ pub fn surface_with_size<TBackend: SkiaBackend + ?Sized>(
AlphaType::Premul,
None,
);
- let surface = match gpu_context.as_mut() {
+ context.surface = match context.gpu.as_mut() {
Some(gpu_context) => gpu::surfaces::render_target(
gpu_context,
gpu::Budgeted::Yes,
@@ -39,7 +50,7 @@ pub fn surface_with_size<TBackend: SkiaBackend + ?Sized>(
FFramesRendererError::Skia(format!("can not create a {width}x{height} surface"))
})?;
- Ok((surface, gpu_context))
+ Ok(context)
}
/// Scales the canvas so `tree` fills `width`x`height`, see `fframes::fit_transform`.
@@ -54,10 +65,36 @@ pub fn apply_fit(canvas: &Canvas, tree: &usvgr::Tree, width: i32, height: i32) {
/// GPU context and render cache between frames.
pub struct SkiaFrameRenderer<'a, TBackend: SkiaBackend> {
backend: &'a TBackend,
- surface: Option<(Surface, Option<gpu::DirectContext>)>,
+ surface: Option<SkiaContext>,
render_cache: crate::render::RenderCache,
}
+impl<TBackend: SkiaBackend> SkiaFrameRenderer<'_, TBackend> {
+ /// Drops the surface and its GPU context. Destroying a context waits for its queue.
+ fn release_surface(&mut self) {
+ if let Some(SkiaContext {
+ surface,
+ gpu,
+ queue_lock,
+ reader,
+ }) = self.surface.take()
+ {
+ // what lives on the context goes first
+ self.render_cache = crate::render::RenderCache::new();
+ drop(surface);
+ drop(reader);
+ let _queue = lock_queue(queue_lock.as_ref());
+ drop(gpu);
+ }
+ }
+}
+
+impl<TBackend: SkiaBackend> Drop for SkiaFrameRenderer<'_, TBackend> {
+ fn drop(&mut self) {
+ self.release_surface();
+ }
+}
+
impl<'a, TBackend: SkiaBackend> SkiaFrameRenderer<'a, TBackend> {
pub fn new(backend: &'a TBackend) -> Self {
Self {
@@ -77,10 +114,16 @@ impl<TBackend: SkiaBackend> FrameRenderer for SkiaFrameRenderer<'_, TBackend> {
height: u32,
) -> FFramesRendererResult<RgbaFrame> {
let (w, h) = (width as i32, height as i32);
- if !matches!(&self.surface, Some((s, _)) if s.width() == w && s.height() == h) {
- self.surface = Some(surface_with_size(self.backend, w, h)?);
+ if !matches!(&self.surface, Some(c) if c.surface.width() == w && c.surface.height() == h) {
+ self.release_surface();
+ self.surface = Some(context_with_size(self.backend, w, h)?);
}
- let (surface, gpu_context) = self.surface.as_mut().expect("surface was just created");
+ let SkiaContext {
+ surface,
+ gpu: gpu_context,
+ queue_lock,
+ ..
+ } = self.surface.as_mut().expect("surface was just created");
let canvas = surface.canvas();
canvas.clear(skia_safe::Color::from_argb(
@@ -94,6 +137,8 @@ impl<TBackend: SkiaBackend> FrameRenderer for SkiaFrameRenderer<'_, TBackend> {
crate::render::render_tree(tree, canvas, &mut self.render_cache);
canvas.restore();
+ // the flush and the readback submit to the queue of the context
+ let _queue = lock_queue(queue_lock.as_ref());
if let Some(gpu_context) = gpu_context.as_mut() {
gpu_context.flush_submit_and_sync_cpu();
}
diff --git a/fframes-skia-renderer/src/lib.rs b/fframes-skia-renderer/src/lib.rs
index 29dcb952..b01b0275 100644
--- a/fframes-skia-renderer/src/lib.rs
+++ b/fframes-skia-renderer/src/lib.rs
@@ -15,6 +15,11 @@ pub use instant_rendering::*;
mod frame_renderer;
pub use frame_renderer::*;
+mod frame_export;
+pub use frame_export::{
+ FrameExportPath, HardwareFrameTarget, SkiaEncoderFrameRenderer, SkiaFrameExport,
+};
+
pub mod render;
#[cfg(feature = "debug")]
diff --git a/fframes-skia-renderer/src/skia_backend.rs b/fframes-skia-renderer/src/skia_backend.rs
index a3d84692..58f8045c 100644
--- a/fframes-skia-renderer/src/skia_backend.rs
+++ b/fframes-skia-renderer/src/skia_backend.rs
@@ -4,13 +4,18 @@ use crate::backends::SkiaBackend;
use crate::skia_pipeline;
use crate::skia_pipeline::Pipeline;
pub use crate::skia_pipeline::{SkiaPipelineConcurrencyPolicy, SkiaPipelineConfig};
+use crate::{SkiaEncoderFrameRenderer, SkiaFrameExport};
use fframes::{AudioTimelineSamples, FrameRenderer, ResolvedRenderingTimeline, Video, usvgr};
-use fframes::{FFramesRenderBackend, FFramesRendererResult};
+use fframes::{
+ EncoderFrameRenderer, EncoderInput, FFramesRenderBackend, FFramesRendererResult,
+ RenderEncodingResult, VideoEncoderInfo,
+};
#[derive(Clone)]
pub struct SkiaFFramesRenderer<'a, T: SkiaBackend + Sync + Send> {
pub(crate) pipeline_config: SkiaPipelineConfig,
pub(crate) backend: &'a T,
+ pub(crate) frame_export: SkiaFrameExport,
}
impl<'a, TSkiaBackend: SkiaBackend> SkiaFFramesRenderer<'a, TSkiaBackend> {
@@ -25,14 +30,38 @@ impl<'a, TSkiaBackend: SkiaBackend> SkiaFFramesRenderer<'a, TSkiaBackend> {
Self {
pipeline_config,
backend: skia_backend_context,
+ frame_export: SkiaFrameExport::default(),
}
}
+
+ /// 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 {
+ self.frame_export = frame_export;
+ self
+ }
}
impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBackend> {
/// Skia previews on the same GPU context: shaders and filters look like in the video.
- fn frame_renderer(&self) -> Option<Box<dyn FrameRenderer + '_>> {
- Some(Box::new(crate::SkiaFrameRenderer::new(self.backend)))
+ fn frame_renderer(&self) -> Option<impl FrameRenderer + '_> {
+ Some(crate::SkiaFrameRenderer::new(self.backend))
+ }
+
+ fn negotiate_encoder_input(
+ &self,
+ encoder: &VideoEncoderInfo<'_>,
+ ) -> RenderEncodingResult<EncoderInput> {
+ crate::frame_export::negotiate(self.backend, self.frame_export, encoder)
+ }
+
+ fn encoder_frame_renderer(
+ &self,
+ input: &EncoderInput,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<impl EncoderFrameRenderer + '_> {
+ SkiaEncoderFrameRenderer::new(self.backend, self.frame_export, input, width, height)
}
fn render_frame<'a, 'media: 'a, TVideo: Video + Sync + Sized>(
@@ -88,6 +117,7 @@ impl<TBackend: SkiaBackend> FFramesRenderBackend for SkiaFFramesRenderer<'_, TBa
logger,
output: output.as_ref(),
pipeline_config: self.pipeline_config,
+ frame_export: self.frame_export,
render_options,
skia: self.backend,
timeline,
diff --git a/fframes-skia-renderer/src/skia_pipeline.rs b/fframes-skia-renderer/src/skia_pipeline.rs
index 8a98709f..635e86e1 100644
--- a/fframes-skia-renderer/src/skia_pipeline.rs
+++ b/fframes-skia-renderer/src/skia_pipeline.rs
@@ -1,4 +1,5 @@
-use crate::SkiaBackend;
+use crate::frame_export::Rendered;
+use crate::{SkiaBackend, SkiaEncoderFrameRenderer, SkiaFrameExport};
use fframes::get_thread_count;
use fframes::{
AudioTimelineSamples, FFramesContext, FrameClaim, FrameScheduler, RenderOptions,
@@ -64,6 +65,7 @@ pub(crate) struct Pipeline<'p, 'a, 'media, TVideo: Video + Sync + Send, TBackend
pub(crate) logger: Arc<dyn FFramesLogger>,
pub(crate) output: &'p Path,
pub(crate) pipeline_config: SkiaPipelineConfig,
+ pub(crate) frame_export: SkiaFrameExport,
pub(crate) skia: &'p TBackend,
pub(crate) timeline: &'a ResolvedRenderingTimeline<'a, AudioTimelineSamples>,
pub(crate) usvg_options: &'a usvgr::Options<'a>,
@@ -73,10 +75,11 @@ pub(crate) struct Pipeline<'p, 'a, 'media, TVideo: Video + Sync + Send, TBackend
struct RenderedFrame {
claim: FrameClaim,
- pixels: Vec<u8>,
+ rendered: Rendered,
}
-/// Recycled frame buffers, a 1080p frame is 8MB and allocating it every frame is not free.
+/// Recycled RGBA buffers for frames that are converted on the CPU, a 1080p frame is 8MB and
+/// allocating it every frame is not free.
#[derive(Default)]
struct BufferPool(Mutex<Vec<Vec<u8>>>);
@@ -98,11 +101,15 @@ impl BufferPool {
/// Renders a video through three pools of threads connected by bounded queues:
///
/// ```text
-/// generators (Video::render_frame + usvgr tree) ──► GPU contexts (draw + readback)
+/// generators (Video::render_frame + usvgr tree) ──► GPU contexts (draw + export)
/// │
/// segment files ◄── SegmentWriter ◄── encoders ◄───┘
/// ```
///
+/// What leaves a GPU context depends on the negotiated encoder input:
+/// hardware frames the encoder reads on the GPU, YUV planes converted on the GPU, or RGBA
+/// the encoder threads convert.
+///
/// The [`FrameScheduler`] gives every generator a contiguous range of frames that is
/// encoded as a separate segment, the segments are concatenated with the audio at the end.
pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend: SkiaBackend>(
@@ -113,6 +120,7 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
logger,
output,
pipeline_config,
+ frame_export,
skia,
timeline,
usvg_options,
@@ -161,6 +169,11 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
render_options,
&logger,
);
+ let encoder_input = writer
+ .encoder_info()
+ .and_then(|encoder| crate::frame_export::negotiate(skia, frame_export, &encoder))
+ .map_err(|err| FFramesRendererError::RenderChunkError(0, err))?;
+ let writer = writer.with_encoder_input(encoder_input);
#[cfg(feature = "debug")]
let metrics = crate::metrics::PipelineMetrics::new(generators, gpu_contexts, workers);
@@ -169,8 +182,11 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
let buffers = BufferPool::default();
let (tree_sender, tree_receiver) = mpsc::sync_channel::<(FrameClaim, usvgr::Tree)>(queue_size);
let (frame_sender, frame_receiver) = mpsc::sync_channel::<RenderedFrame>(queue_size);
- let tree_receiver = Mutex::new(tree_receiver);
- let frame_receiver = Mutex::new(frame_receiver);
+ // Every stage owns its end of the queues, so a stage that stops (all of its threads
+ // failed or are done) closes them and the stages before and after it stop too instead
+ // of waiting on a queue nobody serves.
+ let tree_receiver = Arc::new(Mutex::new(tree_receiver));
+ let frame_receiver = Arc::new(Mutex::new(frame_receiver));
let results = thread::scope(|scope| {
let mark_failed = |result: FFramesRendererResult<()>| {
@@ -207,15 +223,17 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
for _ in 0..gpu_contexts {
let frame_sender = frame_sender.clone();
- let (tree_receiver, buffers, failed, logger) =
- (&tree_receiver, &buffers, &failed, &logger);
+ let tree_receiver = Arc::clone(&tree_receiver);
+ let (buffers, failed, logger, writer) = (&buffers, &failed, &logger, &writer);
#[cfg(feature = "debug")]
let metrics = metrics.renderer_metrics.clone();
handles.push(scope.spawn(move || {
mark_failed(render_frames(
skia,
+ frame_export,
+ writer.encoder_input(),
logger,
- tree_receiver,
+ &tree_receiver,
frame_sender,
buffers,
ctx,
@@ -227,15 +245,16 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
}));
}
drop(frame_sender);
+ drop(tree_receiver);
for _ in 0..scheduler.workers() {
- let (frame_receiver, buffers, failed, writer) =
- (&frame_receiver, &buffers, &failed, &writer);
+ let frame_receiver = Arc::clone(&frame_receiver);
+ let (buffers, failed, writer) = (&buffers, &failed, &writer);
#[cfg(feature = "debug")]
let metrics = metrics.encoder_metrics.clone();
handles.push(scope.spawn(move || {
mark_failed(encode_frames(
- frame_receiver,
+ &frame_receiver,
writer,
buffers,
failed,
@@ -245,6 +264,8 @@ pub(crate) fn render<'p, 'a, 'media: 'a, TVideo: Video + Sync + Send, TBackend:
}));
}
+ drop(frame_receiver);
+
handles
.into_iter()
.map(|handle| {
@@ -357,6 +378,8 @@ fn receive<T>(receiver: &Mutex<Receiver<T>>) -> Option<T> {
#[allow(clippy::too_many_arguments)]
fn render_frames<TBackend: SkiaBackend>(
backend: &TBackend,
+ frame_export: SkiaFrameExport,
+ encoder_input: &fframes::EncoderInput,
logger: &Arc<dyn FFramesLogger>,
tree_receiver: &Mutex<Receiver<(FrameClaim, usvgr::Tree)>>,
frame_sender: SyncSender<RenderedFrame>,
@@ -366,20 +389,15 @@ fn render_frames<TBackend: SkiaBackend>(
background_color: skia_safe::Color,
#[cfg(feature = "debug")] metrics: Arc<crate::metrics::ThreadMetrics>,
) -> FFramesRendererResult<()> {
- // Scaled renders (`scale_resolution`) need a surface of the output size, not the one the
- // backend was created with.
- let output_size = (
- ctx.current_video_size.width as i32,
- ctx.current_video_size.height as i32,
- );
- let (mut surface, mut gpu_context) =
- crate::surface_with_size(backend, output_size.0, output_size.1)?;
- let image_info = surface.image_info();
- let frame_size = image_info.compute_byte_size(image_info.min_row_bytes());
- let row_bytes = image_info.min_row_bytes();
-
- // Persist across frames so static paths/images are converted only once
- let mut render_cache = crate::render::RenderCache::new();
+ // Keeps the surfaces, the GPU context and the render cache (static paths and images are
+ // converted only once) across frames.
+ let mut renderer = SkiaEncoderFrameRenderer::new(
+ backend,
+ frame_export,
+ encoder_input,
+ ctx.current_video_size.width as u32,
+ ctx.current_video_size.height as u32,
+ )?;
while let Some((claim, tree)) = {
#[cfg(feature = "debug")]
@@ -404,35 +422,10 @@ fn render_frames<TBackend: SkiaBackend>(
#[cfg(feature = "debug")]
let start = Instant::now();
- let mut pixels = buffers.take(frame_size);
- let pixmap = skia_safe::Pixmap::new(&image_info, &mut pixels, row_bytes)
- .ok_or_else(|| FFramesRendererError::Custom("Failed to create pixmap".to_string()))?;
-
- let canvas = surface.canvas();
- canvas.clear(background_color);
- canvas.save();
- crate::apply_fit(canvas, &tree, output_size.0, output_size.1);
- crate::render::render_tree(&tree, canvas, &mut render_cache);
- canvas.restore();
-
- if let Some(gpu_context) = gpu_context.as_mut() {
- gpu_context.flush_submit_and_sync_cpu();
- }
-
- let image = surface.image_snapshot();
- if !image.read_pixels_to_pixmap_with_context(
- gpu_context.as_mut(),
- &pixmap,
- (0, 0),
- skia_safe::image::CachingHint::Allow,
- ) {
- return Err(FFramesRendererError::Custom(
- "Failed to read pixels from Skia image".to_string(),
- ));
- }
+ let rendered = renderer.render(&tree, background_color, |size| buffers.take(size))?;
// Video-frame images view the tree's pixel buffers without
- // copying, so the tree has to outlive the flush and readback.
+ // copying, so the tree has to outlive the flush inside `render`.
drop(tree);
logger.log_frame(claim.frame, 0);
@@ -445,7 +438,7 @@ fn render_frames<TBackend: SkiaBackend>(
}
frame_sender
- .send(RenderedFrame { claim, pixels })
+ .send(RenderedFrame { claim, rendered })
.map_err(|_| FFramesRendererError::Custom("Renderer channel closed".to_string()))?;
}
@@ -459,7 +452,7 @@ fn encode_frames(
failed: &AtomicBool,
#[cfg(feature = "debug")] metrics: Arc<crate::metrics::ThreadMetrics>,
) -> FFramesRendererResult<()> {
- while let Some(RenderedFrame { claim, pixels }) = {
+ while let Some(RenderedFrame { claim, rendered }) = {
#[cfg(feature = "debug")]
let wait_start = Instant::now();
let request = receive(frame_receiver);
@@ -476,10 +469,13 @@ fn encode_frames(
#[cfg(feature = "debug")]
let start = Instant::now();
- let released = writer
- .submit_owned(claim, pixels)
- .map_err(|err| FFramesRendererError::RenderChunkError(claim.segment, err))?;
- buffers.give_back(released);
+ match rendered {
+ Rendered::Frame(frame) => writer.submit_frame(claim, frame),
+ Rendered::Rgba(pixels) => writer
+ .submit_owned(claim, pixels)
+ .map(|released| buffers.give_back(released)),
+ }
+ .map_err(|err| FFramesRendererError::RenderChunkError(claim.segment, err))?;
#[cfg(feature = "debug")]
{
diff --git a/fframes-skia-renderer/tests/frame_export.rs b/fframes-skia-renderer/tests/frame_export.rs
new file mode 100644
index 00000000..30eb12b7
--- /dev/null
+++ b/fframes-skia-renderer/tests/frame_export.rs
@@ -0,0 +1,327 @@
+#![cfg(feature = "vulkan")]
+
+use fframes::ffmpeg_sys_fframes::AVPixelFormat::AV_PIX_FMT_YUV420P;
+use fframes::media::FFmpegDecoder;
+use fframes::{
+ AudioMap, Color, Duration, EncoderOptions, FFramesContext, Frame, RenderOptions, Svgr, Video,
+};
+use fframes_skia_renderer::vulkan::SkiaVulkanCtx;
+use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaFrameExport, SkiaPipelineConfig};
+
+const WIDTH: u32 = 322;
+const HEIGHT: u32 = 242;
+
+/// `None` on machines without a Vulkan device (the tests are skipped there).
+fn vulkan() -> Option<SkiaVulkanCtx> {
+ match SkiaVulkanCtx::new(WIDTH as usize, HEIGHT as usize) {
+ Ok(ctx) => Some(ctx),
+ Err(err) => {
+ eprintln!("skipping: no Vulkan device ({err:?})");
+ None
+ }
+ }
+}
+
+const FPS: usize = 10;
+const FRAMES: usize = 30;
+const SWITCH_AT: usize = FRAMES / 2;
+
+#[derive(Debug)]
+struct TwoColors;
+
+impl Video for TwoColors {
+ const FPS: usize = FPS;
+ const WIDTH: usize = WIDTH as usize;
+ const HEIGHT: usize = HEIGHT as usize;
+ 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 fill = if frame.index < SWITCH_AT {
+ "#ff0000"
+ } else {
+ "#0000ff"
+ };
+
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width={Self::WIDTH} height={Self::HEIGHT}>
+ <rect x="0" y="0" width={Self::WIDTH} height={Self::HEIGHT} fill={fill} />
+ </svg>
+ )
+ }
+}
+
+fn center_pixel(decoder: &mut FFmpegDecoder, frame: usize) -> [u8; 4] {
+ unsafe {
+ assert!(
+ decoder.decode_up_to(frame as i64).unwrap(),
+ "frame {frame} is missing from the rendered video"
+ );
+
+ let image = decoder
+ .get_raw_frame()
+ .convert_last_decoded_frame_into_svg_image(None)
+ .unwrap();
+ let offset =
+ ((image.height as usize / 2) * image.width as usize + image.width as usize / 2) * 4;
+ image.data[offset..offset + 4].try_into().unwrap()
+ }
+}
+
+fn assert_color_close(actual: [u8; 4], expected: [u8; 3], frame: usize) {
+ // lossy yuv420p encoding shifts solid colors by a few units
+ let close = actual[..3]
+ .iter()
+ .zip(expected)
+ .all(|(a, e)| a.abs_diff(e) <= 24);
+ assert!(
+ close,
+ "frame {frame}: expected ~{expected:?}, decoded {actual:?}"
+ );
+}
+
+#[test]
+fn renders_videos_through_every_export_mode() {
+ let Some(vulkan) = vulkan() else { return };
+
+ for (mode, pixel_format) in [
+ (SkiaFrameExport::Auto, AV_PIX_FMT_YUV420P),
+ (SkiaFrameExport::GpuConversion, AV_PIX_FMT_YUV420P),
+ (SkiaFrameExport::CpuConversion, AV_PIX_FMT_YUV420P),
+ ] {
+ let dir = std::env::temp_dir().join(format!(
+ "fframes-skia-export-{}-{mode:?}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let output = dir.join("out.mp4");
+
+ fframes::render(
+ &output,
+ &TwoColors,
+ SkiaFFramesRenderer::new_vulkan(&vulkan, SkiaPipelineConfig::default())
+ .unwrap()
+ .frame_export(mode),
+ &RenderOptions {
+ logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,
+ tmp_files_directory: Some(&dir.join("chunks")),
+ video_encoder_options: EncoderOptions {
+ // decodes in software whatever FFmpeg was built with
+ preferred_encoder: Some("mpeg4"),
+ pixel_format,
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ )
+ .unwrap_or_else(|err| panic!("{mode:?}: {err:?}"));
+
+ let mut decoder = unsafe { FFmpegDecoder::new(&output, FPS, 1) }.unwrap();
+ assert_color_close(center_pixel(&mut decoder, 0), [255, 0, 0], 0);
+ assert_color_close(
+ center_pixel(&mut decoder, SWITCH_AT + 2),
+ [0, 0, 255],
+ SWITCH_AT + 2,
+ );
+ drop(decoder);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
+
+#[test]
+fn h264_renders_decode_with_or_without_a_hardware_decoder() {
+ let Some(vulkan) = vulkan() else { return };
+ let encoder_options = EncoderOptions {
+ preferred_encoder: Some("libx264"),
+ ..Default::default()
+ };
+ let dir = std::env::temp_dir().join(format!("fframes-skia-export-{}-h264", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let output = dir.join("out.mp4");
+
+ let encoder = fframes::VideoEncoderInfo::for_output(
+ &output,
+ (WIDTH as i32, HEIGHT as i32, FPS as i32),
+ &encoder_options,
+ )
+ .unwrap();
+ if encoder.name() != "libx264" {
+ eprintln!("skipping: FFmpeg was built without libx264 (the `h264` feature)");
+ return;
+ }
+
+ fframes::render(
+ &output,
+ &TwoColors,
+ SkiaFFramesRenderer::new_vulkan(&vulkan, SkiaPipelineConfig::default()).unwrap(),
+ &RenderOptions {
+ logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,
+ tmp_files_directory: Some(&dir.join("chunks")),
+ video_encoder_options: encoder_options,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ // With FFmpeg's Vulkan support compiled in the decoder asks the GPU first and has to
+ // fall back to software on drivers without H.264 decode.
+ let mut decoder = unsafe { FFmpegDecoder::new(&output, FPS, 1) }.unwrap();
+ assert_color_close(center_pixel(&mut decoder, 0), [255, 0, 0], 0);
+ assert_color_close(
+ center_pixel(&mut decoder, SWITCH_AT + 2),
+ [0, 0, 255],
+ SWITCH_AT + 2,
+ );
+ drop(decoder);
+
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn an_encoder_that_does_not_open_fails_the_render() {
+ let Some(vulkan) = vulkan() else { return };
+ let dir = std::env::temp_dir().join(format!("fframes-skia-export-{}-bad", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+
+ // The encoder is opened by the encoding threads. When they give up, the stages
+ // feeding them have to stop too instead of waiting for room in the queues.
+ let result = fframes::render(
+ dir.join("out.mp4"),
+ &TwoColors,
+ SkiaFFramesRenderer::new_vulkan(&vulkan, SkiaPipelineConfig::default()).unwrap(),
+ &RenderOptions {
+ logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,
+ tmp_files_directory: Some(&dir.join("chunks")),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some("mpeg4"),
+ // a maximum bitrate needs a buffer size, which is not set
+ codec_params: Some(&[("maxrate", "1000")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ );
+
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(
+ result.is_err(),
+ "the encoder was expected to reject its options"
+ );
+}
+
+#[cfg(feature = "vulkan-video")]
+mod vulkan_video {
+ use super::*;
+ use fframes::FFramesRenderBackend;
+
+ #[derive(Debug)]
+ struct TwoColors720;
+
+ impl Video for TwoColors720 {
+ const FPS: usize = 30;
+ const WIDTH: usize = 1280;
+ const HEIGHT: usize = 720;
+ const BACKGROUND_COLOR: Color = Color::BLACK;
+
+ fn duration(&self) -> Duration<'_> {
+ Duration::Frames(60)
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+
+ fn render_frame<'a>(&'a self, frame: Frame, _ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ let fill = if frame.index < 30 {
+ "#ff0000"
+ } else {
+ "#0000ff"
+ };
+
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width={Self::WIDTH} height={Self::HEIGHT}>
+ <rect x="0" y="0" width={Self::WIDTH} height={Self::HEIGHT} fill={fill} />
+ </svg>
+ )
+ }
+ }
+
+ /// Renders through a Vulkan Video encoder and checks the decoded colors. Skipped where
+ /// the driver has no such encoder.
+ fn renders_through(encoder: &str) {
+ let Ok(vulkan) =
+ SkiaVulkanCtx::new_shared_with_encoder(TwoColors720::WIDTH, TwoColors720::HEIGHT)
+ else {
+ eprintln!("skipping: FFmpeg has no Vulkan device");
+ return;
+ };
+
+ let dir = std::env::temp_dir().join(format!(
+ "fframes-skia-export-{}-{encoder}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let output = dir.join("out.mp4");
+ let options = RenderOptions {
+ logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,
+ tmp_files_directory: Some(&dir.join("chunks")),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some(encoder),
+ // Mesa's Intel driver (25.1, `ANV_DEBUG=video-encode`) writes HEVC that
+ // decodes washed out below the quantizer 26, whatever feeds the encoder.
+ codec_params: Some(&[("qp", "26")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let info = fframes::VideoEncoderInfo::for_output(
+ &output,
+ (
+ TwoColors720::WIDTH as i32,
+ TwoColors720::HEIGHT as i32,
+ TwoColors720::FPS as i32,
+ ),
+ &options.video_encoder_options,
+ )
+ .unwrap();
+ let backend =
+ SkiaFFramesRenderer::new_vulkan(&vulkan, SkiaPipelineConfig::default()).unwrap();
+ let hardware = info.name() == encoder
+ && backend
+ .negotiate_encoder_input(&info)
+ .is_ok_and(|input| input.is_hardware());
+ if !hardware {
+ eprintln!("skipping {encoder}: the driver has no such encoder");
+ return;
+ }
+
+ fframes::render(&output, &TwoColors720, backend, &options)
+ .unwrap_or_else(|err| panic!("{encoder}: {err:?}"));
+
+ let mut decoder = unsafe { FFmpegDecoder::new(&output, TwoColors720::FPS, 1) }.unwrap();
+ assert_color_close(center_pixel(&mut decoder, 0), [255, 0, 0], 0);
+ assert_color_close(center_pixel(&mut decoder, 32), [0, 0, 255], 32);
+ drop(decoder);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn hevc_vulkan_reads_the_frames_skia_rendered() {
+ renders_through("hevc_vulkan");
+ }
+
+ #[test]
+ fn h264_vulkan_reads_the_frames_skia_rendered() {
+ renders_through("h264_vulkan");
+ }
+}
diff --git a/fframes-skia-renderer/tests/frame_export_videotoolbox.rs b/fframes-skia-renderer/tests/frame_export_videotoolbox.rs
new file mode 100644
index 00000000..4196c30c
--- /dev/null
+++ b/fframes-skia-renderer/tests/frame_export_videotoolbox.rs
@@ -0,0 +1,148 @@
+#![cfg(all(target_os = "macos", feature = "metal"))]
+
+use fframes::ffmpeg_sys_fframes::AVPixelFormat::AV_PIX_FMT_VIDEOTOOLBOX;
+use fframes::media::FFmpegDecoder;
+use fframes::{
+ AudioMap, Color, Duration, EncoderOptions, FFramesContext, FFramesRenderBackend, Frame,
+ RenderOptions, Svgr, Video, VideoEncoderInfo,
+};
+use fframes_skia_renderer::metal::SkiaMetalCtx;
+use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig};
+
+const FPS: usize = 60;
+// Three 40-frame segments end at fractional seconds and expose truncated MP4 edit lists.
+const FRAMES: usize = 120;
+const SWITCH_AT: usize = FRAMES / 2;
+
+#[derive(Debug)]
+struct TwoColors;
+
+impl Video for TwoColors {
+ const FPS: usize = FPS;
+ const WIDTH: usize = 1280;
+ const HEIGHT: usize = 720;
+ 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 fill = if frame.index < SWITCH_AT {
+ "#ff0000"
+ } else {
+ "#0000ff"
+ };
+
+ fframes::svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width={Self::WIDTH} height={Self::HEIGHT}>
+ <rect x="0" y="0" width={Self::WIDTH} height={Self::HEIGHT} fill={fill} />
+ </svg>
+ )
+ }
+}
+
+fn center_pixel(decoder: &mut FFmpegDecoder, frame: usize) -> [u8; 4] {
+ unsafe {
+ assert!(
+ decoder.decode_up_to(frame as i64).unwrap(),
+ "frame {frame} is missing from the rendered video"
+ );
+
+ let image = decoder
+ .get_raw_frame()
+ .convert_last_decoded_frame_into_svg_image(None)
+ .unwrap();
+ let offset =
+ ((image.height as usize / 2) * image.width as usize + image.width as usize / 2) * 4;
+ image.data[offset..offset + 4].try_into().unwrap()
+ }
+}
+
+fn assert_color_close(actual: [u8; 4], expected: [u8; 3], frame: usize) {
+ // Tight enough to notice the encoder converting RGB with another matrix than the one
+ // the stream is tagged with (BT.709 instead of BT.601 moves pure red by 22).
+ let close = actual[..3]
+ .iter()
+ .zip(expected)
+ .all(|(a, e)| a.abs_diff(e) <= 12);
+ assert!(
+ close,
+ "frame {frame}: expected ~{expected:?}, decoded {actual:?}"
+ );
+}
+
+#[test]
+fn videotoolbox_encoders_read_the_frames_skia_rendered() {
+ let metal = SkiaMetalCtx::new(TwoColors::WIDTH, TwoColors::HEIGHT).expect("a Metal device");
+
+ for encoder in ["h264_videotoolbox", "hevc_videotoolbox"] {
+ let dir = std::env::temp_dir().join(format!(
+ "fframes-skia-export-{}-{encoder}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let output = dir.join("out.mp4");
+ let options = RenderOptions {
+ logger: fframes::fframes_logger::FFramesLoggerVariant::Silent,
+ tmp_files_directory: Some(&dir.join("chunks")),
+ video_encoder_options: EncoderOptions {
+ preferred_encoder: Some(encoder),
+ bitrate: Some(4_000_000),
+ codec_params: Some(&[("allow_sw", "0")]),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let info = VideoEncoderInfo::for_output(
+ &output,
+ (
+ TwoColors::WIDTH as i32,
+ TwoColors::HEIGHT as i32,
+ FPS as i32,
+ ),
+ &options.video_encoder_options,
+ )
+ .unwrap();
+ if info.name() != encoder {
+ eprintln!("skipping {encoder}: FFmpeg was built without the `videotoolbox` feature");
+ continue;
+ }
+
+ let backend = SkiaFFramesRenderer::new_metal(
+ &metal,
+ SkiaPipelineConfig {
+ encoder_threads: 6,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let input = backend.negotiate_encoder_input(&info).unwrap();
+ assert_eq!(
+ input.pixel_format, AV_PIX_FMT_VIDEOTOOLBOX,
+ "{encoder} did not get hardware frames"
+ );
+
+ fframes::render(&output, &TwoColors, backend, &options)
+ .unwrap_or_else(|err| panic!("{encoder}: {err:?}"));
+
+ let mut decoder = unsafe { FFmpegDecoder::new(&output, FPS, 1) }.unwrap();
+ for frame in 0..FRAMES {
+ let expected = if frame < SWITCH_AT {
+ [255, 0, 0]
+ } else {
+ [0, 0, 255]
+ };
+ assert_color_close(center_pixel(&mut decoder, frame), expected, frame);
+ }
+ assert!(!unsafe { decoder.decode_up_to(FRAMES as i64) }.unwrap());
+ drop(decoder);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/fframes-test-utils/src/lib.rs b/fframes-test-utils/src/lib.rs
index 6e4130a2..92034147 100644
--- a/fframes-test-utils/src/lib.rs
+++ b/fframes-test-utils/src/lib.rs
@@ -67,17 +67,15 @@ pub fn assert_compile_time_svgr_eq_runtime(name: &str, svgr: Svgr) {
std::fs::write(diff_path, prefixed_snapshot).unwrap();
- if cfg!(feature = "compile-time-svgtree") {
- panic!(
- "Compile-time svgtree is not equal to base snapshot for test {name}. See diff at {} for more details.",
- diff_path.display()
- )
+ let kind = if cfg!(feature = "compile-time-svgtree") {
+ "Compile-time"
} else {
- panic!(
- "Runtime svgtree is not equal to base snapshot for test {name}. See diff at {} for more details.",
- diff_path.display()
- )
- }
+ "Runtime"
+ };
+ panic!(
+ "{kind} svgtree is not equal to base snapshot for test {name}. See diff at {} for more details.",
+ diff_path.display()
+ )
}
} else {
std::fs::create_dir_all(snapshot_path.parent().unwrap()).unwrap();
diff --git a/fframes/src/diagnostics.rs b/fframes/src/diagnostics.rs
index e3917163..5442bdfe 100644
--- a/fframes/src/diagnostics.rs
+++ b/fframes/src/diagnostics.rs
@@ -331,7 +331,7 @@ mod tests {
assert_eq!(collected, vec![Diagnostic::EmptyFrame]);
let ((), nothing) = collect(|| ());
- assert!(nothing.is_empty());
+ assert_eq!(nothing, Vec::<Diagnostic>::new());
}
#[test]
diff --git a/fframes/src/renderer/cli.rs b/fframes/src/renderer/cli.rs
index 497fb7ab..db96485d 100644
--- a/fframes/src/renderer/cli.rs
+++ b/fframes/src/renderer/cli.rs
@@ -372,10 +372,15 @@ impl<'r, 'a, 'media: 'a, V: Video + Send + Sync, B: FFramesRenderBackend, A: Arg
render(json, cli.scale, video, options, args, backend)
}
command => {
- let mut frame_renderer = backend
- .frame_renderer()
- .unwrap_or_else(|| Box::new(CpuFrameRenderer::default()));
- let frame_renderer = frame_renderer.as_mut();
+ let mut frame_renderer = backend.frame_renderer();
+ let mut fallback;
+ let frame_renderer: &mut dyn FrameRenderer =
+ if let Some(renderer) = frame_renderer.as_mut() {
+ renderer
+ } else {
+ fallback = CpuFrameRenderer::default();
+ &mut fallback
+ };
Previewer::new(video, &options)
.map_err(err)
.and_then(|mut previewer| match command {
diff --git a/fframes/src/renderer/concatenator.rs b/fframes/src/renderer/concatenator.rs
index 4af2fb05..b7ca3640 100644
--- a/fframes/src/renderer/concatenator.rs
+++ b/fframes/src/renderer/concatenator.rs
@@ -42,6 +42,8 @@ impl AvPacketAutoFree {
}
}
+unsafe impl Send for AvPacketAutoFree {}
+
impl Drop for AvPacketAutoFree {
fn drop(&mut self) {
unsafe {
diff --git a/fframes/src/renderer/cpu.rs b/fframes/src/renderer/cpu.rs
index c0050967..8f4a3f67 100644
--- a/fframes/src/renderer/cpu.rs
+++ b/fframes/src/renderer/cpu.rs
@@ -1,6 +1,7 @@
use super::{
- FrameRenderer, FrameScheduler, SegmentWriter, get_thread_count,
- render_backend::FFramesRenderBackend, renderer_error::RenderEncodingError,
+ EncoderFrameRenderer, EncoderInput, FrameRenderer, FrameScheduler, RgbaFrameConverter,
+ SegmentWriter, VideoFrame, get_thread_count, render_backend::FFramesRenderBackend,
+ renderer_error::RenderEncodingError,
};
use crate::{
AbortSignal, AudioTimelineSamples, Frame, RenderOptions, ResolvedRenderingTimeline, TextCache,
@@ -57,9 +58,78 @@ impl Default for CpuRenderingBackend {
}
}
+/// The CPU rasterizer as an [`EncoderFrameRenderer`]: tiny-skia draws premultiplied RGBA
+/// that is converted into the encoder's pixel format with [`RgbaFrameConverter`].
+pub struct CpuEncoderFrameRenderer {
+ pixmap: svgr::tiny_skia::Pixmap,
+ cache: SvgrCache,
+ pixmap_pool: PixmapPool,
+ context: svgr::Context,
+ converter: RgbaFrameConverter,
+}
+
+impl CpuEncoderFrameRenderer {
+ /// `cache_capacity` is the number of static subtrees kept rasterized between frames.
+ pub fn new(
+ cache_capacity: usize,
+ input: &EncoderInput,
+ width: u32,
+ height: u32,
+ ) -> Result<Self, RenderEncodingError> {
+ let pixmap = svgr::tiny_skia::Pixmap::new(width, height)
+ .ok_or_else(|| RenderEncodingError::CantAllocate("pixmap".to_owned()))?;
+
+ Ok(Self {
+ context: svgr::Context::new_from_pixmap_unsafe(&pixmap),
+ pixmap,
+ cache: SvgrCache::new(cache_capacity),
+ pixmap_pool: PixmapPool::new(),
+ converter: RgbaFrameConverter::for_input(input, width as i32, height as i32)?,
+ })
+ }
+}
+
+impl EncoderFrameRenderer for CpuEncoderFrameRenderer {
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: crate::Color,
+ ) -> FFramesRendererResult<VideoFrame> {
+ self.pixmap.fill(Color::from_rgba8(
+ background.r,
+ background.g,
+ background.b,
+ background.a,
+ ));
+
+ svgr::render(
+ tree,
+ super::fit_transform(tree, self.pixmap.width(), self.pixmap.height()),
+ &mut self.pixmap.as_mut(),
+ &mut self.cache,
+ &self.pixmap_pool,
+ &self.context,
+ );
+
+ self.converter
+ .convert(self.pixmap.data())
+ .map_err(|err| FFramesRendererError::from_chunk(0, err))
+ }
+}
+
impl FFramesRenderBackend for CpuRenderingBackend {
- fn frame_renderer(&self) -> Option<Box<dyn FrameRenderer + '_>> {
- Some(Box::new(super::CpuFrameRenderer::new(self.cache_capacity)))
+ fn frame_renderer(&self) -> Option<impl FrameRenderer + '_> {
+ Some(super::CpuFrameRenderer::new(self.cache_capacity))
+ }
+
+ fn encoder_frame_renderer(
+ &self,
+ input: &EncoderInput,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<impl EncoderFrameRenderer + '_> {
+ CpuEncoderFrameRenderer::new(self.cache_capacity, input, width, height)
+ .map_err(|err| FFramesRendererError::from_chunk(0, err))
}
fn render<'a, 'media: 'a, TVideo: Video + Sync + Sized>(
@@ -85,13 +155,6 @@ impl FFramesRenderBackend for CpuRenderingBackend {
std::fs::create_dir(directory)?;
}
- let background_color = Color::from_rgba8(
- TVideo::BACKGROUND_COLOR.r,
- TVideo::BACKGROUND_COLOR.g,
- TVideo::BACKGROUND_COLOR.b,
- TVideo::BACKGROUND_COLOR.a,
- );
-
// The scheduler and segments work in output frames; `frame_offset` maps them back to
// video frames when only a range is rendered.
let frame_range = render_options.output_frame_range(ctx.duration_in_frames);
@@ -116,24 +179,22 @@ impl FFramesRenderBackend for CpuRenderingBackend {
render_options,
&logger,
);
+ let encoder_input = writer
+ .encoder_info()
+ .and_then(|encoder| self.negotiate_encoder_input(&encoder))
+ .map_err(|err| FFramesRendererError::RenderChunkError(0, err))?;
+ let writer = writer.with_encoder_input(encoder_input);
let failed = AtomicBool::new(false);
let render_worker = |worker: usize| -> FFramesRendererResult<()> {
- let pixmap_pool = PixmapPool::new();
let worker_local_decoders = VideoDecodersWorker::new(1);
- let mut svgr_cache = SvgrCache::new(self.cache_capacity);
let break_lines_cache = TextCache::new(self.text_cache_capacity);
let mut converter_cache = usvgr::Cache::new_with_text_cache(self.text_cache_capacity);
-
- let mut pixmap =
- svgr::tiny_skia::Pixmap::new(video_size.width as u32, video_size.height as u32)
- .ok_or_else(|| {
- FFramesRendererError::RenderChunkError(
- worker,
- RenderEncodingError::CantAllocate("pixmap".to_owned()),
- )
- })?;
- let svgr_ctx = svgr::Context::new_from_pixmap_unsafe(&pixmap);
+ let mut renderer = self.encoder_frame_renderer(
+ writer.encoder_input(),
+ video_size.width as u32,
+ video_size.height as u32,
+ )?;
let mut rendered_frames = 0;
while let Some(claim) = scheduler.claim(worker) {
@@ -144,7 +205,6 @@ impl FFramesRenderBackend for CpuRenderingBackend {
return Err(FFramesRendererError::Aborted);
}
- pixmap.fill(background_color);
let video_frame = claim.frame + frame_offset;
let svg = super::render_frame_guarded(
video,
@@ -160,17 +220,10 @@ impl FFramesRenderBackend for CpuRenderingBackend {
let rtree = svg.into_svg_tree(usvg_options, &mut converter_cache, font_db)?;
- svgr::render(
- &rtree,
- super::fit_transform(&rtree, pixmap.width(), pixmap.height()),
- &mut pixmap.as_mut(),
- &mut svgr_cache,
- &pixmap_pool,
- &svgr_ctx,
- );
+ let frame = renderer.render_tree(&rtree, TVideo::BACKGROUND_COLOR)?;
writer
- .submit(claim, pixmap.data())
+ .submit_frame(claim, frame)
.map_err(|err| FFramesRendererError::RenderChunkError(worker, err))?;
logger.log_frame(rendered_frames, worker);
rendered_frames += 1;
diff --git a/fframes/src/renderer/encoder.rs b/fframes/src/renderer/encoder.rs
index 00e764c7..305a9f15 100644
--- a/fframes/src/renderer/encoder.rs
+++ b/fframes/src/renderer/encoder.rs
@@ -1,5 +1,6 @@
use super::{
FFramesLogger,
+ frame_export::{EncoderInput, VideoFrame},
renderer_error::{self, RenderEncodingError},
stream,
stream::Stream,
@@ -283,6 +284,33 @@ impl Encoder {
filename: &Path,
render_options: &RenderOptions,
logger: &Arc<dyn FFramesLogger>,
+ ) -> RenderEncodingResult<Self> {
+ unsafe {
+ Self::new_with_input(
+ output,
+ width,
+ height,
+ fps,
+ filename,
+ render_options,
+ &EncoderInput::software(render_options.video_encoder_options.pixel_format),
+ logger,
+ )
+ }
+ }
+
+ /// Like [`Self::new`] with the video encoder opened for the frames a rendering backend
+ /// negotiated (`FFramesRenderBackend::negotiate_encoder_input`).
+ #[allow(clippy::too_many_arguments)]
+ pub unsafe fn new_with_input(
+ output: EncoderOutput,
+ width: i32,
+ height: i32,
+ fps: i32,
+ filename: &Path,
+ render_options: &RenderOptions,
+ input: &EncoderInput,
+ logger: &Arc<dyn FFramesLogger>,
) -> RenderEncodingResult<Self> {
unsafe {
av_log_set_level(logger.get_libav_log_level());
@@ -307,6 +335,7 @@ impl Encoder {
fps,
oc,
&render_options.video_encoder_options,
+ input,
// Segments already encode in parallel. Letting each encoder auto-size
// its own thread pool multiplies both threads and buffered frames.
i32::from(matches!(output, EncoderOutput::IntermediateChunk)),
@@ -363,22 +392,30 @@ impl Encoder {
..
}: &EncoderFrame,
customize_frame: F,
+ ) -> RenderEncodingResult<()> {
+ unsafe { Self::send_raw_frame(stream, *frame, *packet, customize_frame) }
+ }
+
+ unsafe fn send_raw_frame<F: Fn(*mut AVPacket) -> i32>(
+ stream: &stream::Stream,
+ frame: *mut AVFrame,
+ packet: *mut AVPacket,
+ customize_frame: F,
) -> RenderEncodingResult<()> {
unsafe {
- let avcodec_send_frame = avcodec_send_frame(stream.enc, *frame);
- let mut status = avcodec_send_frame;
+ let mut status = avcodec_send_frame(stream.enc, frame);
if status < 0 {
let error_description = av_error_to_string(status);
return Err(renderer_error::RenderEncodingError::CantEncodeFrame {
error: error_description,
- pts: Some((*(*frame)).pts),
+ pts: Some((*frame).pts),
});
}
while status >= 0 {
- status = avcodec_receive_packet(stream.enc, *packet);
+ status = avcodec_receive_packet(stream.enc, packet);
if status == AVERROR_EOF || status == FFMPEG_AVERROR(EAGAIN) {
break;
@@ -388,11 +425,11 @@ impl Encoder {
let error_description = av_error_to_string(status);
return Err(renderer_error::RenderEncodingError::CantEncodeFrame {
error: format!("avcodec_receive_packet failed: {error_description}"),
- pts: Some((*(*frame)).pts),
+ pts: Some((*frame).pts),
});
}
- let write_status = customize_frame(*packet);
+ let write_status = customize_frame(packet);
if write_status < 0 {
let error_description = av_error_to_string(write_status);
return Err(renderer_error::RenderEncodingError::CantWriteFrame(
@@ -423,6 +460,34 @@ impl Encoder {
}
}
+ /// Encodes a frame of the video stream with `pts` in frames and writes the packets
+ /// that are ready into the file. `packet` is scratch space that is reused between calls.
+ pub unsafe fn send_video_frame(
+ &self,
+ frame: &VideoFrame,
+ pts: i64,
+ packet: *mut AVPacket,
+ ) -> RenderEncodingResult<()> {
+ unsafe {
+ let stream = &self.video_stream;
+ let oc = self.oc;
+ (*frame.as_ptr()).pts = pts;
+
+ Self::send_raw_frame(stream, frame.as_ptr(), packet, |packet| {
+ // VideoToolbox can return packets without a duration. Our video time
+ // base is one frame, including the final packet: otherwise MP4 can
+ // end its edit list at that frame's PTS and discard the last picture.
+ if (*packet).duration == 0 {
+ (*packet).duration = 1;
+ }
+ av_packet_rescale_ts(packet, (*stream.enc).time_base, (*stream.st).time_base);
+
+ (*packet).stream_index = (*stream.st).index;
+ av_interleaved_write_frame(oc, packet)
+ })
+ }
+ }
+
/// Signals the end of the stream to the codec and writes every packet it still
/// holds (lookahead, frame threads, B-frames). The stream can not receive frames
/// afterwards.
@@ -452,6 +517,10 @@ impl Encoder {
});
}
+ if matches!(stream.variant, stream::StreamVariant::Video) && (*packet).duration == 0
+ {
+ (*packet).duration = 1;
+ }
av_packet_rescale_ts(packet, (*stream.enc).time_base, (*stream.st).time_base);
(*packet).stream_index = (*stream.st).index;
let status = av_interleaved_write_frame(self.oc, packet);
diff --git a/fframes/src/renderer/frame_export.rs b/fframes/src/renderer/frame_export.rs
new file mode 100644
index 00000000..f28d89b5
--- /dev/null
+++ b/fframes/src/renderer/frame_export.rs
@@ -0,0 +1,707 @@
+use super::encoder::EncoderOptions;
+use super::renderer_error::{
+ FFramesRendererError, FFramesRendererResult, RenderEncodingError, RenderEncodingResult,
+};
+use super::{FrameRenderer, encoder::av_error_to_string, stream};
+use crate::media::ffmpeg_sys_fframes::SwsFlags::SWS_BICUBIC;
+use crate::media::ffmpeg_sys_fframes::*;
+use crate::{Color, usvgr};
+use std::ffi::{CStr, CString};
+use std::path::Path;
+use std::ptr::NonNull;
+
+fn ffmpeg_error(code: i32) -> RenderEncodingError {
+ RenderEncodingError::FFmpegError(code, av_error_to_string(code))
+}
+
+/// A counted reference to a libav buffer (`AVBufferRef`). Hardware device and frames contexts
+/// are passed around this way.
+pub struct AvBuffer(NonNull<AVBufferRef>);
+
+unsafe impl Send for AvBuffer {}
+unsafe impl Sync for AvBuffer {}
+
+impl AvBuffer {
+ /// Takes ownership of `buffer`, `None` when it is null.
+ ///
+ /// # Safety
+ /// `buffer` must be a valid reference that nothing else unreferences.
+ pub unsafe fn from_raw(buffer: *mut AVBufferRef) -> Option<Self> {
+ NonNull::new(buffer).map(Self)
+ }
+
+ pub fn as_ptr(&self) -> *mut AVBufferRef {
+ self.0.as_ptr()
+ }
+
+ /// The payload of the buffer, e.g. the `AVHWFramesContext` of a frames context.
+ pub fn data<T>(&self) -> *mut T {
+ unsafe { (*self.0.as_ptr()).data.cast() }
+ }
+
+ /// A new reference for a libav struct that unreferences it on its own.
+ pub fn new_ref(&self) -> *mut AVBufferRef {
+ unsafe { av_buffer_ref(self.0.as_ptr()) }
+ }
+}
+
+impl Clone for AvBuffer {
+ fn clone(&self) -> Self {
+ Self(NonNull::new(self.new_ref()).expect("av_buffer_ref: out of memory"))
+ }
+}
+
+impl Drop for AvBuffer {
+ fn drop(&mut self) {
+ unsafe { av_buffer_unref(&mut self.0.as_ptr()) }
+ }
+}
+
+impl std::fmt::Debug for AvBuffer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "AvBuffer({:p})", self.0.as_ptr())
+ }
+}
+
+/// A frame on its way to the video encoder: an owned libav `AVFrame`.
+///
+/// It either carries pixels in the software format of the encoder or references a hardware
+/// surface (a `CVPixelBuffer`, a Vulkan image), in which case the pixels never leave the GPU.
+pub struct VideoFrame(NonNull<AVFrame>);
+
+unsafe impl Send for VideoFrame {}
+
+impl VideoFrame {
+ /// A frame without buffers (`av_frame_alloc`).
+ pub fn empty() -> RenderEncodingResult<Self> {
+ NonNull::new(unsafe { av_frame_alloc() })
+ .map(Self)
+ .ok_or_else(|| RenderEncodingError::CantAllocate("video frame".to_owned()))
+ }
+
+ /// Takes ownership of `frame`, `None` when it is null.
+ ///
+ /// # Safety
+ /// `frame` must come from `av_frame_alloc` and must not be freed by anything else.
+ pub unsafe fn from_raw(frame: *mut AVFrame) -> Option<Self> {
+ NonNull::new(frame).map(Self)
+ }
+
+ /// A frame of a hardware frames pool (`av_hwframe_get_buffer`). What its `data` points
+ /// to depends on the hardware format, e.g. `data[3]` is the `CVPixelBufferRef` of a
+ /// `VideoToolbox` frame and `data[0]` the `AVVkFrame` of a Vulkan one.
+ pub fn from_hw_frames(frames: &AvBuffer) -> RenderEncodingResult<Self> {
+ let frame = Self::empty()?;
+ let status = unsafe { av_hwframe_get_buffer(frames.as_ptr(), frame.as_ptr(), 0) };
+ if status < 0 {
+ return Err(ffmpeg_error(status));
+ }
+ Ok(frame)
+ }
+
+ /// Copies a hardware frame into memory (`av_hwframe_transfer_data`), in the first
+ /// software format its frames context transfers to. The encoder never needs this; it
+ /// is the way to look at what a hardware frame holds.
+ pub fn download(&self) -> RenderEncodingResult<Self> {
+ let frame = Self::empty()?;
+ let status = unsafe { av_hwframe_transfer_data(frame.as_ptr(), self.as_ptr(), 0) };
+ if status < 0 {
+ return Err(ffmpeg_error(status));
+ }
+ Ok(frame)
+ }
+
+ pub fn as_ptr(&self) -> *mut AVFrame {
+ self.0.as_ptr()
+ }
+
+ /// Hands the frame over to the caller, who has to `av_frame_free` it.
+ pub fn into_raw(self) -> *mut AVFrame {
+ let frame = self.0.as_ptr();
+ std::mem::forget(self);
+ frame
+ }
+
+ pub fn width(&self) -> i32 {
+ unsafe { (*self.as_ptr()).width }
+ }
+
+ pub fn height(&self) -> i32 {
+ unsafe { (*self.as_ptr()).height }
+ }
+
+ pub fn pixel_format(&self) -> AVPixelFormat {
+ // set from an `AVPixelFormat` by whoever created the frame
+ unsafe { std::mem::transmute::<i32, AVPixelFormat>((*self.as_ptr()).format) }
+ }
+
+ /// Start and line size of a plane, a null pointer for planes the format does not have
+ /// (and for the pixel planes of hardware frames).
+ pub fn plane(&self, index: usize) -> (*mut u8, i32) {
+ unsafe {
+ let frame = self.as_ptr();
+ ((*frame).data[index], (*frame).linesize[index])
+ }
+ }
+
+ /// Copies the pixels of a plane of a software frame without the line padding.
+ /// `width` and `height` are the size of the plane in bytes and rows.
+ pub fn copy_plane(&self, index: usize, width: usize, height: usize) -> Vec<u8> {
+ let (data, linesize) = self.plane(index);
+ assert!(
+ !data.is_null() && linesize as usize >= width,
+ "frame has no plane {index} of {width} bytes per row"
+ );
+
+ let mut pixels = Vec::with_capacity(width * height);
+ for row in 0..height {
+ pixels.extend_from_slice(unsafe {
+ std::slice::from_raw_parts(data.add(row * linesize as usize), width)
+ });
+ }
+ pixels
+ }
+}
+
+impl Drop for VideoFrame {
+ fn drop(&mut self) {
+ unsafe { av_frame_free(&mut self.0.as_ptr()) }
+ }
+}
+
+impl std::fmt::Debug for VideoFrame {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "VideoFrame({:?} {}x{})",
+ self.pixel_format(),
+ self.width(),
+ self.height()
+ )
+ }
+}
+
+fn pixel_format_flags(format: AVPixelFormat) -> u64 {
+ unsafe {
+ let descriptor = av_pix_fmt_desc_get(format);
+ if descriptor.is_null() {
+ 0
+ } else {
+ (*descriptor).flags
+ }
+ }
+}
+
+/// `true` for formats that reference a hardware surface (`AV_PIX_FMT_VIDEOTOOLBOX`,
+/// `AV_PIX_FMT_VULKAN`, ...) instead of carrying pixels.
+pub fn is_hardware_pixel_format(format: AVPixelFormat) -> bool {
+ pixel_format_flags(format) & AV_PIX_FMT_FLAG_HWACCEL as u64 != 0
+}
+
+/// The video encoder of a render as a backend sees it while negotiating the frames it will
+/// deliver. The codec is resolved the same way `Encoder` does it, nothing is opened yet.
+pub struct VideoEncoderInfo<'a> {
+ codec: *const AVCodec,
+ /// The container wants the codec headers out of band (`AVFMT_GLOBALHEADER`).
+ global_header: bool,
+ pub width: i32,
+ pub height: i32,
+ pub fps: i32,
+ pub options: &'a EncoderOptions<'a>,
+}
+
+impl<'a> VideoEncoderInfo<'a> {
+ /// The encoder that will be opened for `output` (only the extension matters).
+ pub fn for_output(
+ output: &Path,
+ (width, height, fps): (i32, i32, i32),
+ options: &'a EncoderOptions<'a>,
+ ) -> RenderEncodingResult<Self> {
+ let c_filename = CString::new(output.to_string_lossy().as_ref())
+ .map_err(RenderEncodingError::CStringError)?;
+
+ let (codec, global_header) = unsafe {
+ let format = av_guess_format(std::ptr::null(), c_filename.as_ptr(), std::ptr::null());
+ if format.is_null() {
+ return Err(RenderEncodingError::UnknownExtension(output.to_owned()));
+ }
+
+ (
+ stream::find_encoder(options.preferred_encoder, (*format).video_codec, false)?,
+ (*format).flags & AVFMT_GLOBALHEADER != 0,
+ )
+ };
+
+ Ok(Self {
+ codec,
+ global_header,
+ width,
+ height,
+ fps,
+ options,
+ })
+ }
+
+ pub fn as_ptr(&self) -> *const AVCodec {
+ self.codec
+ }
+
+ /// The libav name of the encoder, e.g. `libx264` or `hevc_videotoolbox`.
+ pub fn name(&self) -> &str {
+ unsafe {
+ let name = (*self.codec).name;
+ if name.is_null() {
+ ""
+ } else {
+ CStr::from_ptr(name).to_str().unwrap_or("")
+ }
+ }
+ }
+
+ /// `EncoderOptions::pixel_format`: what the user asked the video to be stored in.
+ pub fn requested_pixel_format(&self) -> AVPixelFormat {
+ self.options.pixel_format
+ }
+
+ /// The pixel formats the encoder takes, `None` when it does not tell.
+ pub fn pixel_formats(&self) -> Option<&[AVPixelFormat]> {
+ unsafe { stream::supported_pixel_formats(self.codec) }
+ }
+
+ pub fn supports(&self, format: AVPixelFormat) -> bool {
+ self.pixel_formats()
+ .is_none_or(|formats| formats.contains(&format))
+ }
+
+ /// Opens the encoder for `input` the way the render will and closes it again. This is
+ /// how a backend finds out that hardware frames it could deliver are not accepted on
+ /// this machine (no such encoder in the driver, unsupported size or format) while it
+ /// can still offer something else.
+ pub fn try_open(&self, input: &EncoderInput) -> RenderEncodingResult<()> {
+ unsafe {
+ let mut context = avcodec_alloc_context3(self.codec);
+ if context.is_null() {
+ return Err(RenderEncodingError::CantAllocate(
+ "encoding context".to_owned(),
+ ));
+ }
+
+ let result = stream::open_video_encoder(
+ context,
+ self.codec,
+ (self.width, self.height, self.fps),
+ self.global_header,
+ self.options,
+ input,
+ 1,
+ );
+ avcodec_free_context(&raw mut context);
+ result
+ }
+ }
+
+ /// The encoder lists `format` explicitly. Unlike [`Self::supports`] this is `false` for
+ /// encoders that do not publish their formats, use it for hardware formats.
+ pub fn lists(&self, format: AVPixelFormat) -> bool {
+ self.pixel_formats()
+ .is_some_and(|formats| formats.contains(&format))
+ }
+}
+
+/// What the video encoders of a render are opened with, the outcome of
+/// `FFramesRenderBackend::negotiate_encoder_input`. Every [`VideoFrame`] submitted to the
+/// render has to match it.
+#[derive(Debug, Clone)]
+pub struct EncoderInput {
+ /// `AVCodecContext::pix_fmt`: a software format, or a hardware one together with
+ /// `hw_frames_ctx`.
+ pub pixel_format: AVPixelFormat,
+ /// The pool the hardware frames come from (`AVCodecContext::hw_frames_ctx`).
+ pub hw_frames_ctx: Option<AvBuffer>,
+ /// `AVCodecContext::hw_device_ctx` for encoders that want the device only.
+ pub hw_device_ctx: Option<AvBuffer>,
+}
+
+impl EncoderInput {
+ /// Frames with pixels in memory.
+ pub fn software(pixel_format: AVPixelFormat) -> Self {
+ Self {
+ pixel_format,
+ hw_frames_ctx: None,
+ hw_device_ctx: None,
+ }
+ }
+
+ /// The pixel format the user requested, as long as the encoder takes it.
+ pub fn requested(encoder: &VideoEncoderInfo<'_>) -> RenderEncodingResult<Self> {
+ let format = encoder.requested_pixel_format();
+ if !encoder.supports(format) {
+ return Err(RenderEncodingError::InvalidPixFmt(format));
+ }
+ Ok(Self::software(format))
+ }
+
+ /// Hardware frames of `format` holding `sw_format` pixels, allocated by libav on `device`
+ /// (see [`hardware_device`]). Get the frames with [`VideoFrame::from_hw_frames`].
+ ///
+ /// `configure` runs before the pool is initialized and may adjust the API specific
+ /// context (`AVHWFramesContext::hwctx`).
+ pub fn hardware_frames(
+ device: &AvBuffer,
+ format: AVPixelFormat,
+ sw_format: AVPixelFormat,
+ (width, height): (i32, i32),
+ configure: impl FnOnce(&mut AVHWFramesContext),
+ ) -> RenderEncodingResult<Self> {
+ unsafe {
+ let frames = AvBuffer::from_raw(av_hwframe_ctx_alloc(device.as_ptr()))
+ .ok_or_else(|| RenderEncodingError::CantAllocate("hardware frames".to_owned()))?;
+
+ let context = &mut *frames.data::<AVHWFramesContext>();
+ context.format = format;
+ context.sw_format = sw_format;
+ context.width = width;
+ context.height = height;
+ configure(context);
+
+ let status = av_hwframe_ctx_init(frames.as_ptr());
+ if status < 0 {
+ return Err(ffmpeg_error(status));
+ }
+
+ Ok(Self {
+ pixel_format: format,
+ hw_frames_ctx: Some(frames),
+ hw_device_ctx: None,
+ })
+ }
+ }
+
+ pub fn is_hardware(&self) -> bool {
+ is_hardware_pixel_format(self.pixel_format)
+ }
+
+ /// The format of the pixels: `pixel_format` itself, or what the hardware frames hold.
+ pub fn software_format(&self) -> AVPixelFormat {
+ match &self.hw_frames_ctx {
+ Some(frames) => unsafe { (*frames.data::<AVHWFramesContext>()).sw_format },
+ None => self.pixel_format,
+ }
+ }
+}
+
+/// Opens a libav hardware device (`av_hwdevice_ctx_create`). Fails when `FFmpeg` was built
+/// without it or the machine has no such device.
+pub fn hardware_device(device_type: AVHWDeviceType) -> RenderEncodingResult<AvBuffer> {
+ unsafe {
+ let mut device = std::ptr::null_mut();
+ let status = av_hwdevice_ctx_create(
+ &raw mut device,
+ device_type,
+ std::ptr::null(),
+ std::ptr::null_mut(),
+ 0,
+ );
+ if status < 0 {
+ return Err(ffmpeg_error(status));
+ }
+
+ AvBuffer::from_raw(device)
+ .ok_or_else(|| RenderEncodingError::CantAllocate("hardware device".to_owned()))
+ }
+}
+
+/// Where the planes of a software frame are inside its pixel buffer.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct FrameLayout {
+ /// Size of the pixel buffer in bytes.
+ pub size: usize,
+ /// `(offset, linesize)` of every plane the format has.
+ pub planes: [Option<(usize, i32)>; 4],
+}
+
+impl FrameLayout {
+ /// The layout libav uses for frames of `format`: lines padded for SIMD access.
+ pub fn of(format: AVPixelFormat, width: i32, height: i32) -> RenderEncodingResult<Self> {
+ const ALIGN: i32 = 64;
+
+ unsafe {
+ let mut linesizes = [0_i32; 4];
+ let status = av_image_fill_linesizes(linesizes.as_mut_ptr(), format, width);
+ if status < 0 {
+ return Err(ffmpeg_error(status));
+ }
+ for linesize in &mut linesizes {
+ *linesize = (*linesize + ALIGN - 1) & !(ALIGN - 1);
+ }
+
+ // encoders may read whole macroblocks
+ let padded_height = (height + 31) & !31;
+ let wide_linesizes = linesizes.map(|linesize| linesize as isize);
+ let mut sizes = [0_usize; 4];
+ let status = av_image_fill_plane_sizes(
+ sizes.as_mut_ptr(),
+ format,
+ padded_height,
+ wide_linesizes.as_ptr(),
+ );
+ if status < 0 {
+ return Err(ffmpeg_error(status));
+ }
+
+ let mut layout = Self::default();
+ for (plane, (&size, &linesize)) in sizes.iter().zip(&linesizes).enumerate() {
+ if size > 0 {
+ layout.planes[plane] = Some((layout.size, linesize));
+ layout.size += size;
+ }
+ }
+ layout.size += ALIGN as usize;
+
+ Ok(layout)
+ }
+ }
+}
+
+/// Hands out software [`VideoFrame`]s of one format and size. The pixel buffers go back to
+/// the pool once the encoder is done with a frame, so a render does not allocate per frame.
+pub struct FramePool {
+ pool: *mut AVBufferPool,
+ format: AVPixelFormat,
+ width: i32,
+ height: i32,
+ layout: FrameLayout,
+}
+
+unsafe impl Send for FramePool {}
+unsafe impl Sync for FramePool {}
+
+impl FramePool {
+ pub fn new(format: AVPixelFormat, width: i32, height: i32) -> RenderEncodingResult<Self> {
+ Self::with_layout(
+ format,
+ width,
+ height,
+ FrameLayout::of(format, width, height)?,
+ )
+ }
+
+ /// A pool with a custom plane layout, for sources that produce all planes in one buffer.
+ pub fn with_layout(
+ format: AVPixelFormat,
+ width: i32,
+ height: i32,
+ layout: FrameLayout,
+ ) -> RenderEncodingResult<Self> {
+ let pool = unsafe { av_buffer_pool_init(layout.size, None) };
+ if pool.is_null() {
+ return Err(RenderEncodingError::CantAllocate("frame pool".to_owned()));
+ }
+
+ Ok(Self {
+ pool,
+ format,
+ width,
+ height,
+ layout,
+ })
+ }
+
+ pub fn layout(&self) -> &FrameLayout {
+ &self.layout
+ }
+
+ /// A writable frame. Its pixels are whatever the previous user of the buffer left.
+ pub fn get(&self) -> RenderEncodingResult<VideoFrame> {
+ let frame = VideoFrame::empty()?;
+
+ unsafe {
+ let buffer = av_buffer_pool_get(self.pool);
+ if buffer.is_null() {
+ return Err(RenderEncodingError::CantAllocate("frame buffer".to_owned()));
+ }
+
+ let raw = &mut *frame.as_ptr();
+ raw.format = self.format as i32;
+ raw.width = self.width;
+ raw.height = self.height;
+ raw.buf[0] = buffer;
+ for (plane, placed) in self.layout.planes.iter().enumerate() {
+ if let Some((offset, linesize)) = *placed {
+ raw.data[plane] = (*buffer).data.add(offset);
+ raw.linesize[plane] = linesize;
+ }
+ }
+ }
+
+ Ok(frame)
+ }
+}
+
+impl Drop for FramePool {
+ fn drop(&mut self) {
+ // buffers that are still referenced by frames keep the pool alive
+ unsafe { av_buffer_pool_uninit(&raw mut self.pool) }
+ }
+}
+
+/// Converts RGBA8 pixels into frames of a software pixel format on the CPU: the built-in
+/// SIMD converter for yuv420p, swscale for every other format.
+pub struct RgbaFrameConverter {
+ pool: FramePool,
+ sws: *mut SwsContext,
+}
+
+unsafe impl Send for RgbaFrameConverter {}
+
+impl RgbaFrameConverter {
+ pub fn new(format: AVPixelFormat, width: i32, height: i32) -> RenderEncodingResult<Self> {
+ if is_hardware_pixel_format(format) {
+ return Err(RenderEncodingError::Internal(format!(
+ "RGBA pixels can not be converted into {format:?} hardware frames"
+ )));
+ }
+
+ let pool = FramePool::new(format, width, height)?;
+ let sws = if format == AVPixelFormat::AV_PIX_FMT_YUV420P {
+ std::ptr::null_mut()
+ } else {
+ let sws = unsafe {
+ sws_getContext(
+ width,
+ height,
+ AVPixelFormat::AV_PIX_FMT_RGBA,
+ width,
+ height,
+ format,
+ SWS_BICUBIC as i32,
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ )
+ };
+ if sws.is_null() {
+ return Err(RenderEncodingError::Internal(
+ "Can not allocate sws".to_owned(),
+ ));
+ }
+ sws
+ };
+
+ Ok(Self { pool, sws })
+ }
+
+ /// For the frames `input` asks for.
+ pub fn for_input(input: &EncoderInput, width: i32, height: i32) -> RenderEncodingResult<Self> {
+ Self::new(input.pixel_format, width, height)
+ }
+
+ /// `rgba` is `width * height * 4` bytes without line padding.
+ pub fn convert(&mut self, rgba: &[u8]) -> RenderEncodingResult<VideoFrame> {
+ let (width, height) = (self.pool.width, self.pool.height);
+ if rgba.len() < width as usize * height as usize * 4 {
+ return Err(RenderEncodingError::Internal(format!(
+ "{} bytes of RGBA do not make a {width}x{height} frame",
+ rgba.len()
+ )));
+ }
+
+ let frame = self.pool.get()?;
+ unsafe {
+ let raw = &*frame.as_ptr();
+ if self.sws.is_null() {
+ super::pix_fmt::fill_yuv420_from_rgba_pixmap_accelerated(
+ width,
+ height,
+ raw.linesize[0],
+ raw.linesize[1],
+ raw.linesize[2],
+ rgba,
+ raw.data[0],
+ raw.data[1],
+ raw.data[2],
+ );
+ } else {
+ let source = [
+ rgba.as_ptr(),
+ std::ptr::null(),
+ std::ptr::null(),
+ std::ptr::null(),
+ ];
+ let source_linesize = [width * 4, 0, 0, 0];
+ sws_scale(
+ self.sws,
+ source.as_ptr(),
+ source_linesize.as_ptr(),
+ 0,
+ height,
+ raw.data.as_ptr(),
+ raw.linesize.as_ptr(),
+ );
+ }
+ }
+
+ Ok(frame)
+ }
+}
+
+impl Drop for RgbaFrameConverter {
+ fn drop(&mut self) {
+ unsafe { sws_freeContext(self.sws) }
+ }
+}
+
+/// Rasterizes frames straight into what the video encoder takes. One per rendering thread;
+/// implementations keep their surfaces, caches and converters between frames.
+///
+/// The CPU backend rasterizes into RGBA and converts with [`RgbaFrameConverter`]. A GPU
+/// backend can convert on the GPU or return hardware frames that are never read back.
+pub trait EncoderFrameRenderer {
+ /// Renders `tree` scaled to the output size over `background`.
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: Color,
+ ) -> FFramesRendererResult<VideoFrame>;
+}
+
+/// An [`EncoderFrameRenderer`] for any [`FrameRenderer`]: renders RGBA and converts it on
+/// the CPU.
+pub struct RgbaEncoderFrameRenderer<R: FrameRenderer> {
+ renderer: R,
+ converter: RgbaFrameConverter,
+ width: u32,
+ height: u32,
+}
+
+impl<R: FrameRenderer> RgbaEncoderFrameRenderer<R> {
+ pub fn new(
+ renderer: R,
+ input: &EncoderInput,
+ width: u32,
+ height: u32,
+ ) -> RenderEncodingResult<Self> {
+ Ok(Self {
+ renderer,
+ converter: RgbaFrameConverter::for_input(input, width as i32, height as i32)?,
+ width,
+ height,
+ })
+ }
+}
+
+impl<R: FrameRenderer> EncoderFrameRenderer for RgbaEncoderFrameRenderer<R> {
+ fn render_tree(
+ &mut self,
+ tree: &usvgr::Tree,
+ background: Color,
+ ) -> FFramesRendererResult<VideoFrame> {
+ let frame = self
+ .renderer
+ .render_tree(tree, background, self.width, self.height)?;
+
+ self.converter
+ .convert(&frame.pixels)
+ .map_err(|err| FFramesRendererError::from_chunk(0, err))
+ }
+}
diff --git a/fframes/src/renderer/mod.rs b/fframes/src/renderer/mod.rs
index efdb3a20..11d222a2 100644
--- a/fframes/src/renderer/mod.rs
+++ b/fframes/src/renderer/mod.rs
@@ -10,6 +10,8 @@ pub mod concatenator;
mod encoder_frame;
mod ffmpeg_helper;
+mod frame_export;
+pub use frame_export::*;
mod renderer_font_source;
mod stream;
diff --git a/fframes/src/renderer/pix_fmt.rs b/fframes/src/renderer/pix_fmt.rs
index ad051e4f..96a1e8a6 100644
--- a/fframes/src/renderer/pix_fmt.rs
+++ b/fframes/src/renderer/pix_fmt.rs
@@ -1,6 +1,18 @@
#![allow(clippy::too_many_arguments)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
+/// The RGB to `YCbCr` conversion every encoder input goes through (BT.601, limited range),
+/// as weights for channel values in `0.0..=1.0`: `[r, g, b, offset]` for Y, Cb and Cr.
+///
+/// These are the coefficients of the integer converter below. Backends that convert on the
+/// GPU use them too, so the streams (tagged as BT.601 limited by the encoder) look the same
+/// whichever way a frame took.
+pub const RGB_TO_YUV: [[f32; 4]; 3] = [
+ [66. / 256., 129. / 256., 25. / 256., 16. / 255.],
+ [-38. / 256., -74. / 256., 112. / 256., 128. / 255.],
+ [112. / 256., -94. / 256., -18. / 256., 128. / 255.],
+];
+
#[inline(always)]
pub fn get_rgb(pixmap: &[u8], i: usize) -> (i32, i32, i32) {
let r = i32::from(pixmap[4 * i]);
@@ -29,11 +41,27 @@ pub fn fill_yuv420_from_rgba_pixmap_base(
// an important note that linesize here can be different from the width of an image so it is required to fill the buffer correctly.
let width = width as usize;
let height = height as usize;
- let frame_size = height * (y_linesize as usize) + width;
+ if width == 0 || height == 0 {
+ return;
+ }
+
+ // the last line of a plane ends with its last pixel, not with the line padding
+ let plane_len =
+ |linesize: i32, columns: usize, rows: usize| (rows - 1) * linesize as usize + columns;
+ let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));
- let y_pixels = std::slice::from_raw_parts_mut(y_pixels_destination, frame_size);
- let cb_pixels = std::slice::from_raw_parts_mut(cb_pixels_destination, frame_size / 2);
- let cr_pixels = std::slice::from_raw_parts_mut(cr_pixels_destination, frame_size / 2);
+ let y_pixels = std::slice::from_raw_parts_mut(
+ y_pixels_destination,
+ plane_len(y_linesize, width, height),
+ );
+ let cb_pixels = std::slice::from_raw_parts_mut(
+ cb_pixels_destination,
+ plane_len(cb_linesize, chroma_width, chroma_height),
+ );
+ let cr_pixels = std::slice::from_raw_parts_mut(
+ cr_pixels_destination,
+ plane_len(cr_linesize, chroma_width, chroma_height),
+ );
for y in 0..height {
for x in 0..width {
diff --git a/fframes/src/renderer/preview.rs b/fframes/src/renderer/preview.rs
index ec5aba2f..51b94862 100644
--- a/fframes/src/renderer/preview.rs
+++ b/fframes/src/renderer/preview.rs
@@ -77,6 +77,19 @@ pub trait FrameRenderer {
) -> FFramesRendererResult<RgbaFrame>;
}
+// The default backend factory returns `None` even without the CPU renderer feature.
+impl FrameRenderer for std::convert::Infallible {
+ fn render_tree(
+ &mut self,
+ _tree: &usvgr::Tree,
+ _background: Color,
+ _width: u32,
+ _height: u32,
+ ) -> FFramesRendererResult<RgbaFrame> {
+ match *self {}
+ }
+}
+
/// The transform that fits a tree into the output size. Videos that hardcode their `WIDTH`
/// as the `<svg width>` are scaled this way when rendering with `scale_resolution`.
pub fn fit_transform(tree: &usvgr::Tree, width: u32, height: u32) -> usvgr::Transform {
diff --git a/fframes/src/renderer/render_backend.rs b/fframes/src/renderer/render_backend.rs
index b26194ad..27f79819 100644
--- a/fframes/src/renderer/render_backend.rs
+++ b/fframes/src/renderer/render_backend.rs
@@ -1,3 +1,7 @@
+use super::frame_export::{
+ EncoderFrameRenderer, EncoderInput, RgbaEncoderFrameRenderer, VideoEncoderInfo,
+};
+use super::renderer_error::{FFramesRendererError, RenderEncodingResult};
use super::{fframes_logger::FFramesLogger, renderer_error::FFramesRendererResult};
use crate::{AudioTimelineSamples, RenderOptions, ResolvedRenderingTimeline, Video, usvgr};
use std::{path::Path, sync::Arc};
@@ -8,8 +12,43 @@ pub trait FFramesRenderBackend {
/// Renders single frames (`fframes::Previewer`, the CLI's `frame`, `strip`, `onion` and
/// `snapshot`) the way this backend renders the video, so previews match the output.
/// `None` uses the built-in CPU renderer.
- fn frame_renderer(&self) -> Option<Box<dyn super::FrameRenderer + '_>> {
- None
+ fn frame_renderer(&self) -> Option<impl super::FrameRenderer + '_> {
+ None::<std::convert::Infallible>
+ }
+
+ /// Picks what the video encoders of a render are opened with, before any of them
+ /// exists. A backend that can produce the encoder's frames natively answers with the
+ /// format it delivers: another software format it converts to on the GPU, or
+ /// hardware frames ([`EncoderInput::hardware_frames`]) the encoder reads without the
+ /// pixels ever being copied into memory.
+ ///
+ /// The default keeps the pixel format requested in `EncoderOptions`.
+ fn negotiate_encoder_input(
+ &self,
+ encoder: &VideoEncoderInfo<'_>,
+ ) -> RenderEncodingResult<EncoderInput> {
+ EncoderInput::requested(encoder)
+ }
+
+ /// Rasterizes frames into what the encoder takes (`input` is the outcome of
+ /// [`Self::negotiate_encoder_input`]), one renderer per rendering thread.
+ ///
+ /// The default renders RGBA with [`Self::frame_renderer`] and converts it on the CPU.
+ fn encoder_frame_renderer(
+ &self,
+ input: &EncoderInput,
+ width: u32,
+ height: u32,
+ ) -> FFramesRendererResult<impl EncoderFrameRenderer + '_> {
+ let renderer = self.frame_renderer().ok_or_else(|| {
+ FFramesRendererError::Custom(
+ "the rendering backend has no frame renderer to produce encoder frames with"
+ .to_owned(),
+ )
+ })?;
+
+ RgbaEncoderFrameRenderer::new(renderer, input, width, height)
+ .map_err(|err| FFramesRendererError::from_chunk(0, err))
}
fn render_frame<'a, 'media: 'a, TVideo: Video + Sync + Sized + Send>(
diff --git a/fframes/src/renderer/renderer_error.rs b/fframes/src/renderer/renderer_error.rs
index 4cb14dc7..299eef68 100644
--- a/fframes/src/renderer/renderer_error.rs
+++ b/fframes/src/renderer/renderer_error.rs
@@ -70,6 +70,12 @@ impl fmt::Display for RenderEncodingError {
}
}
+impl fmt::Debug for RenderEncodingError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{self}")
+ }
+}
+
pub type RenderEncodingResult<T> = Result<T, RenderEncodingError>;
pub enum FFramesRendererError {
diff --git a/fframes/src/renderer/segment_writer.rs b/fframes/src/renderer/segment_writer.rs
index de2b3e99..48283728 100644
--- a/fframes/src/renderer/segment_writer.rs
+++ b/fframes/src/renderer/segment_writer.rs
@@ -3,28 +3,26 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use super::FFramesLogger;
+use super::concatenator::AvPacketAutoFree;
use super::encoder::{Encoder, EncoderOutput};
-use super::encoder_frame::EncoderFrame;
+use super::frame_export::{EncoderInput, RgbaFrameConverter, VideoEncoderInfo, VideoFrame};
use super::renderer_error::{RenderEncodingError, RenderEncodingResult};
use super::scheduler::FrameClaim;
use crate::RenderOptions;
struct Segment {
encoder: Encoder,
- frame: EncoderFrame,
+ packet: AvPacketAutoFree,
next_frame: usize,
end: Option<usize>,
- /// RGBA frames that arrived before the frames preceding them.
- pending: BTreeMap<usize, Vec<u8>>,
+ /// Frames that arrived before the frames preceding them.
+ pending: BTreeMap<usize, VideoFrame>,
+ /// Only for frames submitted as RGBA pixels.
+ converter: Option<RgbaFrameConverter>,
}
type SegmentSlot = Arc<Mutex<Option<Segment>>>;
-enum FramePixels<'p> {
- Borrowed(&'p [u8]),
- Owned(Vec<u8>),
-}
-
/// Encodes the frames handed out by a [`super::FrameScheduler`] into one intermediate
/// file per segment. Frames of a segment may arrive out of order from several threads;
/// they are encoded in order and the file is finalized as soon as its last frame is in.
@@ -37,11 +35,13 @@ pub struct SegmentWriter<'a, 'o, 'm> {
fps: i32,
render_options: &'a RenderOptions<'o, 'm>,
logger: &'a Arc<dyn FFramesLogger>,
+ input: EncoderInput,
open: Mutex<HashMap<usize, SegmentSlot>>,
finished: Mutex<Vec<(usize, PathBuf)>>,
}
impl<'a, 'o, 'm> SegmentWriter<'a, 'o, 'm> {
+ /// A writer whose encoders take the pixel format requested in `render_options`.
pub fn new(
directory: &'a Path,
extension: &str,
@@ -57,38 +57,80 @@ impl<'a, 'o, 'm> SegmentWriter<'a, 'o, 'm> {
fps,
render_options,
logger,
+ input: EncoderInput::software(render_options.video_encoder_options.pixel_format),
open: Mutex::new(HashMap::new()),
finished: Mutex::new(Vec::new()),
}
}
+ /// Opens the encoders for the frames a backend negotiated, see [`Self::encoder_info`].
+ pub fn with_encoder_input(mut self, input: EncoderInput) -> Self {
+ self.input = input;
+ self
+ }
+
+ /// The video encoder the segments will be encoded with, to negotiate its input
+ /// (`FFramesRenderBackend::negotiate_encoder_input`).
+ pub fn encoder_info(&self) -> RenderEncodingResult<VideoEncoderInfo<'a>> {
+ VideoEncoderInfo::for_output(
+ &self.segment_path(0),
+ (self.width, self.height, self.fps),
+ &self.render_options.video_encoder_options,
+ )
+ }
+
+ /// What every frame given to [`Self::submit_frame`] has to be.
+ pub fn encoder_input(&self) -> &EncoderInput {
+ &self.input
+ }
+
fn segment_path(&self, segment: usize) -> PathBuf {
self.directory
.join(format!("{segment:010}.{}", self.extension))
}
- /// Encodes the RGBA pixels of a claimed frame.
+ /// Encodes a claimed frame.
+ pub fn submit_frame(&self, claim: FrameClaim, frame: VideoFrame) -> RenderEncodingResult<()> {
+ self.submit_with(claim, |_| Ok(frame))
+ }
+
+ /// Encodes the RGBA pixels of a claimed frame, converting them on the CPU.
pub fn submit(&self, claim: FrameClaim, rgba: &[u8]) -> RenderEncodingResult<()> {
- self.submit_pixels(claim, FramePixels::Borrowed(rgba))
- .map(|_| ())
+ self.submit_with(claim, |segment| self.convert(segment, rgba))
}
- /// Like [`Self::submit`] but takes the buffer, so a frame that arrives early is kept
- /// without copying. Returns the buffers that are not needed anymore.
+ /// Like [`Self::submit`] for callers that recycle their buffers. Returns the buffers
+ /// that are not needed anymore.
pub fn submit_owned(
&self,
claim: FrameClaim,
rgba: Vec<u8>,
) -> RenderEncodingResult<Vec<Vec<u8>>> {
- self.submit_pixels(claim, FramePixels::Owned(rgba))
+ self.submit(claim, &rgba)?;
+ Ok(vec![rgba])
+ }
+
+ fn convert(&self, segment: &mut Segment, rgba: &[u8]) -> RenderEncodingResult<VideoFrame> {
+ if segment.converter.is_none() {
+ segment.converter = Some(RgbaFrameConverter::for_input(
+ &self.input,
+ self.width,
+ self.height,
+ )?);
+ }
+
+ segment
+ .converter
+ .as_mut()
+ .expect("the converter was just created")
+ .convert(rgba)
}
- fn submit_pixels(
+ fn submit_with(
&self,
claim: FrameClaim,
- pixels: FramePixels,
- ) -> RenderEncodingResult<Vec<Vec<u8>>> {
- let mut released = Vec::new();
+ frame: impl FnOnce(&mut Segment) -> RenderEncodingResult<VideoFrame>,
+ ) -> RenderEncodingResult<()> {
let slot = self
.open
.lock()
@@ -100,23 +142,24 @@ impl<'a, 'o, 'm> SegmentWriter<'a, 'o, 'm> {
let mut guard = slot.lock().unwrap();
if guard.is_none() {
let encoder = unsafe {
- Encoder::new(
+ Encoder::new_with_input(
EncoderOutput::IntermediateChunk,
self.width,
self.height,
self.fps,
&self.segment_path(claim.segment),
self.render_options,
+ &self.input,
self.logger,
)?
};
- let frame = unsafe { EncoderFrame::new(&encoder.video_stream)? };
*guard = Some(Segment {
encoder,
- frame,
+ packet: AvPacketAutoFree::new(),
next_frame: claim.segment,
end: None,
pending: BTreeMap::new(),
+ converter: None,
});
}
@@ -125,24 +168,16 @@ impl<'a, 'o, 'm> SegmentWriter<'a, 'o, 'm> {
segment.end = Some(claim.frame + 1);
}
+ let frame = frame(segment)?;
if claim.frame == segment.next_frame {
- match pixels {
- FramePixels::Borrowed(rgba) => Self::encode(segment, claim.frame, rgba)?,
- FramePixels::Owned(rgba) => {
- Self::encode(segment, claim.frame, &rgba)?;
- released.push(rgba);
- }
- }
- while let Some(rgba) = segment.pending.remove(&segment.next_frame) {
- Self::encode(segment, segment.next_frame, &rgba)?;
- released.push(rgba);
+ Self::encode(segment, claim.frame, &frame)?;
+ // the encoder holds its own reference for as long as it needs the pixels
+ drop(frame);
+ while let Some(frame) = segment.pending.remove(&segment.next_frame) {
+ Self::encode(segment, segment.next_frame, &frame)?;
}
} else {
- let rgba = match pixels {
- FramePixels::Borrowed(rgba) => rgba.to_vec(),
- FramePixels::Owned(rgba) => rgba,
- };
- segment.pending.insert(claim.frame, rgba);
+ segment.pending.insert(claim.frame, frame);
}
if segment.end == Some(segment.next_frame) {
@@ -162,20 +197,18 @@ impl<'a, 'o, 'm> SegmentWriter<'a, 'o, 'm> {
.push((claim.segment, self.segment_path(claim.segment)));
}
- Ok(released)
+ Ok(())
}
- fn encode(segment: &mut Segment, frame: usize, rgba: &[u8]) -> RenderEncodingResult<()> {
+ fn encode(segment: &mut Segment, index: usize, frame: &VideoFrame) -> RenderEncodingResult<()> {
unsafe {
- segment.frame.fill_from_rgba_pixmap(rgba);
// frame indexes are used as pts, av_packet_rescale_ts converts them into the
// stream time base
- segment.frame.set_pts(frame as i64);
segment
.encoder
- .send_frame(&segment.encoder.video_stream, &segment.frame)?;
+ .send_video_frame(frame, index as i64, segment.packet.get())?;
}
- segment.next_frame = frame + 1;
+ segment.next_frame = index + 1;
Ok(())
}
diff --git a/fframes/src/renderer/stream.rs b/fframes/src/renderer/stream.rs
index 50dda43e..460f8ef6 100644
--- a/fframes/src/renderer/stream.rs
+++ b/fframes/src/renderer/stream.rs
@@ -1,5 +1,6 @@
use super::EncoderOptions;
use super::ffmpeg_helper::STEREO_CH_LAYOUT;
+use super::frame_export::EncoderInput;
use super::renderer_error::{RenderEncodingError, RenderEncodingResult};
use crate::ffmpeg_action;
use crate::ffmpeg_loggable_action;
@@ -93,12 +94,165 @@ unsafe fn fit_sample_format(codec: *const AVCodec, requested: AVSampleFormat) ->
}
}
-unsafe fn is_pixel_format_supported(codec: *const AVCodec, pixel_format: AVPixelFormat) -> bool {
- let supported = unsafe {
+/// The pixel formats the encoder takes, `None` when it accepts any (or libav can't tell).
+pub(crate) unsafe fn supported_pixel_formats<'a>(
+ codec: *const AVCodec,
+) -> Option<&'a [AVPixelFormat]> {
+ unsafe {
supported_codec_config::<AVPixelFormat>(codec, AVCodecConfig::AV_CODEC_CONFIG_PIX_FORMAT)
- };
+ }
+}
+
+unsafe fn is_pixel_format_supported(codec: *const AVCodec, pixel_format: AVPixelFormat) -> bool {
+ unsafe { supported_pixel_formats(codec) }.is_none_or(|formats| formats.contains(&pixel_format))
+}
+
+/// The encoder named `preferred_encoder`, otherwise the default encoder of `codec_id`.
+pub(crate) unsafe fn find_encoder(
+ preferred_encoder: Option<&str>,
+ codec_id: AVCodecID,
+ warn_about_fallback: bool,
+) -> RenderEncodingResult<*const AVCodec> {
+ unsafe {
+ let mut codec = if let Some(encoder) = preferred_encoder {
+ let codec_name = CString::new(encoder).map_err(RenderEncodingError::CStringError)?;
+
+ avcodec_find_encoder_by_name(codec_name.as_ptr())
+ } else {
+ std::ptr::null()
+ };
+
+ if codec.is_null() {
+ codec = avcodec_find_encoder(codec_id);
+
+ if let Some(preferred_codec_name) = preferred_encoder
+ && !codec.is_null()
+ && warn_about_fallback
+ {
+ let found_encoder_name = CStr::from_ptr((*codec).name);
+
+ eprintln!(
+ "Warning: Can not find encoder {preferred_codec_name}, continue with {found_encoder_name}",
+ found_encoder_name =
+ found_encoder_name.to_str().unwrap_or("unknown codec name")
+ );
+ }
+ }
+
+ if codec.is_null() {
+ return Err(RenderEncodingError::CannotLocateCodec);
+ }
+
+ Ok(codec)
+ }
+}
+
+/// Configures the context of a video encoder for `input` and opens it.
+pub(crate) unsafe fn open_video_encoder(
+ c: *mut AVCodecContext,
+ codec: *const AVCodec,
+ (width, height, fps): (i32, i32, i32),
+ global_header: bool,
+ encoder_options: &EncoderOptions,
+ input: &EncoderInput,
+ thread_count: i32,
+) -> RenderEncodingResult<()> {
+ unsafe {
+ (*c).codec_id = (*codec).id;
+ (*c).width = width;
+ (*c).height = height;
+ // avcodec_open2 applies codec_params afterwards, so an explicit `threads`
+ // option still overrides this default (including `threads=0` for auto).
+ (*c).thread_count = thread_count;
+ (*c).time_base = AVRational { num: 1, den: fps };
+
+ if !is_pixel_format_supported(codec, input.pixel_format) {
+ return Err(RenderEncodingError::InvalidPixFmt(input.pixel_format));
+ }
+
+ (*c).pix_fmt = input.pixel_format;
+ // The encoder shares the frame pool (and with it the device) the backend
+ // renders into.
+ if let Some(frames) = &input.hw_frames_ctx {
+ (*c).hw_frames_ctx = frames.new_ref();
+ }
+ if let Some(device) = &input.hw_device_ctx {
+ (*c).hw_device_ctx = device.new_ref();
+ }
+ // Every RGBA to YUV path (the built-in yuv420 converter, swscale's
+ // default and the GPU converters of the backends) produces BT.601
+ // limited range. Say so: an untagged HD stream is decoded as BT.709,
+ // shifting colors. Hardware encoders that are fed RGB surfaces
+ // convert with the matrix they are told here.
+ let pix_fmt_desc = av_pix_fmt_desc_get(input.pixel_format);
+ if !pix_fmt_desc.is_null() && (*pix_fmt_desc).flags & AV_PIX_FMT_FLAG_RGB as u64 == 0 {
+ (*c).color_range = AVColorRange::AVCOL_RANGE_MPEG;
+ (*c).colorspace = AVColorSpace::AVCOL_SPC_SMPTE170M;
+ }
+ (*c).gop_size = encoder_options.gop_size;
+ (*c).qmin = encoder_options.qmin;
+ (*c).qmax = encoder_options.qmax;
+ (*c).qcompress = encoder_options.qcompress;
+ (*c).max_qdiff = encoder_options.max_qdiff;
+ (*c).bit_rate_tolerance = encoder_options.bitrate_tolerance;
+
+ if let Some(video_bitrate) = encoder_options.bitrate {
+ (*c).bit_rate = video_bitrate;
+ }
+
+ if global_header {
+ (*c).flags |= AV_CODEC_FLAG_GLOBAL_HEADER as i32;
+ }
+
+ let opts: *mut *mut AVDictionary = &mut std::ptr::null_mut();
+
+ let codec_options = match encoder_options.codec_params {
+ Some(options) => Some(options),
+ None if !(*codec).name.is_null() => {
+ let codec_name = CStr::from_ptr((*codec).name).to_string_lossy();
+
+ match codec_name.as_ref() {
+ "libx264" => Some(
+ [
+ ("preset", "ultrafast"),
+ ("tune", "animation"),
+ ("profile", "main"),
+ ("bframes", "2"),
+ ("crf", "23"),
+ ]
+ .as_slice(),
+ ),
+ "libx265" => Some(
+ [
+ ("preset", "ultrafast"),
+ ("tune", "animation"),
+ ("profile", "main"),
+ ("crf", "23"),
+ ("x265-params", "log-level=none"),
+ ]
+ .as_slice(),
+ ),
+ _ => None,
+ }
+ }
+ _ => None,
+ };
+
+ if let Some(codec_params) = codec_options {
+ for (param, value) in codec_params {
+ let c_param = CString::new(*param).map_err(RenderEncodingError::CStringError)?;
+ let c_value = CString::new(*value).map_err(RenderEncodingError::CStringError)?;
+
+ av_dict_set(opts, c_param.as_ptr(), c_value.as_ptr(), 0);
+ }
+ }
+
+ let status = avcodec_open2(c, codec, opts);
+ av_dict_free(opts);
+ ffmpeg_loggable_action!(status);
- supported.is_none_or(|formats| formats.contains(&pixel_format))
+ Ok(())
+ }
}
impl Stream {
@@ -132,35 +286,7 @@ impl Stream {
*mut AVCodecContext,
)> {
unsafe {
- let mut codec = if let Some(encoder) = preferred_encoder {
- let codec_name =
- CString::new(encoder).map_err(RenderEncodingError::CStringError)?;
-
- avcodec_find_encoder_by_name(codec_name.as_ptr())
- } else {
- std::ptr::null_mut()
- };
-
- if codec.is_null() {
- codec = avcodec_find_encoder(codec_id);
-
- if let Some(preferred_codec_name) = preferred_encoder
- && !codec.is_null()
- {
- let found_encoder_name = CStr::from_ptr((*codec).name);
-
- eprintln!(
- "Warning: Can not find encoder {preferred_codec_name}, continue with {found_encoder_name}",
- found_encoder_name =
- found_encoder_name.to_str().unwrap_or("unknown codec name")
- );
- }
- }
-
- if codec.is_null() {
- return Err(RenderEncodingError::CannotLocateCodec);
- }
-
+ let codec = find_encoder(preferred_encoder, codec_id, true)?;
let codec_id = (*codec).id;
let st = avformat_new_stream(oc, std::ptr::null_mut());
@@ -182,107 +308,32 @@ impl Stream {
fps: i32,
oc: *mut AVFormatContext,
encoder_options: &EncoderOptions,
+ input: &EncoderInput,
thread_count: i32,
) -> RenderEncodingResult<Self> {
unsafe {
- let (codec, codec_id, st, c) = Self::prepare_stream_codec(
+ let (codec, _codec_id, st, c) = Self::prepare_stream_codec(
encoder_options.preferred_encoder,
(*(*oc).oformat).video_codec,
oc,
)?;
- (*c).codec_id = codec_id;
- (*c).width = width;
- (*c).height = height;
- // avcodec_open2 applies codec_params afterwards, so an explicit `threads`
- // option still overrides this default (including `threads=0` for auto).
- (*c).thread_count = thread_count;
(*st).time_base = AVRational { num: 1, den: fps };
- (*c).time_base = (*st).time_base;
-
- if !is_pixel_format_supported(codec, encoder_options.pixel_format) {
- return Err(RenderEncodingError::InvalidPixFmt(
- encoder_options.pixel_format,
- ));
- }
-
- (*c).pix_fmt = encoder_options.pixel_format;
- // Both RGBA → YUV paths (the built-in yuv420 converter and
- // swscale's default) produce BT.601 limited range. Say so: an
- // untagged HD stream is decoded as BT.709, shifting colors.
- let pix_fmt_desc = av_pix_fmt_desc_get(encoder_options.pixel_format);
- if !pix_fmt_desc.is_null() && (*pix_fmt_desc).flags & AV_PIX_FMT_FLAG_RGB as u64 == 0 {
- (*c).color_range = AVColorRange::AVCOL_RANGE_MPEG;
- (*c).colorspace = AVColorSpace::AVCOL_SPC_SMPTE170M;
- }
- (*c).gop_size = encoder_options.gop_size;
- (*c).qmin = encoder_options.qmin;
- (*c).qmax = encoder_options.qmax;
- (*c).qcompress = encoder_options.qcompress;
- (*c).max_qdiff = encoder_options.max_qdiff;
- (*c).bit_rate_tolerance = encoder_options.bitrate_tolerance;
-
- if let Some(video_bitrate) = encoder_options.bitrate {
- (*c).bit_rate = video_bitrate;
- }
-
- if (*(*oc).oformat).flags & AVFMT_GLOBALHEADER != 0 {
- (*c).flags |= AV_CODEC_FLAG_GLOBAL_HEADER as i32;
- }
-
- let opts: *mut *mut AVDictionary = &mut std::ptr::null_mut();
-
- let codec_options = match encoder_options.codec_params {
- Some(options) => Some(options),
- None if !(*codec).name.is_null() => {
- let codec_name = CStr::from_ptr((*codec).name).to_string_lossy();
-
- match codec_name.as_ref() {
- "libx264" => Some(
- [
- ("preset", "ultrafast"),
- ("tune", "animation"),
- ("profile", "main"),
- ("bframes", "2"),
- ("crf", "23"),
- ]
- .as_slice(),
- ),
- "libx265" => Some(
- [
- ("preset", "ultrafast"),
- ("tune", "animation"),
- ("profile", "main"),
- ("crf", "23"),
- ("x265-params", "log-level=none"),
- ]
- .as_slice(),
- ),
- _ => None,
- }
- }
- _ => None,
- };
-
- if let Some(codec_params) = codec_options {
- for (param, value) in codec_params {
- let c_param =
- CString::new(*param).map_err(RenderEncodingError::CStringError)?;
- let c_value =
- CString::new(*value).map_err(RenderEncodingError::CStringError)?;
-
- av_dict_set(opts, c_param.as_ptr(), c_value.as_ptr(), 0);
- }
- }
-
- ffmpeg_loggable_action!(avcodec_open2(c, codec, opts));
+ open_video_encoder(
+ c,
+ codec,
+ (width, height, fps),
+ (*(*oc).oformat).flags & AVFMT_GLOBALHEADER != 0,
+ encoder_options,
+ input,
+ thread_count,
+ )?;
ffmpeg_loggable_action!(avcodec_parameters_from_context((*st).codecpar, c));
if let Some((tag, options)) = encoder_options.tag.zip((*st).codecpar.as_mut()) {
options.codec_tag = tag as u32;
}
- av_dict_free(opts);
Ok(Stream {
st,
enc: c,
diff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.md
index 3614a0f4..f3ca4e2e 100644
--- a/skills/fframes-video/references/api.md
+++ b/skills/fframes-video/references/api.md
@@ -177,6 +177,12 @@ Skia: `SkiaFFramesRenderer::new_metal(&SkiaMetalCtx::new(W, H)?, SkiaPipelineCon
`vulkan`). `backend.frame_renderer()`
returns a renderer for single frames that matches the backend (Skia on the GPU for Skia).
+The Skia backend picks the fastest way to hand frames to the encoder on its own: hardware
+frames (`*_videotoolbox` encoders with `new_metal`; `h264_vulkan`/`hevc_vulkan` with
+`SkiaVulkanCtx::new_shared_with_encoder` and the `vulkan-video` feature), else conversion to
+the encoder's YUV format on the GPU, else on the CPU. `.frame_export(SkiaFrameExport::CpuConversion)`
+on the renderer turns that off.
+
## The project's command line
`main.rs` builds it with `fframes::cli::new`; everything after it is optional: