diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 6004d4a..8350064 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -45,7 +45,7 @@ pub use voelin_media::capture::playback::{AppMatch, AudioApp, AudioApps}; pub use voelin_media::capture::synthetic::Pattern; use voelin_media::capture::synthetic::{SineSource, SyntheticScreen}; use voelin_media::capture::{ - self, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, SourceId, + self, CaptureOptions, CaptureSource, DmaBufRef, FramePacer, FrameSink, ScreenCapture, SourceId, }; use voelin_media::handoff::Handoff; use voelin_media::mix::{ @@ -55,7 +55,10 @@ pub use voelin_media::mix::{Level, SourceState}; use voelin_media::scale::Pyramid; use voelin_media::studio::Studio; use voelin_media::studio::output::{Packet, Track}; -use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame}; +use voelin_media::{ + Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder, + VideoFrame, +}; pub use voelin_media::{EncoderBackend, EncoderPreference}; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, @@ -502,6 +505,11 @@ pub struct StreamerConfig { pub synthetic_size: (u32, u32), /// What the test pattern shows. pub synthetic_pattern: Pattern, + /// Hand the test pattern over as DMA-BUFs of ordinary memory, as the + /// ScreenCast portal hands over the screen + /// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a + /// portal (Linux, `/dev/udmabuf`). + pub synthetic_dmabuf: 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, @@ -524,6 +532,7 @@ impl Default for StreamerConfig { cursor: true, synthetic_size: (1280, 720), synthetic_pattern: Pattern::Simple, + synthetic_dmabuf: false, restore_token: None, layers: Vec::new(), } @@ -612,8 +621,16 @@ pub struct StreamerStats { pub captured_frames: u64, pub capture_fps: f64, /// Mean time to convert a captured frame to I420 and scale it for every - /// layer that is due. + /// layer that is due, on the CPU. pub convert_time: Duration, + /// Captured frames that never reached the CPU: DMA-BUFs converted to + /// NV12 and scaled for every layer on the GPU, for VA-API encoders. + pub gpu_frames: u64, + /// Mean time the capture thread spends on such a frame (it waits for + /// the GPU, so the buffer can go back to the compositor). + pub gpu_convert_time: Duration, + /// Why the GPU path stopped (it fell back to the CPU), if it did. + pub gpu_error: Option, /// Frames dropped between conversion and the encoders, all layers. pub dropped_frames: u64, /// Threads converting and scaling. @@ -636,6 +653,12 @@ struct Layer { spec: Mutex, /// Newest converted frame for the encoder. inbox: Handoff, + /// Newest frame converted on the GPU, instead. + gpu_inbox: Handoff, + /// What every encoder of the layer takes GPU frames at, written by the + /// encoder thread: `width << 32 | height` alignment, 0 if one of them + /// needs frames in memory. + gpu: AtomicU64, /// A keyframe was asked for. keyframe: AtomicBool, stop: AtomicBool, @@ -669,6 +692,8 @@ impl Layer { id: spec.id, spec: Mutex::new(spec.clone()), inbox: Handoff::new(), + gpu_inbox: Handoff::new(), + gpu: AtomicU64::new(0), keyframe: AtomicBool::new(false), stop: AtomicBool::new(false), bitrate: AtomicU64::new(spec.bitrate.max(1)), @@ -731,6 +756,7 @@ impl Settings { struct Rates { capture_fps: f64, convert_time: Duration, + gpu_convert_time: Duration, /// Per layer: id, fps, kbit/s, encode time. layers: Vec<(LayerId, f64, f64, Duration)>, } @@ -751,6 +777,10 @@ struct Shared { converted: AtomicU64, convert_ns: AtomicU64, convert_threads: AtomicUsize, + /// Frames converted on the GPU instead, and the time it took. + gpu_converted: AtomicU64, + gpu_convert_ns: AtomicU64, + gpu_error: Mutex>, /// The layers being encoded, in configuration order. layers: Mutex>>, /// Bumped whenever `layers` or a layer's spec changes. @@ -959,7 +989,8 @@ impl Streamer { let (screen, restore_token): (Box, _) = match &config.source { SourceId::Synthetic => { let (w, h) = config.synthetic_size; - let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern); + let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern) + .with_dmabuf(config.synthetic_dmabuf); screen.start_sink(&SourceId::Synthetic, &options, ingest).await?; (Box::new(screen), None) } @@ -1220,6 +1251,9 @@ impl Streamer { captured_frames: shared.captured.load(Ordering::Relaxed), capture_fps: rates.capture_fps, convert_time: rates.convert_time, + gpu_frames: shared.gpu_converted.load(Ordering::Relaxed), + gpu_convert_time: rates.gpu_convert_time, + gpu_error: lock(&shared.gpu_error).clone(), dropped_frames: layers.iter().map(|l| l.dropped).sum(), convert_threads: shared.convert_threads.load(Ordering::Relaxed), codec, @@ -1487,6 +1521,11 @@ struct IngestLayer { /// converts and scales them for every layer that is due, and hands each /// layer's frame to its encoder. Allocates nothing per frame once the /// frame pools are warm. +/// +/// Frames still in a DMA-BUF (the portal's) are converted and scaled on +/// the GPU instead when every encoder of every layer takes GPU frames +/// (VA-API): the CPU never reads them, and the buffer is free again as +/// soon as the GPU is done with it. struct Ingest { shared: Arc, pyramid: Pyramid, @@ -1497,6 +1536,19 @@ struct Ingest { sizes: Vec<(u32, u32)>, due: Vec, out: Vec>>, + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + gpu: GpuStage, +} + +/// The GPU stage of [`Ingest`]. +#[cfg(all(target_os = "linux", feature = "media-desktop"))] +#[derive(Default)] +struct GpuStage { + /// Made for the first DMA-BUF; `Err` once it failed (the CPU converts + /// from then on). + converter: Option>, + layers: Vec, + out: Vec>>, } impl Ingest { @@ -1514,9 +1566,98 @@ impl Ingest { sizes: Vec::new(), due: Vec::new(), out: Vec::new(), + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + gpu: GpuStage::default(), } } + /// Whether frames go to the GPU: every layer's encoders take GPU frames + /// and the GPU stage has not failed. + fn gpu_path(&self) -> bool { + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + { + !matches!(self.gpu.converter, Some(Err(()))) + && !self.layers.is_empty() + && self + .layers + .iter() + .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) + } + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + false + } + + /// Convert DMA-BUF `frame` on the GPU for every layer that is due; `None` + /// if it is not taken (the backend maps it for [`FrameSink::frame`]). + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + fn gpu_frame(&mut self, frame: &DmaBufRef) -> Option { + use voelin_media::ffmpeg::{GpuConverter, GpuLayer}; + + if self.shared.stopped() { + return Some(false); + } + if !self.gpu_path() { + return None; + } + let shared = self.shared.clone(); + let converter = match &mut self.gpu.converter { + Some(Ok(converter)) => converter, + Some(Err(())) => return None, + None => match GpuConverter::new() { + Ok(converter) => self.gpu.converter.insert(Ok(converter)).as_mut().ok()?, + Err(e) => { + warn!("no GPU conversion of captured frames, the CPU converts them: {e}"); + *lock(&shared.gpu_error) = Some(e.to_string()); + self.gpu.converter = Some(Err(())); + return None; + } + }, + }; + self.pacer.keep(frame.timestamp); + shared.captured.fetch_add(1, Ordering::Relaxed); + shared + .size + .store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + if shared.sink().is_none() { + return Some(true); + } + let mut any = false; + self.gpu.layers.clear(); + for l in &mut self.layers { + let due = !l.layer.stopped() && l.pacer.take(frame.timestamp); + any |= due; + let alignment = l.layer.gpu.load(Ordering::Relaxed); + self.gpu.layers.push(GpuLayer { + size: l.spec.output_size(frame.width, frame.height), + alignment: ((alignment >> 32) as u32, alignment as u32), + due, + }); + } + if !any { + return Some(true); + } + self.gpu.out.clear(); + self.gpu.out.resize(self.layers.len(), None); + let started = Instant::now(); + if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) { + warn!("GPU conversion failed, the CPU converts captured frames from now on: {e}"); + *lock(&shared.gpu_error) = Some(e.to_string()); + self.gpu.converter = Some(Err(())); + self.gpu.out.clear(); + // This frame is counted and its layers' pacing taken: it is + // dropped, and the next one takes the CPU path. + return Some(true); + } + shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + shared.gpu_converted.fetch_add(1, Ordering::Relaxed); + for (l, out) in self.layers.iter().zip(&mut self.gpu.out) { + if let Some(frame) = out.take() { + l.layer.gpu_inbox.put(frame); + } + } + Some(true) + } + /// Pick up layer and frame-rate changes. fn refresh(&mut self) { let fps = self.shared.fps.load(Ordering::Relaxed); @@ -1560,14 +1701,38 @@ impl FrameSink for Ingest { if self.shared.stopped() { return false; } - let fps = self.shared.fps.load(Ordering::Relaxed); - if fps != self.fps { - self.fps = fps; - self.pacer.set_fps(Some(fps)); - } + // Also the layers, which `accepts_dmabuf` (asked next) looks at. + self.refresh(); self.pacer.due(timestamp) } + fn accepts_dmabuf(&self) -> bool { + self.gpu_path() + } + + /// The tiled layout the GPU's own RGB surfaces have, once the GPU stage + /// runs (its first DMA-BUF is LINEAR); none on the CPU path, which + /// cannot read tiled buffers. + fn dmabuf_modifiers(&self) -> &[u64] { + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + if self.gpu_path() + && let Some(Ok(converter)) = &self.gpu.converter + { + return converter.modifiers(); + } + &[] + } + + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + return self.gpu_frame(frame); + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + { + let _ = frame; + None + } + } + fn frame(&mut self, frame: FrameRef<'_>) -> bool { if self.shared.stopped() { return false; @@ -1617,6 +1782,66 @@ impl Drop for Ingest { } } +/// A layer's picture: in memory, or on the GPU (converted from a captured +/// DMA-BUF there). +#[derive(Clone)] +enum Picture { + Cpu(Arc), + Gpu(Arc), +} + +impl Picture { + fn size(&self) -> (u32, u32) { + match self { + Self::Cpu(frame) => (frame.width, frame.height), + Self::Gpu(frame) => (frame.width, frame.height), + } + } + + /// The same picture `later` after it was captured (a still screen sent + /// again; copies a frame in memory). + fn later(&self, later: Duration) -> Self { + match self { + Self::Cpu(frame) => { + let timestamp = frame.timestamp + later; + Self::Cpu(Arc::new((**frame).clone().with_timestamp(timestamp))) + } + Self::Gpu(frame) => Self::Gpu(Arc::new(frame.at(frame.timestamp + later))), + } + } +} + +/// A layer's next picture, from either inbox, or `None` after [`POLL`] or +/// once the layer is closed. The encoder thread is registered with both +/// ([`Handoff::register`]), so a `put` to either wakes it. +fn next_picture(layer: &Layer) -> Option { + let deadline = Instant::now() + POLL; + loop { + if let Some(frame) = layer.gpu_inbox.take() { + return Some(Picture::Gpu(frame)); + } + if let Some(frame) = layer.inbox.take() { + return Some(Picture::Cpu(frame)); + } + let now = Instant::now(); + if now >= deadline || layer.inbox.is_closed() { + return None; + } + std::thread::park_timeout(deadline - now); + } +} + +/// What every encoder of a layer takes GPU frames at, for [`Layer::gpu`]: +/// the largest alignment of them all, or 0 if one of them takes none. +fn gpu_alignment<'a>(encoders: impl IntoIterator) -> u64 { + let mut alignment = (2, 2); + for encoder in encoders { + let Some((w, h)) = encoder.gpu_alignment() else { return 0 }; + alignment = (alignment.0.max(w), alignment.1.max(h)); + } + u64::from(alignment.0) << 32 | u64::from(alignment.1) +} + /// One encoder of a layer: its keyframe and bitrate state. struct LayerEncoder { codec: Codec, @@ -1635,7 +1860,7 @@ impl LayerEncoder { Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps } } - /// Encode `frame` and hand the frames to `sink` (and `studio`'s + /// Encode `picture` and hand the frames to `sink` (and `studio`'s /// outputs); follows the layer's target bitrate and frame rate first. #[allow(clippy::too_many_arguments)] fn encode( @@ -1644,12 +1869,20 @@ impl LayerEncoder { layer: &Layer, sink: &dyn MediaSink, studio: Option<&Studio>, - frame: &VideoFrame, + picture: &Picture, requested: bool, target: u64, ) { let codec = self.codec; let Some(encoder) = &mut self.encoder else { return }; + if matches!(picture, Picture::Gpu(_)) && encoder.gpu_alignment().is_none() { + // The capture switches to frames in memory once it sees this + // encoder (made for a viewer just now); until then it waits, and + // its first frame then is a keyframe. + self.keyframe_due = true; + return; + } + let (width, height) = picture.size(); if target.abs_diff(self.bitrate) * 100 > self.bitrate { match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) { Ok(()) => self.bitrate = target, @@ -1662,15 +1895,15 @@ impl LayerEncoder { } let force = requested || self.keyframe_due; let mut produced_keyframe = false; - let result = encoder.encode_with(frame, force, &mut |chunk| { + let mut out = |chunk: EncodedChunk<'_>| { produced_keyframe |= chunk.keyframe; if let Some(studio) = studio { studio.write_packet(&Packet { track: Track::Video { codec, layer: u32::from(layer.id) }, pts_90khz: chunk.pts_90khz, keyframe: chunk.keyframe, - width: frame.width, - height: frame.height, + width, + height, data: chunk.data, }); } @@ -1688,7 +1921,11 @@ impl LayerEncoder { layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed); shared.video_frames.fetch_add(1, Ordering::Relaxed); } - }); + }; + let result = match picture { + Picture::Cpu(frame) => encoder.encode_with(frame, force, &mut out), + Picture::Gpu(frame) => encoder.encode_gpu(frame, force, &mut out), + }; match result { Ok(()) => self.keyframe_due = force && !produced_keyframe, Err(e) => { @@ -1736,13 +1973,17 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let mut primary_on = true; // The last picture, and when it came: a static screen sends no frames, // so keyframe requests are answered by encoding it again. - let mut last: Option<(Arc, Instant)> = None; + let mut last: Option<(Picture, Instant)> = None; layer.speed.store( primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from), Ordering::Relaxed, ); + // The capture may hand over GPU frames once every encoder takes them. + layer.inbox.register(); + layer.gpu_inbox.register(); + layer.gpu.store(gpu_alignment(primary.encoder.as_deref()), Ordering::Relaxed); while !shared.stopped() && !layer.stopped() { - let frame = layer.inbox.wait_timeout(POLL); + let picture = next_picture(layer); if let Some(next) = lock(&layer.next_encoder).take() { // Another codec: its first frame is a keyframe anyway. *lock(&layer.backend) = Some(next.backend()); @@ -1785,21 +2026,26 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { codecs.extend(primary_on.then_some(primary.codec)); codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec)); } + // The stream codec's encoder counts even while nobody takes it, so + // the capture does not switch paths as viewers come and go. + let encoders = primary.encoder.as_deref().into_iter(); + let gpu = gpu_alignment(encoders.chain(extra.iter().filter_map(|e| e.encoder.as_deref()))); + layer.gpu.store(gpu, Ordering::Relaxed); let requested = layer.keyframe.swap(false, Ordering::Relaxed); let due = primary_on && primary.keyframe_due || extra.iter().any(|e| e.keyframe_due && e.encoder.is_some()); - let frame = match frame { - Some(frame) => { - last = Some((frame.clone(), Instant::now())); - frame + let picture = match picture { + Some(picture) => { + last = Some((picture.clone(), Instant::now())); + picture } None if requested || due => { - let Some((frame, at)) = &last else { + let Some((picture, at)) = &last else { layer.keyframe.store(requested, Ordering::Relaxed); continue; }; - // Same picture, later timestamp (rare: copies the frame). - Arc::new((**frame).clone().with_timestamp(frame.timestamp + at.elapsed())) + // Same picture, later timestamp (rare). + picture.later(at.elapsed()) } None => continue, }; @@ -1813,15 +2059,16 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let started = Instant::now(); if primary_on { let studio = shared.studio.as_deref(); - primary.encode(shared, layer, &*sink, studio, &frame, requested, target); + primary.encode(shared, layer, &*sink, studio, &picture, requested, target); layer.target.store(primary.bitrate, Ordering::Relaxed); } for encoder in &mut extra { - encoder.encode(shared, layer, &*sink, None, &frame, requested, target); + encoder.encode(shared, layer, &*sink, None, &picture, requested, target); } layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); layer.encoded.fetch_add(1, Ordering::Relaxed); - layer.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); + let (width, height) = picture.size(); + layer.size.store(u64::from(width) << 32 | u64::from(height), Ordering::Relaxed); layer.speed.store( primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from), Ordering::Relaxed, @@ -1835,6 +2082,8 @@ struct Sample { captured: u64, converted: u64, convert_ns: u64, + gpu_converted: u64, + gpu_convert_ns: u64, } /// Once a second: rates for [`Streamer::stats`]; every five seconds a @@ -1861,11 +2110,15 @@ fn stats_loop(shared: &Shared) { captured: shared.captured.load(Ordering::Relaxed), converted: shared.converted.load(Ordering::Relaxed), convert_ns: shared.convert_ns.load(Ordering::Relaxed), + gpu_converted: shared.gpu_converted.load(Ordering::Relaxed), + gpu_convert_ns: shared.gpu_convert_ns.load(Ordering::Relaxed), }; let mean = |ns: u64, n: u64| Duration::from_nanos(ns.checked_div(n).unwrap_or(0)); let mut rates = lock(&shared.rates); rates.capture_fps = (now.captured - last.captured) as f64 / secs; rates.convert_time = mean(now.convert_ns - last.convert_ns, now.converted - last.converted); + rates.gpu_convert_time = + mean(now.gpu_convert_ns - last.gpu_convert_ns, now.gpu_converted - last.gpu_converted); rates.layers.clear(); let layers = lock(&shared.layers); for layer in layers.iter() { @@ -1912,9 +2165,10 @@ fn stats_loop(shared: &Shared) { }) .collect(); debug!( - "stream: capture {:.1} fps, convert {:.1} ms, {}", + "stream: capture {:.1} fps, convert {:.1} ms (GPU {:.1} ms), {}", rates.capture_fps, rates.convert_time.as_secs_f64() * 1e3, + rates.gpu_convert_time.as_secs_f64() * 1e3, summary.join(", ") ); } @@ -2742,6 +2996,68 @@ mod tests { (size, first_keyframe == Some(true)) } + /// The test pattern as DMA-BUFs, as the portal hands over the screen: + /// with VA-API encoders on every layer, each frame is converted and + /// scaled on the GPU and none on the CPU; after a switch to libvpx, + /// which needs frames in memory, the CPU converts them again and the + /// stream goes on. Skipped without `h264_vaapi` or `/dev/udmabuf`. + #[cfg(target_os = "linux")] + #[tokio::test(flavor = "multi_thread")] + async fn dmabufs_take_the_gpu_path_while_every_encoder_does() { + let vaapi = voelin_media::ffmpeg::probe() + .iter() + .any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok()); + if !vaapi || !std::path::Path::new("/dev/udmabuf").exists() { + eprintln!("no h264_vaapi or /dev/udmabuf, skipped"); + return; + } + let codecs = Codecs::new(); + let vaapi = EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() }; + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (640, 360), + synthetic_dmabuf: true, + fps: 30, + audio: false, + codec: Codec::H264, + encoder: vaapi, + layers: vec![layer(0, 1.0, None, 1_000_000), layer(5, 0.5, Some(15), 300_000)], + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let mut source = EncodedSource::new(streamer); + let count = |frames: &[EncodedFrame], id| frames.iter().filter(|f| f.layer == id).count(); + let frames = collect(&mut source, |f| count(f, 0) >= 20 && count(f, 5) >= 5).await; + for id in [0, 5] { + assert!(frames.iter().find(|f| f.layer == id).unwrap().keyframe, "layer {id}"); + } + let stats = source.streamer().stats(); + assert_eq!(stats.gpu_error, None); + assert!(stats.gpu_frames >= 20, "{} frames on the GPU", stats.gpu_frames); + let on_cpu = stats.captured_frames - stats.gpu_frames; + assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames); + let sizes: Vec<_> = stats.layers.iter().map(|l| (l.width, l.height)).collect(); + assert_eq!(sizes, [(640, 360), (320, 180)]); + + let libvpx = EncoderPreference { hardware: false, backend: "libvpx".parse().unwrap() }; + let update = StreamerConfigUpdate { + codec: Some(Codec::Vp8), + encoder: Some(libvpx), + ..StreamerConfigUpdate::default() + }; + source.streamer().reconfigure(&codecs, update).unwrap(); + let gpu = source.streamer().stats().gpu_frames; + let frames = collect(&mut source, |f| count(f, 0) >= 40).await; + assert_eq!(decoded_size(Codec::Vp8, &frames, 0), ((640, 360), true)); + let stats = source.streamer().stats(); + assert!( + stats.gpu_frames <= gpu + 2, + "{} frames on the GPU after the switch", + stats.gpu_frames - gpu + ); + assert_eq!(stats.gpu_error, None, "a planned switch, not a failure"); + } + /// Two layers at their own sizes and frame rates, keyframes per layer, /// then a new codec and another layer set while streaming. #[cfg(feature = "media-desktop")] diff --git a/crates/voelin-media/src/capture/dmabuf.rs b/crates/voelin-media/src/capture/dmabuf.rs index d8d07cb..8846ed8 100644 --- a/crates/voelin-media/src/capture/dmabuf.rs +++ b/crates/voelin-media/src/capture/dmabuf.rs @@ -1,11 +1,13 @@ //! CPU access to LINEAR DMA-BUFs (screen capture buffers a compositor //! shares): a read-only mapping, and `DMA_BUF_IOCTL_SYNC` around each read //! so caches are coherent with what the GPU wrote. Tiled buffers cannot be -//! read like this; they need a GPU import (not done here). +//! read like this; they go to the GPU (`ffmpeg::GpuConverter`). Also +//! DMA-BUFs of ordinary memory ([`Udmabuf`]), to drive that path without a +//! compositor. #![allow(unsafe_code)] use std::io; -use std::os::fd::{BorrowedFd, RawFd}; +use std::os::fd::{BorrowedFd, OwnedFd, RawFd}; use memmap2::{Mmap, MmapOptions}; @@ -21,6 +23,92 @@ const DMA_BUF_SYNC_END: u64 = 1 << 2; /// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`. const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::(b'b', 0); +/// `struct udmabuf_create` of ``; `UDMABUF_CREATE` returns +/// the new DMA-BUF. +#[repr(C)] +struct UdmabufCreate { + memfd: u32, + flags: u32, + offset: u64, + size: u64, +} + +/// `UDMABUF_FLAGS_CLOEXEC`. +const UDMABUF_CLOEXEC: u32 = 1; + +// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) only +// reads the struct and returns a new descriptor. +unsafe impl rustix::ioctl::Ioctl for UdmabufCreate { + type Output = OwnedFd; + const IS_MUTATING: bool = false; + + fn opcode(&self) -> rustix::ioctl::Opcode { + rustix::ioctl::opcode::write::(b'u', 0x42) + } + + fn as_ptr(&mut self) -> *mut std::ffi::c_void { + (&raw mut *self).cast() + } + + unsafe fn output_from_ptr( + out: rustix::ioctl::IoctlOutput, + _: *mut std::ffi::c_void, + ) -> rustix::io::Result { + // SAFETY: the descriptor the kernel just made, ours to own. + Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) }) + } +} + +/// A DMA-BUF of ordinary memory that the CPU writes into: a sealed memfd +/// shared through `/dev/udmabuf` (LINEAR rows, any pitch). What a +/// compositor that renders on the CPU hands over, and the way to drive the +/// DMA-BUF path without one (the test pattern's +/// [`with_dmabuf`](super::synthetic::SyntheticScreen::with_dmabuf)). Needs +/// read and write access to `/dev/udmabuf`. +pub(crate) struct Udmabuf { + map: memmap2::MmapMut, + dmabuf: OwnedFd, +} + +impl Udmabuf { + /// A buffer of at least `len` bytes (whole pages). + pub fn new(len: usize) -> io::Result { + use rustix::fs::{MemfdFlags, SealFlags}; + + let len = len.max(1).next_multiple_of(4096); + let flags = MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING; + let memfd = std::fs::File::from(rustix::fs::memfd_create("voelin-udmabuf", flags)?); + memfd.set_len(len as u64)?; + // udmabuf only takes memory that cannot shrink under it. + rustix::fs::fcntl_add_seals(&memfd, SealFlags::SHRINK)?; + let device = std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf")?; + let create = UdmabufCreate { + memfd: std::os::fd::AsRawFd::as_raw_fd(&memfd) as u32, + flags: UDMABUF_CLOEXEC, + offset: 0, + size: len as u64, + }; + // SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf. + let dmabuf = unsafe { rustix::ioctl::ioctl(&device, create) }?; + // SAFETY: our own sealed memfd, which nothing else writes or + // truncates; the mapping keeps its pages after the file is closed. + let map = unsafe { memmap2::MmapOptions::new().len(len).map_mut(&memfd) }?; + Ok(Self { map, dmabuf }) + } + + pub fn fd(&self) -> RawFd { + std::os::fd::AsRawFd::as_raw_fd(&self.dmabuf) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn bytes_mut(&mut self) -> &mut [u8] { + &mut self.map + } +} + /// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a /// DMA-BUF answers with its buffer object's size without moving anything). pub(crate) fn size_of(fd: RawFd) -> Option { diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 2dbc3aa..f064d63 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -28,7 +28,7 @@ use crate::queue::{FrameReceiver, FrameSender, frame_channel}; use crate::{Error, Result}; #[cfg(all(target_os = "linux", feature = "pipewire"))] -mod dmabuf; +pub(crate) mod dmabuf; pub mod external; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod pipewire_audio; @@ -129,6 +129,15 @@ pub trait FrameSink: Send { let _ = frame; None } + + /// Tiled DRM format modifiers of RGB buffers the sink takes now + /// ([`accepts_dmabuf`](Self::accepts_dmabuf)), best first; backends that + /// negotiate buffers (the portal) offer them ahead of LINEAR, and offer + /// again when this changes. The CPU cannot read tiled buffers, so a sink + /// lists only what it imports. + fn dmabuf_modifiers(&self) -> &[u64] { + &[] + } } /// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`. diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index 71e9772..631a5b7 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -288,6 +288,8 @@ struct VideoState { fps: u32, /// Offer DMA-BUFs. dmabuf: bool, + /// The sink's tiled modifiers the offer was made with (ahead of LINEAR). + modifiers: Vec, /// Mappings of the DMA-BUFs PipeWire cycles through. maps: Vec, /// Time spent handing DMA-BUF frames to the sink, and how many. @@ -315,12 +317,15 @@ fn video_stream( let stream = pw::stream::StreamRc::new(core.clone(), "voelin-screen-capture", props) .map_err(|e| format!("PipeWire stream: {e}"))?; let fps = sink.max_fps().max(1); + let modifiers = sink.dmabuf_modifiers().to_vec(); + let formats = enum_formats(fps, dmabuf, &modifiers)?; let state = VideoState { sink, format: None, started: Instant::now(), fps, dmabuf, + modifiers, maps: Vec::new(), dmabuf_time: Duration::ZERO, dmabuf_frames: 0, @@ -359,7 +364,6 @@ fn video_stream( .register() .map_err(|e| format!("PipeWire listener: {e}"))?; - let formats = enum_formats(fps, dmabuf)?; let mut pods = formats.iter().map(|f| pod(f)).collect::, _>>()?; stream .connect( @@ -397,15 +401,24 @@ fn framerate_range(fps: u32) -> Property { ) } -fn modifier_property(fixed: bool) -> Property { +/// The modifiers we take, best first: the sink's tiled ones, then LINEAR, +/// which the CPU can always read. +fn our_modifiers(tiled: &[u64]) -> Vec { + tiled.iter().map(|&m| m as i64).chain([MODIFIER_LINEAR]).collect() +} + +/// The modifier property of a DMA-BUF format: a choice of `modifiers` the +/// producer must not fixate (we pick, see [`format_changed`]), or one fixed +/// modifier. +fn modifier_property(modifiers: &[i64], fixed: bool) -> Property { let flags = pw::spa::sys::SPA_POD_PROP_FLAG_MANDATORY | if fixed { 0 } else { pw::spa::sys::SPA_POD_PROP_FLAG_DONT_FIXATE }; let value = if fixed { - Value::Long(MODIFIER_LINEAR) + Value::Long(modifiers[0]) } else { Value::Choice(ChoiceValue::Long(Choice( ChoiceFlags::empty(), - ChoiceEnum::Enum { default: MODIFIER_LINEAR, alternatives: vec![MODIFIER_LINEAR] }, + ChoiceEnum::Enum { default: modifiers[0], alternatives: modifiers.to_vec() }, ))) }; Property { @@ -415,6 +428,19 @@ fn modifier_property(fixed: bool) -> Property { } } +/// The modifiers a producer's modifier property leaves to choose from. +fn offered_modifiers(prop: &pw::spa::pod::PodProp) -> Vec { + use pw::spa::pod::deserialize::PodDeserializer; + match PodDeserializer::deserialize_any_from(prop.value().as_bytes()).map(|(_, v)| v) { + Ok(Value::Long(m)) => vec![m], + Ok(Value::Choice(ChoiceValue::Long(Choice( + _, + ChoiceEnum::Enum { default, alternatives }, + )))) => std::iter::once(default).chain(alternatives).collect(), + _ => Vec::new(), + } +} + fn format_object(properties: Vec) -> Value { Value::Object(Object { type_: SpaTypes::ObjectParamFormat.as_raw(), @@ -423,9 +449,15 @@ fn format_object(properties: Vec) -> Value { }) } -/// The formats we offer: each pixel format as a LINEAR DMA-BUF (if -/// `dmabuf`), then all of them in shared memory. -fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result>, String> { +/// The formats we offer: each pixel format as a DMA-BUF (if `dmabuf`) with +/// the sink's tiled modifiers ahead of LINEAR, then all of them in shared +/// memory. +fn enum_formats( + fps: u32, + dmabuf: bool, + tiled: &[u64], +) -> std::result::Result>, String> { + let modifiers = our_modifiers(tiled); let mut formats = Vec::new(); let base = || { vec![ @@ -437,7 +469,7 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result>, Str for format in FORMATS { let mut properties = base(); properties.push(property!(FormatProperties::VideoFormat, Id, format)); - properties.push(modifier_property(false)); + properties.push(modifier_property(&modifiers, false)); properties.push(size_range()); properties.push(framerate_range(fps)); formats.push(serialize(format_object(properties))?); @@ -461,10 +493,10 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result>, Str Ok(formats) } -/// Offer formats again (another frame rate, or no DMA-BUFs); PipeWire -/// renegotiates. -fn renegotiate(stream: &pw::stream::Stream, fps: u32, dmabuf: bool) { - let result = enum_formats(fps, dmabuf).and_then(|formats| { +/// Offer formats again (another frame rate, other modifiers, or no +/// DMA-BUFs); PipeWire renegotiates. +fn renegotiate(stream: &pw::stream::Stream, state: &VideoState) { + let result = enum_formats(state.fps, state.dmabuf, &state.modifiers).and_then(|formats| { let mut pods = formats.iter().map(|f| pod(f)).collect::, _>>()?; stream.update_params(&mut pods).map_err(|e| e.to_string()) @@ -494,12 +526,17 @@ fn format_changed( .and_then(|o| o.find_prop(Id(FormatProperties::VideoModifier.as_raw()))); let modifier = match modifier { Some(prop) if prop.flags().contains(PodPropFlags::DONT_FIXATE) => { - // The producer left the choice to us; we only take LINEAR. + // The producer left the choice to us: the best of ours that it + // can make, else LINEAR. + let theirs = offered_modifiers(prop); + let ours = our_modifiers(&state.modifiers); + let chosen = ours.into_iter().find(|m| theirs.contains(m)).unwrap_or(MODIFIER_LINEAR); + debug!(offered = ?theirs, chosen, "screen capture modifier"); let mut properties = vec![ property!(FormatProperties::MediaType, Id, MediaType::Video), property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), property!(FormatProperties::VideoFormat, Id, info.format()), - modifier_property(true), + modifier_property(&[chosen], true), property!( FormatProperties::VideoSize, Rectangle, @@ -539,16 +576,20 @@ fn format_changed( } fn process(stream: &pw::stream::Stream, state: &mut VideoState) { - // Follow the sink's frame rate: ask the compositor for another rate. + // Follow the sink: ask the compositor for another rate, or buffers with + // the modifiers the sink takes now. let fps = state.sink.max_fps().max(1); - if fps != state.fps { + let modifiers = state.sink.dmabuf_modifiers(); + if fps != state.fps || (state.dmabuf && modifiers != state.modifiers.as_slice()) { state.fps = fps; - renegotiate(stream, fps, state.dmabuf); + state.modifiers = modifiers.to_vec(); + renegotiate(stream, state); } let Some(mut buffer) = stream.dequeue_buffer() else { return }; let Some(format) = state.format else { return }; if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) && !state.sink.accepts_dmabuf() { - // Tiled: the CPU cannot read it (we only offer LINEAR). + // Tiled, and the sink no longer imports it: the CPU cannot read it. + // The new offer (above) brings LINEAR buffers. return; } let timestamp = state.started.elapsed(); @@ -661,7 +702,7 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { "screen capture DMA-BUFs cannot be mapped; switching to shared memory" ); state.dmabuf = false; - renegotiate(stream, state.fps, false); + renegotiate(stream, state); } return; } @@ -718,7 +759,7 @@ fn probe_dmabuf( "reading DMA-BUFs takes {per_pixel:.1} ns per pixel; switching screen capture to shared memory" ); state.dmabuf = false; - renegotiate(stream, state.fps, false); + renegotiate(stream, state); } } @@ -748,20 +789,32 @@ mod tests { /// left to us to fixate) per pixel format, then shared memory. #[test] fn offered_formats() { - let formats = enum_formats(60, true).unwrap(); + // A sink that imports one tiled modifier (an AMD one here). + const TILED: u64 = 0x0200_0000_28a0_1f04; + let formats = enum_formats(60, true, &[TILED]).unwrap(); assert_eq!(formats.len(), FORMATS.len() + 1); for (i, bytes) in formats.iter().enumerate() { let object = pod(bytes).unwrap().as_object().unwrap(); let modifier = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())); if i < FORMATS.len() { - let flags = modifier.expect("a modifier").flags(); + let modifier = modifier.expect("a modifier"); + let flags = modifier.flags(); assert!(flags.contains(PodPropFlags::MANDATORY | PodPropFlags::DONT_FIXATE)); + // Read back as a producer's choice is: ours first, LINEAR last. + let offered = offered_modifiers(modifier); + assert_eq!(offered.first(), Some(&(TILED as i64))); + assert_eq!(offered.last(), Some(&MODIFIER_LINEAR)); } else { assert!(modifier.is_none(), "shared memory has no modifier"); } } - assert_eq!(enum_formats(30, false).unwrap().len(), 1); - let fixed = serialize(format_object(vec![modifier_property(true)])).unwrap(); + let linear_only = enum_formats(60, true, &[]).unwrap(); + let object = pod(&linear_only[0]).unwrap().as_object().unwrap(); + let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap(); + assert_eq!(offered_modifiers(prop), [MODIFIER_LINEAR, MODIFIER_LINEAR]); + assert_eq!(enum_formats(30, false, &[TILED]).unwrap().len(), 1); + let fixed = + serialize(format_object(vec![modifier_property(&[MODIFIER_LINEAR], true)])).unwrap(); let object = pod(&fixed).unwrap().as_object().unwrap(); let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap(); assert_eq!(prop.value().get_long().unwrap(), MODIFIER_LINEAR); diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index c9b71b5..55056c4 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, - SourceId, Ticker, Worker, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, DmaBufRef, FrameSink, QueueSink, + ScreenCapture, SourceId, Ticker, Worker, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::{FrameReceiver, frame_channel}; @@ -224,6 +224,7 @@ pub struct SyntheticScreen { pattern: Pattern, desktop: Option>, worker: Option, + dmabuf: bool, } impl SyntheticScreen { @@ -236,7 +237,18 @@ 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 } + Self { width, height, pattern, desktop, worker: None, dmabuf: false } + } + + /// Draw into a DMA-BUF of ordinary memory and offer it to sinks that + /// take DMA-BUFs ([`FrameSink::accepts_dmabuf`]) as a LINEAR `XR24` + /// buffer, as the ScreenCast portal does; sinks that do not, or decline + /// it, get the same memory as a frame. Linux with the `pipewire` + /// feature and access to `/dev/udmabuf`; elsewhere frames are handed + /// over as before. + pub fn with_dmabuf(mut self, enabled: bool) -> Self { + self.dmabuf = enabled; + self } pub fn pattern(&self) -> Pattern { @@ -251,6 +263,7 @@ impl SyntheticScreen { pattern: self.pattern, desktop: self.desktop.clone(), worker: None, + dmabuf: self.dmabuf, } } @@ -268,8 +281,15 @@ impl SyntheticScreen { /// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing /// its memory. pub fn render(&self, n: u64, out: &mut Vec) { + out.resize(self.width as usize * self.height as usize * 4, 0); + self.draw(n, out); + } + + /// [`render`](Self::render) into the first `width * height * 4` bytes of + /// `out`. + fn draw(&self, n: u64, out: &mut [u8]) { let (w, h) = (self.width as usize, self.height as usize); - out.resize(w * h * 4, 0); + let out = &mut out[..w * h * 4]; match &self.desktop { Some(desktop) => desktop.draw(out, w, n as usize * 3), None => { @@ -349,17 +369,28 @@ impl ScreenCapture for SyntheticScreen { let (width, height) = (pattern.width, pattern.height); let mut fps = sink.max_fps(); let mut ticker = Ticker::new(fps); - let mut buffer = Vec::new(); + let mut buffer = Buffer::new(&pattern); let started = Instant::now(); let mut n = 0; loop { let timestamp = started.elapsed(); if sink.wants(timestamp) { - pattern.render(n, &mut buffer); - let plane = PlaneRef::new(&buffer, width as usize * 4); - let frame = - FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) }; - if !sink.frame(frame) { + let bytes = buffer.bytes(); + pattern.draw(n, bytes); + let taken = match buffer.dmabuf(&pattern, timestamp) { + Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame), + _ => None, + }; + let more = taken.unwrap_or_else(|| { + let plane = PlaneRef::new(buffer.bytes(), width as usize * 4); + sink.frame(FrameRef { + width, + height, + timestamp, + pixels: PixelsRef::Bgra(plane), + }) + }); + if !more { break; } n += 1; @@ -382,6 +413,58 @@ impl ScreenCapture for SyntheticScreen { } } +/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary +/// memory ([`SyntheticScreen::with_dmabuf`]). +enum Buffer { + Memory(Vec), + #[cfg(all(target_os = "linux", feature = "pipewire"))] + Dmabuf(super::dmabuf::Udmabuf), +} + +impl Buffer { + fn new(pattern: &SyntheticScreen) -> Self { + let len = pattern.width as usize * pattern.height as usize * 4; + #[cfg(all(target_os = "linux", feature = "pipewire"))] + if pattern.dmabuf { + match super::dmabuf::Udmabuf::new(len) { + Ok(buffer) => return Self::Dmabuf(buffer), + Err(e) => tracing::warn!("test pattern without DMA-BUFs (/dev/udmabuf): {e}"), + } + } + Self::Memory(vec![0; len]) + } + + 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(), + } + } + + /// The buffer as a LINEAR `XR24` DMA-BUF, if it is one. + fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option { + match self { + Self::Memory(_) => { + let _ = (pattern, timestamp); + None + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + Self::Dmabuf(buffer) => Some(DmaBufRef { + width: pattern.width, + height: pattern.height, + timestamp, + fourcc: super::drm_fourcc(b"XR24"), + modifier: super::DRM_MOD_LINEAR, + fd: buffer.fd(), + size: buffer.len(), + planes: [(0, pattern.width as usize * 4), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + }), + } + } +} + /// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers. pub struct SineSource { frequency: f32, @@ -523,4 +606,61 @@ mod tests { assert_eq!((buffer.channels, buffer.frames()), (2, 480)); tone.stop(); } + + /// With DMA-BUFs, a sink that takes them gets the pattern as a LINEAR + /// `XR24` DMA-BUF that reads back as the pattern; one that declines it + /// gets the same picture as a frame. + #[cfg(all(target_os = "linux", feature = "pipewire"))] + #[tokio::test] + async fn the_pattern_as_dmabufs() { + use std::sync::mpsc; + + /// Takes DMA-BUFs (or declines them) and reports what it got. + struct Sink { + take: bool, + got: mpsc::Sender<(bool, Vec)>, + } + impl FrameSink for Sink { + fn max_fps(&self) -> u32 { + 50 + } + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + let PixelsRef::Bgra(plane) = frame.pixels else { panic!("BGRA") }; + self.got.send((false, plane.row(0, 64 * 4).to_vec())).is_ok() + } + fn accepts_dmabuf(&self) -> bool { + true + } + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + assert_eq!(frame.fourcc, crate::capture::drm_fourcc(b"XR24")); + assert_eq!((frame.width, frame.height, frame.planes[0].1), (64, 48, 256)); + if !self.take { + return None; + } + let map = super::super::dmabuf::DmaBufMap::new(frame.fd, frame.size).unwrap(); + let row = map.read(|bytes| bytes[..64 * 4].to_vec()); + Some(self.got.send((true, row)).is_ok()) + } + } + + if !std::path::Path::new("/dev/udmabuf").exists() { + eprintln!("no /dev/udmabuf, skipped"); + return; + } + let mut expected = Vec::new(); + SyntheticScreen::new(64, 48).render(0, &mut expected); + for take in [true, false] { + let mut screen = SyntheticScreen::new(64, 48).with_dmabuf(true); + let (got, frames) = mpsc::channel(); + let sink = Box::new(Sink { take, got }); + screen + .start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink) + .await + .unwrap(); + let (dmabuf, row) = frames.recv_timeout(Duration::from_secs(5)).unwrap(); + screen.stop(); + assert_eq!(dmabuf, take, "taken as a DMA-BUF"); + assert_eq!(row, expected[..64 * 4], "the first row of frame 0"); + } + } } 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..7fc088e 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,19 @@ 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| { + let a = a.max(2); + 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 +691,7 @@ impl FfmpegEncoder { low_power: false, dmabuf_checked: false, alignment, + gpu: None, }) } @@ -735,11 +757,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 +812,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 +884,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 +941,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 +1115,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 +1129,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 +1165,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 +1195,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 +1222,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 +1412,45 @@ 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 frame.surface.0.is_null() { + return Err(self.unavailable("a GPU frame without a surface (out of memory)".into())); + } + 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 +2045,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 +2132,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 +2304,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 +2315,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; @@ -2317,9 +2341,9 @@ mod tests { // The buffers: the driver's own (tiled), and a LINEAR one with a // padded pitch in system memory, which is what the portal negotiates. - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", feature = "pipewire"))] let linear = linear_dmabuf(&picture, (SIZE.0 as usize * 4).next_multiple_of(256)); - #[cfg(not(target_os = "linux"))] + #[cfg(not(all(target_os = "linux", feature = "pipewire")))] let linear: Option<((), DmaBufRef)> = None; if linear.is_none() { eprintln!("no /dev/udmabuf: the LINEAR buffer is skipped"); @@ -2384,91 +2408,33 @@ mod tests { } } - /// `struct udmabuf_create` of ``, and `UDMABUF_CREATE` - /// returning the new DMA-BUF. - #[cfg(target_os = "linux")] - #[repr(C)] - struct UdmabufCreate { - memfd: u32, - flags: u32, - offset: u64, - size: u64, - } - - // SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) - // only reads the struct and returns a new descriptor. - #[cfg(target_os = "linux")] - unsafe impl rustix::ioctl::Ioctl for UdmabufCreate { - type Output = std::os::fd::OwnedFd; - const IS_MUTATING: bool = false; - - fn opcode(&self) -> rustix::ioctl::Opcode { - rustix::ioctl::opcode::write::(b'u', 0x42) - } - - fn as_ptr(&mut self) -> *mut std::ffi::c_void { - (&raw mut *self).cast() - } - - unsafe fn output_from_ptr( - out: rustix::ioctl::IoctlOutput, - _: *mut std::ffi::c_void, - ) -> rustix::io::Result { - // SAFETY: the descriptor the kernel just made, ours to own. - Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) }) - } - } - - /// `picture` (BGRA) in a LINEAR DMA-BUF of system memory, rows `stride` - /// bytes apart: `/dev/udmabuf` over a sealed memfd. The descriptor has - /// to outlive the returned buffer. `None` without access to + /// `picture` (BGRA) in a LINEAR DMA-BUF of ordinary memory, rows + /// `stride` bytes apart ([`Udmabuf`](crate::capture::dmabuf::Udmabuf)); + /// the buffer has to outlive the reference. `None` without access to /// `/dev/udmabuf`. - #[cfg(target_os = "linux")] + #[cfg(all(target_os = "linux", feature = "pipewire"))] fn linear_dmabuf( picture: &VideoFrame, stride: usize, - ) -> Option<(std::os::fd::OwnedFd, DmaBufRef)> { - use rustix::fs::{MemfdFlags, SealFlags}; - use std::io::Write; - use std::os::fd::AsRawFd; - + ) -> Option<(crate::capture::dmabuf::Udmabuf, DmaBufRef)> { let FrameData::Bgra(pixels) = &picture.data else { return None }; let (w, h) = (picture.width as usize, picture.height as usize); - let size = (stride * h).next_multiple_of(4096); - let memfd = rustix::fs::memfd_create( - "voelin-linear-dmabuf", - MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING, - ) - .ok()?; - let mut bytes = vec![0; size]; - for (y, row) in bytes.chunks_exact_mut(stride).take(h).enumerate() { + let mut buffer = crate::capture::dmabuf::Udmabuf::new(stride * h).ok()?; + for (y, row) in buffer.bytes_mut().chunks_exact_mut(stride).take(h).enumerate() { row[..w * 4].copy_from_slice(pixels.row(y, w * 4)); } - let mut file = std::fs::File::from(memfd); - file.write_all(&bytes).ok()?; - rustix::fs::fcntl_add_seals(&file, SealFlags::SHRINK).ok()?; - let device = - std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf").ok()?; - let create = UdmabufCreate { - memfd: file.as_raw_fd() as u32, - flags: 1, - offset: 0, - size: size as u64, - }; - // SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf. - let fd = unsafe { rustix::ioctl::ioctl(&device, create) }.ok()?; let frame = DmaBufRef { width: picture.width, height: picture.height, timestamp: Duration::ZERO, fourcc: drm_fourcc(b"XR24"), modifier: crate::capture::DRM_MOD_LINEAR, - fd: fd.as_raw_fd(), - size, + fd: buffer.fd(), + size: buffer.len(), planes: [(0, stride), (0, 0), (0, 0), (0, 0)], plane_count: 1, }; - Some((fd, frame)) + Some((buffer, frame)) } /// What the CPU spends per frame on its way into a VA-API encoder at diff --git a/crates/voelin-media/src/ffmpeg/gpu.rs b/crates/voelin-media/src/ffmpeg/gpu.rs new file mode 100644 index 0000000..ff8cccc --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/gpu.rs @@ -0,0 +1,385 @@ +//! 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)) + } + + /// Another frame of the same surface (NULL, which encoders refuse, if + /// memory runs out). + pub(crate) fn new_ref(&self) -> Self { + let api = &Ffmpeg::get().expect("a surface exists only with FFmpeg").api; + // SAFETY: a new frame takes a reference to ours; freed on failure. + unsafe { + let mut frame = (api.av_frame_alloc)(); + if !frame.is_null() && (api.av_frame_ref)(frame, self.0) < 0 { + (api.av_frame_free)(&mut frame); + } + 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..b329bd2 100644 --- a/crates/voelin-media/src/frame.rs +++ b/crates/voelin-media/src/frame.rs @@ -284,6 +284,47 @@ 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 + } + + /// The same picture at another time (another reference to the same + /// surface), e.g. to send a still screen again. + pub fn at(&self, timestamp: Duration) -> Self { + Self { + width: self.width, + height: self.height, + timestamp, + #[cfg(feature = "ffmpeg")] + surface: self.surface.new_ref(), + } + } +} + +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/handoff.rs b/crates/voelin-media/src/handoff.rs index 145373f..9c08176 100644 --- a/crates/voelin-media/src/handoff.rs +++ b/crates/voelin-media/src/handoff.rs @@ -95,6 +95,14 @@ impl Handoff { } } + /// Make the calling thread the consumer that [`put`](Self::put) wakes + /// (what the first [`wait_timeout`](Self::wait_timeout) does), for a + /// thread that waits on several handoffs itself + /// (`std::thread::park_timeout`, then [`take`](Self::take) from each). + pub fn register(&self) { + self.consumer.get_or_init(std::thread::current); + } + /// Wake the consumer and make waits return at once (items can still be /// taken). pub fn close(&self) { 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}; diff --git a/docs/media.md b/docs/media.md index 0b73842..b121203 100644 --- a/docs/media.md +++ b/docs/media.md @@ -20,7 +20,8 @@ video, recording, a replay buffer, WHIP) is described in | `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz | | `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer` (`make_mut_bytes()`, stride `width * 4`) | | `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` | -| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()` | +| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API) | +| `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time) | | `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | | `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time) | | `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | @@ -29,8 +30,9 @@ video, recording, a replay buffer, WHIP) is described in | `EncoderReport { ffmpeg, zero_copy, encoders: Vec }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference | | `EncoderBackend` | `Libvpx`, `OpenH264`, `Ffmpeg("h264_vaapi")`, `Hardware("mediacodec")`; `name()` is the settings spelling | | `ffmpeg::{Ffmpeg, probe, FfmpegEncoder, BACKENDS}` | FFmpeg loaded at runtime (feature `ffmpeg`), see [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) | +| `ffmpeg::{GpuConverter, GpuLayer}` | an RGB DMA-BUF converted to NV12 and scaled for every simulcast layer on the GPU (`convert(&DmaBufRef, &[GpuLayer], out)`), `modifiers()` it imports; see zero-copy under [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) | | `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user | -| `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool` | +| `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool`; `accepts_dmabuf()`, `dmabuf(&DmaBufRef) -> Option` (a frame still in GPU memory, offered before it is mapped) and `dmabuf_modifiers()` (tiled layouts the sink imports) | | `FramePacer` | frame-rate cap by timestamps, evenly spaced | | `convert::Converter` | `to_i420_into(&FrameRef, &mut VideoFrame)`: any stride, BGRx/BGRA/RGBx/RGBA/I420/NV12, row bands on all cores, no allocation | | `scale::{PlaneScaler, Pyramid, scale_i420}` | area-average downscaling (bilinear up), 2x2 box fast path; `Pyramid::process(&FrameRef, sizes, due, out)` converts once and derives every size from the nearest larger one | @@ -65,7 +67,8 @@ PipeWire). The desktop app and voelinctl use `media-desktop`, the Android app ``` streamer: capture thread ── FrameSink: pace, convert + scale (Pyramid on all cores) - │ one Handoff per layer (newest frame wins) + │ or, for a DMA-BUF and VA-API encoders: GpuConverter (on the GPU) + │ one Handoff per layer (newest frame wins; one more for GPU frames) ├─ encoder thread, layer 0 ─┐ ├─ encoder thread, layer 1 ─┤ └─ ... ├─ MediaSink: StreamSink / EncodedSource @@ -80,7 +83,8 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder stream is live. The audio is mixed from `StreamerConfig::audio_sources` (see [Stream audio](#stream-audio)); without any, it is desktop audio without Voelin, or a quiet sine tone with the test pattern - (`SourceId::Synthetic`, `synthetic_pattern`). The portal's restore token + (`SourceId::Synthetic`, `synthetic_pattern`; `synthetic_dmabuf` hands it + over as DMA-BUFs, as the portal does). The portal's restore token is available afterwards (`restore_token()`) to store. `Streamer::start_studio(&codecs, config, studio)` streams the Stream Studio's composite instead, encoded from the start for the studio's @@ -93,6 +97,22 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder layer's newest frame goes through a one-slot handoff to that layer's encoder thread; a frame the encoder was too busy for is replaced and counted, never queued, so latency stays one frame. +- GPU path (Linux): a frame still in a DMA-BUF (the portal's) is taken as + it is when every encoder of every layer takes GPU frames (VA-API; each + encoder thread publishes what its encoders take, `Layer::gpu`). One + `GpuConverter` call on the capture thread converts it to NV12 and scales + it for every layer that is due, into surfaces of our own at sizes the + layer's encoders encode exactly, and returns once the GPU is done, so + the buffer goes straight back to the compositor; the CPU never reads it. + Each layer's surface reaches its encoder thread through a second + handoff (the thread waits on both) and is encoded as it is + (`encode_gpu`). Anything else takes the CPU path as before, and the + capture switches between the two by itself: an encoder that needs frames + in memory (libvpx, x264, or one made for a viewer of another codec) + makes the sink decline the next DMA-BUF, so the portal maps it, and a + conversion that fails turns the GPU path off for the capture + (`StreamerStats::gpu_error`). Nothing is allocated per frame on this + path either (the surfaces' frames are recycled). - Simulcast: `StreamerConfig::layers` (`voelin_stream::LayerSpec`; empty: one layer 0 at `bitrate_kbps`) are all encoded, each with its own encoder at `output_size()` of the source, its own frame-rate cap (`max_fps`, @@ -125,6 +145,7 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder tell codecs apart (`EncodedSource`, a `FrameSource`) get the stream codec only, so their offers must list it alone (`voelinctl stream start` does). - `stats()`: `StreamerStats` with capture fps, convert time and threads, + the GPU path (`gpu_frames`, `gpu_convert_time`, `gpu_error`), dropped frames, codec, and per layer (`LayerStats`) size, frames, keyframes, dropped, fps, kbit/s, encode time, target bitrate, threads, encoder speed, the stream codec's `backend` and the `codecs` encoded; the audio mix's level and limiter gain, and per audio @@ -416,17 +437,24 @@ the software encoders above are used as before. in: FFmpeg 9's `h264_vaapi` crashes (SIGSEGV in `avcodec_send_frame`) when drained before its first frame, which is what dropping an encoder whose first frame failed used to do. -- Zero-copy (Linux): `FfmpegEncoder::encode_dmabuf(&DmaBufRef, ...)` maps a - DRM PRIME frame onto a VA-API surface (`av_hwframe_map`), so the CPU never - reads the buffer. NV12 buffers (one layer of two planes, which is how a - compositor hands one over) go to the encoder as they are. RGB buffers - (`XR24`, `AR24`, `XB24`, `AB24`: what screen capture delivers) are - mapped onto a surface of their own size and converted into the session's - NV12 surface by VA-API video processing (`ffmpeg/vpp.rs`: libva's - `VAEntrypointVideoProc` on FFmpeg's own `VADisplay`, found through - `AVHWDeviceContext.hwctx`), cropped to the coded size on the way; the - call returns once the GPU has read the buffer, so it can go back to the - compositor. libva is the library FFmpeg's VA-API support already loaded +- Zero-copy (Linux): a DMA-BUF is mapped as a DRM PRIME frame onto a + VA-API surface (`av_hwframe_map`), so the CPU never reads it. RGB buffers + (`XR24`, `AR24`, `XB24`, `AB24`: what screen capture delivers) go through + `GpuConverter` (`ffmpeg/gpu.rs`): mapped onto a surface of their own + size, then converted to NV12 by VA-API video processing (`ffmpeg/vpp.rs`: + libva's `VAEntrypointVideoProc` on FFmpeg's own `VADisplay`, found + through `AVHWDeviceContext.hwctx`) once per simulcast layer, the whole + picture scaled to the layer's size and cropped to its encoders' + alignment, into NV12 surfaces from pools of our own. They travel as + `GpuFrame`s, recycled once nothing holds them, and VA-API encoders take + them as they are (`encode_gpu`; FFmpeg's VA-API encoders accept surfaces + from any pool of the device). The call returns once the GPU has read the + buffer, so it can go back to the compositor. The streamer's sink drives + this for every layer (see the GPU path in [the pipeline](#the-pipeline-in-voelin-core-media-module)); + `FfmpegEncoder::encode_dmabuf(&DmaBufRef, ...)` does the same for one + encoder, and takes NV12 buffers (one layer of two planes, which is how a + compositor hands one over) straight into the encoder. + libva is the library FFmpeg's VA-API support already loaded (`libva.so.2`, ABI unchanged since libva 2); FFmpeg itself has this conversion only in libavfilter (`scale_vaapi`), which would be another library and a filter graph for one call. The input is described with @@ -435,14 +463,11 @@ the software encoders above are used as before. the transfer function and every dark pixel came out about 5 levels too bright. Anything else (another format, an encoder that is not VA-API) fails with `Error::CodecUnavailable` and the caller maps the buffer for - the CPU path. The capture side has the hook (`FrameSink::accepts_dmabuf` - / `dmabuf`: the portal offers a buffer before mapping it), but the - streamer's sink (`Ingest` in voelin-core) does not accept DMA-BUFs yet, - so no captured frame takes this path in the app. The portal negotiates - LINEAR DMA-BUFs, which the import takes (tested); tiled ones would save - the compositor a copy but need the modifiers the encoder's driver - imports, which are not known on the capture side. See [the - measurements](#zero-copy-measured). + the CPU path. Tiled buffers: `GpuConverter::modifiers()` is the layout + the driver gives its own RGB surfaces (it imports what it makes; on the + RX 7900 GRE `0x200000028a01f04`), offered only if it needs a single plane + (no compression metadata); the portal offers it ahead of LINEAR (see + [Capture](#capture)). See [the measurements](#zero-copy-measured). Installing FFmpeg (runtime libraries only, no `-dev` packages): @@ -553,16 +578,22 @@ Notes: desktop's picker. Choices persist with `PersistMode::ExplicitlyRevoked`: store `PortalCapture::restore_token()` (e.g. in `voelin-store` settings) and pass it to `PortalCapture::with_restore_token` next time. The cursor is embedded when - the portal supports it. Buffers: LINEAR DMA-BUFs are offered first (a - mandatory modifier property we fixate; mapped once per buffer, read - between `DMA_BUF_IOCTL_SYNC` start and end), shared memory - (BGRx/BGRA/RGBx/RGBA) second. If reading DMA-BUFs is slower than 1 ns per - pixel over the first 30 frames (uncached VRAM), the stream renegotiates to - shared memory; `VOELIN_PORTAL_DMABUF=0` or `with_dmabuf(false)` skips them. - A sink that accepts DMA-BUFs gets them before anything is mapped (with - the buffer object's size, which compositors leave out of `maxsize`), and - then the CPU never reads them. Tiled modifiers are not offered (see - zero-copy above). The frame rate + the portal supports it. Buffers: DMA-BUFs are offered first (a + mandatory modifier property we fixate: the sink's tiled modifiers, best + first, then LINEAR), shared memory (BGRx/BGRA/RGBx/RGBA) second. A sink + that accepts DMA-BUFs (the streamer's, while its encoders take GPU + frames) gets them before anything is mapped (with the buffer object's + size, which compositors leave out of `maxsize`), and then the CPU never + reads them; its tiled modifiers (`FrameSink::dmabuf_modifiers`) are + offered from the second frame, and when the compositor leaves the choice + to us the first of ours it can make is taken. When the sink's list + changes (a switch to an encoder that needs frames in memory, a failed GPU + conversion) the formats are offered again, so LINEAR buffers come back + before the CPU has to read one. LINEAR buffers the sink does not take + are mapped once per buffer and read between `DMA_BUF_IOCTL_SYNC` start + and end; if that is slower than 1 ns per pixel over the first 30 frames + (uncached VRAM), the stream renegotiates to shared memory. + `VOELIN_PORTAL_DMABUF=0` or `with_dmabuf(false)` skips DMA-BUFs. The frame rate asked of the compositor is the sink's cap, renegotiated when it changes; compositors send frames only when the screen changes. Without a session bus or portal, `start` returns `Error::CaptureUnavailable`; a cancelled @@ -603,6 +634,9 @@ voelinctl stream bench --res 1280x720 --encoder h264_vaapi voelinctl stream bench --res 2560x1440 --fps 30 \ --layer scale=1,bitrate=6M --layer scale=0.5,bitrate=1500k,fps=30 \ --layer size=640x360,bitrate=400k,fps=15 +# 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 # 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 @@ -614,7 +648,8 @@ cargo bench -p voelin-media --bench convert `--pattern desktop` (default) is a code-editor-like picture whose document scrolls three pixels per frame, about as costly to encode as real screen content; `--pattern simple` is the flat test pattern. The bench prints -capture fps, convert time and threads, per layer fps, kbit/s, keyframes, +capture fps, how many frames each path converted (CPU, or GPU for +DMA-BUFs no CPU read) and the time per frame of each, per layer fps, kbit/s, keyframes, frames dropped by the handoff, encode time, threads and `cpu-used`, CPU use and allocations per captured and per encoded frame. @@ -754,8 +789,8 @@ the CPU reads its memory uncached, so the same conversion costs 44 times the time and 48 times the CPU. `SLOW_DMABUF_NS_PER_PIXEL` exists for exactly this, but at 6.0 ns per pixel it never fired against the DMA-BUF path's 3.24; it now sits between the two measurements. Zero-copy is the real answer -for this hardware — the buffer would never be read by the CPU at all; the -next section measures the encoder's half of it. +for this hardware — the buffer is never read by the CPU at all; the next +section measures it, without a portal so far. ### Zero-copy, measured @@ -763,7 +798,7 @@ Same machine, `h264_vaapi`, release build: what the CPU spends per 2560x1440 frame on its way into the encoder, 600 frames after 30 of warm-up, CPU time of every thread of the process (`ffmpeg::encoder::tests::zero_copy_cpu_cost`, run with `--ignored`). -"Shared memory" is the path a captured frame takes today: the picture +"Shared memory" is the CPU path of a captured frame: the picture converted to I420 on every core (`convert::Converter`), interleaved to NV12 and uploaded into a VA-API surface by `encode_with`. "DMA-BUF" is an RGB (`XR24`) DMA-BUF of the same picture through `encode_dmabuf`: imported, @@ -784,10 +819,41 @@ within 0.7 on average (another chroma filter at edges), and through buffer and from a LINEAR one with a padded pitch (`/dev/udmabuf`), which is what the portal negotiates. -What this does not show yet is a real capture through it: the streamer's -sink does not take DMA-BUFs yet (see the zero-copy bullet above), so the -Wayland numbers above are all shared memory. A capture through the GPU -path needs that sink and another portal run. +The whole streamer, both paths: `voelinctl stream bench` (release), the +desktop pattern drawn into memory (CPU path) or into a LINEAR `XR24` +DMA-BUF of ordinary memory, as a compositor hands one over (`--dmabuf`, +GPU path), 10 s after 2 s of warm-up unless said otherwise. "Capture +thread" is the time per frame spent converting: on the CPU path the +pyramid's wall time on 32 threads, on the GPU path the wait for the GPU. +"cores" is the whole process, the pattern's own drawing included on both +paths (with a real capture the compositor draws). + +| run | path | frames converted | capture thread | layers: fps, kbit/s, encode ms | cores | +|---|---|---|---|---|---| +| 1440p60 `h264_vaapi`, 10 Mbit/s | CPU | 600 of 600 | 0.27-0.28 ms | 60.0, 10112, 4.09-4.16 | 0.34-0.52 | +| | GPU | 600 of 600 on the GPU, none on the CPU | 2.02-2.73 ms | 60.0, 9972, 2.61-2.62 | 0.10 | +| simulcast 1440p30 8 Mbit/s + 720p30 2 Mbit/s + 360p15 600 kbit/s, `h264_vaapi` | CPU | 300 of 300 | 0.44-0.49 ms | 30.0, 7666, 4.57; 30.0, 2121, 1.95-2.06; 15.0, 596, 1.11-1.32 | 0.26-0.38 | +| | GPU | 300 of 300 on the GPU | 3.72-5.87 ms (three conversions) | 30.0, 7472-7740, 2.73-2.79; 30.0, 2097-2108, 0.99-1.01; 15.0, 596-597, 1.84-2.48 | 0.06 | +| 1080p60 `av1_vaapi`, 6 Mbit/s, 5 s | CPU | 300 of 300 | 0.17 ms | 60.0, 5916, 2.30 (1920x1072 encoded) | 0.29 | +| | GPU | 300 of 300 on the GPU | 3.38 ms | 60.0, 5894, 1.43 (made at 1920x1072) | 0.06 | + +Two runs each except AV1 (one). Every run held the full frame rate with +nothing dropped, and both paths allocate 1.02 times per encoded frame (the +`Arc<[u8]>` of `EncodedFrame`). The GPU path takes a quarter to a fifth of +the CPU, and that is with the pattern still drawn by this process; what is +left is mostly that drawing. Its capture-thread time is the thread waiting +for the GPU, once per layer: 2-6 ms of the 16.7 or 33 ms a frame may take, +during which the CPU is idle. These buffers live in system memory, which +the GPU reads over PCIe; a compositor's are normally in video memory. The +encoders get a little faster too (no upload in front of them). + +What this does not show yet is a real capture through it: the portal has +not been run since the sink takes DMA-BUFs (it shows a dialog on the +desktop), so the Wayland numbers above are all the CPU path. +`voelinctl stream bench --source portal --encoder h264_vaapi` prints +whether frames took the GPU path; with +`RUST_LOG=voelin_media::capture::portal=debug` also the modifiers offered +and chosen. Build profiles: the dev profile builds the media hot path (yuv, voelin-media, str0m, x11rb-protocol, pipewire, wayland-client, ...) with @@ -847,7 +913,7 @@ has not run on Windows yet. | wlroots capture (wlr-screencopy v3): outputs, pixels, a change arriving as a new frame, queue API | `tests/wlroots_capture.rs` against headless sway 1.9 (`VOELIN_WLROOTS_TEST_DISPLAY`) | tested; the ext-image-copy-capture path is untested (sway 1.9 predates it) | | Converter (strides, unpadded last row, odd sizes, RGBA/I420/NV12), scaler (flat, area average, half), pyramid (sharing, recycling, steady-state pools) | unit tests | tested | | Simulcast layers (sizes, fps caps, per-layer keyframes), reconfigure (codec, layers, fps) | `voelin-core` `media::tests::simulcast_layers_and_reconfigure` | tested | -| Portal DMA-BUF negotiation | unit test of the offered formats; a real capture (row below) | formats parse; LINEAR DMA-BUFs negotiated with the compositor of the 2560x1440 desktop below | +| Portal DMA-BUF negotiation | unit test of the offered formats (a tiled modifier ahead of LINEAR, read back as a compositor's choice); a real capture (row below) | formats parse; LINEAR DMA-BUFs negotiated with the compositor of the 2560x1440 desktop below. The tiled offer and the renegotiation when the sink's modifiers change have not met a compositor yet | | Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested | | Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | `voelinctl stream bench --source portal` on a 2560x1440 Wayland desktop | tested: it delivered no frames at all (the DMA-BUF mapping length), and the DMA-BUF path cost 19.5 cores where shared memory costs 0.41. Both fixed; 1440p60 now runs on 0.55 cores (see the table above). Portal audio is still untested | | Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only | @@ -869,7 +935,10 @@ has not run on Windows yet. | RGB DMA-BUFs converted to NV12 on the GPU (VA-API video processing): against the CPU conversion, then through `h264_vaapi` and `av1_vaapi` (cropping 642x362 to 640x352) to our decoders, from a tiled buffer and from a LINEAR one with a padded pitch | `ffmpeg::encoder::tests::an_rgb_dmabuf_is_converted_on_the_gpu`, `vpp::tests` (the parameter struct against libva 2.24's header) | tested on the Radeon RX 7900 GRE: Y identical to the CPU's, U/V within 0.7 on average, within 0.3 dB of the CPU path after encoding. It found Mesa converting the transfer function by default (dark pixels 5 levels too bright), now described away | | CPU cost of the GPU path | `zero_copy_cpu_cost` (`--ignored`) | measured: 0.08-0.09 ms per 2560x1440 frame against 4.3-5.2 ms through shared memory (see above) | | A failed DMA-BUF import: an error, the encoder goes on, and drops cleanly | `tests/ffmpeg.rs` `dmabuf_import_is_refused_cleanly` (`/dev/null` as the buffer) | tested: it found FFmpeg 9's `h264_vaapi` crashing when a session that never got a frame is flushed; such sessions are no longer flushed | -| Zero-copy from screen capture | – | not reached: the encoder side works (rows above) and the portal hands a DMA-BUF to a sink that accepts one, but the streamer's sink (`Ingest` in voelin-core) does not, so no captured frame has gone through it | +| GPU frames for every simulcast layer: converted and scaled from one DMA-BUF, cropped to each encoder's alignment, recycled, encoded from their surfaces (`encode_gpu`) and decoded | `ffmpeg::encoder::tests::gpu_frames_for_every_layer` | tested on the Radeon RX 7900 GRE: 40.4 dB (full size) and 48.5 dB (scaled) against the CPU pyramid's pictures; the driver's tiled RGB layout `0x200000028a01f04` reported for the portal | +| The streamer's GPU path: DMA-BUFs taken while every encoder takes GPU frames, the CPU path after a switch to libvpx | `voelin-core` `media::tests::dmabufs_take_the_gpu_path_while_every_encoder_does` (the test pattern as DMA-BUFs, two layers, `h264_vaapi`) | tested: every frame of both layers on the GPU at their own sizes; after the switch the CPU converts again and the VP8 stream decodes | +| The test pattern as DMA-BUFs (`/dev/udmabuf`), taken or declined | `capture::synthetic::tests::the_pattern_as_dmabufs` | tested | +| Zero-copy from a real screen capture | `voelinctl stream bench --source portal --encoder h264_vaapi` | not run yet (a portal capture asks the person at the desktop); everything up to the portal is tested with the test pattern as DMA-BUFs (rows above, and the measurements) | | Offer [VP9, VP8], a viewer that decodes only VP8 → its own VP8 encoder, VP9 idle, pictures decoded | `voelin-core/tests/media_live.rs` `ts6_viewer_gets_the_codec_it_chose` (`VOELIN_LIVE=1`) | tested against the TeamSpeak 6 dev server (our client on both ends) | | Several codecs against official TeamSpeak viewers | – | not tested (no official client here) | | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index 511b006..a8e8fb8 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -71,6 +71,11 @@ struct BenchArgs { /// as real screen content) or `simple` (a flat background). #[arg(long, default_value = "desktop")] pattern: String, + /// Hand the test pattern over as DMA-BUFs of ordinary memory, as the + /// portal hands over the screen (Linux, `/dev/udmabuf`): with VA-API + /// encoders the frames are then converted and scaled on the GPU. + #[arg(long)] + dmabuf: 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)] @@ -293,6 +298,8 @@ struct Sample { layers: Vec<(LayerId, LayerSnapshot)>, sent: u64, captured: u64, + /// Captured frames converted on the GPU (never read by the CPU). + gpu: u64, /// Frames the handoffs to the encoders dropped, per layer. dropped: Vec<(LayerId, u64)>, } @@ -309,6 +316,7 @@ fn sample(sink: &BenchSink, streamer: &Streamer) -> Sample { layers: sink.snapshot(), sent: stats.video_frames, captured: stats.captured_frames, + gpu: stats.gpu_frames, dropped: stats.layers.iter().map(|l| (l.id, l.dropped)).collect(), } } @@ -345,6 +353,7 @@ fn bench(args: BenchArgs) -> Result<()> { source: source.clone(), synthetic_size: (width, height), synthetic_pattern: pattern, + synthetic_dmabuf: args.dmabuf, fps: args.fps, bitrate_kbps: args.bitrate, codec, @@ -411,13 +420,20 @@ fn bench(args: BenchArgs) -> Result<()> { let secs = (end.at - start.at).as_secs_f64(); let captured = end.captured - start.captured; + let gpu = end.gpu - start.gpu; let ms = |d: Duration| d.as_secs_f64() * 1000.0; println!( - "capture: {:.1} fps; convert + scale: {:.2} ms per frame on {} threads", + "capture: {:.1} fps; convert + scale: CPU {} frames, {:.2} ms per frame on {} threads; \ + GPU (DMA-BUF, never read by the CPU) {gpu} frames, {:.2} ms per frame", captured as f64 / secs, + captured - gpu.min(captured), ms(stats.convert_time), stats.convert_threads, + ms(stats.gpu_convert_time), ); + if let Some(e) = &stats.gpu_error { + println!("GPU path stopped: {e}"); + } let mut output_frames = 0; for ((id, a), (_, b)) in start.layers.iter().zip(&end.layers) { let frames = b.frames - a.frames;