From a1dae8565d1030c5c90d343eed0f9675ace09c79 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 07:33:30 +0300 Subject: [PATCH] voelin-media: GPU frames for every simulcast layer, encoded from their surfaces The streamer's zero-copy path needs the conversion and the encoding on different threads: the captured buffer has to go back to the compositor at once, while each layer's encoder runs on its own thread. So split what encode_dmabuf did in one call: - GpuConverter (ffmpeg/gpu.rs), on the capture thread: maps an RGB DMA-BUF onto a VA-API surface and converts it with VA-API video processing into an NV12 surface per layer that is due, the whole picture scaled to the layer's size and cropped to its encoder's alignment. The surfaces come from pools of our own and travel as GpuFrames, which are recycled once nothing holds them, so nothing is allocated per frame once the pools are warm. It also reports the tiled modifier the driver gives its own RGB surfaces, for the portal to offer. - VideoEncoder::gpu_alignment and encode_gpu: VA-API encoders take a GpuFrame's surface as it is (the encoder references it until it is done); every other encoder says it takes none. encode_dmabuf's RGB path now goes through the same converter instead of a second copy of the import and conversion in the session. Checked on the RX 7900 GRE: h264_vaapi encodes surfaces from a pool other than its own; the scaled 640x352 layer is 48.5 dB against the CPU pyramid's picture and the full one 40.4 dB (Y identical, chroma within 0.7); each layer's surface decodes through OpenH264; frames come back once released; the driver's tiled RGB modifier is 0x200000028a01f04. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/src/codec/mod.rs | 26 ++ crates/voelin-media/src/ffmpeg/encoder.rs | 528 +++++++++++----------- crates/voelin-media/src/ffmpeg/gpu.rs | 371 +++++++++++++++ crates/voelin-media/src/ffmpeg/mod.rs | 4 + crates/voelin-media/src/ffmpeg/sys.rs | 1 + crates/voelin-media/src/ffmpeg/vpp.rs | 38 +- crates/voelin-media/src/frame.rs | 29 ++ crates/voelin-media/src/lib.rs | 2 +- 8 files changed, 729 insertions(+), 270 deletions(-) create mode 100644 crates/voelin-media/src/ffmpeg/gpu.rs diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 138f2e7..c0c9566 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -257,6 +257,32 @@ pub trait VideoEncoder: Send { fn speed(&self) -> Option { None } + + /// Whether this encoder takes [`GpuFrame`](crate::GpuFrame)s + /// ([`encode_gpu`](Self::encode_gpu)), and then the multiple their + /// width and height must be of (a size it encodes exactly; GPU frames + /// are made at that size instead of being cropped here). `None` for + /// encoders that need the pixels in memory: all but VA-API. + fn gpu_alignment(&self) -> Option<(u32, u32)> { + None + } + + /// Encode a frame that is in GPU memory, like + /// [`encode_with`](Self::encode_with). Only for encoders with a + /// [`gpu_alignment`](Self::gpu_alignment), and frames of a size that is a + /// multiple of it; the rest fail with `Error::CodecUnavailable`. + fn encode_gpu( + &mut self, + frame: &crate::GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let _ = (frame, force_keyframe, out); + Err(Error::CodecUnavailable { + codec: self.codec(), + reason: format!("{} takes no frames in GPU memory", self.backend()), + }) + } } /// A video decoder. diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index f2e2a7b..f1e1859 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -15,6 +15,7 @@ use std::ffi::c_int; use std::sync::OnceLock; use std::time::{Duration, Instant}; +use super::gpu::{self, GpuConverter, GpuLayer, RGB_FOURCCS}; use super::layout::{self, HwFramesFields}; use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; use super::{Ffmpeg, take_log, vpp}; @@ -25,7 +26,7 @@ use crate::codec::{ VideoEncoder, }; use crate::convert; -use crate::frame::{FrameData, VideoFrame}; +use crate::frame::{FrameData, GpuFrame, VideoFrame}; use crate::{Error, Result}; /// How a backend takes frames. @@ -454,7 +455,7 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { /// The `VADisplay` of the process's VA-API device (the first field of its /// `AVVAAPIDeviceContext`). -fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result { +pub(crate) fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result { let device = vaapi_device(ffmpeg)?; let name = cstr("vaapi"); // SAFETY: a C string; `device` is a live VA-API device reference, whose @@ -466,6 +467,56 @@ fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result { } } +/// A pool of VA-API surfaces of `sw_format` (an `AVPixelFormat`) and +/// `width` x `height` on the process's device (an `AVHWFramesContext` +/// reference); surfaces are made on demand and recycled. +pub(crate) fn vaapi_pool( + ffmpeg: &Ffmpeg, + width: u32, + height: u32, + sw_format: c_int, +) -> std::result::Result { + let api = &ffmpeg.api; + let device = vaapi_device(ffmpeg)?; + let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?; + // SAFETY: `device` is a live device reference. + let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; + if pool.is_null() { + return Err("av_hwframe_ctx_alloc failed".into()); + } + // SAFETY: `pool` was just allocated on `device`. + let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } { + Ok(f) => f, + Err(e) => { + // SAFETY: allocated above. + unsafe { (api.av_buffer_unref)(&mut pool) }; + return Err(e); + } + }; + // SAFETY: the fields were located and checked on this very context; + // setting them before av_hwframe_ctx_init is what FFmpeg expects. + let ret = unsafe { + let ctx = (*pool.cast::()).data.cast::(); + layout::write::(ctx, fields.format, vaapi); + layout::write::(ctx, fields.sw_format, sw_format); + layout::write::(ctx, fields.width, width as c_int); + layout::write::(ctx, fields.height, height as c_int); + // Surfaces are allocated on demand and recycled by the pool. + layout::write::(ctx, fields.initial_pool_size, 0); + (api.av_hwframe_ctx_init)(pool) + }; + if ret < 0 { + // SAFETY: allocated above. + unsafe { (api.av_buffer_unref)(&mut pool) }; + return Err(format!( + "VA-API surface pool: {}{}", + api.error_text(ret), + log_suffix("AVHWFramesContext") + )); + } + Ok(pool) +} + /// FFmpeg's recent messages, appended to an error. fn log_suffix(context: &str) -> String { let log = take_log(context); @@ -527,8 +578,6 @@ struct Session { opened: Instant, timestamps: Timestamps, nv12: bool, - /// RGB DMA-BUFs: made on the first one; why not, if they cannot be. - rgb: Option>, /// An AMF encoder: opened and closed under [`amf_lock`]. amf: bool, } @@ -552,47 +601,6 @@ fn amf_lock() -> std::sync::MutexGuard<'static, ()> { AMF.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } -/// What RGB DMA-BUFs need on their way into the session's NV12 surfaces: -/// a frames context of their own size to be mapped onto (FFmpeg gives an -/// imported surface the size of the destination's frames context, and the -/// session's has the coded size), the frame that holds the mapping, and -/// the GPU colour conversion. -struct RgbImport { - pool: Ptr, - mapped: Ptr, - size: (u32, u32), - converter: vpp::Converter, -} - -// SAFETY: as `Session`, which owns it. -unsafe impl Send for RgbImport {} - -impl Drop for RgbImport { - fn drop(&mut self) { - let api = &Ffmpeg::get().expect("an import exists only with FFmpeg").api; - // SAFETY: both are NULL or ours. - unsafe { - (api.av_frame_free)(&mut self.mapped); - (api.av_buffer_unref)(&mut self.pool); - } - } -} - -/// The VA-API surface of a VA-API frame (`data[3]`, `hwcontext_vaapi.h`). -/// -/// # Safety -/// `frame` must be a live frame of format `AV_PIX_FMT_VAAPI` holding a -/// surface. -unsafe fn surface_id(frame: Ptr) -> std::ffi::c_uint { - // SAFETY: guaranteed by the caller. - unsafe { (*frame.cast::()).data[3] as usize as std::ffi::c_uint } -} - -/// The DRM formats of RGB buffers the conversion takes (8 bits per -/// channel, 4 bytes per pixel; what screen capture offers). -const RGB_FOURCCS: [u32; 4] = - [drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")]; - impl Drop for Session { fn drop(&mut self) { let api = &Ffmpeg::get().expect("a session exists only with FFmpeg").api; @@ -640,6 +648,16 @@ pub struct FfmpegEncoder { /// Sizes it encodes exactly are multiples of these /// ([`BackendStatus::alignment`]). alignment: (u32, u32), + /// For RGB DMA-BUFs ([`encode_dmabuf`](Self::encode_dmabuf)): made on + /// the first one; why not, if it cannot be. + gpu: Option>, +} + +/// `size` cropped to a multiple of `alignment` (even at least, for 4:2:0 +/// chroma; at least 2x2): what an encoder of that alignment encodes exactly. +pub(crate) fn exact_size(size: (u32, u32), alignment: (u32, u32)) -> (u32, u32) { + let crop = |v: u32, a: u32| if v >= a { v / a * a } else { (v & !1).max(2) }; + (crop(size.0, alignment.0), crop(size.1, alignment.1)) } impl FfmpegEncoder { @@ -670,6 +688,7 @@ impl FfmpegEncoder { low_power: false, dmabuf_checked: false, alignment, + gpu: None, }) } @@ -735,11 +754,10 @@ impl FfmpegEncoder { } /// The encoder size: the frame cropped to a multiple of the backend's - /// alignment (even at least, for 4:2:0 chroma), so that the stream - /// declares exactly the picture it carries; at least 2x2. + /// alignment, so that the stream declares exactly the picture it + /// carries ([`exact_size`]). fn coded_size(&self, width: u32, height: u32) -> (u32, u32) { - let crop = |v: u32, a: u32| if v >= a { v / a * a } else { (v & !1).max(2) }; - (crop(width, self.alignment.0), crop(height, self.alignment.1)) + exact_size((width, height), self.alignment) } /// Open a session for `width` x `height`. @@ -791,7 +809,7 @@ impl FfmpegEncoder { opened: Instant::now(), timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, - rgb: None, + amf: false, }; // SAFETY: `ctx` is a live codec context; the first child is its @@ -863,7 +881,8 @@ impl FfmpegEncoder { self.apply(ctx, private, setting)?; } if self.spec.is_vaapi() { - session.pool = self.vaapi_pool(width, height, self.ffmpeg.pix.nv12)?; + session.pool = vaapi_pool(self.ffmpeg, width, height, self.ffmpeg.pix.nv12) + .map_err(|e| self.unavailable(e))?; let offset = self.ffmpeg.codec_hw_frames.clone().map_err(|e| self.unavailable(e))?; // SAFETY: `offset` is AVCodecContext.hw_frames_ctx (checked at // load); the context takes the new reference and frees it. @@ -919,45 +938,6 @@ impl FfmpegEncoder { /// A VA-API surface pool of `sw_format` (an `AVPixelFormat`) for `width` /// x `height`. - fn vaapi_pool(&self, width: u32, height: u32, sw_format: c_int) -> Result { - let api = &self.ffmpeg.api; - let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?; - let vaapi = - self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; - // SAFETY: `device` is a live device reference. - let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; - if pool.is_null() { - return Err(self.unavailable("av_hwframe_ctx_alloc failed".into())); - } - // SAFETY: `pool` was just allocated on `device`. - let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } { - Ok(f) => f, - Err(e) => { - // SAFETY: allocated above. - unsafe { (api.av_buffer_unref)(&mut pool) }; - return Err(self.unavailable(e)); - } - }; - // SAFETY: the fields were located and checked on this very context; - // setting them before av_hwframe_ctx_init is what FFmpeg expects. - let ret = unsafe { - let ctx = (*pool.cast::()).data.cast::(); - layout::write::(ctx, fields.format, vaapi); - layout::write::(ctx, fields.sw_format, sw_format); - layout::write::(ctx, fields.width, width as c_int); - layout::write::(ctx, fields.height, height as c_int); - // Surfaces are allocated on demand and recycled by the pool. - layout::write::(ctx, fields.initial_pool_size, 0); - (api.av_hwframe_ctx_init)(pool) - }; - if ret < 0 { - // SAFETY: allocated above. - unsafe { (api.av_buffer_unref)(&mut pool) }; - return Err(self.error("VA-API surface pool", ret)); - } - Ok(pool) - } - /// Copy the I420 picture into the session's frame (cropped to the coded /// size; NV12 interleaved where the backend wants it). fn fill(&self, session: &Session, frame: &VideoFrame) -> Result<()> { @@ -1132,9 +1112,8 @@ impl FfmpegEncoder { /// (their size must be one it encodes exactly), and stay in use until /// this frame's packet came out (the encoder reads them one frame deep). /// RGB buffers (`XR24`, `AR24`, `XB24`, `AB24`: what screen capture - /// delivers) are converted into the session's NV12 surfaces on the GPU - /// (VA-API video processing), cropped to the coded size, and - /// are no longer read when this returns. + /// delivers) are converted to NV12 on the GPU ([`GpuConverter`]), cropped + /// to the coded size, and are no longer read when this returns. /// /// Anything else fails with `Error::CodecUnavailable`; callers then map /// the buffer and use [`encode_with`](VideoEncoder::encode_with). @@ -1147,11 +1126,35 @@ impl FfmpegEncoder { if !self.spec.is_vaapi() { return Err(self.unavailable(format!("{} does not import DMA-BUFs", self.spec.name))); } - let rgb = RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1; - if !rgb && (frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2) { + if RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1 { + let converter = match self + .gpu + .get_or_insert_with(|| GpuConverter::new().map_err(|e| e.to_string())) + { + Ok(converter) => converter, + Err(e) => { + return Err(Error::CodecUnavailable { + codec: self.spec.codec, + reason: e.clone(), + }); + } + }; + let layer = GpuLayer { + size: (frame.width, frame.height), + alignment: self.alignment, + due: true, + }; + let mut converted = [None]; + if let Err(e) = converter.convert(frame, &[layer], &mut converted) { + return Err(self.unavailable(e.to_string())); + } + let gpu = converted[0].take().expect("a due layer gets a frame"); + return self.encode_gpu(&gpu, force_keyframe, out); + } + if frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2 { return Err(self.unavailable("only NV12 and RGB DMA-BUFs are imported".into())); } - if !rgb && self.coded_size(frame.width, frame.height) != (frame.width, frame.height) { + if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) { return Err(self.unavailable(format!( "{}x{} is not a size {} encodes exactly", frame.width, frame.height, self.spec.name @@ -1159,16 +1162,16 @@ impl FfmpegEncoder { } let refs = self.ffmpeg.frame_refs.clone().map_err(|e| self.unavailable(e))?; let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; - let result = self.import_and_send(&mut session, frame, rgb, force, refs, out); + let result = self.import_and_send(&mut session, frame, force, refs, out); self.session = Some(session); result } + /// Map an NV12 DMA-BUF onto a surface of the session and encode it. fn import_and_send( &mut self, session: &mut Session, frame: &DmaBufRef, - rgb: bool, force: bool, refs: layout::FrameRefs, out: &mut dyn FnMut(EncodedChunk<'_>), @@ -1189,35 +1192,25 @@ impl FfmpegEncoder { } self.dmabuf_checked = true; } - let (pool, hw) = (session.pool, session.hw); - if rgb { - let import = self.rgb_import(session, frame)?; - self.map_dmabuf(frame, import.pool, import.mapped, refs)?; - // SAFETY: `hw` is our frame (unreferenced after each frame), the - // pool the session's; both surfaces belong to the process's - // device, the converter's display. - let converted = unsafe { - let ret = (api.av_hwframe_get_buffer)(pool, hw, 0); - let converted = if ret < 0 { - Err(self.error("VA-API surface", ret)) - } else { - let done = import.converter.convert(surface_id(import.mapped), surface_id(hw)); - done.map_err(|e| self.unavailable(e)) - }; - // The buffer has been read: the mapping can go. - (api.av_frame_unref)(import.mapped); - converted - }; - if let Err(e) = converted { - // SAFETY: our frame. - unsafe { (api.av_frame_unref)(hw) }; - return Err(e); - } - } else { - self.map_dmabuf(frame, pool, hw, refs)?; - } + let hw = session.hw; + gpu::map_dmabuf(self.ffmpeg, frame, session.pool, hw, refs).map_err(|e| { + Error::Encoder { codec: self.spec.codec, message: format!("{}: {e}", self.spec.name) } + })?; let pts = self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64); + self.send_surface(session, pts, force, out) + } + + /// Encode the surface in `session.hw` (taken from the session's frame + /// afterwards; the encoder keeps its own reference while it needs it). + fn send_surface( + &self, + session: &mut Session, + pts: i64, + force: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let hw = session.hw; let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; // SAFETY: offsets checked at load for this release's AVFrame; `hw` // holds a surface until the unref. @@ -1226,103 +1219,11 @@ impl FfmpegEncoder { layout::write::(hw, self.ffmpeg.frame.pict_type, pict_type); } let result = self.send(session, hw, out); - // SAFETY: our frame; the encoder holds its own reference. - unsafe { (api.av_frame_unref)(hw) }; + // SAFETY: our frame. + unsafe { (self.ffmpeg.api.av_frame_unref)(hw) }; result.map(|_| ()) } - /// The session's [`RgbImport`] for `frame`, made on first use (again - /// when the buffers change size within the session's coded size). - fn rgb_import<'s>(&self, session: &'s mut Session, frame: &DmaBufRef) -> Result<&'s RgbImport> { - let size = (frame.width, frame.height); - let stale = match &session.rgb { - None => true, - Some(Ok(import)) => import.size != size, - Some(Err(_)) => false, - }; - if stale { - session.rgb = None; - session.rgb = Some(self.new_rgb_import(size, (session.width, session.height))); - } - match session.rgb.as_ref().expect("made above") { - Ok(import) => Ok(import), - Err(e) => Err(self.unavailable(e.clone())), - } - } - - fn new_rgb_import( - &self, - size: (u32, u32), - coded: (u32, u32), - ) -> std::result::Result { - let bgr0 = self.ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?; - let display = vaapi_display(self.ffmpeg)?; - let converter = vpp::Converter::new(display, coded.0, coded.1)?; - let pool = self.vaapi_pool(size.0, size.1, bgr0).map_err(|e| e.to_string())?; - // SAFETY: an allocation (NULL is freed as nothing by the drop). - let mapped = unsafe { (self.ffmpeg.api.av_frame_alloc)() }; - let import = RgbImport { pool, mapped, size, converter }; - if import.mapped.is_null() { Err("out of memory".into()) } else { Ok(import) } - } - - /// Map DMA-BUF `frame` onto a VA-API surface in `dst` (one of our - /// frames), which gets a reference to `pool`: the import takes that - /// frames context's size and device. - fn map_dmabuf( - &self, - frame: &DmaBufRef, - pool: Ptr, - dst: Ptr, - refs: layout::FrameRefs, - ) -> Result<()> { - let api = &self.ffmpeg.api; - let drm_prime = - self.ffmpeg.pix.drm_prime.ok_or_else(|| self.unavailable("no DRM PRIME".into()))?; - let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API".into()))?; - let mut descriptor = - sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() }; - descriptor.objects[0] = - sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier }; - descriptor.layers[0].format = frame.fourcc; - descriptor.layers[0].nb_planes = frame.plane_count as c_int; - for (plane, &(offset, pitch)) in - descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count]) - { - *plane = - sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; - } - // SAFETY: the descriptor lives in a buffer the source frame owns - // (buf[0], checked offset), so FFmpeg can keep it while mapped; the - // destination frame gets a reference to the pool at the checked - // hw_frames_ctx offset; av_frame_free / av_frame_unref release both. - unsafe { - let mut buffer = (api.av_buffer_allocz)(std::mem::size_of::()); - let mut src = (api.av_frame_alloc)(); - if buffer.is_null() || src.is_null() { - (api.av_buffer_unref)(&mut buffer); - (api.av_frame_free)(&mut src); - return Err(self.unavailable("out of memory".into())); - } - let data = (*buffer.cast::()).data; - data.cast::().write(descriptor); - let head = src.cast::(); - (*head).format = drm_prime; - (*head).width = frame.width as c_int; - (*head).height = frame.height as c_int; - (*head).data[0] = data; - layout::write::(src, refs.buf, buffer); - (*dst.cast::()).format = vaapi; - layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool)); - let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ); - (api.av_frame_free)(&mut src); - if ret < 0 { - (api.av_frame_unref)(dst); - return Err(self.error("DMA-BUF import", ret)); - } - } - Ok(()) - } - /// The pts of a frame taken at `timestamp`: frame numbers at the /// session's rate (its time base), strictly increasing; remembered with /// the 90 kHz time for the packets. @@ -1508,6 +1409,42 @@ impl VideoEncoder for FfmpegEncoder { } Ok(()) } + + /// VA-API encoders take NV12 surfaces of the sizes they encode exactly. + fn gpu_alignment(&self) -> Option<(u32, u32)> { + self.spec.is_vaapi().then_some(self.alignment) + } + + /// The surface goes to the encoder as it is: the encoder takes a + /// reference, so it stays out of its pool until the encoder is done. + fn encode_gpu( + &mut self, + frame: &GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + if !self.spec.is_vaapi() { + return Err(self.unavailable(format!("{} takes no VA-API surfaces", self.spec.name))); + } + if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) { + return Err(self.unavailable(format!( + "{}x{} is not a size {} encodes exactly", + frame.width, frame.height, self.spec.name + ))); + } + let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; + let pts = self.stamp(&mut session, frame.timestamp, frame.pts_90khz()); + // SAFETY: `hw` is our frame, unreferenced after each frame; + // `surface` is a live VA-API frame of the same device. + let ret = unsafe { (self.ffmpeg.api.av_frame_ref)(session.hw, frame.surface.0) }; + let result = if ret < 0 { + Err(self.error("GPU frame", ret)) + } else { + self.send_surface(&mut session, pts, force, out) + }; + self.session = Some(session); + result + } } /// A gradient test picture. @@ -2102,8 +2039,7 @@ mod tests { ) -> Self { let ffmpeg = Ffmpeg::get().unwrap(); let api = &ffmpeg.api; - let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); - let pool = encoder.vaapi_pool(width, height, sw_format).expect("a VA-API surface pool"); + let pool = vaapi_pool(ffmpeg, width, height, sw_format).expect("a VA-API surface pool"); // SAFETY: `pool` is a live frames context of this process's // VA-API device; the frames are ours and freed by the drop. The // exported frame's `data[0]` is the AVDRMFrameDescriptor FFmpeg @@ -2190,6 +2126,113 @@ mod tests { } } + /// The picture of a GPU frame, read back into memory as I420. + fn download(frame: &GpuFrame) -> VideoFrame { + let ffmpeg = Ffmpeg::get().unwrap(); + let api = &ffmpeg.api; + let (w, h) = (frame.width as usize, frame.height as usize); + let mut out = VideoFrame::black_i420(frame.width, frame.height); + let FrameData::I420 { y, u, v } = &mut out.data else { unreachable!() }; + // SAFETY: `sw` is ours and freed below; a downloaded plane holds + // `linesize * rows` bytes. + unsafe { + let mut sw = (api.av_frame_alloc)(); + (*sw.cast::()).format = ffmpeg.pix.nv12; + assert!((api.av_hwframe_transfer_data)(sw, frame.surface.0, 0) >= 0, "download"); + let head = &*sw.cast::(); + let rows = |i: usize, rows: usize| { + let stride = head.linesize[i] as usize; + std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride) + }; + for (row, src) in rows(0, h).enumerate() { + y.data[row * w..][..w].copy_from_slice(&src[..w]); + } + let cw = w / 2; + for (row, src) in rows(1, h / 2).enumerate() { + for (i, pair) in src[..cw * 2].chunks_exact(2).enumerate() { + u.data[row * u.stride + i] = pair[0]; + v.data[row * v.stride + i] = pair[1]; + } + } + (api.av_frame_free)(&mut sw); + } + out + } + + /// One captured RGB DMA-BUF made into a GPU frame per simulcast layer: + /// full size, half and a fixed 640x360 at AV1's alignment, each the + /// whole picture scaled (cropped to the alignment) as the CPU pyramid + /// does it, and each encoded by `h264_vaapi` straight from its surface + /// and decoded. The frames are recycled once nothing holds them. + #[test] + fn gpu_frames_for_every_layer() { + const SIZE: (u32, u32) = (1280, 720); + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().unwrap(); + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + SIZE.0, + SIZE.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let picture = screen.frame(5, 30); + let rgb = + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + let mut converter = GpuConverter::new().expect("VA-API video processing"); + eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers()); + let layers = [ + GpuLayer { size: SIZE, alignment: (2, 2), due: true }, + GpuLayer { size: (640, 360), alignment: (64, 16), due: true }, + GpuLayer { size: (320, 180), alignment: (2, 2), due: false }, + ]; + let mut out = [None, None, None]; + converter.convert(&rgb.frame, &layers, &mut out).expect("converted"); + assert!(out[2].is_none(), "a layer that is not due gets nothing"); + let sizes: Vec<_> = out.iter().flatten().map(|f| (f.width, f.height)).collect(); + assert_eq!(sizes, [SIZE, (640, 352)], "cropped to the alignment"); + + let cpu = convert::to_i420(&picture).unwrap().into_owned(); + let mut half = VideoFrame::black_i420(640, 360); + let mut workers = crate::workers::Workers::new("voelin-test-scale", 1); + crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap(); + for frame in out.iter().flatten() { + // The CPU's picture at the layer's size, cropped the same way. + let reference = if (frame.width, frame.height) == SIZE { &cpu } else { &half }; + let mut cropped = reference.view(); + (cropped.width, cropped.height) = (frame.width, frame.height); + let gpu = download(frame); + let psnr = convert::psnr(&cropped.to_frame(), &gpu).unwrap(); + eprintln!("{}x{}: PSNR {psnr:.1} dB against the CPU's", frame.width, frame.height); + assert!(psnr > 30.0, "{}x{}: {psnr:.1} dB", frame.width, frame.height); + + let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + let mut decoder = decoder(Codec::H264); + let mut packets = 0; + encoder + .encode_gpu(frame, true, &mut |chunk| { + packets += 1; + if let Some(decoder) = &mut decoder { + let decoded = decoder.decode(chunk.data).unwrap().expect("a picture"); + assert_eq!((decoded.width, decoded.height), (frame.width, frame.height)); + let psnr = convert::psnr(&gpu, &decoded).unwrap(); + assert!(psnr > 30.0, "decoded at {psnr:.1} dB"); + } + }) + .expect("encoded from the surface"); + assert!(packets > 0); + } + // Once nothing holds them, the same frames come back. + let first: Vec<*const GpuFrame> = + out.iter().flatten().map(std::sync::Arc::as_ptr).collect(); + out = [None, None, None]; + converter.convert(&rgb.frame, &layers, &mut out).expect("converted again"); + let again: Vec<*const GpuFrame> = + out.iter().flatten().map(std::sync::Arc::as_ptr).collect(); + assert_eq!(first, again, "recycled"); + } + /// Our decoder for `codec`, if this build and machine have one: OpenH264 /// with `VOELIN_OPENH264_LIB`, dav1d with `--features av1`. fn decoder(codec: Codec) -> Option> { @@ -2255,7 +2298,6 @@ mod tests { return; } let ffmpeg = Ffmpeg::get().unwrap(); - let api = &ffmpeg.api; let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( SIZE.0, SIZE.1, @@ -2267,45 +2309,21 @@ mod tests { assert_eq!(rgb.frame.plane_count, 1); // The conversion alone: the GPU's NV12 against the CPU's I420. - let converter = - vpp::Converter::new(vaapi_display(ffmpeg).unwrap(), SIZE.0, SIZE.1).unwrap(); - let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); - let mut pool = encoder.vaapi_pool(SIZE.0, SIZE.1, ffmpeg.pix.nv12).unwrap(); + let mut converter = GpuConverter::new().expect("VA-API video processing"); + let layer = GpuLayer { size: SIZE, alignment: (2, 2), due: true }; + let mut converted = [None]; + converter.convert(&rgb.frame, &[layer], &mut converted).expect("converted"); + let downloaded = download(converted[0].as_ref().unwrap()); + drop((converted, converter)); let cpu = convert::to_i420(&picture).unwrap(); let FrameData::I420 { y, u, v } = &cpu.data else { unreachable!() }; + let FrameData::I420 { y: gy, u: gu, v: gv } = &downloaded.data else { unreachable!() }; let (w, h, cw, ch) = (SIZE.0 as usize, SIZE.1 as usize, SIZE.0 as usize / 2, SIZE.1 as usize / 2); - let mut gpu = [Vec::new(), Vec::new(), Vec::new()]; - // SAFETY: frames and pool are ours and freed below; the downloaded - // planes hold `linesize * rows` bytes. - unsafe { - let (mut out, mut sw) = ((api.av_frame_alloc)(), (api.av_frame_alloc)()); - assert!((api.av_hwframe_get_buffer)(pool, out, 0) >= 0); - converter.convert(surface_id(rgb.surface), surface_id(out)).expect("converted"); - (*sw.cast::()).format = ffmpeg.pix.nv12; - assert!((api.av_hwframe_transfer_data)(sw, out, 0) >= 0, "download"); - let head = &*sw.cast::(); - let plane = |i: usize, rows: usize| { - let stride = head.linesize[i] as usize; - std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride) - }; - for row in plane(0, h) { - gpu[0].extend_from_slice(&row[..w]); - } - for row in plane(1, ch) { - for pair in row[..cw * 2].chunks_exact(2) { - gpu[1].push(pair[0]); - gpu[2].push(pair[1]); - } - } - (api.av_frame_free)(&mut sw); - (api.av_frame_free)(&mut out); - (api.av_buffer_unref)(&mut pool); - } - drop(converter); for (name, gpu, cpu, width, rows) in - [("Y", &gpu[0], y, w, h), ("U", &gpu[1], u, cw, ch), ("V", &gpu[2], v, cw, ch)] + [("Y", gy, y, w, h), ("U", gu, u, cw, ch), ("V", gv, v, cw, ch)] { + let gpu: Vec = (0..rows).flat_map(|r| gpu.row(r, width).to_vec()).collect(); let cpu: Vec = (0..rows).flat_map(|r| cpu.row(r, width).to_vec()).collect(); let mean = gpu.iter().zip(&cpu).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::() as f64 / cpu.len() as f64; diff --git a/crates/voelin-media/src/ffmpeg/gpu.rs b/crates/voelin-media/src/ffmpeg/gpu.rs new file mode 100644 index 0000000..666437f --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/gpu.rs @@ -0,0 +1,371 @@ +//! Captured RGB DMA-BUFs converted and scaled into NV12 VA-API surfaces on +//! the GPU, for VA-API encoders: screen sharing without the CPU reading a +//! pixel. +//! +//! A DMA-BUF (what the ScreenCast portal hands over) is mapped onto a VA-API +//! surface ([`map_dmabuf`]), and VA-API video processing ([`super::vpp`]) +//! converts it to NV12 at the size of every layer that wants a frame, into +//! surfaces from pools of our own. The buffer is free again once +//! [`GpuConverter::convert`] returns; the surfaces travel to the encoders as +//! [`GpuFrame`]s ([`VideoEncoder::encode_gpu`](crate::VideoEncoder::encode_gpu)) +//! and go back to their pools when the last reference is dropped. The +//! frames are recycled, so nothing is allocated per frame once the pools +//! are warm. +#![allow(unsafe_code)] + +use std::ffi::{c_int, c_uint}; +use std::sync::Arc; +use std::time::Duration; + +use super::encoder::{exact_size, vaapi_display, vaapi_pool}; +use super::layout::{self, FrameRefs}; +use super::sys::{self, FrameHead, Ptr}; +use super::{Ffmpeg, vpp}; +use crate::capture::{DRM_MOD_INVALID, DRM_MOD_LINEAR, DmaBufRef, drm_fourcc}; +use crate::frame::GpuFrame; +use crate::{Error, Result}; + +/// The DRM formats of RGB buffers the conversion takes (8 bits per +/// channel, 4 bytes per pixel, one plane; what screen capture offers). +pub(crate) const RGB_FOURCCS: [u32; 4] = + [drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")]; + +/// An `AVFrame` that holds a VA-API surface (or nothing yet). Freeing it +/// gives the surface back to its pool. +pub(crate) struct Surface(pub(crate) Ptr); + +// SAFETY: the frame is ours. Once it holds a surface it is only read: its +// surface id, and as the source of `av_frame_ref`, which takes references +// of its own (FFmpeg's buffer references are thread-safe). +unsafe impl Send for Surface {} +unsafe impl Sync for Surface {} + +impl Surface { + fn alloc(ffmpeg: &Ffmpeg) -> Result { + // SAFETY: an allocation; NULL is checked. + let frame = unsafe { (ffmpeg.api.av_frame_alloc)() }; + if frame.is_null() { + return Err(Error::Convert("out of memory".into())); + } + Ok(Self(frame)) + } + + /// The VA-API surface id (`data[3]` of an `AV_PIX_FMT_VAAPI` frame, + /// `hwcontext_vaapi.h`). + pub(crate) fn id(&self) -> c_uint { + // SAFETY: a live frame; `data` is its leading field. + unsafe { (*self.0.cast::()).data[3] as usize as c_uint } + } +} + +impl Drop for Surface { + fn drop(&mut self) { + if let Ok(ffmpeg) = Ffmpeg::get() { + // SAFETY: our frame (or NULL). + unsafe { (ffmpeg.api.av_frame_free)(&mut self.0) }; + } + } +} + +/// Map DMA-BUF `frame` onto a VA-API surface in `dst` (an unreferenced frame +/// of ours), which takes a reference to `pool`: the surface gets that frames +/// context's device. The surface reads the buffer itself, without a copy; +/// unreferencing `dst` lets the buffer go. +pub(crate) fn map_dmabuf( + ffmpeg: &Ffmpeg, + frame: &DmaBufRef, + pool: Ptr, + dst: Ptr, + refs: FrameRefs, +) -> std::result::Result<(), String> { + let api = &ffmpeg.api; + let drm_prime = ffmpeg.pix.drm_prime.ok_or("no DRM PRIME pixel format")?; + let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?; + let mut descriptor = + sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() }; + descriptor.objects[0] = + sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier }; + descriptor.layers[0].format = frame.fourcc; + descriptor.layers[0].nb_planes = frame.plane_count as c_int; + for (plane, &(offset, pitch)) in + descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count]) + { + *plane = sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; + } + // SAFETY: the descriptor lives in a buffer the source frame owns (buf[0], + // checked offset), so FFmpeg can keep it while mapped; the destination + // gets a reference to the pool at the checked hw_frames_ctx offset; + // av_frame_free / av_frame_unref release both. + unsafe { + let mut buffer = (api.av_buffer_allocz)(size_of::()); + let mut src = (api.av_frame_alloc)(); + if buffer.is_null() || src.is_null() { + (api.av_buffer_unref)(&mut buffer); + (api.av_frame_free)(&mut src); + return Err("out of memory".into()); + } + let data = (*buffer.cast::()).data; + data.cast::().write(descriptor); + let head = src.cast::(); + (*head).format = drm_prime; + (*head).width = frame.width as c_int; + (*head).height = frame.height as c_int; + (*head).data[0] = data; + layout::write::(src, refs.buf, buffer); + (*dst.cast::()).format = vaapi; + layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool)); + let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ); + (api.av_frame_free)(&mut src); + if ret < 0 { + (api.av_frame_unref)(dst); + return Err(format!("DMA-BUF import: {}", api.error_text(ret))); + } + } + Ok(()) +} + +/// One output of [`GpuConverter::convert`]: a layer's size, the multiple +/// its encoder takes, and whether it wants this frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GpuLayer { + /// The size the whole picture is scaled to. + pub size: (u32, u32), + /// What the encoded width and height must be a multiple of + /// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)): + /// the scaled picture is cropped to it at the right and bottom, as + /// encoders crop frames in memory. + pub alignment: (u32, u32), + pub due: bool, +} + +/// NV12 surfaces of one size, and the frames that hold them, reused once +/// nothing else does. +struct Output { + size: (u32, u32), + pool: Ptr, + frames: Vec>, +} + +impl Drop for Output { + fn drop(&mut self) { + // Frames still held elsewhere keep their surfaces and the pool. + self.frames.clear(); + if let Ok(ffmpeg) = Ffmpeg::get() { + // SAFETY: our reference. + unsafe { (ffmpeg.api.av_buffer_unref)(&mut self.pool) }; + } + } +} + +/// See the [module docs](self). One per capture, used from one thread. +pub struct GpuConverter { + ffmpeg: &'static Ffmpeg, + refs: FrameRefs, + display: vpp::Display, + /// Video processing, and the source size it was made for. + vpp: Option<(vpp::Converter, (u32, u32))>, + /// The frames context DMA-BUFs of this size are mapped onto. + import: Option<(Ptr, (u32, u32))>, + /// Holds a mapping while it is converted. + mapped: Surface, + outputs: Vec, + modifiers: Vec, +} + +// SAFETY: the FFmpeg and libva objects are ours and used from one thread +// at a time (`&mut self`). +unsafe impl Send for GpuConverter {} + +impl GpuConverter { + /// A converter on the process's VA-API device, or why there is none (no + /// FFmpeg, no VA-API device, no video processing). + pub fn new() -> Result { + let ffmpeg = Ffmpeg::get().map_err(|e| Error::Convert(e.into()))?; + let refs = ffmpeg.frame_refs.clone().map_err(Error::Convert)?; + let display = vaapi_display(ffmpeg).map_err(Error::Convert)?; + // Fail now rather than on the first frame. + vpp::Converter::new(display, 64, 64).map_err(Error::Convert)?; + let mut converter = Self { + ffmpeg, + refs, + display, + vpp: None, + import: None, + mapped: Surface::alloc(ffmpeg)?, + outputs: Vec::new(), + modifiers: Vec::new(), + }; + converter.modifiers.extend(converter.tiled_modifier()); + Ok(converter) + } + + /// The tiled DRM format modifiers RGB buffers may have besides LINEAR: + /// the one this GPU's driver gives RGB surfaces of its own (it imports + /// what it makes), if that is tiled and needs a single plane (no + /// compression metadata). Empty if there is none. + pub fn modifiers(&self) -> &[u64] { + &self.modifiers + } + + fn tiled_modifier(&self) -> Option { + let ffmpeg = self.ffmpeg; + let api = &ffmpeg.api; + let drm_prime = ffmpeg.pix.drm_prime?; + // The size of a typical screen: drivers may lay out small surfaces + // differently. + let mut pool = vaapi_pool(ffmpeg, 1920, 1080, ffmpeg.pix.bgr0?).ok()?; + let (surface, drm) = (Surface::alloc(ffmpeg).ok()?, Surface::alloc(ffmpeg).ok()?); + // SAFETY: frames and pool are ours; the exported frame's data[0] is + // the descriptor FFmpeg filled, read while the mapping lives (`drm` + // goes before `surface`). + let modifier = unsafe { + let mut modifier = None; + if (api.av_hwframe_get_buffer)(pool, surface.0, 0) >= 0 { + (*drm.0.cast::()).format = drm_prime; + let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT; + if (api.av_hwframe_map)(drm.0, surface.0, flags) >= 0 { + let d = *(*drm.0.cast::()).data[0].cast::(); + let layers = &d.layers[..(d.nb_layers.max(0) as usize).min(d.layers.len())]; + let planes: c_int = layers.iter().map(|l| l.nb_planes).sum(); + let m = d.objects[0].format_modifier; + let tiled = m != DRM_MOD_LINEAR && m != DRM_MOD_INVALID; + modifier = (d.nb_objects == 1 && planes == 1 && tiled).then_some(m); + } + } + modifier + }; + drop(drm); + drop(surface); + // SAFETY: our reference. + unsafe { (api.av_buffer_unref)(&mut pool) }; + modifier + } + + /// Convert `frame`, an RGB DMA-BUF (`XR24`, `AR24`, `XB24` or `AB24` in + /// one plane, LINEAR or one of [`modifiers`](Self::modifiers)), for every + /// due layer: each gets an NV12 [`GpuFrame`] in `out` (same index), the + /// whole picture scaled to the layer's size and cropped to its alignment. + /// The buffer is no longer read when this returns. On an error nothing + /// in `out` is valid for this frame. + pub fn convert( + &mut self, + frame: &DmaBufRef, + layers: &[GpuLayer], + out: &mut [Option>], + ) -> Result<()> { + if !RGB_FOURCCS.contains(&frame.fourcc) || frame.plane_count != 1 { + return Err(Error::Convert("not an RGB DMA-BUF of one plane".into())); + } + let source = (frame.width, frame.height); + self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size)); + self.prepare(source)?; + let pool = self.import.as_ref().expect("prepared").0; + map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?; + let result = self.convert_mapped(frame, layers, out); + // SAFETY: our frame; this lets the buffer go. + unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) }; + result + } + + /// The import pool and the video processing for buffers of `source`'s + /// size. + fn prepare(&mut self, source: (u32, u32)) -> Result<()> { + if self.import.as_ref().is_none_or(|(_, size)| *size != source) { + if let Some((mut pool, _)) = self.import.take() { + // SAFETY: our reference. + unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; + } + let bgr0 = self.ffmpeg.pix.bgr0.ok_or(Error::Convert("no bgr0 pixel format".into()))?; + let pool = vaapi_pool(self.ffmpeg, source.0, source.1, bgr0).map_err(Error::Convert)?; + self.import = Some((pool, source)); + } + if self.vpp.as_ref().is_none_or(|(_, size)| *size != source) { + self.vpp = None; + let converter = + vpp::Converter::new(self.display, source.0, source.1).map_err(Error::Convert)?; + self.vpp = Some((converter, source)); + } + Ok(()) + } + + fn convert_mapped( + &mut self, + frame: &DmaBufRef, + layers: &[GpuLayer], + out: &mut [Option>], + ) -> Result<()> { + let input = self.mapped.id(); + for (layer, slot) in layers.iter().zip(out.iter_mut()) { + if !layer.due { + continue; + } + let exact = exact_size(layer.size, layer.alignment); + // The part of the picture that scales to `exact`: all of it + // scales to `size`, the rest is cropped. + let part = |full: u32, kept: u32, of: u32| { + (u64::from(full) * u64::from(kept) / u64::from(of.max(1))).max(1) as u32 + }; + let src = ( + part(frame.width, exact.0, layer.size.0), + part(frame.height, exact.1, layer.size.1), + ); + let gpu = self.output(exact, frame.timestamp)?; + let (vpp, _) = self.vpp.as_ref().expect("prepared"); + vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?; + *slot = Some(gpu); + } + Ok(()) + } + + /// A frame with a fresh NV12 surface of `size`: one that nothing else + /// holds any more, else a new one. + fn output(&mut self, size: (u32, u32), timestamp: Duration) -> Result> { + let ffmpeg = self.ffmpeg; + let index = match self.outputs.iter().position(|o| o.size == size) { + Some(i) => i, + None => { + let pool = + vaapi_pool(ffmpeg, size.0, size.1, ffmpeg.pix.nv12).map_err(Error::Convert)?; + self.outputs.push(Output { size, pool, frames: Vec::new() }); + self.outputs.len() - 1 + } + }; + let output = &mut self.outputs[index]; + let free = match output.frames.iter_mut().position(|f| Arc::get_mut(f).is_some()) { + Some(free) => free, + None => { + let surface = Surface::alloc(ffmpeg)?; + output.frames.push(Arc::new(GpuFrame { + width: size.0, + height: size.1, + timestamp, + surface, + })); + output.frames.len() - 1 + } + }; + let frame = Arc::get_mut(&mut output.frames[free]).expect("nothing else holds it"); + frame.timestamp = timestamp; + let api = &ffmpeg.api; + // SAFETY: our frame; unreferencing gives its old surface back (once + // the encoder that referenced it is done), then it takes a new one. + let ret = unsafe { + (api.av_frame_unref)(frame.surface.0); + (api.av_hwframe_get_buffer)(output.pool, frame.surface.0, 0) + }; + if ret < 0 { + return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret)))); + } + Ok(output.frames[free].clone()) + } +} + +impl Drop for GpuConverter { + fn drop(&mut self) { + self.outputs.clear(); + if let Some((mut pool, _)) = self.import.take() { + // SAFETY: our reference. + unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) }; + } + } +} diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 712a3ce..aed49f5 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -19,10 +19,14 @@ use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; pub mod encoder; +mod gpu; mod layout; pub mod sys; mod vpp; +pub(crate) use gpu::Surface; +pub use gpu::{GpuConverter, GpuLayer}; + pub use encoder::{ BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe, }; diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index 8d6f8ce..1cadd07 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -199,6 +199,7 @@ api! { fn av_frame_get_buffer(frame: Ptr, align: c_int) -> c_int; fn av_frame_make_writable(frame: Ptr) -> c_int; fn av_frame_unref(frame: Ptr); + fn av_frame_ref(dst: Ptr, src: Ptr) -> c_int; fn av_opt_set(obj: Ptr, name: *const c_char, val: *const c_char, flags: c_int) -> c_int; fn av_opt_set_int(obj: Ptr, name: *const c_char, val: i64, flags: c_int) -> c_int; fn av_opt_set_q(obj: Ptr, name: *const c_char, val: Rational, flags: c_int) -> c_int; diff --git a/crates/voelin-media/src/ffmpeg/vpp.rs b/crates/voelin-media/src/ffmpeg/vpp.rs index 03d1d70..243f5a5 100644 --- a/crates/voelin-media/src/ffmpeg/vpp.rs +++ b/crates/voelin-media/src/ffmpeg/vpp.rs @@ -171,14 +171,12 @@ impl Va { } /// A VA-API video processing context that converts RGB surfaces into NV12 -/// ones of `width` x `height`. +/// ones, cropping and scaling on the way. pub struct Converter { va: &'static Va, display: Display, config: c_uint, context: c_uint, - width: u32, - height: u32, } // SAFETY: libva serialises calls per display; the context is used from one @@ -187,8 +185,8 @@ unsafe impl Send for Converter {} impl Converter { /// A context on `display` (FFmpeg's, see - /// [`layout::device_hwctx`](super::layout::device_hwctx)) for output - /// surfaces of `width` x `height`. + /// [`layout::device_hwctx`](super::layout::device_hwctx)) for pictures of + /// up to `width` x `height`. pub fn new(display: Display, width: u32, height: u32) -> Result { let va = Va::get()?; let mut config = 0; @@ -224,24 +222,36 @@ impl Converter { unsafe { (va.destroy_config)(display, config) }; return Err(e); } - Ok(Self { va, display, config, context, width, height }) + Ok(Self { va, display, config, context }) } - /// Convert the top-left `width` x `height` of RGB surface `input` into - /// NV12 surface `output` (both of this display): BT.601, limited range, - /// what the encoders signal and the CPU path ([`crate::convert`]) - /// produces. + /// Convert the top-left `src` (width, height) of RGB surface `input` + /// into the top-left `dst` of NV12 surface `output` (both of this + /// display), scaled if the two differ: BT.601, limited range, what the + /// encoders signal and the CPU path ([`crate::convert`]) produces. /// /// Returns once the GPU has read `input`, so a captured buffer can go /// back to the compositor; `output` is ready for an encoder of the same /// display, which orders its reads after this. - pub fn convert(&self, input: c_uint, output: c_uint) -> Result<(), String> { + pub fn convert( + &self, + input: c_uint, + src: (u32, u32), + output: c_uint, + dst: (u32, u32), + ) -> Result<(), String> { let va = self.va; - let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 }; + let rect = |(width, height): (u32, u32)| Rectangle { + x: 0, + y: 0, + width: width.min(u32::from(u16::MAX)) as u16, + height: height.min(u32::from(u16::MAX)) as u16, + }; + let (src, dst) = (rect(src), rect(dst)); let mut parameters = PipelineParameters { surface: input, - surface_region: ®ion, - output_region: ®ion, + surface_region: &src, + output_region: &dst, output_background_color: 0xff00_0000, output_color_standard: COLOR_STANDARD_BT601, pipeline_flags: 0, diff --git a/crates/voelin-media/src/frame.rs b/crates/voelin-media/src/frame.rs index 4727851..884e65d 100644 --- a/crates/voelin-media/src/frame.rs +++ b/crates/voelin-media/src/frame.rs @@ -284,6 +284,35 @@ impl VideoFrame { } } +/// A picture in GPU memory: an NV12 VA-API surface, converted and scaled +/// from a captured DMA-BUF on the GPU (`ffmpeg::GpuConverter`, Linux) so +/// that no CPU reads its pixels, for the encoders that take one +/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)). +/// Dropping it gives the surface back to its pool. Only this crate makes +/// them. +#[non_exhaustive] +pub struct GpuFrame { + pub width: u32, + pub height: u32, + /// As [`VideoFrame::timestamp`]. + pub timestamp: Duration, + #[cfg(feature = "ffmpeg")] + pub(crate) surface: crate::ffmpeg::Surface, +} + +impl GpuFrame { + /// The timestamp on the 90 kHz RTP video clock. + pub fn pts_90khz(&self) -> u64 { + (self.timestamp.as_micros() * u128::from(VIDEO_CLOCK_RATE) / 1_000_000) as u64 + } +} + +impl std::fmt::Debug for GpuFrame { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "GpuFrame({}x{} at {:?})", self.width, self.height, self.timestamp) + } +} + /// Interleaved 32-bit float audio at [`AUDIO_SAMPLE_RATE`]. #[derive(Clone, Debug, PartialEq)] pub struct AudioBuffer { diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 7a6a83f..6f8c151 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -49,7 +49,7 @@ pub use codec::{ VideoEncoder, }; pub use frame::{ - AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, + AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, }; pub use queue::{FrameReceiver, FrameSender, frame_channel};