diff --git a/Cargo.lock b/Cargo.lock index b0b86b3..fee7ebc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9194,6 +9194,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "voelin-stream", "wasapi", "wayland-client", "wayland-protocols", @@ -9303,6 +9304,7 @@ dependencies = [ "unicode-segmentation", "voelin-audio", "voelin-core", + "voelin-gateway-proto", "voelin-model", "voelin-platform", "voelin-query", diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index c6dfab0..e7aa7fb 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -78,3 +78,7 @@ against or offered back to upstream. "Voelin patch"). TeamSpeak 6 sends some times, e.g. `datetime` of `notifyfilelist`, in milliseconds, which failed to parse and dropped the whole message (empty file lists). Values from 10^11 on (year 5138 in seconds) are taken as milliseconds. +10. **Test logger** (`tsclientlib/src/tests.rs`, "Voelin patch"). The tests' shared + tracing setup used `init`, which panics when quickcheck (`use_logging`) has + already installed a `log` logger; the panic poisoned the `Lazy` and failed every + later test of the binary, depending on test order. It uses `try_init` now. diff --git a/crates/proto/tsclientlib/src/tests.rs b/crates/proto/tsclientlib/src/tests.rs index d5752e8..8e44234 100644 --- a/crates/proto/tsclientlib/src/tests.rs +++ b/crates/proto/tsclientlib/src/tests.rs @@ -2,7 +2,11 @@ use once_cell::sync::Lazy; use ts_bookkeeping::messages::s2c::InMessage; use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType}; -static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init()); +// Voelin patch: `try_init`. quickcheck's logging installs a `log` logger, after +// which `init` panics, poisons this `Lazy` and fails every test that follows. +static TRACING: Lazy<()> = Lazy::new(|| { + let _ = tracing_subscriber::fmt().with_test_writer().try_init(); +}); pub(crate) fn create_logger() { Lazy::force(&TRACING); } diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index b776502..bb1cb9c 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). @@ -62,7 +62,7 @@ yuv = "0.8.19" ashpd = { version = "0.13.13", default-features = false, features = ["camera", "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 } @@ -80,6 +80,10 @@ windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" serde_json = "1" +# 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/capture/dmabuf.rs b/crates/voelin-media/src/capture/dmabuf.rs index a82aa74..d8d07cb 100644 --- a/crates/voelin-media/src/capture/dmabuf.rs +++ b/crates/voelin-media/src/capture/dmabuf.rs @@ -21,6 +21,18 @@ 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); +/// 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 { + if fd < 0 { + return None; + } + // SAFETY: borrowed for the call from a caller that holds it open. + let fd = unsafe { BorrowedFd::borrow_raw(fd) }; + let end = rustix::fs::seek(fd, rustix::fs::SeekFrom::End(0)).ok()?; + usize::try_from(end).ok().filter(|&size| size > 0) +} + /// A read-only mapping of a DMA-BUF. pub(crate) struct DmaBufMap { fd: RawFd, @@ -97,5 +109,7 @@ mod tests { assert_eq!(map.fd(), file.as_raw_fd()); assert_eq!(map.read(|b| b.iter().map(|&x| u64::from(x)).sum::()), 7 * 8192); assert!(DmaBufMap::new(-1, 10).is_err()); + assert_eq!(size_of(file.as_raw_fd()), Some(8192)); + assert_eq!(size_of(-1), None); } } diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index 7fecbd2..71e9772 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -11,9 +11,13 @@ //! (`BGRx` / `BGRA` / `RGBx` / `RGBA`) second, so compositors without //! DMA-BUF support use shared memory. When reading DMA-BUFs turns out slow //! (buffers in memory the CPU reads uncached, e.g. a discrete GPU's VRAM), -//! the stream switches to shared memory. Tiled DMA-BUFs would need a GPU -//! import and are not offered. Frames go to the [`FrameSink`] while the -//! buffer is dequeued; nothing is copied before conversion. The frame rate +//! the stream switches to shared memory. A sink that +//! [accepts DMA-BUFs](FrameSink::accepts_dmabuf) (a VA-API encoder, which +//! converts and encodes them on the GPU) gets them before anything is +//! mapped, and then the CPU never reads them. Tiled DMA-BUFs are not +//! offered: the modifiers the encoder's driver imports are not known here. +//! Frames go to the [`FrameSink`] while the buffer is dequeued; nothing is +//! copied before conversion. The frame rate //! follows the sink's cap: the compositor is asked for up to that rate and //! sends frames when the screen changes. @@ -31,7 +35,7 @@ use pw::spa::pod::{ use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Id, Rectangle, SpaTypes}; use tracing::{debug, warn}; -use crate::capture::dmabuf::DmaBufMap; +use crate::capture::dmabuf::{self, DmaBufMap}; use crate::capture::pw::{PwThread, pod, serialize}; use crate::capture::{ BoxFuture, CaptureOptions, CaptureSource, DRM_MOD_LINEAR, DmaBufRef, FrameSink, QueueSink, @@ -248,9 +252,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 +293,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 +324,7 @@ fn video_stream( maps: Vec::new(), dmabuf_time: Duration::ZERO, dmabuf_frames: 0, + dmabuf_failures: 0, logged: None, mainloop: mainloop.downgrade(), }; @@ -582,7 +604,12 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { fourcc, modifier: format.modifier.map_or(DRM_MOD_LINEAR, |m| m as u64), fd: data.fd(), - size: (raw.mapoffset + raw.maxsize) as usize, + // As for the mapping below: compositors leave `maxsize` 0 for + // a DMA-BUF, whose size is its buffer object's. + size: match (raw.mapoffset + raw.maxsize) as usize { + 0 => dmabuf::size_of(data.fd()).unwrap_or(raw.mapoffset as usize + needed), + size => size, + }, planes: [(raw.mapoffset as usize + offset, stride), (0, 0), (0, 0), (0, 0)], plane_count: 1, }; @@ -600,14 +627,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/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 53a3bfb..d2f5757 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -17,7 +17,7 @@ use std::time::{Duration, Instant}; use super::layout::{self, HwFramesFields}; use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; -use super::{Ffmpeg, take_log}; +use super::{Ffmpeg, take_log, vpp}; use crate::capture::{DmaBufRef, drm_fourcc}; use crate::codec::hw::EncoderFactory; use crate::codec::{ @@ -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 { @@ -397,6 +452,20 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { .map_err(Clone::clone) } +/// The `VADisplay` of the process's VA-API device (the first field of its +/// `AVVAAPIDeviceContext`). +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 + // API context starts with the display. + unsafe { + let kind = (ffmpeg.api.av_hwdevice_find_type_by_name)(name.as_ptr()); + let hwctx = layout::device_hwctx(device, kind)?; + Ok(layout::read::(hwctx, 0)) + } +} + /// FFmpeg's recent messages, appended to an error. fn log_suffix(context: &str) -> String { let log = take_log(context); @@ -448,6 +517,8 @@ struct Session { hw: Ptr, packet: Ptr, last_pts: Option, + /// A frame went in (so there is something to flush). + sent: bool, /// No packet came out yet: the first one starts the stream, so it is a /// keyframe even where the wrapper does not flag it (rav1e). first_packet: bool, @@ -456,12 +527,55 @@ struct Session { opened: Instant, timestamps: Timestamps, nv12: bool, + /// RGB DMA-BUFs: made on the first one; why not, if they cannot be. + rgb: Option>, } // SAFETY: the FFmpeg objects belong to this session alone and are used from // one thread at a time (`&mut self`). unsafe impl Send for Session {} +/// 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; @@ -504,6 +618,9 @@ pub struct FfmpegEncoder { low_power: bool, /// `AVFrame.hw_frames_ctx` was checked on a surface of this encoder. dmabuf_checked: bool, + /// Sizes it encodes exactly are multiples of these + /// ([`BackendStatus::alignment`]). + alignment: (u32, u32), } impl FfmpegEncoder { @@ -516,6 +633,12 @@ impl FfmpegEncoder { })?; let ffmpeg = Ffmpeg::get() .map_err(|e| Error::CodecUnavailable { codec: spec.codec, reason: e.to_owned() })?; + // What the probe measured, once it is done (its own encoders run + // before that, at sizes every backend encodes exactly). + let alignment = PROBE + .get() + .and_then(|p| p.iter().find(|s| s.spec == spec)) + .map_or((2, 2), |s| s.alignment); Ok(Self { ffmpeg, spec, @@ -524,6 +647,7 @@ impl FfmpegEncoder { reinit: Reinit::No, low_power: false, dmabuf_checked: false, + alignment, }) } @@ -588,9 +712,12 @@ impl FfmpegEncoder { Ok(()) } - /// The encoder size: even (4:2:0 chroma), at least 2x2. - fn coded_size(width: u32, height: u32) -> (u32, u32) { - ((width & !1).max(2), (height & !1).max(2)) + /// 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. + 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)) } /// Open a session for `width` x `height`. @@ -637,10 +764,12 @@ impl FfmpegEncoder { hw: std::ptr::null_mut(), packet: std::ptr::null_mut(), last_pts: None, + sent: false, first_packet: true, opened: Instant::now(), timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, + rgb: None, }; // SAFETY: `ctx` is a live codec context; the first child is its // private options object (NULL if the codec has none). @@ -677,7 +806,15 @@ impl FfmpegEncoder { // SVT-AV1 takes CBR from its own `rc=2` and rejects a maximum // that is not above the target. generic("maxrate", if self.spec.name == "libsvtav1" { 0 } else { bitrate }), - generic("bufsize", bitrate), + // A one-second buffer, except for VA-API AV1: with one second + // Mesa's rate control overshot by 3.5 % at 1080p60 / 6 Mbit/s and + // 7.9 % at 1440p60 / 10 Mbit/s (RX 7900 GRE, desktop pattern); + // with two it lands within 1.2 % at both and at 720p30, no frame + // skipped, the largest 68 KB against 64 KB at 1440p60. + generic( + "bufsize", + u64::from(bitrate) * if self.spec.name == "av1_vaapi" { 2 } else { 1 }, + ), generic("g", gop), generic("bf", 0), generic("colorspace", "smpte170m"), @@ -688,12 +825,22 @@ 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)?; } if self.spec.is_vaapi() { - session.pool = self.vaapi_pool(width, height)?; + session.pool = self.vaapi_pool(width, height, self.ffmpeg.pix.nv12)?; 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. @@ -743,8 +890,9 @@ impl FfmpegEncoder { Ok(session) } - /// A VA-API surface pool (NV12) for `width` x `height`. - fn vaapi_pool(&self, width: u32, height: u32) -> Result { + /// 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 = @@ -768,7 +916,7 @@ impl FfmpegEncoder { let ret = unsafe { let ctx = (*pool.cast::()).data.cast::(); layout::write::(ctx, fields.format, vaapi); - layout::write::(ctx, fields.sw_format, self.ffmpeg.pix.nv12); + 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. @@ -875,6 +1023,14 @@ impl FfmpegEncoder { frame: Ptr, out: &mut dyn FnMut(EncodedChunk<'_>), ) -> Result { + if frame.is_null() && !session.sent { + // Nothing to flush, and FFmpeg 9's VA-API encoders crash when + // drained before their first frame (h264_vaapi on an RX 7900 + // GRE: SIGSEGV in avcodec_send_frame), which is what dropping an + // encoder whose first frame failed (a DMA-BUF import, a surface + // upload) used to do. + return Ok(false); + } let api = &self.ffmpeg.api; let mut keyframe = false; loop { @@ -887,6 +1043,7 @@ impl FfmpegEncoder { if ret < 0 && ret != sys::EOF { return Err(self.error("send", ret)); } + session.sent |= !frame.is_null(); break; } keyframe |= self.drain(session, out)?; @@ -902,7 +1059,7 @@ impl FfmpegEncoder { force_keyframe: bool, out: &mut dyn FnMut(EncodedChunk<'_>), ) -> Result<(Session, bool)> { - let (w, h) = Self::coded_size(width, height); + let (w, h) = self.coded_size(width, height); let mut force = force_keyframe; let reopen = match &self.session { None => true, @@ -940,17 +1097,20 @@ impl FfmpegEncoder { result } - /// Encode a frame that is still in a DMA-BUF, without a copy: the buffer - /// becomes a VA-API surface (`av_hwframe_map` of a DRM PRIME frame) that - /// the encoder reads directly. + /// Encode a frame that is still in a DMA-BUF, without the CPU reading + /// it: the buffer becomes a VA-API surface (`av_hwframe_map` of a DRM + /// PRIME frame). /// - /// VA-API backends and NV12 buffers only: the RGB frames screen capture - /// delivers first need a colour conversion on the GPU (VA-API video - /// processing), which is not implemented. Anything else fails with - /// `Error::CodecUnavailable`; callers then map the buffer and use - /// [`encode_with`](VideoEncoder::encode_with). The buffer must stay - /// unchanged until this frame's packet came out (the encoder reads it - /// asynchronously, one frame deep). + /// VA-API backends only. NV12 buffers go to the encoder as they are + /// (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. + /// + /// Anything else fails with `Error::CodecUnavailable`; callers then map + /// the buffer and use [`encode_with`](VideoEncoder::encode_with). pub fn encode_dmabuf( &mut self, frame: &DmaBufRef, @@ -960,33 +1120,30 @@ impl FfmpegEncoder { if !self.spec.is_vaapi() { return Err(self.unavailable(format!("{} does not import DMA-BUFs", self.spec.name))); } - if frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2 { - return Err(self.unavailable( - "only NV12 DMA-BUFs are imported (RGB needs GPU colour conversion)".into(), - )); + let rgb = RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1; + if !rgb && (frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2) { + return Err(self.unavailable("only NV12 and RGB DMA-BUFs are imported".into())); } - if Self::coded_size(frame.width, frame.height) != (frame.width, frame.height) { - return Err(self.unavailable("odd frame size".into())); + if !rgb && 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 refs = self.ffmpeg.frame_refs.clone().map_err(|e| self.unavailable(e))?; - 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 session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; - let result = self.import_and_send(&mut session, frame, force, refs, drm_prime, vaapi, out); + let result = self.import_and_send(&mut session, frame, rgb, force, refs, out); self.session = Some(session); result } - #[allow(clippy::too_many_arguments)] // the parts of one import fn import_and_send( &mut self, session: &mut Session, frame: &DmaBufRef, + rgb: bool, force: bool, refs: layout::FrameRefs, - drm_prime: c_int, - vaapi: c_int, out: &mut dyn FnMut(EncodedChunk<'_>), ) -> Result<()> { let api = &self.ffmpeg.api; @@ -1005,6 +1162,96 @@ 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 pts = + self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64); + 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. + unsafe { + layout::write::(hw, self.ffmpeg.frame.pts, pts); + 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) }; + 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] = @@ -1017,8 +1264,6 @@ impl FfmpegEncoder { *plane = sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; } - let pts = - self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64); // 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 @@ -1039,22 +1284,16 @@ impl FfmpegEncoder { (*head).height = frame.height as c_int; (*head).data[0] = data; layout::write::(src, refs.buf, buffer); - let dst = session.hw; (*dst.cast::()).format = vaapi; - layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(session.pool)); + 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)); } - let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; - layout::write::(dst, self.ffmpeg.frame.pts, pts); - layout::write::(dst, self.ffmpeg.frame.pict_type, pict_type); - let result = self.send(session, dst, out); - (api.av_frame_unref)(dst); - result.map(|_| ()) } + Ok(()) } /// The pts of a frame taken at `timestamp`: frame numbers at the @@ -1119,24 +1358,34 @@ impl FfmpegEncoder { result.map(|_| ()) } - /// Encode one frame and flush the encoder (the self-test): the packets, - /// and whether one was a keyframe. - fn self_test(&mut self, width: u32, height: u32) -> Result<(usize, bool)> { + /// Encode one frame and flush the encoder (the self-test), which has to + /// give a keyframe; the size an AV1 stream declares. + fn self_test(&mut self, width: u32, height: u32) -> Result> { let frame = test_frame(width, height); let mut packets = 0; let mut keyframe = false; - self.encode_with(&frame, true, &mut |chunk| { - packets += 1; - keyframe |= chunk.keyframe; - })?; - let mut session = self.session.take().expect("opened by the frame"); - let flushed = self.send(&mut session, std::ptr::null_mut(), &mut |chunk| { + let mut declared = None; + let av1 = self.spec.codec == Codec::Av1; + let mut take = |chunk: EncodedChunk<'_>| { packets += 1; keyframe |= chunk.keyframe; + if declared.is_none() && av1 { + declared = av1_frame_size(chunk.data); + } + }; + let encoded = self.encode_with(&frame, true, &mut take); + let flushed = encoded.and_then(|()| { + let mut session = self.session.take().expect("opened by the frame"); + self.send(&mut session, std::ptr::null_mut(), &mut take) }); - drop(session); flushed?; - Ok((packets, keyframe)) + match (packets, keyframe) { + (0, _) => Err(self.unavailable("no packet from the test frame".into())), + (_, false) => { + Err(self.unavailable("the test frame did not come out as a keyframe".into())) + } + _ => Ok(declared), + } } } @@ -1251,24 +1500,145 @@ 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, + /// The sizes it encodes exactly are multiples of these; frames are + /// cropped to them. (2, 2) for most; AV1 on an RDNA3 GPU is (64, 16): + /// it pads anything else (1366x768 comes out as 1408x768, 1600x900 as + /// 1600x912, 1080 rows as 1082), and AV1 has no cropping like H.264's + /// SPS (its render size is a display hint decoders do not apply), so a + /// viewer would show the padding. + pub alignment: (u32, u32), } /// Size of the self-test frame. const TEST_SIZE: (u32, u32) = (320, 240); -fn test_backend(spec: &'static BackendSpec) -> std::result::Result<(), String> { +/// Size of the AV1 self-test frame: 2 more than a power of two, so its next +/// multiple of 4, 8, ... 256 is a different size each, and the size the +/// stream declares tells which alignment the encoder pads to. +/// +/// Not a multiple of 8: the RDNA3 encoder pads a height that is 8 more than +/// a multiple of 16 by 2 rows only (1080 to 1082), any other by up to 16. +const AV1_TEST_SIZE: (u32, u32) = (258, 258); + +/// The alignment that turns `tested` into the `declared` size: the power of +/// two whose next multiple of `tested` is `declared` (2 if they are equal, +/// or if no power of two explains it, which leaves frames uncropped). +fn alignment_of(tested: u32, declared: u32) -> u32 { + (2..=8).map(|s| 1 << s).find(|a| tested.next_multiple_of(*a) == declared).unwrap_or(2) +} + +fn test_backend(spec: &'static BackendSpec) -> std::result::Result<(u32, u32), String> { let config = EncoderConfig { fps: 30, bitrate_bps: 500_000, ..EncoderConfig::default() }; let mut encoder = FfmpegEncoder::new(spec.name, config).map_err(|e| e.to_string())?; - match encoder.self_test(TEST_SIZE.0, TEST_SIZE.1) { - Ok((0, _)) => Err("no packet from the test frame".into()), - Ok((_, false)) => Err("the test frame did not come out as a keyframe".into()), - Ok(_) => Ok(()), + let (w, h) = if spec.codec == Codec::Av1 { AV1_TEST_SIZE } else { TEST_SIZE }; + match encoder.self_test(w, h) { + Ok(Some((dw, dh))) => Ok((alignment_of(w, dw), alignment_of(h, dh))), + Ok(None) => Ok((2, 2)), Err(Error::CodecUnavailable { reason, .. }) => Err(reason), Err(Error::Encoder { message, .. }) => Err(message), Err(e) => Err(e.to_string()), } } +/// The frame size an AV1 stream declares: `max_frame_width_minus_1 + 1` and +/// `max_frame_height_minus_1 + 1` of the first sequence header OBU in +/// `data` (AV1 specification 5.3 and 5.5), or `None` if there is none. +fn av1_frame_size(data: &[u8]) -> Option<(u32, u32)> { + const OBU_SEQUENCE_HEADER: u8 = 1; + let mut rest = data; + while let [header, tail @ ..] = rest { + let mut body = if header & 0x04 != 0 { tail.get(1..)? } else { tail }; + let size = if header & 0x02 != 0 { + let mut size = 0usize; + let mut i = 0; + loop { + let byte = *body.get(i)?; + size |= usize::from(byte & 0x7f) << (7 * i); + i += 1; + if byte & 0x80 == 0 { + break; + } + if i == 8 { + return None; + } + } + body = &body[i..]; + size + } else { + body.len() + }; + let payload = body.get(..size)?; + if (header >> 3) & 0xf == OBU_SEQUENCE_HEADER { + return av1_sequence_size(payload); + } + rest = &body[size..]; + } + None +} + +/// `sequence_header_obu()` up to the maximum frame size. +fn av1_sequence_size(payload: &[u8]) -> Option<(u32, u32)> { + let mut pos = 0usize; + let mut read = |bits: u32| -> Option { + (0..bits).try_fold(0u32, |value, _| { + let bit = (payload.get(pos / 8)? >> (7 - pos % 8)) & 1; + pos += 1; + Some(value << 1 | u32::from(bit)) + }) + }; + read(3)?; // seq_profile + read(1)?; // still_picture + if read(1)? == 1 { + // reduced_still_picture_header + read(5)?; // seq_level_idx[0] + } else { + let mut decoder_model = false; + let mut delay_bits = 0; + if read(1)? == 1 { + // timing_info: display tick, time scale, equal_picture_interval + read(32)?; + read(32)?; + if read(1)? == 1 { + // num_ticks_per_picture_minus_1, uvlc() + let mut zeros = 0; + while read(1)? == 0 { + zeros += 1; + } + if zeros < 32 { + read(zeros)?; + } + } + decoder_model = read(1)? == 1; + if decoder_model { + delay_bits = read(5)? + 1; // buffer_delay_length_minus_1 + read(32)?; // num_units_in_decoding_tick + read(10)?; // buffer_removal_time / frame_presentation_time lengths + } + } + let initial_display_delay = read(1)? == 1; + for _ in 0..=read(5)? { + read(12)?; // operating_point_idc + if read(5)? > 7 { + read(1)?; // seq_tier + } + if decoder_model && read(1)? == 1 { + // operating_parameters_info: both buffer delays, low_delay_mode_flag + read(delay_bits)?; + read(delay_bits)?; + read(1)?; + } + if initial_display_delay && read(1)? == 1 { + read(4)?; + } + } + } + let (width_bits, height_bits) = (read(4)? + 1, read(4)? + 1); + Some((read(width_bits)? + 1, read(height_bits)? + 1)) +} + /// Whether FFmpeg has `name` at all (cheap, before any self-test). fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool { let name = cstr(name); @@ -1276,42 +1646,201 @@ 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(target_os = "linux")] + saved: std::os::fd::OwnedFd, + #[cfg(target_os = "linux")] + file: std::path::PathBuf, +} + +impl QuietStderr { + #[cfg(target_os = "linux")] + 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(target_os = "linux"))] + fn start() -> Option { + None + } +} + +impl Drop for QuietStderr { + fn drop(&mut self) { + #[cfg(target_os = "linux")] + { + 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(()) +} + +/// The result of [`probe`], once it ran. +static PROBE: OnceLock> = OnceLock::new(); + /// 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 (tested, 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) + }), + }; + let alignment = *tested.as_ref().unwrap_or(&(2, 2)); + BackendStatus { spec, available: tested.map(|_| ()), took, alignment } }) .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, + alignment = ?status.alignment, + "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 }) } @@ -1400,6 +1929,575 @@ 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}" + ); + } + } + } + } + } + + /// The frame size of a sequence header that takes every optional branch + /// (timing info, decoder model, two operating points), behind a temporal + /// delimiter, and the alignment derived from it. + #[test] + fn av1_declared_size_and_alignment() { + // (value, bits), most significant bit first. + let fields: &[(u32, u32)] = &[ + (0, 3), // seq_profile + (0, 1), // still_picture + (0, 1), // reduced_still_picture_header + (1, 1), // timing_info_present_flag + (1, 32), // num_units_in_display_tick + (60, 32), // time_scale + (1, 1), // equal_picture_interval + (0b011, 3), // num_ticks_per_picture_minus_1 = 2, uvlc + (1, 1), // decoder_model_info_present_flag + (9, 5), // buffer_delay_length_minus_1 + (1, 32), // num_units_in_decoding_tick + (0, 10), // the two time lengths + (1, 1), // initial_display_delay_present_flag + (1, 5), // operating_points_cnt_minus_1 + (0x103, 12), // operating_point_idc[0] + (9, 5), // seq_level_idx[0], > 7 + (0, 1), // seq_tier[0] + (1, 1), // decoder_model_present_for_this_op[0] + (500, 10), // decoder_buffer_delay + (500, 10), // encoder_buffer_delay + (0, 1), // low_delay_mode_flag + (1, 1), // initial_display_delay_present_for_this_op[0] + (9, 4), // initial_display_delay_minus_1[0] + (0x001, 12), // operating_point_idc[1] + (4, 5), // seq_level_idx[1] + (0, 1), // decoder_model_present_for_this_op[1] + (0, 1), // initial_display_delay_present_for_this_op[1] + (10, 4), // frame_width_bits_minus_1 + (10, 4), // frame_height_bits_minus_1 + (1919, 11), // max_frame_width_minus_1 + (1081, 11), // max_frame_height_minus_1 + (0xa5, 8), // what follows + ]; + let mut payload = Vec::new(); + let mut n = 0; + for &(value, bits) in fields { + for i in (0..bits).rev() { + if n % 8 == 0 { + payload.push(0); + } + *payload.last_mut().unwrap() |= (((value >> i) & 1) as u8) << (7 - n % 8); + n += 1; + } + } + // Temporal delimiter (type 2, empty), then the sequence header + // (type 1), both with a size field. + let mut stream = vec![2 << 3 | 2, 0, 1 << 3 | 2, payload.len() as u8]; + stream.extend_from_slice(&payload); + assert_eq!(av1_frame_size(&stream), Some((1920, 1082))); + assert_eq!(av1_frame_size(&stream[..stream.len() - 8]), None, "cut short"); + assert_eq!(av1_frame_size(&[2 << 3 | 2, 0]), None, "no sequence header"); + + assert_eq!(alignment_of(258, 258), 2); + assert_eq!(alignment_of(258, 260), 4); + assert_eq!(alignment_of(258, 272), 16); + assert_eq!(alignment_of(258, 320), 64); + assert_eq!(alignment_of(258, 512), 256); + assert_eq!(alignment_of(258, 4096), 2, "not an alignment: left alone"); + } + + fn usable(name: &str) -> bool { + probe().iter().any(|s| s.spec.name == name && s.available.is_ok()) + } + + /// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given) + /// exported as a DRM PRIME DMA-BUF: what a compositor hands over, + /// tiling modifier and all. The buffer is valid while this lives. + struct Exported { + pool: Ptr, + surface: Ptr, + drm: Ptr, + frame: DmaBufRef, + } + + impl Exported { + fn new( + (width, height): (u32, u32), + sw_format: c_int, + fourcc: u32, + picture: Option<&VideoFrame>, + ) -> Self { + let ffmpeg = Ffmpeg::get().unwrap(); + let api = &ffmpeg.api; + let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + let pool = encoder.vaapi_pool(width, height, sw_format).expect("a VA-API surface pool"); + // SAFETY: `pool` is a live frames context of this process's + // VA-API device; the frames are ours and freed by the drop. The + // exported frame's `data[0]` is the AVDRMFrameDescriptor FFmpeg + // filled, valid while the frame holds the mapping. + unsafe { + let mut exported = Exported { + pool, + surface: (api.av_frame_alloc)(), + drm: (api.av_frame_alloc)(), + frame: DmaBufRef { + width, + height, + timestamp: Duration::ZERO, + fourcc, + modifier: 0, + fd: -1, + size: 0, + planes: [(0, 0); 4], + plane_count: 0, + }, + }; + let (surface, drm) = (exported.surface, exported.drm); + assert!(!surface.is_null() && !drm.is_null()); + let ret = (api.av_hwframe_get_buffer)(pool, surface, 0); + assert!(ret >= 0, "av_hwframe_get_buffer: {}", api.error_text(ret)); + if let Some(picture) = picture { + let FrameData::Bgra(pixels) = &picture.data else { panic!("BGRA only") }; + let mut sw = (api.av_frame_alloc)(); + let head = sw.cast::(); + ((*head).width, (*head).height) = (width as c_int, height as c_int); + (*head).format = sw_format; + assert!((api.av_frame_get_buffer)(sw, 0) >= 0); + let stride = (*head).linesize[0] as usize; + let rows = + std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize); + for (y, row) in rows.chunks_exact_mut(stride).enumerate() { + row[..width as usize * 4] + .copy_from_slice(pixels.row(y, width as usize * 4)); + } + let ret = (api.av_hwframe_transfer_data)(surface, sw, 0); + (api.av_frame_free)(&mut sw); + assert!(ret >= 0, "upload: {}", api.error_text(ret)); + } + (*drm.cast::()).format = ffmpeg.pix.drm_prime.expect("DRM PRIME"); + let ret = (api.av_hwframe_map)( + drm, + surface, + sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT, + ); + assert!(ret >= 0, "this driver cannot export a VA-API surface as a DMA-BUF"); + let descriptor = + *(*drm.cast::()).data[0].cast::(); + assert_eq!(descriptor.nb_objects, 1, "one buffer object"); + // The driver may describe a surface one plane per layer (NV12 + // as R8 for Y and GR88 for UV) rather than as one layer, which + // is how a compositor hands it over. Both name the same bytes + // of the same object, so flatten the layers into planes. + let object = descriptor.objects[0]; + let frame = &mut exported.frame; + for layer in &descriptor.layers[..descriptor.nb_layers as usize] { + for plane in &layer.planes[..layer.nb_planes as usize] { + frame.planes[frame.plane_count] = + (plane.offset as usize, plane.pitch as usize); + frame.plane_count += 1; + } + } + (frame.modifier, frame.fd, frame.size) = + (object.format_modifier, object.fd, object.size); + assert!(frame.fd >= 0 && frame.size > 0); + exported + } + } + } + + impl Drop for Exported { + fn drop(&mut self) { + let api = &Ffmpeg::get().unwrap().api; + // SAFETY: ours; the mapping goes before the surface it maps. + unsafe { + (api.av_frame_free)(&mut self.drm); + (api.av_frame_free)(&mut self.surface); + (api.av_buffer_unref)(&mut self.pool); + } + } + } + + /// 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> { + match codec { + #[cfg(feature = "openh264")] + Codec::H264 => { + let path = std::env::var_os("VOELIN_OPENH264_LIB")?; + let library = crate::codec::h264::OpenH264::load(path).ok()?; + Some(Box::new(library.decoder().ok()?)) + } + #[cfg(feature = "av1")] + Codec::Av1 => Some(Box::new(crate::codec::av1::Dav1dDecoder::new().ok()?)), + _ => None, + } + } + + /// The zero-copy path with a real DMA-BUF, on the GPU. + /// + /// The probe reports the import as available from the offsets alone, so + /// this makes a VA-API surface, exports it as a DMA-BUF and feeds it back + /// to an encoder through [`FfmpegEncoder::encode_dmabuf`]: the import, + /// the `AVFrame.hw_frames_ctx` check and the encode, for real. + /// + /// Skipped without a working `h264_vaapi`. + #[test] + fn a_dmabuf_really_reaches_a_vaapi_encoder() { + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let nv12 = Ffmpeg::get().unwrap().pix.nv12; + let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None); + let frame = exported.frame; + assert_eq!(frame.plane_count, 2, "NV12 has two planes"); + let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + let mut packets = 0; + let mut keyframe = false; + encoder + .encode_dmabuf(&frame, true, &mut |chunk| { + packets += 1; + keyframe |= chunk.keyframe; + }) + .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 + ); + } + + /// An RGB DMA-BUF, what screen capture hands over, converted to NV12 on + /// the GPU: the conversion against the CPU's ([`convert`]), then through + /// the encoders to our decoders. 642x362 is not a size the AV1 encoder of + /// an RDNA3 GPU encodes exactly, so there the conversion also crops. + /// + /// Skipped without a working `h264_vaapi`; the decoding without + /// decoders. + #[test] + fn an_rgb_dmabuf_is_converted_on_the_gpu() { + const SIZE: (u32, u32) = (642, 362); + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().unwrap(); + let api = &ffmpeg.api; + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + SIZE.0, + SIZE.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let picture = screen.frame(3, 30); + let rgb = + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + 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 cpu = convert::to_i420(&picture).unwrap(); + let FrameData::I420 { y, u, v } = &cpu.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)] + { + 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; + eprintln!("{name}: GPU and CPU conversion differ by {mean:.2} on average"); + // Chroma differs a little at edges (another subsampling filter); + // another matrix, range or transfer function moves whole areas. + assert!(mean < 1.0, "{name} differs by {mean:.2}: another matrix, range or transfer?"); + } + + // 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")] + let linear = linear_dmabuf(&picture, (SIZE.0 as usize * 4).next_multiple_of(256)); + #[cfg(not(target_os = "linux"))] + let linear: Option<((), DmaBufRef)> = None; + if linear.is_none() { + eprintln!("no /dev/udmabuf: the LINEAR buffer is skipped"); + } + let buffers: Vec = + std::iter::once(rgb.frame).chain(linear.as_ref().map(|(_, frame)| *frame)).collect(); + + // Through the encoders, decoded: as good as the same picture + // converted and uploaded by the CPU. + for name in ["h264_vaapi", "av1_vaapi"] { + if !usable(name) { + continue; + } + // The lowest PSNR through the CPU path (`None`), then each buffer. + let paths = std::iter::once(None).chain(buffers.iter().map(Some)); + let mut psnr = Vec::new(); + let mut coded = (0, 0); + for buffer in paths { + let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap(); + let (cw, ch) = encoder.coded_size(SIZE.0, SIZE.1); + coded = (cw, ch); + let mut decoder = decoder(encoder.codec()); + let (mut packets, mut worst) = (0, f64::INFINITY); + for n in 0..4u32 { + let timestamp = Duration::from_secs(n.into()) / 30; + let mut take = |chunk: EncodedChunk<'_>| { + packets += 1; + let Some(decoder) = &mut decoder else { return }; + let Some(decoded) = decoder.decode(chunk.data).unwrap() else { return }; + assert_eq!((decoded.width, decoded.height), (cw, ch), "{name}"); + let mut source = picture.view(); + (source.width, source.height) = (cw, ch); + worst = worst.min(convert::psnr(&source.to_frame(), &decoded).unwrap()); + }; + let result = match buffer { + Some(buffer) => { + let frame = DmaBufRef { timestamp, ..*buffer }; + encoder.encode_dmabuf(&frame, n == 0, &mut take) + } + None => { + let frame = picture.clone().with_timestamp(timestamp); + encoder.encode_with(&frame, n == 0, &mut take) + } + }; + result.unwrap_or_else(|e| panic!("{name}: {e}")); + } + assert!(packets >= 3, "{name}: {packets} packets"); + psnr.push(worst); + } + let cpu = psnr[0]; + for (buffer, gpu) in buffers.iter().zip(&psnr[1..]) { + assert!( + gpu.is_infinite() || *gpu > cpu - 0.5, + "{name}: {gpu:.1} dB against {cpu:.1}" + ); + eprintln!( + "{name}: {}x{} XR24 DMA-BUF (modifier {:#x}, pitch {}) encoded at {}x{}, lowest \ + PSNR {gpu:.1} dB (the CPU path {cpu:.1} dB)", + SIZE.0, SIZE.1, buffer.modifier, buffer.planes[0].1, coded.0, coded.1 + ); + } + } + } + + /// `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 + /// `/dev/udmabuf`. + #[cfg(target_os = "linux")] + 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; + + 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() { + 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, + planes: [(0, stride), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + }; + Some((fd, frame)) + } + + /// What the CPU spends per frame on its way into a VA-API encoder at + /// 2560x1440: the shared-memory path (the picture converted to I420 on + /// every core, then interleaved and uploaded by `encode_with`) against + /// an RGB DMA-BUF converted on the GPU. CPU time is every thread of the + /// process (`/proc/self/task/*/schedstat`), so run it alone: + /// `cargo test -p voelin-media --release --lib zero_copy_cpu_cost -- + /// --ignored --nocapture`. + #[test] + #[ignore = "a measurement, not a check"] + fn zero_copy_cpu_cost() { + const SIZE: (u32, u32) = (2560, 1440); + const FRAMES: u32 = 600; + if !usable("h264_vaapi") { + eprintln!("no usable h264_vaapi, skipped"); + return; + } + let ffmpeg = Ffmpeg::get().unwrap(); + let cpu_time = || -> Duration { + let tasks = std::fs::read_dir("/proc/self/task").unwrap().flatten(); + tasks + .filter_map(|t| std::fs::read_to_string(t.path().join("schedstat")).ok()) + .filter_map(|s| s.split_whitespace().next()?.parse().ok()) + .map(Duration::from_nanos) + .sum() + }; + let measure = |what: &str, encode: &mut dyn FnMut(Duration)| { + for n in 0..30 { + encode(Duration::from_secs(n) / 60); + } + let (cpu, wall) = (cpu_time(), Instant::now()); + for n in 30..30 + FRAMES { + encode(Duration::from_secs(n.into()) / 60); + } + let per_frame = |d: Duration| d.as_secs_f64() * 1e3 / f64::from(FRAMES); + let (cpu, wall) = (per_frame(cpu_time() - cpu), per_frame(wall.elapsed())); + eprintln!( + "{what}: {cpu:.2} ms CPU and {wall:.2} ms wall per frame, {:.2} cores at 60 fps", + cpu * 60.0 / 1e3 + ); + }; + let screen = crate::capture::synthetic::SyntheticScreen::with_pattern( + SIZE.0, + SIZE.1, + crate::capture::synthetic::Pattern::Desktop, + ); + let picture = screen.frame(0, 60); + let config = EncoderConfig { fps: 60, bitrate_bps: 10_000_000, ..EncoderConfig::default() }; + + let mut converter = convert::Converter::new(0); + let mut i420 = VideoFrame::black_i420(SIZE.0, SIZE.1); + let mut encoder = FfmpegEncoder::new("h264_vaapi", config.clone()).unwrap(); + measure("CPU: convert on every core, interleave, upload", &mut |timestamp| { + let mut source = picture.view(); + source.timestamp = timestamp; + converter.to_i420_into(&source, &mut i420).unwrap(); + encoder.encode_with(&i420, false, &mut |_| {}).unwrap(); + }); + drop(encoder); + + let rgb = + Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture)); + let mut encoder = FfmpegEncoder::new("h264_vaapi", config).unwrap(); + measure("GPU: RGB DMA-BUF imported and converted", &mut |timestamp| { + let frame = DmaBufRef { timestamp, ..rgb.frame }; + encoder.encode_dmabuf(&frame, false, &mut |_| {}).unwrap(); + }); + } + #[test] fn settings_per_backend() { let config = EncoderConfig::default(); diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 3947825..dbf2d2b 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -13,11 +13,15 @@ //! | `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 | +//! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout | //! //! 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; @@ -316,6 +320,51 @@ pub unsafe fn hw_frames_fields(frames: Ptr, device: Ptr) -> Result Result { + // SAFETY: guaranteed by the caller; `data` is the leading field pair, + // and both layouts lie within the smaller one (the current struct). + unsafe { + let ctx = (*device.cast::()).data.cast::(); + for (kind_at, hwctx_at) in [ + (offset_of!(DevicePublic, kind), offset_of!(DevicePublic, hwctx)), + (offset_of!(DeviceWithInternal, kind), offset_of!(DeviceWithInternal, hwctx)), + ] { + if read::(ctx, kind_at) == kind { + let hwctx: Ptr = read(ctx, hwctx_at); + return if hwctx.is_null() { Err("no device context".into()) } else { Ok(hwctx) }; + } + } + } + Err("unknown AVHWDeviceContext layout".into()) +} + /// Offsets of `buf[0]` and `hw_frames_ctx` in `AVFrame`, for importing /// DMA-BUFs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -324,8 +373,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 +394,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 +406,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 +474,35 @@ 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; `AVHWDeviceContext` `type` 8, `hwctx` 16. + #[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); + assert_eq!(offset_of!(DevicePublic, kind), 8); + assert_eq!(offset_of!(DevicePublic, hwctx), 16); + // 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); + } } diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index e565fff..712a3ce 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -21,6 +21,7 @@ use std::sync::{Mutex, OnceLock}; pub mod encoder; mod layout; pub mod sys; +mod vpp; pub use encoder::{ BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe, @@ -37,6 +38,8 @@ pub(crate) struct PixFmts { pub nv12: c_int, pub vaapi: Option, pub drm_prime: Option, + /// `bgr0`: B, G, R, x in memory, the DRM `XR24` of captured screens. + pub bgr0: Option, } /// What was loaded, for logs and the UI. @@ -98,6 +101,7 @@ impl Ffmpeg { nv12, vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")), drm_prime: api.pix_fmt("drm_prime"), + bgr0: api.pix_fmt("bgr0"), }; let codec_hw_frames = layout::codec_hw_frames(&api); let frame_refs = layout::frame_refs(&api, yuv420p); diff --git a/crates/voelin-media/src/ffmpeg/vpp.rs b/crates/voelin-media/src/ffmpeg/vpp.rs new file mode 100644 index 0000000..03d1d70 --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/vpp.rs @@ -0,0 +1,344 @@ +//! RGB to NV12 on the GPU (VA-API video processing), so that a captured +//! RGB DMA-BUF reaches a VA-API encoder without the CPU reading a pixel. +//! +//! libva is what FFmpeg's VA-API support is built on, not one of FFmpeg's +//! libraries: it is opened at runtime (`libva.so.2`, which libavutil has +//! already loaded once a VA-API device exists) and driven on FFmpeg's own +//! `VADisplay`, so FFmpeg's surfaces (`AVFrame.data[3]`) are used as they +//! are. FFmpeg does the same conversion only in libavfilter (`scale_vaapi`), +//! which would be one more library to find and a filter graph to drive for +//! what is one call here. libva 2 has kept its ABI since 2017: structs are +//! padded to a fixed size and new fields take reserved space. +#![allow(unsafe_code)] + +use std::ffi::{CStr, c_char, c_int, c_uint, c_void}; +use std::sync::OnceLock; + +use libloading::Library; + +/// `VADisplay`. +pub type Display = *mut c_void; + +/// `VAProfileNone`, `VAEntrypointVideoProc`, `VA_PROGRESSIVE`, +/// `VAProcPipelineParameterBufferType`. +const PROFILE_NONE: c_int = -1; +const ENTRYPOINT_VIDEO_PROC: c_int = 10; +const PROGRESSIVE: c_int = 1; +const PROC_PIPELINE_PARAMETER_BUFFER: c_int = 41; +/// `VAProcColorStandardBT601`, `VAProcColorStandardExplicit`, +/// `VA_SOURCE_RANGE_REDUCED` / `_FULL`. +const COLOR_STANDARD_BT601: c_int = 1; +const COLOR_STANDARD_EXPLICIT: c_int = 13; +const RANGE_REDUCED: u8 = 1; +const RANGE_FULL: u8 = 2; +/// ISO/IEC 23091-2 code points: SMPTE 170M (BT.601) primaries and transfer, +/// and the identity matrix (RGB). +const SMPTE170M: u8 = 6; +const MATRIX_IDENTITY: u8 = 0; + +/// `VARectangle`. +#[repr(C)] +struct Rectangle { + x: i16, + y: i16, + width: u16, + height: u16, +} + +/// `VAProcColorProperties`. +#[repr(C)] +#[derive(Default)] +struct ColorProperties { + chroma_sample_location: u8, + color_range: u8, + colour_primaries: u8, + transfer_characteristics: u8, + matrix_coefficients: u8, + reserved: [u8; 3], +} + +/// `VAProcPipelineParameterBuffer` of libva 2 (224 bytes on 64-bit +/// targets). +#[repr(C)] +struct PipelineParameters { + surface: c_uint, + surface_region: *const Rectangle, + surface_color_standard: c_int, + output_region: *const Rectangle, + output_background_color: u32, + output_color_standard: c_int, + pipeline_flags: u32, + filter_flags: u32, + filters: *mut c_uint, + num_filters: u32, + forward_references: *mut c_uint, + num_forward_references: u32, + backward_references: *mut c_uint, + num_backward_references: u32, + rotation_state: u32, + blend_state: *const c_void, + mirror_state: u32, + additional_outputs: *mut c_uint, + num_additional_outputs: u32, + input_surface_flag: u32, + output_surface_flag: u32, + input_color_properties: ColorProperties, + output_color_properties: ColorProperties, + processing_mode: c_int, + output_hdr_metadata: *mut c_void, + #[cfg(target_pointer_width = "64")] + reserved: [u32; 16], + #[cfg(not(target_pointer_width = "64"))] + reserved: [u32; 19], +} + +/// The libva functions used, with their `va.h` signatures. +struct Va { + create_config: + unsafe extern "C" fn(Display, c_int, c_int, *mut c_void, c_int, *mut c_uint) -> c_int, + destroy_config: unsafe extern "C" fn(Display, c_uint) -> c_int, + create_context: unsafe extern "C" fn( + Display, + c_uint, + c_int, + c_int, + c_int, + *mut c_uint, + c_int, + *mut c_uint, + ) -> c_int, + destroy_context: unsafe extern "C" fn(Display, c_uint) -> c_int, + create_buffer: unsafe extern "C" fn( + Display, + c_uint, + c_int, + c_uint, + c_uint, + *mut c_void, + *mut c_uint, + ) -> c_int, + destroy_buffer: unsafe extern "C" fn(Display, c_uint) -> c_int, + begin_picture: unsafe extern "C" fn(Display, c_uint, c_uint) -> c_int, + render_picture: unsafe extern "C" fn(Display, c_uint, *mut c_uint, c_int) -> c_int, + end_picture: unsafe extern "C" fn(Display, c_uint) -> c_int, + sync_surface: unsafe extern "C" fn(Display, c_uint) -> c_int, + error_str: unsafe extern "C" fn(c_int) -> *const c_char, + _lib: Library, +} + +impl Va { + fn get() -> Result<&'static Va, String> { + static VA: OnceLock> = OnceLock::new(); + VA.get_or_init(|| { + // SAFETY: libva has no initialisers with requirements; once a + // VA-API device exists this is the copy libavutil loaded. + let lib = unsafe { Library::new("libva.so.2") }.map_err(|e| format!("libva: {e}"))?; + macro_rules! symbol { + ($name:literal) => { + // SAFETY: looked up with its C signature from va.h; the + // library stays loaded as long as the pointers (`_lib`). + *unsafe { lib.get($name) }.map_err(|e| format!("libva: {e}"))? + }; + } + Ok(Va { + create_config: symbol!(b"vaCreateConfig\0"), + destroy_config: symbol!(b"vaDestroyConfig\0"), + create_context: symbol!(b"vaCreateContext\0"), + destroy_context: symbol!(b"vaDestroyContext\0"), + create_buffer: symbol!(b"vaCreateBuffer\0"), + destroy_buffer: symbol!(b"vaDestroyBuffer\0"), + begin_picture: symbol!(b"vaBeginPicture\0"), + render_picture: symbol!(b"vaRenderPicture\0"), + end_picture: symbol!(b"vaEndPicture\0"), + sync_surface: symbol!(b"vaSyncSurface\0"), + error_str: symbol!(b"vaErrorStr\0"), + _lib: lib, + }) + }) + .as_ref() + .map_err(Clone::clone) + } + + /// `Err` with libva's text for a status other than `VA_STATUS_SUCCESS`. + fn check(&self, what: &str, status: c_int) -> Result<(), String> { + if status == 0 { + return Ok(()); + } + // SAFETY: returns a static string for any status. + let text = unsafe { CStr::from_ptr((self.error_str)(status)) }; + Err(format!("{what}: {}", text.to_string_lossy())) + } +} + +/// A VA-API video processing context that converts RGB surfaces into NV12 +/// ones of `width` x `height`. +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 +// thread at a time (`&self` of a session behind `&mut`). +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`. + pub fn new(display: Display, width: u32, height: u32) -> Result { + let va = Va::get()?; + let mut config = 0; + // SAFETY: a live display; no attributes; out pointer. + let status = unsafe { + (va.create_config)( + display, + PROFILE_NONE, + ENTRYPOINT_VIDEO_PROC, + std::ptr::null_mut(), + 0, + &mut config, + ) + }; + va.check("no VA-API video processing", status)?; + let mut context = 0; + // SAFETY: the config just made; no render targets (surfaces are + // named per picture); out pointer. + let status = unsafe { + (va.create_context)( + display, + config, + width as c_int, + height as c_int, + PROGRESSIVE, + std::ptr::null_mut(), + 0, + &mut context, + ) + }; + if let Err(e) = va.check("VA-API video processing context", status) { + // SAFETY: made above. + unsafe { (va.destroy_config)(display, config) }; + return Err(e); + } + Ok(Self { va, display, config, context, width, height }) + } + + /// 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. + /// + /// 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> { + let va = self.va; + let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 }; + let mut parameters = PipelineParameters { + surface: input, + surface_region: ®ion, + output_region: ®ion, + output_background_color: 0xff00_0000, + output_color_standard: COLOR_STANDARD_BT601, + pipeline_flags: 0, + filter_flags: 0, + filters: std::ptr::null_mut(), + num_filters: 0, + forward_references: std::ptr::null_mut(), + num_forward_references: 0, + backward_references: std::ptr::null_mut(), + num_backward_references: 0, + rotation_state: 0, + blend_state: std::ptr::null(), + mirror_state: 0, + additional_outputs: std::ptr::null_mut(), + num_additional_outputs: 0, + input_surface_flag: 0, + output_surface_flag: 0, + // The input is described with the output's primaries and transfer, + // so the driver applies the matrix and nothing else, as the CPU + // path does. Left to itself (no standard, or sRGB) Mesa also + // converts the transfer function: measured on an RX 7900 GRE, + // grey 30 came out as Y 47 instead of 42, every dark pixel about + // 5 levels too bright. + surface_color_standard: COLOR_STANDARD_EXPLICIT, + input_color_properties: ColorProperties { + color_range: RANGE_FULL, + colour_primaries: SMPTE170M, + transfer_characteristics: SMPTE170M, + matrix_coefficients: MATRIX_IDENTITY, + ..Default::default() + }, + output_color_properties: ColorProperties { + color_range: RANGE_REDUCED, + ..Default::default() + }, + processing_mode: 0, + output_hdr_metadata: std::ptr::null_mut(), + reserved: Default::default(), + }; + let (display, context) = (self.display, self.context); + // SAFETY: surfaces and context of this display; the parameters are + // copied by vaCreateBuffer (and the regions they point to live until + // vaEndPicture returns); the buffer is ours to destroy afterwards. + unsafe { + va.check("vaBeginPicture", (va.begin_picture)(display, context, output))?; + let mut buffer = 0; + let status = (va.create_buffer)( + display, + context, + PROC_PIPELINE_PARAMETER_BUFFER, + size_of::() as c_uint, + 1, + (&raw mut parameters).cast(), + &mut buffer, + ); + let rendered = va.check("vaCreateBuffer", status).and_then(|()| { + va.check("vaRenderPicture", (va.render_picture)(display, context, &mut buffer, 1)) + }); + // A picture that was begun has to end, rendered or not. + let ended = va.check("vaEndPicture", (va.end_picture)(display, context)); + if status == 0 { + (va.destroy_buffer)(display, buffer); + } + rendered?; + ended?; + va.check("vaSyncSurface", (va.sync_surface)(display, output)) + } + } +} + +impl Drop for Converter { + fn drop(&mut self) { + // SAFETY: made in `new` on this display, no longer used. + unsafe { + (self.va.destroy_context)(self.display, self.context); + (self.va.destroy_config)(self.display, self.config); + } + } +} + +#[cfg(test)] +mod tests { + use std::mem::offset_of; + + use super::*; + + /// The mirror against `va/va_vpp.h` of libva 2.24 (x86-64), compiled. + #[cfg(target_pointer_width = "64")] + #[test] + fn pipeline_parameters_match_the_header() { + assert_eq!(size_of::(), 224); + assert_eq!(offset_of!(PipelineParameters, output_color_standard), 36); + assert_eq!(offset_of!(PipelineParameters, rotation_state), 92); + assert_eq!(offset_of!(PipelineParameters, input_surface_flag), 124); + assert_eq!(offset_of!(PipelineParameters, input_color_properties), 132); + assert_eq!(offset_of!(PipelineParameters, output_color_properties), 140); + assert_eq!(offset_of!(PipelineParameters, processing_mode), 148); + assert_eq!(offset_of!(ColorProperties, color_range), 1); + } +} diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index 4f8e2ad..18d0cac 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -41,19 +41,21 @@ fn decoder(codec: Codec) -> Option> { } } -/// Twelve frames of the moving test pattern, a keyframe forced at 8, a -/// bitrate change at 5: keyframes where asked, timestamps kept, and (with a -/// decoder) every picture decodable at PSNR > 28 dB. -fn roundtrip(name: &'static str) { - let screen = SyntheticScreen::new(W, H); +/// Twelve frames of the moving test pattern at `w` x `h`, a keyframe forced +/// at 8, a bitrate change at 5: keyframes where asked, timestamps kept, and +/// (with a decoder) every picture decodable at its own size, PSNR > 28 dB. +fn roundtrip(name: &'static str, w: u32, h: u32) { + let screen = SyntheticScreen::new(w, h); let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() }; let mut encoder = FfmpegEncoder::new(name, config).unwrap(); assert_eq!(encoder.backend(), EncoderBackend::Ffmpeg(name)); + let (aw, ah) = probe().iter().find(|s| s.spec.name == name).unwrap().alignment; let codec = encoder.codec(); let mut decoder = decoder(codec); let mut keyframes = Vec::new(); let mut sent = Vec::new(); let mut decoded = 0; + let mut worst = f64::INFINITY; let mut sources = Vec::new(); // Frames in until the first packet came out (the encoder's delay). let mut delay = None; @@ -81,15 +83,25 @@ fn roundtrip(name: &'static str) { if let Some(decoder) = &mut decoder && let Some(picture) = decoder.decode(&f.data).unwrap() { - assert_eq!((picture.width, picture.height), (W, H)); - let psnr = convert::psnr(&sources[index], &picture).unwrap(); - assert!(psnr > 28.0, "{name} frame {index}: PSNR {psnr:.1} dB"); + // The top-left part the encoder's alignment allows, never + // padding (which the viewer would see). + let (pw, ph) = (picture.width, picture.height); + assert!( + pw <= w && ph <= h && w - pw < aw && h - ph < ah, + "{name}: {w}x{h} decoded as {pw}x{ph} (alignment {aw}x{ah})" + ); + let mut source = sources[index].view(); + (source.width, source.height) = (pw, ph); + let psnr = convert::psnr(&source.to_frame(), &picture).unwrap(); + assert!(psnr > 28.0, "{name} {w}x{h} frame {index}: PSNR {psnr:.1} dB"); + worst = worst.min(psnr); decoded += 1; } } } eprintln!( - "{name}: {} packets from {} frames (first after {delay:?}), keyframes at {keyframes:?}, decoded {decoded}", + "{name} {w}x{h} (alignment {aw}x{ah}): {} packets from {} frames (first after \ + {delay:?}), keyframes at {keyframes:?}, decoded {decoded}, lowest PSNR {worst:.1} dB", sent.len(), sources.len() ); @@ -139,7 +151,7 @@ fn software_encoders_roundtrip() { let mut tested = Vec::new(); for name in ["libx264", "libopenh264", "libsvtav1", "librav1e", "libaom-av1"] { if available(name) { - roundtrip(name); + roundtrip(name, W, H); tested.push(name); } else { eprintln!("{name} skipped: not available"); @@ -148,6 +160,40 @@ 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. +/// +/// Also at 1920x1080, which is not a whole number of 16-pixel macroblocks: +/// the H.264 SPS has to crop the 1088 coded rows, and AV1 has no cropping at +/// all, so a GPU that only encodes aligned sizes shows as a wrong decoded +/// size. +/// +/// 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, W, H); + roundtrip(name, 1920, 1080); + } + eprintln!("tested: {names:?}"); +} + #[test] fn x264_is_constrained_high_and_changes_size() { if ffmpeg().is_none() || !available("libx264") { @@ -183,11 +229,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 +256,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") { @@ -255,29 +400,46 @@ fn bitrate_changes_without_live_reconfiguration() { assert!(!key(&mut encoder, 6, false)); } -/// DMA-BUF import is for VA-API encoders and NV12 buffers; anything else is -/// refused as unavailable, so the caller maps the buffer instead. +/// DMA-BUF import is for VA-API encoders and NV12 or RGB buffers; anything +/// else is refused as unavailable, so the caller maps the buffer instead. A +/// buffer the driver cannot import is an error, not a crash: the encoder +/// takes the next frame, and drops cleanly although nothing went in (FFmpeg +/// 9's VA-API encoders crash when drained before their first frame). #[cfg(target_os = "linux")] #[test] fn dmabuf_import_is_refused_cleanly() { + use std::os::fd::AsRawFd; use voelin_media::capture::{DRM_MOD_LINEAR, DmaBufRef, drm_fourcc}; if ffmpeg().is_none() { return; } + let not_a_dmabuf = std::fs::File::open("/dev/null").unwrap(); let frame = DmaBufRef { width: W, height: H, timestamp: Duration::ZERO, fourcc: drm_fourcc(b"XR24"), modifier: DRM_MOD_LINEAR, - fd: -1, + fd: not_a_dmabuf.as_raw_fd(), size: (W * H * 4) as usize, planes: [(0, (W * 4) as usize), (0, 0), (0, 0), (0, 0)], plane_count: 1, }; - for name in ["libx264", "h264_vaapi"] { + let unavailable = |name: &str, frame: &DmaBufRef| { let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap(); - let err = encoder.encode_dmabuf(&frame, true, &mut |_| {}).unwrap_err(); + let err = encoder.encode_dmabuf(frame, true, &mut |_| {}).unwrap_err(); assert!(matches!(err, voelin_media::Error::CodecUnavailable { .. }), "{name}: {err}"); + }; + unavailable("libx264", &frame); + unavailable("h264_vaapi", &DmaBufRef { fourcc: drm_fourcc(b"YUYV"), ..frame }); + if !available("h264_vaapi") { + return; } + let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + assert!(encoder.encode_dmabuf(&frame, true, &mut |_| {}).is_err(), "/dev/null imported"); + drop(encoder); + let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap(); + assert!(encoder.encode_dmabuf(&frame, true, &mut |_| {}).is_err()); + let black = voelin_media::VideoFrame::black_i420(W, H); + assert!(!encoder.encode(&black, true).unwrap().is_empty(), "no packet after a failed import"); } diff --git a/crates/voelin-media/tests/pipewire_apps.rs b/crates/voelin-media/tests/pipewire_apps.rs index da12d5a..94e0f37 100644 --- a/crates/voelin-media/tests/pipewire_apps.rs +++ b/crates/voelin-media/tests/pipewire_apps.rs @@ -200,7 +200,34 @@ impl Daemons { std::fs::write( conf.join("voelin-test-sink.conf"), "context.objects = [ { factory = adapter args = { factory.name = support.null-audio-sink \ - node.name = voelin-test-sink media.class = Audio/Sink audio.position = [ FL FR ] } } ]\n", + node.name = voelin-test-sink media.class = Audio/Sink audio.position = [ FL FR ] \ + priority.session = 3000 priority.driver = 3000 } } ]\n", + ) + .unwrap(); + // No hardware: WirePlumber's default profile monitors the sound + // cards, Bluetooth and cameras, and the tones would play on the + // machine's real speakers. 0.5 reads the profile, 0.4 the Lua + // fragments; each ignores the other's files. + let wireplumber_conf = dir.join("config/wireplumber"); + for sub in ["wireplumber.conf.d", "main.lua.d", "bluetooth.lua.d"] { + std::fs::create_dir_all(wireplumber_conf.join(sub)).unwrap(); + } + std::fs::write( + wireplumber_conf.join("wireplumber.conf.d/voelin-test.conf"), + "wireplumber.profiles = { main = { hardware.audio = disabled \ + hardware.bluetooth = disabled hardware.video-capture = disabled } }\n", + ) + .unwrap(); + std::fs::write( + wireplumber_conf.join("main.lua.d/51-voelin-test.lua"), + "if alsa_monitor then alsa_monitor.enabled = false end\n\ + if v4l2_monitor then v4l2_monitor.enabled = false end\n\ + if libcamera_monitor then libcamera_monitor.enabled = false end\n", + ) + .unwrap(); + std::fs::write( + wireplumber_conf.join("bluetooth.lua.d/51-voelin-test.lua"), + "if bluez_monitor then bluez_monitor.enabled = false end\n", ) .unwrap(); let mut command = Command::new(pipewire); diff --git a/crates/voelin-platform/Cargo.toml b/crates/voelin-platform/Cargo.toml index d55c6cc..7f8a538 100644 --- a/crates/voelin-platform/Cargo.toml +++ b/crates/voelin-platform/Cargo.toml @@ -10,7 +10,8 @@ publish.workspace = true [features] default = ["portal", "x11"] -# Wayland global shortcuts through xdg-desktop-portal (Linux). +# Wayland global shortcuts and the file chooser through xdg-desktop-portal +# (Linux). portal = ["dep:ashpd", "dep:futures-util"] # X11 global hotkeys through XInput2 raw events (Linux). x11 = ["dep:x11rb"] @@ -23,7 +24,7 @@ tokio = { version = "1", features = ["rt", "sync"] } tracing = "0.1" [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] -ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts"], optional = true } +ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser"], optional = true } futures-util = { version = "0.3", optional = true } notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] } x11rb = { version = "0.13", features = ["xinput"], optional = true } diff --git a/crates/voelin-platform/src/files.rs b/crates/voelin-platform/src/files.rs new file mode 100644 index 0000000..c28bf91 --- /dev/null +++ b/crates/voelin-platform/src/files.rs @@ -0,0 +1,84 @@ +//! Asking the user for a file. +//! +//! Linux uses xdg-desktop-portal's file chooser (feature `portal`), which +//! works on Wayland and X11 and inside a Flatpak. Other platforms have no +//! backend yet; [`available`] says so, so a window can hide what it cannot +//! offer. + +use std::path::PathBuf; + +use crate::{Error, Result}; + +/// Whether [`pick_file`] can ask the user. +pub const fn available() -> bool { + cfg!(all(unix, not(target_os = "macos"), feature = "portal")) +} + +/// Ask the user for one existing file; `None` when they cancelled. +pub async fn pick_file(title: &str) -> Result> { + #[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] + return portal_pick(title).await; + #[cfg(not(all(unix, not(target_os = "macos"), feature = "portal")))] + { + let _ = title; + Err(Error::Unsupported("no file chooser on this platform".into())) + } +} + +#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] +async fn portal_pick(title: &str) -> Result> { + use ashpd::desktop::file_chooser::SelectedFiles; + + let request = SelectedFiles::open_file() + .title(title) + .multiple(false) + .modal(true) + .send() + .await + .map_err(|e| Error::Backend(e.to_string()))?; + let files = match request.response() { + Ok(files) => files, + // Cancelling is not a failure. + Err(ashpd::Error::Response(_)) => return Ok(None), + Err(e) => return Err(Error::Backend(e.to_string())), + }; + Ok(files.uris().first().and_then(|uri| file_uri_path(uri.as_str()))) +} + +/// The path of a `file://` URI, with percent escapes resolved. +#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))] +fn file_uri_path(uri: &str) -> Option { + let rest = uri.strip_prefix("file://")?; + // file:///path and file://localhost/path both mean a local file. + let path = rest.strip_prefix("localhost").unwrap_or(rest); + let bytes = path.as_bytes(); + let mut out: Vec = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?; + if let Ok(byte) = u8::from_str_radix(hex, 16) { + out.push(byte); + i += 3; + continue; + } + } + out.push(bytes[i]); + i += 1; + } + let path = PathBuf::from(String::from_utf8(out).ok()?); + path.is_absolute().then_some(path) +} + +#[cfg(all(test, unix, not(target_os = "macos"), feature = "portal"))] +mod tests { + use super::*; + + #[test] + fn paths_of_file_uris() { + assert_eq!(file_uri_path("file:///tmp/a%20b.png"), Some("/tmp/a b.png".into())); + assert_eq!(file_uri_path("file://localhost/tmp/x"), Some("/tmp/x".into())); + assert_eq!(file_uri_path("https://example.com/x"), None); + assert_eq!(file_uri_path("file://relative"), None); + } +} diff --git a/crates/voelin-platform/src/lib.rs b/crates/voelin-platform/src/lib.rs index aa406ff..47a62f0 100644 --- a/crates/voelin-platform/src/lib.rs +++ b/crates/voelin-platform/src/lib.rs @@ -3,12 +3,14 @@ //! - [`hotkey`]: global push-to-talk hotkeys with press and release events //! (xdg-desktop-portal on Wayland, XInput2 on X11, a keyboard hook on //! Windows) +//! - [`files`]: asking the user for a file (xdg-desktop-portal) //! - [`notify`]: desktop notifications //! - [`paths`]: data, config, cache and state directories //! - [`crash`]: opt-in local crash reports (panic hook) //! - [`notices`]: third-party notices for the About page pub mod crash; +pub mod files; pub mod hotkey; pub mod notices; pub mod notify; diff --git a/crates/voelin-stream/src/peer.rs b/crates/voelin-stream/src/peer.rs index e1e99e9..320e1c9 100644 --- a/crates/voelin-stream/src/peer.rs +++ b/crates/voelin-stream/src/peer.rs @@ -178,6 +178,11 @@ pub enum PeerError { Io(#[from] std::io::Error), #[error("invalid SDP: {0}")] Sdp(String), + /// The offer's video uses none of the codecs we decode. + #[error( + "no video codec in common: the stream offers {offered}, this client decodes {accepted}" + )] + NoCommonCodec { offered: String, accepted: String }, #[error("WebRTC: {0}")] Rtc(#[from] RtcError), #[error("no usable local address")] @@ -304,10 +309,24 @@ impl Peer { /// Viewer side: accept the streamer's offer; returns our SDP answer. pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> { // Our codecs in the order of the offer, then the rest. - let mut codecs: Vec<_> = offered_video_codecs(offer) - .into_iter() - .filter(|c| config.accept_video_codecs.contains(c)) - .collect(); + let offered = offered_video_codecs(offer); + let mut codecs: Vec<_> = + offered.iter().copied().filter(|c| config.accept_video_codecs.contains(c)).collect(); + // Without one, the answer's video section would list no payload type, + // which no peer (str0m included) can parse. + if config.video + && codecs.is_empty() + && offer.lines().any(|l| l.trim_start().starts_with("m=video ")) + { + let names = |codecs: &[VideoCodec]| match codecs { + [] => "none we know".to_owned(), + _ => codecs.iter().map(|c| c.sdp_name()).collect::>().join(", "), + }; + return Err(PeerError::NoCommonCodec { + offered: names(&offered), + accepted: names(&config.accept_video_codecs), + }); + } for c in &config.accept_video_codecs { if !codecs.contains(c) { codecs.push(*c); @@ -924,6 +943,23 @@ mod tests { assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); } + /// An offer of codecs we cannot decode is refused with the reason, not + /// answered with a video section the streamer cannot parse. + #[tokio::test] + async fn no_common_codec_is_refused() { + let streamer = + PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() }; + let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap(); + let vp8_only = + PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() }; + let error = Peer::answer(&vp8_only, &offer).await.err().expect("refused"); + assert!(matches!(error, PeerError::NoCommonCodec { .. }), "{error}"); + assert_eq!( + error.to_string(), + "no video codec in common: the stream offers H264, this client decodes VP8" + ); + } + /// Several codecs offered: the streamer learns which one each viewer's /// answer chose; H.264 carries the level the stream needs. #[tokio::test] diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index c10e18b..f56c220 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -31,6 +31,8 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } unicode-segmentation = "1.13" voelin-audio = { path = "../voelin-audio" } voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device"] } +# Gateway data types (topics, pins, reactions, capability names). +voelin-gateway-proto = { path = "../voelin-gateway-proto" } voelin-model = { path = "../voelin-model" } # Crash reports and notices everywhere; hotkey backends on desktop (below). voelin-platform = { path = "../voelin-platform", default-features = false } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 6e52435..fc42ae1 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -19,8 +19,10 @@ use tokio::runtime::Runtime; use tracing::warn; use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings}; use voelin_core::stream::StreamInfo; -use voelin_core::{AudioSettings, Command, Engine, Event, SessionState, VoiceState}; -use voelin_model::{Capabilities, ChannelId, ChatTarget, Presence}; +use voelin_core::{ + AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState, +}; +use voelin_model::{Capabilities, ChannelId, ChatTarget, GroupInfo, Presence}; use voelin_platform::crash; use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; @@ -108,20 +110,76 @@ impl Secrets for FallbackSecrets { } } +/// A message of a chat with the handle the UI knows it by: the engine's +/// local ids are 64 bit, a Slint `int` is not. +pub(crate) struct Msg { + pub key: i32, + pub message: HistoryMessage, +} + /// A chat of a session: its lines are the model the chat view shows while /// the tab is selected, so a new message is one row appended. pub(crate) struct Tab { pub target: ChatTarget, pub title: String, pub lines: Rc>, - /// The last message, for grouping the next one. + /// The messages, oldest first, by `(ts_ms, id)`. + pub messages: Vec, + /// Live messages of a session that keeps no history (no server unique + /// id yet): grouped from the message before, without ids. pub last: Option, pub unread: i32, + /// Nothing older exists as far as the engine can tell. + pub complete: bool, + /// A gateway page arrived: the chat is not only what we saw. + pub synced: bool, + /// An older page was asked for. + pub loading: bool, + /// The next message handle. + next_key: i32, + /// The pins of this chat, once asked for. + pub pins: Vec, + pub pins_loaded: bool, + /// The gateway topics of this chat, and the open one with its messages. + pub topics: Vec, + pub topics_loaded: bool, + pub topic: Option, + pub topic_messages: Vec, + /// The message jumped to from the pins. + pub marked: Option, } impl Tab { pub fn new(target: ChatTarget, title: String) -> Self { - Self { target, title, lines: Rc::new(VecModel::default()), last: None, unread: 0 } + Self { + target, + title, + lines: Rc::new(VecModel::default()), + messages: Vec::new(), + last: None, + unread: 0, + complete: false, + synced: false, + loading: false, + next_key: 1, + pins: Vec::new(), + pins_loaded: false, + topics: Vec::new(), + topics_loaded: false, + topic: None, + topic_messages: Vec::new(), + marked: None, + } + } + + /// A handle for a message that has none yet. + pub fn take_key(&mut self) -> i32 { + self.next_key += 1; + self.next_key + } + + pub fn message(&self, key: i32) -> Option<&HistoryMessage> { + self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message) } } @@ -140,6 +198,23 @@ pub(crate) struct SessionView { pub streams: Vec, /// Clients whose stored volume was sent for this voice connection. pub applied_playback: HashSet, + /// Avatar pictures in the engine's cache, by unique id + /// ([`Event::AvatarReady`]). + pub avatars: HashMap, + /// Icons in the engine's cache, by icon id ([`Event::IconReady`]). + pub icons: HashMap, + /// The server groups in display order ([`Event::Groups`]). + pub server_groups: Vec, + /// What the session's gateway offers (`voelin_gateway_proto::feature`). + pub gateway_caps: Vec, + /// The client whose member card is open. + pub member_card: Option, + /// Viewers of the streams in the gateway's directory, by stream id. + pub stream_viewers: HashMap, + /// Downloads started from chat, by transfer id. + pub downloads: HashMap, + /// The next transfer id. + pub next_transfer: u64, } impl Default for SessionView { @@ -155,6 +230,14 @@ impl Default for SessionView { focused_own_channel: false, streams: Vec::new(), applied_playback: HashSet::new(), + avatars: HashMap::new(), + icons: HashMap::new(), + server_groups: Vec::new(), + gateway_caps: Vec::new(), + member_card: None, + stream_viewers: HashMap::new(), + downloads: HashMap::new(), + next_transfer: 1, } } } @@ -177,6 +260,24 @@ impl SessionView { pub fn unread(&self) -> i32 { self.tabs.iter().map(|t| t.unread).sum() } + + /// The session's gateway offers this feature + /// (`voelin_gateway_proto::feature`). + pub fn gateway_has(&self, feature: &str) -> bool { + self.gateway_caps.iter().any(|c| c == feature) + } + + /// The chat history is kept by the engine (it knows the server): its + /// messages come with ids, reactions and pins. + pub fn has_history(&self) -> bool { + self.state.server_uid.is_some() + } + + /// The avatar picture of a client, if the engine fetched one. + pub fn avatar(&self, client: u16) -> Option<&PathBuf> { + let uid = self.presence.clients.get(&client)?.uid.as_deref()?; + self.avatars.get(uid) + } } /// The models the Bridge shows, created once and updated row by row @@ -185,9 +286,15 @@ pub(crate) struct Models { pub servers: Rc>, pub tree: Rc>, pub members: Rc>, + pub server_members: Rc>, pub tabs: Rc>, pub streams: Rc>, pub viewers: Rc>, + pub pins: Rc>, + pub topics: Rc>, + pub topic_messages: Rc>, + /// The quality choices of the watched stream. + pub qualities: Rc>, /// Shown when there is no chat. pub no_chat: Rc>, } @@ -198,17 +305,27 @@ impl Models { servers: Rc::default(), tree: Rc::default(), members: Rc::default(), + server_members: Rc::default(), tabs: Rc::default(), streams: Rc::default(), viewers: Rc::default(), + pins: Rc::default(), + topics: Rc::default(), + topic_messages: Rc::default(), + qualities: Rc::default(), no_chat: Rc::default(), }; bridge.set_servers(ModelRc::from(models.servers.clone())); bridge.set_tree(ModelRc::from(models.tree.clone())); bridge.set_members(ModelRc::from(models.members.clone())); + bridge.set_server_members(ModelRc::from(models.server_members.clone())); bridge.set_tabs(ModelRc::from(models.tabs.clone())); bridge.set_streams(ModelRc::from(models.streams.clone())); bridge.set_share_viewers(ModelRc::from(models.viewers.clone())); + bridge.set_pins(ModelRc::from(models.pins.clone())); + bridge.set_topics(ModelRc::from(models.topics.clone())); + bridge.set_topic_messages(ModelRc::from(models.topic_messages.clone())); + bridge.set_viewer_qualities(ModelRc::from(models.qualities.clone())); bridge.set_messages(ModelRc::from(models.no_chat.clone())); models } @@ -227,6 +344,13 @@ pub(crate) struct App { pub status: String, /// The top bar's search: filters the channel tree. pub tree_filter: String, + /// The members panel's search. + pub member_filter: String, + /// The topics drawer's search. + pub topic_filter: String, + /// The voice channel view is shown (its people come first in the + /// members panel). + pub voice_view: bool, /// The settings service (shared with the engine); `settings`, `audio` /// and `playback` are working copies of its keys. pub prefs: Settings, @@ -237,6 +361,8 @@ pub(crate) struct App { pub inputs: DeviceChoices, pub outputs: DeviceChoices, pub playback: ClientPlaybackMap, + /// The engine's contacts, by unique id ([`Event::ContactsChanged`]). + pub contacts: HashMap, /// The client in the volume dialog: session, client id, unique id. pub playback_dialog: Option<(i64, u16, Option)>, pub mic_test: bool, @@ -261,6 +387,9 @@ pub(crate) struct App { pub open_client_pending: bool, /// The notices are in the About page's model. pub notices_loaded: bool, + /// Files being uploaded to a channel from the composer: session, + /// channel and name, so the link can be posted when they are up. + pub uploads: HashMap, /// The Stream Studio (studio.rs). pub studio: crate::studio::StudioState, } @@ -373,6 +502,12 @@ pub fn run(options: RunOptions) -> Result<()> { }; let store = Store::open(&dir.join("client.db")).context("failed to open the client database")?; + // Chat history and contacts live in the client database; without this + // the engine would keep them for this run only. + match History::open(&dir.join("client.db")) { + Ok(history) => engine.send(Command::AttachHistory(history)), + Err(e) => warn!(%e, "chat history is not stored this time"), + } let identity = match store.identities()?.first() { Some(entry) => store.identity(entry.id)?, None => { @@ -425,6 +560,9 @@ pub fn run(options: RunOptions) -> Result<()> { models, status: String::new(), tree_filter: String::new(), + member_filter: String::new(), + topic_filter: String::new(), + voice_view: false, prefs, settings, audio, @@ -432,6 +570,7 @@ pub fn run(options: RunOptions) -> Result<()> { inputs: DeviceChoices::default(), outputs: DeviceChoices::default(), playback, + contacts: HashMap::new(), playback_dialog: None, mic_test: false, ptt, @@ -446,6 +585,7 @@ pub fn run(options: RunOptions) -> Result<()> { autoshare: switches.autoshare, open_client_pending: switches.open_client, notices_loaded: false, + uploads: HashMap::new(), studio: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); @@ -666,7 +806,49 @@ impl App { Event::MicrophoneTestError { message } => { self.set_status(format!("Microphone test: {message}")) } - Event::Chat { session, message } => self.add_message(session as i64, message), + // Only for sessions the engine keeps no history for (it does not + // know the server yet): those get ids and reactions instead. + Event::Chat { session, message } => { + let id = session as i64; + if !self.sessions.entry(id).or_default().has_history() { + self.add_message(id, message); + } + } + Event::ChatHistory { session, target, messages, source, complete } => { + self.history_batch(session as i64, &target, messages, source, complete); + } + Event::Gateway { session, update } => self.gateway_update(session as i64, update), + Event::Groups { session, server_groups, .. } => { + let view = self.sessions.entry(session as i64).or_default(); + view.server_groups = (*server_groups).clone(); + // Display order, as TeamSpeak sorts them. + view.server_groups.sort_by_key(|g| (g.sort_id, g.id)); + if self.current == Some(session as i64) { + self.refresh_tree(); + } + } + Event::AvatarReady { session, client_uid, path, .. } => { + let view = self.sessions.entry(session as i64).or_default(); + view.avatars.insert(client_uid, path); + if self.current == Some(session as i64) { + self.refresh_tree(); + self.refresh_chat(); + } + } + Event::IconReady { session, icon, path } => { + let view = self.sessions.entry(session as i64).or_default(); + view.icons.insert(icon, path); + if self.current == Some(session as i64) { + self.refresh_tree(); + } + } + Event::Transfer { session, transfer, state } => { + self.transfer_progress(session as i64, transfer, state); + } + Event::ContactsChanged { contacts } => { + self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); + self.refresh_member_card(); + } // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. Event::Error { .. } if self.demo_ui => {} Event::Error { message, .. } => self.set_status(message), diff --git a/crates/voelin-ui/src/appearance.rs b/crates/voelin-ui/src/appearance.rs index ac4cc5f..93d329b 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -8,7 +8,7 @@ use tracing::warn; use crate::app::{App, AppearanceForm, Bridge, Nav, Theme}; use crate::images; use crate::settings::{ - ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_NARROW_BREAKPOINT, UI_THEME, + ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT, UI_THEME, }; impl App { @@ -23,7 +23,12 @@ impl App { let t = ui.global::(); t.set_mode(theme.as_str().into()); t.set_font_scale(scale); - ui.global::