diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 43f6e9c..db200a0 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -575,6 +575,9 @@ pub struct StreamerConfig { /// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a /// portal (Linux, `/dev/udmabuf`). pub synthetic_dmabuf: bool, + /// With `synthetic_dmabuf`: buffers in video memory drawn in advance, as + /// a compositor's are ([`SyntheticScreen::with_video_memory`]; VA-API). + pub synthetic_video_memory: bool, /// Portal restore token from an earlier share: the desktop may skip its /// dialog. The new one is [`Streamer::restore_token`]. pub restore_token: Option, @@ -598,6 +601,7 @@ impl Default for StreamerConfig { synthetic_size: (1280, 720), synthetic_pattern: Pattern::Simple, synthetic_dmabuf: false, + synthetic_video_memory: false, restore_token: None, layers: Vec::new(), } @@ -1058,7 +1062,8 @@ impl Streamer { SourceId::Synthetic => { let (w, h) = config.synthetic_size; let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern) - .with_dmabuf(config.synthetic_dmabuf); + .with_dmabuf(config.synthetic_dmabuf) + .with_video_memory(config.synthetic_video_memory); screen.start_sink(&SourceId::Synthetic, &options, ingest).await?; (Box::new(screen), None) } diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index 55056c4..3841490 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -225,6 +225,7 @@ pub struct SyntheticScreen { desktop: Option>, worker: Option, dmabuf: bool, + video_memory: bool, } impl SyntheticScreen { @@ -237,7 +238,7 @@ impl SyntheticScreen { let (width, height) = (width.max(16), height.max(16)); let desktop = (pattern == Pattern::Desktop) .then(|| Arc::new(Desktop::render(width as usize, height as usize))); - Self { width, height, pattern, desktop, worker: None, dmabuf: false } + Self { width, height, pattern, desktop, worker: None, dmabuf: false, video_memory: false } } /// Draw into a DMA-BUF of ordinary memory and offer it to sinks that @@ -251,6 +252,20 @@ impl SyntheticScreen { self } + /// With [`with_dmabuf`](Self::with_dmabuf): the DMA-BUFs are buffers in + /// video memory in the GPU driver's own (tiled) layout, as a + /// compositor's are, drawn once in advance ([`VIDEO_MEMORY_FRAMES`] + /// frames of the pattern, handed over in turn) so the source costs + /// nothing per frame. The GPU reads ordinary memory over the bus, several + /// times slower (measured on a Radeon RX 7900 GRE: 9.7 ms against 0.16 + /// for a 3840x2160 conversion), and `/dev/udmabuf` refuses buffers of + /// more than 64 MiB by default (7680x4320 is 132). Linux with the `ffmpeg` + /// feature and VA-API; elsewhere, ordinary memory as before. + pub fn with_video_memory(mut self, enabled: bool) -> Self { + self.video_memory = enabled; + self + } + pub fn pattern(&self) -> Pattern { self.pattern } @@ -264,6 +279,7 @@ impl SyntheticScreen { desktop: self.desktop.clone(), worker: None, dmabuf: self.dmabuf, + video_memory: self.video_memory, } } @@ -375,13 +391,19 @@ impl ScreenCapture for SyntheticScreen { loop { let timestamp = started.elapsed(); if sink.wants(timestamp) { - let bytes = buffer.bytes(); - pattern.draw(n, bytes); - let taken = match buffer.dmabuf(&pattern, timestamp) { + // Buffers in video memory are drawn in advance; memory + // only for a sink that declines them. + if !buffer.drawn_in_advance() { + pattern.draw(n, buffer.bytes()); + } + let taken = match buffer.dmabuf(&pattern, n, timestamp) { Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame), _ => None, }; let more = taken.unwrap_or_else(|| { + if buffer.drawn_in_advance() { + pattern.draw(n, buffer.bytes()); + } let plane = PlaneRef::new(buffer.bytes(), width as usize * 4); sink.frame(FrameRef { width, @@ -413,17 +435,31 @@ impl ScreenCapture for SyntheticScreen { } } -/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary -/// memory ([`SyntheticScreen::with_dmabuf`]). +/// Frames of the pattern drawn in advance into video memory +/// ([`SyntheticScreen::with_video_memory`]), handed over in turn. +pub const VIDEO_MEMORY_FRAMES: usize = 8; + +/// Where the test pattern is drawn: plain memory, a DMA-BUF of ordinary +/// memory ([`SyntheticScreen::with_dmabuf`]), or buffers in video memory +/// drawn in advance (and memory for a sink that declines them). enum Buffer { Memory(Vec), #[cfg(all(target_os = "linux", feature = "pipewire"))] Dmabuf(super::dmabuf::Udmabuf), + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + Video(Vec, Vec), } impl Buffer { fn new(pattern: &SyntheticScreen) -> Self { let len = pattern.width as usize * pattern.height as usize * 4; + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + if pattern.dmabuf && pattern.video_memory { + match Self::video_memory(pattern) { + Ok(frames) => return Self::Video(frames, vec![0; len]), + Err(e) => tracing::warn!("test pattern not in video memory: {e}"), + } + } #[cfg(all(target_os = "linux", feature = "pipewire"))] if pattern.dmabuf { match super::dmabuf::Udmabuf::new(len) { @@ -434,21 +470,54 @@ impl Buffer { Self::Memory(vec![0; len]) } + /// [`VIDEO_MEMORY_FRAMES`] frames of the pattern in VA-API surfaces of + /// the driver's layout, exported as DMA-BUFs. + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + fn video_memory( + pattern: &SyntheticScreen, + ) -> std::result::Result, String> { + let ffmpeg = crate::ffmpeg::Ffmpeg::get().map_err(str::to_owned)?; + let bgr0 = ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?; + let size = (pattern.width, pattern.height); + (0..VIDEO_MEMORY_FRAMES as u64) + .map(|n| { + let picture = pattern.frame(n, 1); + crate::ffmpeg::Exported::new(size, bgr0, super::drm_fourcc(b"XR24"), Some(&picture)) + }) + .collect() + } + + /// The frames are in video memory already. + fn drawn_in_advance(&self) -> bool { + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + if let Self::Video(..) = self { + return true; + } + false + } + fn bytes(&mut self) -> &mut [u8] { match self { Self::Memory(bytes) => bytes, #[cfg(all(target_os = "linux", feature = "pipewire"))] Self::Dmabuf(buffer) => buffer.bytes_mut(), + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + Self::Video(_, bytes) => bytes, } } - /// The buffer as a LINEAR `XR24` DMA-BUF, if it is one. - fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option { + /// Frame `n` as an `XR24` DMA-BUF, if the buffers are DMA-BUFs. + fn dmabuf(&self, pattern: &SyntheticScreen, n: u64, timestamp: Duration) -> Option { match self { Self::Memory(_) => { - let _ = (pattern, timestamp); + let _ = (pattern, n, timestamp); None } + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + Self::Video(frames, _) => { + let exported = &frames[n as usize % frames.len()]; + Some(DmaBufRef { timestamp, ..exported.frame }) + } #[cfg(all(target_os = "linux", feature = "pipewire"))] Self::Dmabuf(buffer) => Some(DmaBufRef { width: pattern.width, @@ -663,4 +732,72 @@ mod tests { assert_eq!(row, expected[..64 * 4], "the first row of frame 0"); } } + + /// In video memory: the frames drawn in advance come in turn, each its + /// own buffer; a sink that declines them gets memory frames. + #[cfg(all(target_os = "linux", feature = "ffmpeg"))] + #[tokio::test] + async fn the_pattern_in_video_memory() { + use std::sync::mpsc; + + /// Takes DMA-BUFs (or declines them) and reports each one's fd. + struct Sink { + take: bool, + got: mpsc::Sender>, + } + impl FrameSink for Sink { + fn max_fps(&self) -> u32 { + 100 + } + fn frame(&mut self, _: FrameRef<'_>) -> bool { + self.got.send(None).is_ok() + } + fn accepts_dmabuf(&self) -> bool { + true + } + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + assert_eq!((frame.width, frame.height), (256, 128)); + self.take.then(|| self.got.send(Some(frame.fd)).is_ok()) + } + } + + let exports = + crate::ffmpeg::Ffmpeg::get().ok().and_then(|f| f.pix.bgr0).is_some_and(|bgr0| { + crate::ffmpeg::Exported::new( + (64, 64), + bgr0, + super::super::drm_fourcc(b"XR24"), + None, + ) + .is_ok() + }); + if !exports { + eprintln!("no VA-API surfaces to export, skipped"); + return; + } + for take in [true, false] { + let mut screen = + SyntheticScreen::new(256, 128).with_dmabuf(true).with_video_memory(true); + let (got, frames) = mpsc::channel(); + let sink = Box::new(Sink { take, got }); + screen + .start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink) + .await + .unwrap(); + let mut fds = std::collections::BTreeSet::new(); + for _ in 0..2 * VIDEO_MEMORY_FRAMES { + match frames.recv_timeout(Duration::from_secs(5)).unwrap() { + Some(fd) => { + assert!(take, "declined, yet a DMA-BUF"); + fds.insert(fd); + } + None => assert!(!take, "taken, yet a memory frame"), + } + } + screen.stop(); + if take { + assert_eq!(fds.len(), VIDEO_MEMORY_FRAMES, "each buffer in turn"); + } + } + } } diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 1b60e3f..8f28445 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -1993,6 +1993,7 @@ impl EncoderFactory for FfmpegFactory { #[cfg(test)] mod tests { + use super::gpu::Exported; use super::*; #[test] @@ -2136,112 +2137,6 @@ mod tests { probe().iter().any(|s| s.spec.name == name && s.available.is_ok()) } - /// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given) - /// exported as a DRM PRIME DMA-BUF: what a compositor hands over, - /// tiling modifier and all. The buffer is valid while this lives. - struct Exported { - pool: Ptr, - surface: Ptr, - drm: Ptr, - frame: DmaBufRef, - } - - impl Exported { - fn new( - (width, height): (u32, u32), - sw_format: c_int, - fourcc: u32, - picture: Option<&VideoFrame>, - ) -> Self { - let ffmpeg = Ffmpeg::get().unwrap(); - let api = &ffmpeg.api; - 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 - // filled, valid while the frame holds the mapping. - unsafe { - let mut exported = Exported { - pool, - surface: (api.av_frame_alloc)(), - drm: (api.av_frame_alloc)(), - frame: DmaBufRef { - width, - height, - timestamp: Duration::ZERO, - fourcc, - modifier: 0, - fd: -1, - size: 0, - planes: [(0, 0); 4], - plane_count: 0, - }, - }; - let (surface, drm) = (exported.surface, exported.drm); - assert!(!surface.is_null() && !drm.is_null()); - let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); - assert!(ret >= 0, "av_hwframe_get_buffer: {}", api.error_text(ret)); - if let Some(picture) = picture { - let FrameData::Bgra(pixels) = &picture.data else { panic!("BGRA only") }; - let mut sw = (api.av_frame_alloc)(); - let head = sw.cast::(); - ((*head).width, (*head).height) = (width as c_int, height as c_int); - (*head).format = sw_format; - assert!((api.av_frame_get_buffer)(sw, 0) >= 0); - let stride = (*head).linesize[0] as usize; - let rows = - std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize); - for (y, row) in rows.chunks_exact_mut(stride).enumerate() { - row[..width as usize * 4] - .copy_from_slice(pixels.row(y, width as usize * 4)); - } - let ret = (api.av_hwframe_transfer_data)(surface, sw, 0); - (api.av_frame_free)(&mut sw); - assert!(ret >= 0, "upload: {}", api.error_text(ret)); - } - (*drm.cast::()).format = ffmpeg.pix.drm_prime.expect("DRM PRIME"); - let ret = (api.av_hwframe_map)( - drm, - surface, - sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT, - ); - assert!(ret >= 0, "this driver cannot export a VA-API surface as a DMA-BUF"); - let descriptor = - *(*drm.cast::()).data[0].cast::(); - assert_eq!(descriptor.nb_objects, 1, "one buffer object"); - // The driver may describe a surface one plane per layer (NV12 - // as R8 for Y and GR88 for UV) rather than as one layer, which - // is how a compositor hands it over. Both name the same bytes - // of the same object, so flatten the layers into planes. - let object = descriptor.objects[0]; - let frame = &mut exported.frame; - for layer in &descriptor.layers[..descriptor.nb_layers as usize] { - for plane in &layer.planes[..layer.nb_planes as usize] { - frame.planes[frame.plane_count] = - (plane.offset as usize, plane.pitch as usize); - frame.plane_count += 1; - } - } - (frame.modifier, frame.fd, frame.size) = - (object.format_modifier, object.fd, object.size); - assert!(frame.fd >= 0 && frame.size > 0); - exported - } - } - } - - impl Drop for Exported { - fn drop(&mut self) { - let api = &Ffmpeg::get().unwrap().api; - // SAFETY: ours; the mapping goes before the surface it maps. - unsafe { - (api.av_frame_free)(&mut self.drm); - (api.av_frame_free)(&mut self.surface); - (api.av_buffer_unref)(&mut self.pool); - } - } - } - /// The picture of a GPU frame, read back into memory as I420. fn download(frame: &GpuFrame) -> VideoFrame { let ffmpeg = Ffmpeg::get().unwrap(); @@ -2295,7 +2190,8 @@ mod tests { ); let picture = screen.frame(5, 30); let rgb = - Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); let mut converter = GpuConverter::new().expect("VA-API video processing"); eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers()); let layers = [ @@ -2380,7 +2276,7 @@ mod tests { return; } let nv12 = Ffmpeg::get().unwrap().pix.nv12; - let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None); + let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None).unwrap(); let frame = exported.frame; assert_eq!(frame.plane_count, 2, "NV12 has two planes"); let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); @@ -2421,7 +2317,8 @@ mod tests { ); let picture = screen.frame(3, 30); let rgb = - Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); assert_eq!(rgb.frame.plane_count, 1); // The conversion alone: the GPU's NV12 against the CPU's I420. @@ -2607,7 +2504,8 @@ mod tests { drop(encoder); let rgb = - Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); let mut encoder = FfmpegEncoder::new("h264_vaapi", config).unwrap(); measure("GPU: RGB DMA-BUF imported and converted", &mut |timestamp| { let frame = DmaBufRef { timestamp, ..rgb.frame }; @@ -2615,6 +2513,75 @@ mod tests { }); } + /// What the GPU path costs per captured frame: the DMA-BUF import alone, + /// and the whole conversion (import, VPP to NV12, the wait for the GPU), + /// from a buffer of the driver's own (video memory, tiled) and from a + /// LINEAR one of ordinary memory where `/dev/udmabuf` allows its size. + /// `cargo test -p voelin-media --release --lib gpu_conversion_cost -- + /// --ignored --nocapture`. + #[cfg(feature = "pipewire")] + #[test] + #[ignore = "a measurement, not a check"] + fn gpu_conversion_cost() { + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().unwrap(); + for size in [(1920, 1080), (3840, 2160), (7680, 4320)] { + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + size.0, + size.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let picture = screen.frame(3, 60); + let vram = + Exported::new(size, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)) + .unwrap(); + let len = size.0 as usize * size.1 as usize * 4; + let mut ram = crate::capture::dmabuf::Udmabuf::new(len).ok(); + if let Some(ram) = &mut ram { + let FrameData::Bgra(pixels) = &picture.data else { unreachable!() }; + ram.bytes_mut().copy_from_slice(&pixels.data[..len]); + } + let linear = ram.as_ref().map(|ram| DmaBufRef { + fd: ram.fd(), + size: ram.len(), + modifier: crate::capture::DRM_MOD_LINEAR, + planes: [(0, size.0 as usize * 4), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + ..vram.frame + }); + let mut converter = GpuConverter::new().unwrap(); + let layer = [GpuLayer { size, alignment: (2, 2), due: true }]; + let mut out = [None]; + for (what, frame) in [("video memory", Some(vram.frame)), ("udmabuf", linear)] { + let Some(frame) = frame else { + eprintln!("{}x{} {what}: no buffer of that size", size.0, size.1); + continue; + }; + converter.convert(&frame, &layer, &mut out).unwrap(); + let started = Instant::now(); + for _ in 0..100 { + converter.import_only(&frame).unwrap(); + } + let import = started.elapsed() / 100; + let started = Instant::now(); + for _ in 0..100 { + converter.convert(&frame, &layer, &mut out).unwrap(); + } + let convert = started.elapsed() / 100; + eprintln!( + "{}x{} {what}: import {:.2} ms, whole conversion {:.2} ms", + size.0, + size.1, + import.as_secs_f64() * 1e3, + convert.as_secs_f64() * 1e3 + ); + } + } + } + /// On Linux an AMF encoder is not even made unless asked for, so AMF's /// runtime is never loaded by default; other backends are made as /// before. diff --git a/crates/voelin-media/src/ffmpeg/gpu.rs b/crates/voelin-media/src/ffmpeg/gpu.rs index ff8cccc..882407f 100644 --- a/crates/voelin-media/src/ffmpeg/gpu.rs +++ b/crates/voelin-media/src/ffmpeg/gpu.rs @@ -138,6 +138,142 @@ pub(crate) fn map_dmabuf( Ok(()) } +/// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given) +/// exported as a DRM PRIME DMA-BUF: a buffer in video memory as a +/// compositor hands one over, the driver's tiling modifier and all. The +/// buffer ([`frame`](Self::frame)) is valid while this lives. +#[cfg(target_os = "linux")] +pub(crate) struct Exported { + pool: Ptr, + surface: Ptr, + drm: Ptr, + pub(crate) frame: DmaBufRef, +} + +// SAFETY: the frames and the pool are ours; FFmpeg's buffer references are +// thread-safe and the surface is only read once it is made. +#[cfg(target_os = "linux")] +unsafe impl Send for Exported {} + +#[cfg(target_os = "linux")] +impl Exported { + pub(crate) fn new( + (width, height): (u32, u32), + sw_format: c_int, + fourcc: u32, + picture: Option<&crate::frame::VideoFrame>, + ) -> std::result::Result { + let ffmpeg = Ffmpeg::get().map_err(str::to_owned)?; + let api = &ffmpeg.api; + let pool = vaapi_pool(ffmpeg, width, height, sw_format)?; + let mut exported = Exported { + pool, + // SAFETY: allocations, checked below; the drop frees them. + surface: unsafe { (api.av_frame_alloc)() }, + drm: unsafe { (api.av_frame_alloc)() }, + frame: DmaBufRef { + width, + height, + timestamp: Duration::ZERO, + fourcc, + modifier: 0, + fd: -1, + size: 0, + planes: [(0, 0); 4], + plane_count: 0, + }, + }; + let (surface, drm) = (exported.surface, exported.drm); + if surface.is_null() || drm.is_null() { + return Err("out of memory".into()); + } + // SAFETY: `pool` is a live frames context of this process's VA-API + // device; the frames are ours. The exported frame's `data[0]` is the + // AVDRMFrameDescriptor FFmpeg filled, valid while the frame holds + // the mapping; a picture's rows are `width * 4` bytes. + unsafe { + let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); + if ret < 0 { + return Err(format!("VA-API surface: {}", api.error_text(ret))); + } + if let Some(picture) = picture { + let crate::frame::FrameData::Bgra(pixels) = &picture.data else { + return Err("only BGRA pictures are uploaded".into()); + }; + let mut sw = (api.av_frame_alloc)(); + if sw.is_null() { + return Err("out of memory".into()); + } + let head = sw.cast::(); + ((*head).width, (*head).height) = (width as c_int, height as c_int); + (*head).format = sw_format; + let mut ret = (api.av_frame_get_buffer)(sw, 0); + if ret >= 0 { + let stride = (*head).linesize[0] as usize; + let rows = + std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize); + for (y, row) in rows.chunks_exact_mut(stride).enumerate() { + row[..width as usize * 4] + .copy_from_slice(pixels.row(y, width as usize * 4)); + } + ret = (api.av_hwframe_transfer_data)(surface, sw, 0); + } + (api.av_frame_free)(&mut sw); + if ret < 0 { + return Err(format!("upload: {}", api.error_text(ret))); + } + } + (*drm.cast::()).format = + ffmpeg.pix.drm_prime.ok_or("no DRM PRIME format")?; + let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT; + if (api.av_hwframe_map)(drm, surface, flags) < 0 { + return Err("this driver cannot export a VA-API surface as a DMA-BUF".into()); + } + let descriptor = *(*drm.cast::()).data[0].cast::(); + if descriptor.nb_objects != 1 { + return Err(format!("{} buffer objects, not one", descriptor.nb_objects)); + } + // The driver may describe a surface one plane per layer (NV12 as + // R8 for Y and GR88 for UV) rather than as one layer, which is how + // a compositor hands it over. Both name the same bytes of the same + // object, so the layers are flattened into planes. + let object = descriptor.objects[0]; + let frame = &mut exported.frame; + let layers = descriptor.layers.iter().take(descriptor.nb_layers.max(0) as usize); + for layer in layers { + for plane in layer.planes.iter().take(layer.nb_planes.max(0) as usize) { + if frame.plane_count == frame.planes.len() { + return Err("more than four planes".into()); + } + frame.planes[frame.plane_count] = (plane.offset as usize, plane.pitch as usize); + frame.plane_count += 1; + } + } + (frame.modifier, frame.fd, frame.size) = + (object.format_modifier, object.fd, object.size); + if frame.fd < 0 || frame.size == 0 { + return Err("no DMA-BUF exported".into()); + } + } + Ok(exported) + } +} + +#[cfg(target_os = "linux")] +impl Drop for Exported { + fn drop(&mut self) { + if let Ok(ffmpeg) = Ffmpeg::get() { + // SAFETY: ours (or NULL); the mapping goes before the surface it + // maps. + unsafe { + (ffmpeg.api.av_frame_free)(&mut self.drm); + (ffmpeg.api.av_frame_free)(&mut self.surface); + (ffmpeg.api.av_buffer_unref)(&mut self.pool); + } + } + } +} + /// 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)] @@ -281,6 +417,17 @@ impl GpuConverter { result } + /// Map `frame` and let it go again: the import alone, for measuring. + #[cfg(test)] + pub(crate) fn import_only(&mut self, frame: &DmaBufRef) -> Result<()> { + self.prepare((frame.width, frame.height))?; + let pool = self.import.as_ref().expect("prepared").0; + map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?; + // SAFETY: our frame. + unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) }; + Ok(()) + } + /// The import pool and the video processing for buffers of `source`'s /// size. fn prepare(&mut self, source: (u32, u32)) -> Result<()> { diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 88eefc1..e8cc979 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -30,6 +30,8 @@ mod layout; pub mod sys; mod vpp; +#[cfg(target_os = "linux")] +pub(crate) use gpu::Exported; pub(crate) use gpu::Surface; pub use gpu::{GpuConverter, GpuLayer}; diff --git a/docs/media.md b/docs/media.md index 629f6ee..1625e85 100644 --- a/docs/media.md +++ b/docs/media.md @@ -903,6 +903,11 @@ voelinctl stream bench --res 2560x1440 --fps 30 \ # The pattern handed over as DMA-BUFs, as the portal hands over the screen # (Linux, /dev/udmabuf): with VA-API encoders the GPU path, no portal needed voelinctl stream bench --res 2560x1440 --fps 60 --encoder h264_vaapi --dmabuf +# The same from buffers in video memory in the driver's tiled layout, drawn +# in advance (eight frames in turn), as a compositor hands them over: the +# udmabuf ones are ordinary memory the GPU reads over the bus several times +# slower, and /dev/udmabuf refuses more than 64 MiB (7680x4320 is 132 MiB) +voelinctl stream bench --res 7680x4320 --fps 60 --encoder av1_vaapi --vram # A real screen capture instead of the pattern (the portal asks the user; # --start-timeout bounds the wait so it cannot hang): voelinctl stream bench --source portal --fps 60 --encoder h264_vaapi diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index f2ef8ae..8fa035d 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -85,6 +85,13 @@ struct BenchArgs { /// encoders the frames are then converted and scaled on the GPU. #[arg(long)] dmabuf: bool, + /// The pattern drawn in advance into DMA-BUFs in video memory (VA-API + /// surfaces in the driver's layout), as a compositor hands over the + /// screen; implies --dmabuf. Without it the DMA-BUFs are ordinary + /// memory, which the GPU reads over the bus several times slower, and + /// which `/dev/udmabuf` limits to 64 MiB (7680x4320 needs 132). + #[arg(long)] + vram: bool, /// Video codec: vp8, vp9, h264, av1 or h265 [default: the codec of /// --encoder if named, else the first the encoder choice gives]. #[arg(long)] @@ -388,7 +395,8 @@ fn bench(args: BenchArgs) -> Result<()> { source: source.clone(), synthetic_size: (width, height), synthetic_pattern: pattern, - synthetic_dmabuf: args.dmabuf, + synthetic_dmabuf: args.dmabuf || args.vram, + synthetic_video_memory: args.vram, fps: args.fps, bitrate_kbps: args.bitrate, codec,