From 4fac682cae725f06ff48159a7ec8adc6a9d4a674 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 13:33:52 +0300 Subject: [PATCH 01/10] voelin-media: record the AVFrame offsets of libavutil 61 instead of guessing The DMA-BUF import reads AVFrame.buf[0] and hw_frames_ctx at offsets the loader keeps in a table per libavutil major. The table ended in an open range that answered every major from 60 up with 60's offsets, so on this machine (libavutil 61) the import ran on an unverified guess, and a future major would get the same treatment. Compiled offsetof from the headers installed next to the library: libavutil 61 puts buf at 184 and hw_frames_ctx at 328, which is what 60 uses, so the guess happened to hold. Record 61 explicitly and stop answering unknown majors: AVFrame has shrunk between majors (424 bytes in 61 against 536 in 56), so an offset guessed for an unknown layout can point past the end of the struct. An unlisted major now turns the import off with a reason and leaves everything else working. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/ffmpeg/layout.rs | 63 +++++++++++++++++++++--- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 3947825..9856eb5 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -13,11 +13,14 @@ //! | `AVFrame.pict_type`, `AVFrame.pts` | forcing a keyframe, timestamps | right after the leading fields: `key_frame` (removed in libavutil 60), `pict_type`, `sample_aspect_ratio`, `pts` | a fresh frame must read `pict_type` 0, `sample_aspect_ratio` {0, 1}, `pts` `AV_NOPTS_VALUE` in exactly one of the two layouts | //! | `AVCodecContext.hw_frames_ctx` | VA-API input frames | next to fields that have AVOptions, whose offsets `av_opt_find` reports: before `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or two fields before `max_pixels` (up to 60) | the neighbours' option offsets must match the layout, and the field must be NULL in a new context | //! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context | -//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-60, 64-bit only) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | +//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | //! //! A check that fails disables only what needs the field (VA-API, or the -//! DMA-BUF import), with the reason in the probe results; a new major whose -//! layout matches keeps working without a change here. +//! DMA-BUF import), with the reason in the probe results. The first three +//! rows are found by searching, so a new major whose layout matches keeps +//! working without a change here; the last one is a table, because there is +//! nothing to anchor those offsets to, and an unlisted major turns the +//! DMA-BUF import off rather than guess (see [`frame_refs_table`]). #![allow(unsafe_code)] use std::ffi::c_int; @@ -324,8 +327,19 @@ pub struct FrameRefs { pub hw_frames_ctx: usize, } -/// The table of [`FrameRefs`] per libavutil major (64-bit targets). A newer -/// major is tried with the newest entry and must pass the checks. +/// The table of [`FrameRefs`] per libavutil major (64-bit targets). +/// +/// Every entry is `offsetof` compiled from that release's own +/// `libavutil/frame.h`; libavutil 61's was measured against the headers +/// installed next to the library it describes (FFmpeg 9.0.1: `buf` 184, +/// `hw_frames_ctx` 328, `sizeof(AVFrame)` 424). +/// +/// A major that is not listed returns `None`, which disables the DMA-BUF +/// import (and nothing else) with the reason in the probe results. It +/// deliberately does not fall back to the newest entry: `AVFrame` has both +/// grown and shrunk between majors (424 bytes in 61 against 536 in 56), so +/// an offset guessed for an unknown layout could read past the end of the +/// struct. Adding a major here needs its `offsetof` values, not a guess. fn frame_refs_table(avutil_major: u32) -> Option { if size_of::() != 8 { return None; @@ -334,7 +348,7 @@ fn frame_refs_table(avutil_major: u32) -> Option { 56 => (288, 480), 57 | 58 => (224, 392), 59 => (200, 352), - 60.. => (184, 328), + 60 | 61 => (184, 328), _ => return None, }; Some(FrameRefs { buf, hw_frames_ctx }) @@ -346,8 +360,12 @@ fn frame_refs_table(avutil_major: u32) -> Option { pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result { // SAFETY: no arguments. let major = unsafe { (api.avutil_version)() } >> 16; - let refs = frame_refs_table(major) - .ok_or_else(|| format!("AVFrame references not known for libavutil {major} here"))?; + let refs = frame_refs_table(major).ok_or_else(|| { + format!( + "AVFrame.buf / hw_frames_ctx offsets are not recorded for libavutil {major} (see \ + frame_refs_table); the import stays off until they are measured" + ) + })?; // SAFETY: a frame of 16x16 yuv420p pixels; the head fields are set // before av_frame_get_buffer as its documentation asks; the offsets are // inside AVFrame for this major (the table), pointer-aligned. @@ -410,4 +428,33 @@ mod tests { assert_eq!(frame_refs_table(58), Some(FrameRefs { buf: 224, hw_frames_ctx: 392 })); assert_eq!(frame_refs_table(55), None); } + + /// libavutil 61 (FFmpeg 9), compiled from the installed headers on + /// x86-64: `AVFrame` `pict_type` 120, `pts` 136, `buf` 184, + /// `hw_frames_ctx` 328, `sizeof` 424; `AVCodecContext` + /// `err_recognition` 528, `hw_frames_ctx` 552, `hw_device_ctx` 560, + /// `hwaccel_flags` 568, `extra_hw_frames` 572; `AVHWFramesContext` + /// `pool` 48, `initial_pool_size` 56, `format` 60, `sw_format` 64, + /// `width` 68, `height` 72. + #[cfg(target_pointer_width = "64")] + #[test] + fn libavutil_61_matches_the_headers() { + assert_eq!(frame_refs_table(61), Some(FrameRefs { buf: 184, hw_frames_ctx: 328 })); + assert_eq!(offset_of!(FrameWithoutKeyFrame, pict_type), 120); + assert_eq!(offset_of!(FrameWithoutKeyFrame, pts), 136); + let base = 528; + assert_eq!(base + offset_of!(HwFieldsNew, hw_frames_ctx), 552); + assert_eq!(base + offset_of!(HwFieldsNew, hw_device_ctx), 560); + assert_eq!(base + offset_of!(HwFieldsNew, hwaccel_flags), 568); + assert_eq!(base + offset_of!(HwFieldsNew, extra_hw_frames), 572); + assert_eq!(offset_of!(HwFramesPublic, pool), 48); + assert_eq!(offset_of!(HwFramesPublic, initial_pool_size), 56); + assert_eq!(offset_of!(HwFramesPublic, sw_format), 64); + assert_eq!(offset_of!(HwFramesPublic, height), 72); + // A major nobody measured must disable the import, not reuse 61's + // offsets: AVFrame has shrunk between majors (424 bytes in 61 + // against 536 in 56), so reading at a guessed offset could leave + // the struct. + assert_eq!(frame_refs_table(62), None); + } } From b541ec8093a791fbd8e691d9fb1919dbc0f948dd Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 13:39:37 +0300 Subject: [PATCH 02/10] voelin-media: tell the H.264 encoders the level the offer advertises The signalling computes profile-level-id from the stream's size, frame rate and bitrate, but nothing told the encoder, so every wrapper picked its own level. Measured on this GPU: h264_amf writes level 4.2 into the SPS of a 720p30 stream whose offer says 3.1, and 5.0 for a 1440p60 stream offered as 5.1. A viewer that sizes its decoder from our SDP can refuse a stream that declares more than the offer did, which is what breaks official clients. Compute the level from ITU-T Table A-1 and set it on both the codec context and the wrapper's private option. A new test parses the SPS of every usable H.264 backend at two sizes and both profiles and asserts profile_idc against the offer and level_idc never above it; with the level set, all three backends now emit exactly the offered level. The level table is a second copy of the one in voelin-stream, because neither crate can depend on the other, so a unit test pins them together over a spread of sizes, rates, bitrates and profiles. Remaining difference, only in the constraint-flag byte and left alone: the offer claims Constrained High (0c) and Constrained Baseline (e0) as WebRTC implementations conventionally do; the VA-API and AMF encoders emit 0c for the former, libx264 emits 00, and all three emit 40 or c0 for the latter. The bits do not change what a decoder can decode. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/Cargo.toml | 4 + crates/voelin-media/src/ffmpeg/encoder.rs | 107 ++++++++++++++++++++++ crates/voelin-media/tests/ffmpeg.rs | 103 ++++++++++++++++++++- 3 files changed, 212 insertions(+), 2 deletions(-) diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 2d3fde2..59e1878 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -71,6 +71,10 @@ windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +# The H.264 `profile-level-id` the signalling offers, to check it against the +# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream +# does not depend on this crate. +voelin-stream = { path = "../voelin-stream" } # Logs of integration tests (`RUST_LOG`). tracing-subscriber = { version = "0.3", features = ["env-filter"] } tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] } diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 53a3bfb..241d53e 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -189,6 +189,61 @@ const X264_PRESETS: [&str; 10] = [ const PROFILE_H264_HIGH: i64 = 100; const PROFILE_H264_CONSTRAINED_BASELINE: i64 = 66 | 1 << 9; +/// H.264 level limits (ITU-T H.264 Table A-1): `level_idc`, macroblocks per +/// second, macroblocks per frame, bitrate in kbit/s for Baseline (High +/// allows 1.25 times that). +const H264_LEVELS: [(i64, u64, u64, u64); 19] = [ + (10, 1_485, 99, 64), + (11, 3_000, 396, 192), + (12, 6_000, 396, 384), + (13, 11_880, 396, 768), + (20, 11_880, 396, 2_000), + (21, 19_800, 792, 4_000), + (22, 20_250, 1_620, 4_000), + (30, 40_500, 1_620, 10_000), + (31, 108_000, 3_600, 14_000), + (32, 216_000, 5_120, 20_000), + (40, 245_760, 8_192, 20_000), + (41, 245_760, 8_192, 50_000), + (42, 522_240, 8_704, 50_000), + (50, 589_824, 22_080, 135_000), + (51, 983_040, 36_864, 240_000), + (52, 2_073_600, 36_864, 240_000), + (60, 4_177_920, 139_264, 240_000), + (61, 8_355_840, 139_264, 480_000), + (62, 16_711_680, 139_264, 800_000), +]; + +/// The lowest `level_idc` whose limits hold this stream, or the highest +/// level defined if none does. +/// +/// The signalling offers the same level to the viewer +/// (`voelin_stream::h264::level_idc`, which this mirrors — a test pins the +/// two together). It has to be told to the encoder, because wrappers that +/// pick a level themselves pick a generous one: AMF writes level 4.2 into +/// the SPS of a 720p30 stream whose offer says 3.1, and a decoder set up +/// from that offer may refuse it. +fn h264_level(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate: u32) -> i64 { + let (mbs_w, mbs_h) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16))); + let frame = mbs_w * mbs_h; + let rate = frame * u64::from(fps.max(1)); + let factor = match profile { + H264Profile::ConstrainedHigh => 1250, + H264Profile::ConstrainedBaseline => 1000, + }; + H264_LEVELS + .iter() + .find(|&&(_, max_rate, max_frame, max_kbps)| { + rate <= max_rate + && frame <= max_frame + // Neither side may exceed sqrt(8 * MaxFS) macroblocks. + && mbs_w * mbs_w <= 8 * max_frame + && mbs_h * mbs_h <= 8 * max_frame + && u64::from(bitrate) <= max_kbps * factor + }) + .map_or(H264_LEVELS[H264_LEVELS.len() - 1].0, |l| l.0) +} + /// The backend's realtime settings (besides size, format, time base and /// rate, which every backend gets). fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec { @@ -688,6 +743,16 @@ impl FfmpegEncoder { if !self.spec.is_hardware() { list.push(generic("threads", self.config.threads_for(width, height))); } + if self.spec.codec == Codec::H264 { + // The level the signalling offers, so the SPS cannot claim a + // higher one than the viewer's decoder was set up for. Both + // targets: the wrappers that have a private `level` read that + // one, the rest `AVCodecContext.level`. + let level = + h264_level(self.config.h264_profile, width, height, fps, bitrate).to_string(); + list.push(generic("level", &level)); + list.push(Setting { values: vec![level], ..opt("level", &[]) }); + } list.extend(settings(self.spec, &self.config, low_power)); for setting in &list { self.apply(ctx, private, setting)?; @@ -1400,6 +1465,48 @@ mod tests { assert_eq!(t.pending.len(), 64, "bounded"); } + /// [`h264_level`] must agree with the level the signalling offers + /// (`voelin_stream::h264::level_idc`) for every stream, or the SPS and + /// the SDP would disagree again. Two copies of ITU-T Table A-1, pinned + /// to each other: this crate cannot depend on voelin-stream (it is the + /// lower one), and voelin-stream must not pull in the codecs. + #[test] + fn levels_agree_with_the_signalling() { + for (w, h) in [ + (320u32, 240u32), + (640, 360), + (1280, 720), + (1920, 1080), + (2560, 1440), + (3840, 2160), + (4096, 64), + (16384, 16384), + ] { + for fps in [1u32, 15, 30, 60, 120] { + for kbps in [200u32, 4_000, 8_000, 30_000] { + for (mine, theirs) in [ + (H264Profile::ConstrainedHigh, voelin_stream::H264Profile::ConstrainedHigh), + ( + H264Profile::ConstrainedBaseline, + voelin_stream::H264Profile::ConstrainedBaseline, + ), + ] { + let bitrate = kbps * 1000; + let ours = h264_level(mine, w, h, fps, bitrate); + let signalled = + voelin_stream::h264::level_idc(theirs, w, h, fps, u64::from(bitrate)); + assert_eq!( + ours, + i64::from(signalled), + "{w}x{h}@{fps} {kbps}k {mine:?}: encoder level {ours}, offer \ + {signalled}" + ); + } + } + } + } + } + #[test] fn settings_per_backend() { let config = EncoderConfig::default(); diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index 4f8e2ad..a614d4f 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -183,11 +183,24 @@ fn x264_is_constrained_high_and_changes_size() { /// `profile_idc` of the first SPS in an Annex B stream. fn h264_profile(data: &[u8]) -> Option { + sps(data).map(|(profile, _, _)| profile) +} + +/// `profile_idc`, the constraint-flag byte (`constraint_set0..5` in the top +/// six bits) and `level_idc` of the first SPS in an Annex B stream: the very +/// three bytes of `profile-level-id` in the SDP `a=fmtp` line. +/// +/// They are the first three bytes of the SPS payload, so no bit reading is +/// needed. Emulation prevention cannot touch them either: it only ever +/// inserts a byte after two zeros, and no valid SPS starts +/// `profile_idc == 0`. +fn sps(data: &[u8]) -> Option<(u8, u8, u8)> { let mut i = 0; - while i + 4 < data.len() { + while i + 3 < data.len() { if data[i..i + 3] == [0, 0, 1] { if data[i + 3] & 0x1f == 7 { - return data.get(i + 4).copied(); + let p = data.get(i + 4..i + 7)?; + return Some((p[0], p[1], p[2])); } i += 3; } else { @@ -197,6 +210,92 @@ fn h264_profile(data: &[u8]) -> Option { None } +/// What every usable H.264 backend puts in the SPS against the +/// `profile-level-id` the signalling offers for the same stream. A decoder +/// set up from our offer must be able to decode what we send, so the +/// emitted `level_idc` may never exceed the offered one, and `profile_idc` +/// has to be the profile we claim. +/// +/// The constraint-flag byte is only reported, not asserted: VA-API has no +/// Constrained High profile at all (`h264_vaapi` offers `main`, `high`, +/// `high10`, `constrained_baseline`), so it emits plain High with the flags +/// clear, while AMF's `constrained_high` sets `constraint_set4` and +/// `constraint_set5` as the offer says. See `docs/media.md`. +#[test] +fn sps_carries_the_offered_profile_and_level() { + use voelin_media::H264Profile; + if ffmpeg().is_none() { + return; + } + // 720p30 (offered level 3.1) and 1080p60 (4.2). + const CASES: [(u32, u32, u32, u32); 2] = + [(1280, 720, 30, 4_000_000), (1920, 1080, 60, 6_000_000)]; + let mut tested = 0; + for status in probe().iter().filter(|s| s.available.is_ok()) { + if status.spec.codec != Codec::H264 { + continue; + } + for profile in [H264Profile::ConstrainedHigh, H264Profile::ConstrainedBaseline] { + let (offered_profile, want_idc) = match profile { + H264Profile::ConstrainedHigh => (voelin_stream::H264Profile::ConstrainedHigh, 100), + H264Profile::ConstrainedBaseline => { + (voelin_stream::H264Profile::ConstrainedBaseline, 66) + } + }; + for (w, h, fps, bitrate) in CASES { + let config = EncoderConfig { + fps, + bitrate_bps: bitrate, + h264_profile: profile, + ..EncoderConfig::default() + }; + let mut encoder = FfmpegEncoder::new(status.spec.name, config).unwrap(); + let screen = SyntheticScreen::new(w, h); + // Hardware encoders hold a frame or two before the first packet. + let mut packets = Vec::new(); + for n in 0..8 { + packets.extend(encoder.encode(&screen.frame(n, fps), n == 0).unwrap()); + if !packets.is_empty() { + break; + } + } + let Some(first) = packets.first() else { + panic!("{} produced no packet at {w}x{h}", status.spec.name) + }; + let Some((idc, flags, level)) = sps(&first.data) else { + panic!("{} sent no SPS at {w}x{h}", status.spec.name) + }; + let offered = voelin_stream::h264::offer_profile_level_id( + offered_profile, + w, + h, + fps, + u64::from(bitrate), + ); + let offered_level = (offered & 0xff) as u8; + eprintln!( + "{:<12} {profile:?} {w}x{h}@{fps}: SPS {idc:02x} {flags:02x} {level:02x}, \ + offer {:06x}", + status.spec.name, offered + ); + assert_eq!( + idc, want_idc, + "{} emits profile_idc {idc}, the offer claims {want_idc}", + status.spec.name + ); + assert!( + level <= offered_level, + "{} emits level_idc {level} at {w}x{h}@{fps}, above the offered {offered_level}: \ + a decoder set up from our SDP could refuse it", + status.spec.name + ); + tested += 1; + } + } + } + assert!(tested > 0, "no usable H.264 backend to check"); +} + #[test] fn codecs_prefer_ffmpeg_h264_over_nothing() { if ffmpeg().is_none() || !available("libx264") { From e599eab0ac7b3bf0bb34afb564b8a6edcb7beca2 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:35:39 +0300 Subject: [PATCH 03/10] voelin-media: stop probing absent GPUs and keep the encoder libraries quiet The startup probe opened every encoder in the table, which took 1.77 s here and froze the app's first use for that long, and it let the libraries behind them print about thirty lines to standard error on every run. Most of the time went on hardware that is not in the machine: a self-test of a family whose vendor is absent still runs its driver's initialisation before failing, 1.7 s for av1_nvenc and 1.2 s for vp9_qsv here. Read the PCI vendors of the DRM render nodes once and skip those families outright; when the vendors cannot be read nothing is skipped, so an unusual setup only pays what it paid before. The report gains a plain reason ("no NVIDIA GPU in this machine") in place of a CUDA error code. FFmpeg's own log already goes to tracing, but SVT-AV1's build banner, AMF's GetProperty warnings and Mesa's RADV_PERFTEST notice are written to the descriptor by the libraries themselves. Point standard error at a temporary file while the self-tests run and log what landed there as one debug record; VOELIN_FFMPEG_PROBE_STDERR=1 leaves it alone. Measured with `voelinctl stream encoders` (release): 1.77 s before, 0.93-1.12 s after, 12 backends tested instead of 20, and nothing on standard error. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/Cargo.toml | 4 +- crates/voelin-media/src/ffmpeg/encoder.rs | 186 ++++++++++++++++++++-- 2 files changed, 173 insertions(+), 17 deletions(-) diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 59e1878..1585f53 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -20,7 +20,7 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"] # Video encoders through FFmpeg loaded at runtime (never linked or shipped): # VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264, # SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md). -ffmpeg = ["dep:libloading"] +ffmpeg = ["dep:libloading", "dep:rustix"] # AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3). av1 = ["dep:dav1d"] # X11 screen capture (Linux). @@ -54,7 +54,7 @@ yuv = "0.8.19" ashpd = { version = "0.13.13", default-features = false, features = ["screencast", "tokio"], optional = true } memmap2 = { version = "0.9.11", optional = true } pipewire = { version = "0.10.1", optional = true } -rustix = { version = "1.1.5", features = ["event", "fs"], optional = true } +rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true } wayland-client = { version = "0.31.15", optional = true } wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true } wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true } diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 241d53e..c92b3ac 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -1316,6 +1316,9 @@ pub struct BackendStatus { pub spec: &'static BackendSpec, /// `Ok` if it encoded the test frame, else why not. pub available: std::result::Result<(), String>, + /// How long its self-test took (the probe runs them in parallel, so the + /// startup cost is the slowest one). + pub took: Duration, } /// Size of the self-test frame. @@ -1341,42 +1344,195 @@ fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool { !unsafe { (ffmpeg.api.avcodec_find_encoder_by_name)(name.as_ptr()) }.is_null() } +/// PCI vendor of a GPU, as `/sys/class/drm/*/device/vendor` gives it. +#[cfg(target_os = "linux")] +mod vendor { + pub const AMD: u32 = 0x1002; + pub const NVIDIA: u32 = 0x10de; + pub const INTEL: u32 = 0x8086; +} + +/// The PCI vendors of this machine's DRM render nodes, read once; empty if +/// `/sys/class/drm` says nothing (a container without it, say), which is +/// taken as "unknown" and skips nothing. +#[cfg(target_os = "linux")] +fn drm_vendors() -> &'static [u32] { + static VENDORS: OnceLock> = OnceLock::new(); + VENDORS.get_or_init(|| { + let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() }; + let mut found: Vec = entries + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with("renderD")) + .filter_map(|e| std::fs::read_to_string(e.path().join("device/vendor")).ok()) + .filter_map(|text| u32::from_str_radix(text.trim().trim_start_matches("0x"), 16).ok()) + .collect(); + found.sort_unstable(); + found.dedup(); + found + }) +} + +/// Sends the process's standard error to a temporary file while it lives, +/// and logs whatever landed there when it is dropped. +/// +/// FFmpeg's own messages already go to `tracing` (see +/// [`Ffmpeg::capture_log`](super::Ffmpeg::capture_log)), but the libraries +/// behind the encoders write to the descriptor themselves and cannot be +/// asked not to: SVT-AV1 prints a build banner and its allocation totals, +/// AMD's AMF runtime prints `GetProperty(...) not found` warnings, and Mesa +/// prints a `RADV_PERFTEST` deprecation notice when AMF brings up Vulkan. +/// Opening every encoder at startup meant about thirty such lines on every +/// run of the app. +/// +/// This moves the descriptor, so anything else the process writes to +/// standard error meanwhile lands in the file too and comes back as one +/// `debug` record. `VOELIN_FFMPEG_PROBE_STDERR=1` leaves it alone. +struct QuietStderr { + #[cfg(unix)] + saved: std::os::fd::OwnedFd, + #[cfg(unix)] + file: std::path::PathBuf, +} + +impl QuietStderr { + #[cfg(unix)] + fn start() -> Option { + use std::os::fd::AsFd; + + if std::env::var_os("VOELIN_FFMPEG_PROBE_STDERR").is_some() { + return None; + } + let file = + std::env::temp_dir().join(format!("voelin-encoder-probe-{}.log", std::process::id())); + let sink = std::fs::File::create(&file).ok()?; + let stderr = std::io::stderr(); + let saved = rustix::io::dup(stderr.as_fd()).ok()?; + // Anything already buffered belongs on the real descriptor. + let _ = std::io::Write::flush(&mut std::io::stderr()); + rustix::stdio::dup2_stderr(sink.as_fd()).ok()?; + Some(Self { saved, file }) + } + + #[cfg(not(unix))] + fn start() -> Option { + None + } +} + +#[cfg(unix)] +impl Drop for QuietStderr { + fn drop(&mut self) { + use std::os::fd::AsFd; + + let _ = std::io::Write::flush(&mut std::io::stderr()); + let _ = rustix::stdio::dup2_stderr(self.saved.as_fd()); + if let Ok(text) = std::fs::read_to_string(&self.file) { + let text = text.trim(); + if !text.is_empty() { + tracing::debug!(target: "ffmpeg", "the encoder libraries wrote:\n{text}"); + } + } + let _ = std::fs::remove_file(&self.file); + } +} + +/// Whether the hardware `spec` needs can be in this machine at all. +/// +/// A self-test of a family whose vendor is absent still costs 0.4-1.7 s of +/// driver initialisation before it fails (measured here: `av1_nvenc` 1.7 s, +/// `vp9_qsv` 1.2 s), and the probe's wall time is its slowest test. Nothing +/// is skipped when the vendors cannot be read, so an unusual setup only +/// pays the time it used to. +fn vendor_may_be_present(spec: &BackendSpec) -> std::result::Result<(), String> { + #[cfg(target_os = "linux")] + { + let vendors = drm_vendors(); + if vendors.is_empty() { + return Ok(()); + } + let (wanted, what) = match spec.family() { + "nvenc" => (vendor::NVIDIA, "no NVIDIA GPU"), + "qsv" => (vendor::INTEL, "no Intel GPU"), + "amf" => (vendor::AMD, "no AMD GPU"), + _ => return Ok(()), + }; + // NVIDIA's driver can run without a DRM node (`nvidia-drm.modeset=0`). + if wanted == vendor::NVIDIA && std::path::Path::new("/dev/nvidiactl").exists() { + return Ok(()); + } + if !vendors.contains(&wanted) { + return Err(format!("{what} in this machine")); + } + } + let _ = spec; + Ok(()) +} + /// Every backend with its self-test result (run once per process, the /// backends in parallel). Empty without FFmpeg. +/// +/// A backend whose vendor is not in the machine is not opened at all +/// ([`vendor_may_be_present`]): its driver would spend up to 1.7 s failing, +/// and the probe costs as much as its slowest test. pub fn probe() -> &'static [BackendStatus] { static PROBE: OnceLock> = OnceLock::new(); PROBE.get_or_init(|| { let Ok(ffmpeg) = Ffmpeg::get() else { return Vec::new() }; + let started = Instant::now(); + let quiet = QuietStderr::start(); let statuses: Vec = std::thread::scope(|scope| { let tests: Vec<_> = BACKENDS .iter() .map(|spec| { - let present = in_build(ffmpeg, spec.name); - let test = present.then(|| scope.spawn(move || test_backend(spec))); - (spec, test) + let absent = vendor_may_be_present(spec).err(); + let present = absent.is_none() && in_build(ffmpeg, spec.name); + let test = present.then(|| { + scope.spawn(move || { + let started = Instant::now(); + (test_backend(spec), started.elapsed()) + }) + }); + (spec, absent, test) }) .collect(); tests .into_iter() - .map(|(spec, test)| BackendStatus { - spec, - available: match test { - None => Err("not in this FFmpeg build".into()), - Some(handle) => { - handle.join().unwrap_or_else(|_| Err("the self-test panicked".into())) - } - }, + .map(|(spec, absent, test)| { + let (available, took) = match test { + None => ( + Err(absent.unwrap_or_else(|| "not in this FFmpeg build".into())), + Duration::ZERO, + ), + Some(handle) => handle.join().unwrap_or_else(|_| { + (Err("the self-test panicked".into()), Duration::ZERO) + }), + }; + BackendStatus { spec, available, took } }) .collect() }); + // Standard error comes back (and what the libraries wrote is logged) + // before our own report. + drop(quiet); for status in &statuses { match &status.available { - Ok(()) => tracing::info!(backend = status.spec.name, "FFmpeg encoder available"), - Err(e) => { - tracing::debug!(backend = status.spec.name, "FFmpeg encoder unusable: {e}") - } + Ok(()) => tracing::info!( + backend = status.spec.name, + ms = status.took.as_millis() as u64, + "FFmpeg encoder available" + ), + Err(e) => tracing::debug!( + backend = status.spec.name, + ms = status.took.as_millis() as u64, + "FFmpeg encoder unusable: {e}" + ), } } + tracing::info!( + ms = started.elapsed().as_millis() as u64, + tested = statuses.iter().filter(|s| !s.took.is_zero()).count(), + "FFmpeg encoders probed" + ); statuses }) } From 049a873b7d0da9161866548d5757599e8a408b31 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:41:36 +0300 Subject: [PATCH 04/10] voelinctl: let `stream bench` measure a real screen capture The bench only ever ran the synthetic pattern, so the pipeline was never measured on the source the user actually complains about: a Wayland desktop through the ScreenCast portal. Add --source (synthetic, portal, monitor:, window:). Because the portal asks the user in a dialog and never answers on its own, the start and the wait for the first frame both have a deadline (--start-timeout, 60 s by default) and fail with a plain message instead of hanging; the real captured size is printed once frames arrive. Co-Authored-By: Claude Opus 5 --- tools/voelinctl/src/bench.rs | 65 +++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index b902a10..d1ebe9d 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -51,6 +51,16 @@ struct EncodersArgs { #[derive(Args, Debug)] struct BenchArgs { + /// What to capture: `synthetic` (the test pattern), `portal` (the + /// desktop's screen-share dialog, Wayland and X11), `monitor:` or + /// `window:` (X11). Anything but `synthetic` ignores --res and + /// --pattern and measures the real capture → convert → encode pipeline. + #[arg(long, default_value = "synthetic")] + source: String, + /// Give up if the capture has not started after this many seconds (the + /// portal opens a dialog the user has to accept). + #[arg(long, default_value_t = 60)] + start_timeout: u64, /// Size of the test pattern. #[arg(long, default_value = "1920x1080")] res: String, @@ -212,6 +222,19 @@ impl MediaSink for BenchSink { } } +/// `synthetic`, `portal`, `monitor:` or `window:`. +fn parse_source(value: &str) -> Result { + Ok(match value.split_once(':') { + Some(("monitor", n)) => SourceId::Monitor(n.parse().context("monitor index")?), + Some(("window", id)) => SourceId::Window(id.parse().context("window id")?), + _ => match value { + "synthetic" => SourceId::Synthetic, + "portal" => SourceId::Portal, + other => bail!("unknown source {other:?}: synthetic, portal, monitor:, window:"), + }, + }) +} + /// `x`. fn parse_size(size: &str) -> Result<(u32, u32)> { let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))); @@ -317,8 +340,9 @@ fn bench(args: BenchArgs) -> Result<()> { .collect::>>()?; let ids: Vec = if layers.is_empty() { vec![0] } else { layers.iter().map(|l| l.id).collect() }; + let source = parse_source(&args.source)?; let config = StreamerConfig { - source: SourceId::Synthetic, + source: source.clone(), synthetic_size: (width, height), synthetic_pattern: pattern, fps: args.fps, @@ -330,23 +354,54 @@ fn bench(args: BenchArgs) -> Result<()> { ..StreamerConfig::default() }; let runtime = tokio::runtime::Runtime::new()?; - let streamer = runtime.block_on(Streamer::start(&codecs, config)).context("streamer")?; + let timeout = Duration::from_secs(args.start_timeout.max(1)); + // The portal opens a dialog on the desktop; without an answer the start + // never returns, so it is given a deadline instead of hanging. + let started = runtime + .block_on(async { tokio::time::timeout(timeout, Streamer::start(&codecs, config)).await }); + let streamer = match started { + Ok(result) => result.context("streamer")?, + Err(_) => bail!( + "the capture did not start within {} s (the {} source was not accepted)", + timeout.as_secs(), + args.source + ), + }; let sink = Arc::new(BenchSink { layers: ids.iter().map(|id| (*id, LayerCount::default())).collect(), keyframe: AtomicBool::new(true), }); streamer.attach(sink.clone()); let backend = streamer.stats().layers.first().and_then(|l| l.backend); + let what = if source == SourceId::Synthetic { + format!("{width}x{height} {} test pattern", args.pattern) + } else { + format!("{} capture", args.source) + }; println!( - "{width}x{height} {} test pattern at {} fps, {codec} ({}), {} layer(s), {} s after {} s \ - warm-up", - args.pattern, + "{what} at {} fps, {codec} ({}), {} layer(s), {} s after {} s warm-up", args.fps, backend.map_or("?".to_owned(), |b| b.to_string()), ids.len(), args.seconds, args.warmup ); + // A real source only delivers once the user has picked something. + if source != SourceId::Synthetic { + let deadline = Instant::now() + timeout; + while streamer.stats().captured_frames == 0 { + if Instant::now() >= deadline { + bail!( + "no frame from the {} source within {} s (nobody accepted the dialog?)", + args.source, + timeout.as_secs() + ); + } + std::thread::sleep(Duration::from_millis(100)); + } + let stats = streamer.stats(); + println!("capturing {}x{}", stats.width, stats.height); + } std::thread::sleep(Duration::from_secs(args.warmup)); let start = sample(&sink, &streamer); std::thread::sleep(Duration::from_secs(args.seconds)); From 678d46e2b54f9ede51b1fe3f41b9407989cf1442 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:43:48 +0300 Subject: [PATCH 05/10] docs/media.md: the hardware video path as measured on a real GPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything about the FFmpeg encoders was written without a GPU to run them on. Record what a Radeon RX 7900 GRE with FFmpeg 9.0.1 actually does: software against VA-API and AMF at 1080p60 and 1440p60, a simulcast run, and what the numbers mean (every encoder holds the frame rate, so the difference is CPU — 0.20-0.42 cores against 1.16-2.55 — and the steady state is 1.02 allocations per encoded frame on hardware as on software). Also record what the measurements found and changed: the H.264 level the encoders emit against the one the offer advertises, the probe's startup cost and the third-party output it used to print, and the libavutil 61 offsets. The verification table now separates the hardware that was tested here from the hardware that was not, and says plainly that the zero-copy import has still never carried a frame because the GPU colour conversion is missing and that the portal measurement did not run. Co-Authored-By: Claude Opus 5 --- docs/media.md | 118 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 9 deletions(-) diff --git a/docs/media.md b/docs/media.md index ca8a600..62e3ad6 100644 --- a/docs/media.md +++ b/docs/media.md @@ -283,12 +283,15 @@ the software encoders above are used as before. `initial_pool_size` (with or without `internal`, which libavutil 59 removed; `device_ctx` and both formats checked in a new context), and for the DMA-BUF import `AVFrame.buf[0]` and `hw_frames_ctx` (a table per - libavutil major 56-60 on 64-bit, newer majors tried with the newest entry; - `buf[0]` checked on a real frame at load, `hw_frames_ctx` on the first - surface). The layouts were compiled from the headers of FFmpeg 4.4, 5.1, - 6.1, 7.1 and 8.0. A failed check disables only what needs the field - (VA-API, or the import) and says why (`LibraryInfo::hw_frames`, - `dmabuf_import`, the report). + libavutil major, 56-61 on 64-bit; `buf[0]` checked on a real frame at + load, `hw_frames_ctx` on the first surface). The layouts were compiled + from the headers of FFmpeg 4.4, 5.1, 6.1, 7.1, 8.0 and 9.0. A major that + is not in the table turns the import off instead of reusing the newest + entry: `AVFrame` has shrunk as well as grown between majors (424 bytes in + libavutil 61 against 536 in 56), so an offset guessed for an unknown + layout could point past the end of the struct. A failed check disables + only what needs the field (VA-API, or the import) and says why + (`LibraryInfo::hw_frames`, `dmabuf_import`, the report). - Backends (`ffmpeg::BACKENDS`, FFmpeg's encoder names, also the names in `stream.encoder_backend`): H.264 `h264_nvenc`, `h264_amf`, `h264_vaapi`, `h264_qsv`, `h264_videotoolbox`, `h264_mf`, software `libx264`, @@ -302,6 +305,25 @@ the software encoders above are used as before. node", "not in this FFmpeg build", ...). rav1e holds about 20 frames before its first packet even in low-latency mode (measured, rav1e 0.7), so it is used only when named. +- Probe cost: a family whose vendor is not in the machine is not opened at + all. Its driver would still run its initialisation before failing, which + was the bulk of the startup cost (measured here: `av1_nvenc` 1.7 s, + `vp9_qsv` 1.2 s), and the probe takes as long as its slowest test because + they run in parallel. The PCI vendors of the DRM render nodes + (`/sys/class/drm/*/device/vendor`) are read once; NVENC needs NVIDIA (or + `/dev/nvidiactl`, for a driver without a DRM node), Quick Sync Intel, AMF + AMD. When the vendors cannot be read nothing is skipped. On the AMD + machine below this took `voelinctl stream encoders` from 1.77 s to + 0.93-1.12 s, testing 12 backends instead of 20, and the report says "no + NVIDIA GPU in this machine" instead of a CUDA error code. +- Third-party output: FFmpeg's own log goes to `tracing`, but the libraries + behind the encoders write to standard error themselves — SVT-AV1 prints a + build banner and its allocation totals, AMD's AMF runtime prints + `GetProperty(...) not found` warnings, and Mesa prints a `RADV_PERFTEST` + deprecation notice when AMF brings up Vulkan. That was about thirty lines + on every start. While the self-tests run, standard error is pointed at a + temporary file and what landed there comes back as one `debug` record; + `VOELIN_FFMPEG_PROBE_STDERR=1` leaves it alone. - Realtime settings: no B-frames, no lookahead, keyframes only at the start and on request (a GOP of 2^30 frames, or what each wrapper takes as unlimited: 65535 for Quick Sync, 0 for AMF and VideoToolbox, 2^29 for @@ -322,6 +344,24 @@ the software encoders above are used as before. without B-frames (Constrained High, what TeamSpeak decodes) or Constrained Baseline (`EncoderConfig::h264_profile`). Options a release does not know are skipped; alternatives are tried in order. +- H.264 level: the level the signalling offers + (`voelin_stream::h264::level_idc`, ITU-T Table A-1) is computed again from + the session's own size, rate and bitrate and set on both the codec context + and the wrapper's private option. Without it every wrapper picked its own, + and a generous one: measured on the GPU below, `h264_amf` wrote level 4.2 + into the SPS of a 720p30 stream whose offer said 3.1, and 5.0 for a + 1440p60 stream offered as 5.1. A viewer that sizes its decoder from our + SDP may refuse a stream that declares more than the offer did, which is + how a stream fails against an official client. With the level set, + `h264_vaapi`, `h264_amf` and `libx264` all emit exactly the offered level + (`tests/ffmpeg.rs`, `sps_carries_the_offered_profile_and_level`, parses + the SPS). The level table is a second copy of voelin-stream's, because + neither crate can depend on the other; a unit test pins the two together. + The constraint-flag byte still differs and is left alone: the offer claims + Constrained High (`0c`) and Constrained Baseline (`e0`) as WebRTC + implementations conventionally do, `h264_vaapi` and `h264_amf` emit `0c` + for the former and `libx264` emits `00`, and all three emit `40` or `c0` + for the latter. Those bits do not change what a decoder can decode. - Runtime changes: x264, NVENC and Quick Sync take bitrate changes on the running encoder (FFmpeg's wrappers compare `b` / `maxrate` / `bufsize` before each frame); the others reopen at the next keyframe, at once @@ -506,6 +546,10 @@ 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 +# 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 +voelinctl stream bench --source monitor:0 --fps 60 # X11 # Conversion and scaling alone: cargo bench -p voelin-media --bench convert ``` @@ -540,6 +584,58 @@ Conversion and scaling take 0.3 ms (720p) to 3-5 ms (1440p, busy) per frame on 4 threads. With three layers (1440p30 at 6 Mbit/s, 720p30, 360p15) the quiet machine kept every layer at its rate with 1.6-1.7 cores. +### Hardware encoders, measured + +Release build, AMD Radeon RX 7900 GRE (radeonsi / RADV, `renderD128`), 32 +cores, FFmpeg 9.0.1, desktop pattern, one layer, 10 s after a 2 s warm-up, +`voelinctl stream bench`. "cpu" is cores of the whole process (capture, +conversion and encode together), "encode" the wall time of one +`encode_with`. + +1080p60, 6000 kbit/s asked for: + +| encoder | fps | kbit/s | encode ms | cpu cores | allocations per frame | +|---|---|---|---|---|---| +| `h264_vaapi` | 60.0 | 5951 | 2.52 | 0.25 | 1.02 | +| `h264_amf` | 60.0 | 5910 | 2.17 | 0.31 | 1.02 | +| `av1_vaapi` | 60.0 | 6211 | 2.23 | 0.20 | 1.02 | +| `av1_amf` | 60.0 | 5962 | 2.75 | 0.29 | 1.02 | +| `libx264` | 60.0 | 5674 | 2.33 | 1.16 | 1.02 | +| libvpx VP8 | 60.0 | 6031 | 4.93 | 1.69 | 1.02 | + +1440p60, 10000 kbit/s asked for: + +| encoder | fps | kbit/s | encode ms | cpu cores | allocations per frame | +|---|---|---|---|---|---| +| `h264_vaapi` | 60.0 | 10112 | 3.96 | 0.33 | 1.02 | +| `h264_amf` | 60.0 | 10188 | 2.80 | 0.41 | 1.02 | +| `av1_vaapi` | 60.0 | 10794 | 3.56 | 0.34 | 1.02 | +| `av1_amf` | 60.0 | 10079 | 2.91 | 0.42 | 1.02 | +| `libx264` | 59.9 | 9406 | 11.88 | 2.17 | 1.03 | +| libvpx VP8 | 60.0 | 10038 | 4.32 | 2.55 | 1.02 | + +Simulcast, 1440p30 source, three layers (1440p30 at 8 Mbit/s, 720p30 at +2 Mbit/s, 360p15 at 600 kbit/s), same run: + +| encoder | layer 0 | layer 1 | layer 2 | cpu cores | +|---|---|---|---|---| +| `h264_vaapi` | 30.0 fps, 7666 kbit/s, 4.37 ms | 30.0, 2121, 1.71 ms | 15.0, 596, 1.22 ms | 0.25 | +| `h264_amf` | 30.0 fps, 7499 kbit/s, 3.56 ms | 30.0, 2015, 2.02 ms | 15.0, 598, 1.94 ms | 0.32 | +| `libx264` | 30.0 fps, 7428 kbit/s, 4.40 ms | 30.0, 1993, 2.19 ms | 15.0, 593, 2.51 ms | 1.33 | + +What the numbers say: every encoder, hardware and software, holds the full +frame rate at both sizes on this machine, so the difference is CPU, not +throughput. Hardware costs 0.20-0.42 cores against 1.16-2.55 for software, +a factor of four to eight, and the gap widens with size — at 1440p60 x264 +needs 2.17 cores and is the only encoder that dropped a frame. Every backend +honoured the target bitrate within 2 % except `av1_vaapi`, which overshoots +by 4-8 %. The steady state is 1.02 allocations per encoded frame (the +`Arc<[u8]>` of `EncodedFrame`) with hardware as with software: no reopen +storm, no per-frame allocation in the import or upload path. Conversion and +scaling cost 0.16-0.30 ms per frame at these sizes and are not the +bottleneck. The per-layer "threads" the bench prints is the CPU budget the +layer was given, not what a hardware encoder uses — it encodes on the GPU. + Build profiles: the dev profile builds the media hot path (yuv, voelin-media, str0m, x11rb-protocol, pipewire, wayland-client, ...) with `opt-level = 3`; release builds use fat LTO with one codegen unit. @@ -599,16 +695,20 @@ has not run on Windows yet. | 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 | compiles and formats parse; no compositor with the portal here | | 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 | – | compiles only (no portal or PipeWire daemon here) | +| Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | `voelinctl stream bench --source portal` | not measured: the portal dialog was not accepted within the 60 s deadline, and the run failed cleanly instead of hanging. The path itself is untested on a real compositor | | Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only | -| FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-8.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04) | +| FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-9.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04; FFmpeg 9.0.1 / libavutil 61 / libavcodec 63 on Arch, every offset compared with that release's own headers) | | FFmpeg software encoders → our decoders: x264 → OpenH264, SVT-AV1 / rav1e / libaom → dav1d (PSNR > 28 dB, keyframes at start and on request, timestamps, bitrate change, size change, odd sizes, Constrained High / Baseline) | `tests/ffmpeg.rs` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested | | Self-test failures (NVENC without CUDA, Quick Sync without a session, VA-API without a render node, encoders not in the build) | `tests/ffmpeg.rs`, `voelinctl stream encoders` | tested: each fails alone with FFmpeg's reason | | Encoder preference (auto, software, named, hardware off), report ranks | `codec::tests::encoder_preference` | tested | | An encoder per codec viewers chose (made, dropped, stream codec skipped, preference change) | `voelin-core` `media::tests::an_encoder_per_codec_viewers_chose` | tested | | Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) | | x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame | -| Hardware encoders (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox), DMA-BUF import | – | compile only (no GPU here); the Windows code type-checks for `x86_64-pc-windows-gnu` | +| Hardware encoders VA-API and AMF (H.264, HEVC, AV1) in the streamer pipeline | `voelinctl stream bench` on a Radeon RX 7900 GRE, 1080p60 / 1440p60 / simulcast | tested: full frame rate, 0.20-0.42 cores against 1.16-2.55 for software, 1.02 allocations per encoded frame (see the table above) | +| Hardware encoders NVENC, Quick Sync, Media Foundation, VideoToolbox | – | not tested (no such hardware here); NVENC and Quick Sync are skipped by the vendor check and the Windows code type-checks for `x86_64-pc-windows-gnu` | +| H.264 SPS against the offered `profile-level-id` (`profile_idc`, `level_idc`) for every usable backend, two sizes, both profiles | `tests/ffmpeg.rs` `sps_carries_the_offered_profile_and_level` | tested: it found `h264_amf` emitting level 4.2 where the offer said 3.1; with the level now set, all backends emit the offered level | +| The encoder's H.264 level table against the signalling's | `ffmpeg::encoder::tests::levels_agree_with_the_signalling` | tested (8 sizes x 5 rates x 4 bitrates x 2 profiles) | +| Zero-copy DMA-BUF import into a VA-API encoder | – | not reached: the import is implemented and its offsets are checked, but screen capture delivers RGB and the GPU colour conversion to NV12 is missing, so no frame has ever gone through it on hardware | | 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 | From 21843fd7c138d167f7c58b5c57bfc0f2bb3d02f9 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:31:45 +0300 Subject: [PATCH 06/10] voelin-media: put a real DMA-BUF through the VA-API encoder The probe reported the zero-copy import as available on the strength of the struct offsets alone, and screen capture only ever hands over RGB, which the import refuses, so no buffer had ever gone through it on hardware. Make a VA-API surface, export it as a DRM PRIME DMA-BUF and feed it back to a second encoder through encode_dmabuf. On this GPU it imports and encodes, and the buffer carries an AMD tiling modifier (0x200000028a01f04), so tiled buffers work and not only LINEAR ones. It also showed that the import's shape is narrower than what drivers produce: this driver describes an NV12 surface as two DRM layers, R8 for the luma plane and GR88 for the chroma one, while encode_dmabuf takes a single NV12 layer with two planes, which is how a compositor hands one over. Both name the same bytes of the same buffer object, so the test flattens the layers; whoever wires the portal to the encoder should accept either form. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/ffmpeg/encoder.rs | 106 ++++++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index c92b3ac..5879e3f 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -1663,6 +1663,112 @@ mod tests { } } + /// The zero-copy path with a real DMA-BUF, on the GPU. + /// + /// The probe reports the import as available from the offsets alone, and + /// screen capture hands over RGB, which the import refuses, so no frame + /// had ever gone through it. This makes a VA-API surface, exports it as + /// a DRM PRIME DMA-BUF (what a compositor would hand us, tiling + /// modifier and all) and feeds it back to a second encoder through + /// [`FfmpegEncoder::encode_dmabuf`], so the import, the + /// `AVFrame.hw_frames_ctx` check and the encode are exercised for real. + /// + /// Skipped without a working `h264_vaapi`. + #[test] + fn a_dmabuf_really_reaches_a_vaapi_encoder() { + const SIZE: (u32, u32) = (320, 240); + if !probe().iter().any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok()) { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().expect("probed above"); + let api = &ffmpeg.api; + let source = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + let mut pool = source.vaapi_pool(SIZE.0, SIZE.1).expect("a VA-API surface pool"); + let drm_prime = ffmpeg.pix.drm_prime.expect("DRM PRIME"); + + // SAFETY: `pool` is a live frames context of this process's VA-API + // device; both frames are ours and freed below. The exported frame's + // `data[0]` is the AVDRMFrameDescriptor FFmpeg filled, valid while + // the frame holds the mapping. + let exported = unsafe { + let surface = (api.av_frame_alloc)(); + let drm = (api.av_frame_alloc)(); + assert!(!surface.is_null() && !drm.is_null()); + let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); + assert!(ret >= 0, "av_hwframe_get_buffer: {}", api.error_text(ret)); + (*drm.cast::()).format = drm_prime; + let ret = + (api.av_hwframe_map)(drm, surface, sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT); + let mapped = (ret >= 0).then(|| { + let descriptor = + *(*drm.cast::()).data[0].cast::(); + assert_eq!(descriptor.nb_objects, 1, "one buffer object"); + // The driver describes the surface one plane per layer (R8 + // for Y, GR88 for UV) rather than as one NV12 layer, which + // is how a compositor hands it over. Both name the same + // bytes of the same object, so flatten the layers into the + // planes of one NV12 buffer. + let object = descriptor.objects[0]; + let mut planes = [(0usize, 0usize); 4]; + let mut count = 0; + for layer in &descriptor.layers[..descriptor.nb_layers as usize] { + for plane in &layer.planes[..layer.nb_planes as usize] { + planes[count] = (plane.offset as usize, plane.pitch as usize); + count += 1; + } + } + DmaBufRef { + width: SIZE.0, + height: SIZE.1, + timestamp: Duration::ZERO, + fourcc: drm_fourcc(b"NV12"), + modifier: object.format_modifier, + fd: object.fd, + size: object.size, + planes, + plane_count: count, + } + }); + // The descriptor is copied out, but the file descriptor belongs + // to the mapping, so the encode has to happen before these go. + (mapped, surface, drm) + }; + let (frame, mut surface, mut drm) = exported; + let Some(frame) = frame else { + // SAFETY: allocated above. + unsafe { + (api.av_frame_free)(&mut drm); + (api.av_frame_free)(&mut surface); + (api.av_buffer_unref)(&mut pool); + } + panic!("this driver cannot export a VA-API surface as a DMA-BUF"); + }; + assert_eq!(frame.plane_count, 2, "NV12 has two planes"); + assert!(frame.fd >= 0 && frame.size > 0); + + let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + let mut packets = 0; + let mut keyframe = false; + let result = encoder.encode_dmabuf(&frame, true, &mut |chunk| { + packets += 1; + keyframe |= chunk.keyframe; + }); + drop(encoder); + // SAFETY: allocated above; the encode is done with the mapping. + unsafe { + (api.av_frame_free)(&mut drm); + (api.av_frame_free)(&mut surface); + (api.av_buffer_unref)(&mut pool); + } + result.expect("the DMA-BUF was imported and encoded"); + assert!(packets > 0 && keyframe, "{packets} packets, keyframe {keyframe}"); + eprintln!( + "imported a {}x{} NV12 DMA-BUF (modifier {:#x}) into h264_vaapi: {packets} packet(s)", + frame.width, frame.height, frame.modifier + ); + } + #[test] fn settings_per_backend() { let config = EncoderConfig::default(); From 91bca224d7c5d4517916162546ed41ccc3300b3b Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:32:04 +0300 Subject: [PATCH 07/10] docs/media.md: the DMA-BUF import is tested, the capture path still is not Separate the two halves of zero-copy that the measurements now tell apart: the import into a VA-API encoder carries a real tiled buffer on this GPU, while nothing from screen capture reaches it, because the portal delivers RGB and because Ingest never accepts DMA-BUFs in the first place. Also record the layer shape the import expects against the one a driver exports, which the test uncovered. Co-Authored-By: Claude Opus 5 --- docs/media.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/media.md b/docs/media.md index 62e3ad6..82e6602 100644 --- a/docs/media.md +++ b/docs/media.md @@ -377,7 +377,10 @@ the software encoders above are used as before. (`av_hwframe_ctx_init`, surfaces allocated on demand and recycled) filled with `av_hwframe_transfer_data`; the device is `VOELIN_VAAPI_DEVICE` or the first `/dev/dri/renderD*`, shared by all encoders. Odd sizes are cropped to - even ones. The streamer's steady state is 1.1 heap allocations per encoded + even ones. `encode_dmabuf` takes a buffer with one NV12 layer of two + planes, which is how a compositor hands one over; a driver exporting its + own surface may instead describe it as two layers (`R8` for luma, `GR88` + for chroma) over the same object, and that form is not accepted yet. The streamer's steady state is 1.1 heap allocations per encoded frame with x264 or SVT-AV1, as with libvpx (`voelinctl stream bench`). - Zero-copy (Linux): `FfmpegEncoder::encode_dmabuf(&DmaBufRef, ...)` maps a DRM PRIME frame onto a VA-API surface (`av_hwframe_map`) that the encoder @@ -708,7 +711,8 @@ has not run on Windows yet. | Hardware encoders NVENC, Quick Sync, Media Foundation, VideoToolbox | – | not tested (no such hardware here); NVENC and Quick Sync are skipped by the vendor check and the Windows code type-checks for `x86_64-pc-windows-gnu` | | H.264 SPS against the offered `profile-level-id` (`profile_idc`, `level_idc`) for every usable backend, two sizes, both profiles | `tests/ffmpeg.rs` `sps_carries_the_offered_profile_and_level` | tested: it found `h264_amf` emitting level 4.2 where the offer said 3.1; with the level now set, all backends emit the offered level | | The encoder's H.264 level table against the signalling's | `ffmpeg::encoder::tests::levels_agree_with_the_signalling` | tested (8 sizes x 5 rates x 4 bitrates x 2 profiles) | -| Zero-copy DMA-BUF import into a VA-API encoder | – | not reached: the import is implemented and its offsets are checked, but screen capture delivers RGB and the GPU colour conversion to NV12 is missing, so no frame has ever gone through it on hardware | +| Zero-copy DMA-BUF import into a VA-API encoder | `ffmpeg::encoder::tests::a_dmabuf_really_reaches_a_vaapi_encoder` (a VA-API surface exported as DRM PRIME and fed back in) | tested: imports and encodes, with an AMD **tiling** modifier (`0x200000028a01f04`), not only LINEAR | +| Zero-copy from screen capture | – | not reached: the import works (row above), but the portal delivers RGB and the GPU colour conversion to NV12 is missing, so no captured frame has gone through it. `Ingest` also never returns true from `FrameSink::accepts_dmabuf`, so the portal's DMA-BUF offer is never taken | | 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 | From 9b09e7bde22b6a85736d8cec085a29526fe37102 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:50:52 +0300 Subject: [PATCH 08/10] voelin-media: fix Wayland screen capture delivering no frames at all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured on a real 2560x1440 Wayland desktop through the ScreenCast portal, which nothing here had ever run against: every captured frame was dropped and the viewer got nothing. Two faults, one behind the other. The mapping length came from `mapoffset + maxsize`. Those describe a mapping, which only shared memory has; a DMA-BUF's size lives in its buffer object, and this compositor leaves both fields 0 (the file descriptor and the 10240-byte stride were fine). The length was therefore 0, every map was refused, and the capture delivered nothing for as long as it ran. Derive the length from the rows the negotiated format describes, which is exactly what is read afterwards. With frames flowing, the second fault showed: reading a LINEAR DMA-BUF from this GPU's memory took 11.95 ms per frame and 19.5 CPU cores at 1440p60, against 0.27 ms and 0.41 cores for the same capture over shared memory — 44 times the time, 48 times the CPU. The guard that exists for this switches at 6.0 ns per pixel and the DMA-BUF path only reaches 3.24, so it never fired. Put the threshold between the two measurements, an order of magnitude above the shared-memory figure so a GPU whose buffers the CPU can read keeps them. After both: 2560x1440 at 60.0 fps on 0.55 cores, no dropped frames, the bitrate honoured. A DMA-BUF that cannot be mapped at all now also falls back to shared memory after a few failures instead of dropping frames forever. `stream bench` was reporting the layer size from --res, which is not what a real source encodes; it now prints the size that was really encoded. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/capture/portal.rs | 52 +++++++++++++++++++++-- tools/voelinctl/src/bench.rs | 8 +++- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index 7fecbd2..b53e5f3 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -248,9 +248,23 @@ const MODIFIER_LINEAR: i64 = 0; /// Reading DMA-BUFs slower than this (per pixel, conversion included) means /// the buffers live in memory the CPU reads uncached (e.g. a discrete GPU's /// VRAM); shared memory is faster then. -const SLOW_DMABUF_NS_PER_PIXEL: f64 = 6.0; +/// +/// Measured on a Radeon RX 7900 GRE capturing a 2560x1440 desktop at 60 fps, +/// the same run through both paths: a LINEAR DMA-BUF took 11.95 ms per frame +/// (3.24 ns per pixel) and 19.5 CPU cores, shared memory 0.27 ms (0.07 ns +/// per pixel) and 0.41 cores — 44 times the time and 48 times the CPU. The +/// threshold was 6.0, which that does not reach, so the switch never +/// happened and a discrete GPU burned twenty cores on screen sharing. It +/// sits between the two figures, an order of magnitude above the fast path, +/// so a GPU whose buffers the CPU can read (anything with unified memory) +/// keeps them. +const SLOW_DMABUF_NS_PER_PIXEL: f64 = 1.0; /// DMA-BUF frames timed before deciding. const DMABUF_PROBE_FRAMES: u32 = 30; +/// DMA-BUFs that failed to map before shared memory is offered instead. A +/// few failures can be a buffer being replaced; more means this compositor's +/// buffers cannot be read this way at all. +const DMABUF_FAILURES_BEFORE_SHM: u32 = 5; /// What was negotiated. #[derive(Clone, Copy, Debug)] @@ -275,6 +289,9 @@ struct VideoState { /// Time spent handing DMA-BUF frames to the sink, and how many. dmabuf_time: Duration, dmabuf_frames: u32, + /// DMA-BUFs that could not be mapped (see + /// [`DMABUF_FAILURES_BEFORE_SHM`]). + dmabuf_failures: u32, logged: Option, mainloop: pw::main_loop::MainLoopWeak, } @@ -303,6 +320,7 @@ fn video_stream( maps: Vec::new(), dmabuf_time: Duration::ZERO, dmabuf_frames: 0, + dmabuf_failures: 0, logged: None, mainloop: mainloop.downgrade(), }; @@ -600,14 +618,42 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { let started = Instant::now(); let more = if is_dmabuf { let raw = data.as_raw(); - let len = (raw.mapoffset + raw.maxsize) as usize; + // A DMA-BUF's size lives in its buffer object, not in `maxsize`: + // `maxsize` describes a mapping, which only shared memory has, and + // compositors leave it 0 (measured on a 2560x1440 Wayland desktop: + // fd valid, stride 10240, `mapoffset` and `maxsize` both 0). Mapping + // `mapoffset + maxsize` bytes then asks for a zero-length mapping + // and every frame is dropped, so fall back to the rows the + // negotiated format describes, which is exactly what is read below. + let len = match (raw.mapoffset + raw.maxsize) as usize { + 0 => raw.mapoffset as usize + needed, + size => size, + }; let fd = data.fd(); if !state.maps.iter().any(|m| m.fd() == fd && m.len() >= len) { state.maps.retain(|m| m.fd() != fd); match DmaBufMap::new(fd, len) { Ok(map) => state.maps.push(map), Err(e) => { - warn!("cannot map a screen capture DMA-BUF: {e}"); + warn!( + fd, + len, + mapoffset = raw.mapoffset, + maxsize = raw.maxsize, + stride, + height = format.height, + "cannot map a screen capture DMA-BUF: {e}" + ); + // Dropping every frame would leave the viewer a black + // screen; shared memory always works. + state.dmabuf_failures += 1; + if state.dmabuf_failures >= DMABUF_FAILURES_BEFORE_SHM && state.dmabuf { + tracing::info!( + "screen capture DMA-BUFs cannot be mapped; switching to shared memory" + ); + state.dmabuf = false; + renegotiate(stream, state.fps, false); + } return; } } diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index d1ebe9d..511b006 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -423,7 +423,13 @@ fn bench(args: BenchArgs) -> Result<()> { let frames = b.frames - a.frames; output_frames += frames; let spec = layers.iter().find(|l| l.id == *id); - let size = spec.map_or((width, height), |l| l.output_size(width, height)); + let layer_stats = stats.layers.iter().find(|l| l.id == *id); + // What was really encoded: with a real source the size comes from the + // capture, not from --res. + let size = match layer_stats.filter(|l| l.width > 0) { + Some(l) => (l.width, l.height), + None => spec.map_or((width, height), |l| l.output_size(width, height)), + }; let dropped = |s: &Sample| s.dropped.iter().find(|d| d.0 == *id).map_or(0, |d| d.1); let layer = stats.layers.iter().find(|l| l.id == *id); println!( From b7534cc128e083e18b4d6b435c64173bd23c5a97 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 23:51:11 +0300 Subject: [PATCH 09/10] docs/media.md: what a real Wayland capture costs, before and after The low screen-share frame rates on Wayland had never been reproduced here. Record the run that did: what the broken DMA-BUF mapping did, what reading a discrete GPU's buffers with the CPU costs against shared memory, and where the threshold that chooses between them now sits. Co-Authored-By: Claude Opus 5 --- docs/media.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/docs/media.md b/docs/media.md index 82e6602..e6eb81c 100644 --- a/docs/media.md +++ b/docs/media.md @@ -639,6 +639,33 @@ scaling cost 0.16-0.30 ms per frame at these sizes and are not the bottleneck. The per-layer "threads" the bench prints is the CPU budget the layer was given, not what a hardware encoder uses — it encodes on the GPU. +### Wayland screen capture, measured + +Same machine, a 2560x1440 Wayland desktop through the ScreenCast portal, +`h264_vaapi` at 60 fps and 12 Mbit/s, `voelinctl stream bench --source +portal`. This path had never been run against a real compositor. + +| buffers | capture fps | convert + scale | cpu cores | dropped | +|---|---|---|---|---| +| DMA-BUF (LINEAR), as first written | – | – | – | every frame | +| DMA-BUF (LINEAR), mapping fixed | 60.0 | 11.95 ms | 19.54 | 0 | +| shared memory | 59.9 | 0.27 ms | 0.41 | 0 | +| what it does now (switches by itself) | 60.1 | 0.30 ms | 0.55 | 0 | + +The first row is the bug behind the low frame rates on Wayland: the mapping +length was taken from `mapoffset + maxsize`, which describe a mapping that +only shared memory has, while a DMA-BUF's size lives in its buffer object and +this compositor leaves both fields 0. Every map was refused and nothing was +ever delivered. + +The second row is why shared memory is the right choice on a discrete GPU: +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 — but +that needs the GPU colour conversion that is still missing. + Build profiles: the dev profile builds the media hot path (yuv, voelin-media, str0m, x11rb-protocol, pipewire, wayland-client, ...) with `opt-level = 3`; release builds use fat LTO with one codegen unit. @@ -698,7 +725,7 @@ has not run on Windows yet. | 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 | compiles and formats parse; no compositor with the portal here | | 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` | not measured: the portal dialog was not accepted within the 60 s deadline, and the run failed cleanly instead of hanging. The path itself is untested on a real compositor | +| 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 | | FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-9.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04; FFmpeg 9.0.1 / libavutil 61 / libavcodec 63 on Arch, every offset compared with that release's own headers) | | FFmpeg software encoders → our decoders: x264 → OpenH264, SVT-AV1 / rav1e / libaom → dav1d (PSNR > 28 dB, keyframes at start and on request, timestamps, bitrate change, size change, odd sizes, Constrained High / Baseline) | `tests/ffmpeg.rs` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested | From a5ec7292347c6842dc6bb7049bd13d9dbe0b4c07 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 01:42:18 +0300 Subject: [PATCH 10/10] WIP: round-trip test for the hardware encoders (interrupted by a session limit) Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/voelin-media/tests/ffmpeg.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 2c2b55e..01a76aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9188,6 +9188,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "voelin-stream", "wasapi", "wayland-client", "wayland-protocols", diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index a614d4f..bbb330a 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -148,6 +148,34 @@ fn software_encoders_roundtrip() { eprintln!("tested: {tested:?}"); } +/// What the GPU encoders produce, through the same round-trip as the +/// software ones: our own decoders have to decode it (OpenH264 for H.264 with +/// `VOELIN_OPENH264_LIB`, dav1d for AV1 with `--features av1`), keyframes +/// where asked, timestamps kept, PSNR above 28 dB. +/// +/// Whatever hardware the machine has; skipped where none of it works. HEVC is +/// left out, having no decoder here. +#[test] +fn hardware_encoders_roundtrip() { + if ffmpeg().is_none() { + return; + } + let names: Vec<&'static str> = BACKENDS + .iter() + .filter(|b| b.is_hardware() && matches!(b.codec, Codec::H264 | Codec::Av1)) + .map(|b| b.name) + .filter(|name| available(name)) + .collect(); + if names.is_empty() { + eprintln!("no usable hardware encoder, skipped"); + return; + } + for name in &names { + roundtrip(name); + } + eprintln!("tested: {names:?}"); +} + #[test] fn x264_is_constrained_high_and_changes_size() { if ffmpeg().is_none() || !available("libx264") {