From badfb328a02f579ee5bb34743c2bf72f13149fd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 19:15:38 +0000 Subject: [PATCH 1/9] voelin-media: load FFmpeg at runtime for more video encoders (WIP) Hardware encoders (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox) and more software ones (x264, OpenH264, SVT-AV1, rav1e, libaom) through whatever FFmpeg is installed, found with libloading and never linked. Codec settings go through AVOptions only; the few struct fields without an accessor are located and checked at runtime, so any major version with a matching layout works. Each backend encodes one test frame at startup and is skipped with a reason if that fails. Codecs gains an encoder preference (hardware on/off, auto / software / a named backend) and a report of every backend for the UI. Codec gets H265 for peers that negotiate HEVC. Work in progress: committed early so it cannot be lost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/Cargo.toml | 7 +- crates/voelin-media/src/codec/h264.rs | 11 +- crates/voelin-media/src/codec/hw.rs | 114 +- crates/voelin-media/src/codec/mediacodec.rs | 5 +- crates/voelin-media/src/codec/mod.rs | 328 ++++- crates/voelin-media/src/ffmpeg/encoder.rs | 1199 +++++++++++++++++++ crates/voelin-media/src/ffmpeg/layout.rs | 411 +++++++ crates/voelin-media/src/ffmpeg/mod.rs | 247 ++++ crates/voelin-media/src/ffmpeg/sys.rs | 569 +++++++++ crates/voelin-media/src/lib.rs | 10 +- 10 files changed, 2773 insertions(+), 128 deletions(-) create mode 100644 crates/voelin-media/src/ffmpeg/encoder.rs create mode 100644 crates/voelin-media/src/ffmpeg/layout.rs create mode 100644 crates/voelin-media/src/ffmpeg/mod.rs create mode 100644 crates/voelin-media/src/ffmpeg/sys.rs diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 1dccab6..fb44818 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -9,7 +9,7 @@ repository.workspace = true publish.workspace = true [features] -default = ["vpx", "openh264", "openh264-download", "x11", "pipewire", "wlroots"] +default = ["vpx", "openh264", "openh264-download", "ffmpeg", "x11", "pipewire", "wlroots"] # VP8 and VP9 through the system libvpx (pkg-config `vpx`). vpx = ["dep:libvpx-native-sys"] # H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The @@ -17,6 +17,10 @@ vpx = ["dep:libvpx-native-sys"] openh264 = ["dep:openh264"] # Download of Cisco's OpenH264 binary over HTTPS with a SHA-256 check. 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"] # AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3). av1 = ["dep:dav1d"] # X11 screen capture (Linux). @@ -33,6 +37,7 @@ str0m = ["dep:str0m"] [dependencies] bzip2 = { version = "0.6.1", optional = true } dav1d = { version = "0.11.1", optional = true } +libloading = { version = "0.8.9", optional = true } libvpx-native-sys = { version = "5.0.17", optional = true } openh264 = { version = "0.9.8", default-features = false, features = ["libloading"], optional = true } reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true } diff --git a/crates/voelin-media/src/codec/h264.rs b/crates/voelin-media/src/codec/h264.rs index d1a8a4c..68675ad 100644 --- a/crates/voelin-media/src/codec/h264.rs +++ b/crates/voelin-media/src/codec/h264.rs @@ -173,14 +173,7 @@ impl OpenH264 { } } -/// H.264 profile of the encoder output. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum H264Profile { - /// Constrained High (what TeamSpeak clients decode). - #[default] - ConstrainedHigh, - ConstrainedBaseline, -} +pub use super::H264Profile; /// OpenH264 encoder. pub struct OpenH264Encoder { @@ -196,8 +189,8 @@ impl OpenH264Encoder { fn new(library: OpenH264, config: EncoderConfig) -> Result { let mut encoder = Self { library, + profile: config.h264_profile, config, - profile: H264Profile::default(), encoder: None, output: Vec::new(), }; diff --git a/crates/voelin-media/src/codec/hw.rs b/crates/voelin-media/src/codec/hw.rs index 5d26b17..3d80de0 100644 --- a/crates/voelin-media/src/codec/hw.rs +++ b/crates/voelin-media/src/codec/hw.rs @@ -1,38 +1,44 @@ -//! Hardware video encoders. +//! Encoder factories found at runtime. //! -//! The streamer prefers a GPU encoder over software VP8 / OpenH264. None is -//! implemented yet; the factories below mark where they plug in: -//! -//! - Linux: VA-API (H.264 Constrained High / VP8 / VP9 on Intel and AMD), e.g. -//! through `cros-libva`. TODO. -//! - Windows: Media Foundation H.264 encoder MFT (NVENC / QuickSync / AMF -//! behind it). TODO. +//! - FFmpeg (feature `ffmpeg`, desktop): VA-API, NVENC, Quick Sync, AMF, +//! Media Foundation and VideoToolbox encoders, plus software ones FFmpeg +//! wraps (x264, OpenH264, SVT-AV1, rav1e, libaom); one factory per backend +//! that passed its self-test ([`crate::ffmpeg::probe`]). //! - Android: MediaCodec ([`super::mediacodec`]). use crate::Result; -use crate::codec::{Codec, EncoderConfig, VideoEncoder}; +use crate::codec::{Codec, EncoderBackend, EncoderConfig, VideoEncoder}; -/// Creates encoders of one hardware API. -pub trait HardwareEncoderFactory: Send + Sync { - /// Short name for logs and settings (`"vaapi"`, `"mediafoundation"`). +/// Creates encoders of one backend. +pub trait EncoderFactory: Send + Sync { + /// Short name for logs and settings (`"h264_vaapi"`, `"mediacodec"`). fn name(&self) -> &'static str; - /// Codecs this device can encode, best first. + /// Codecs this backend encodes, best first. fn codecs(&self) -> Vec; fn create(&self, codec: Codec, config: &EncoderConfig) -> Result>; + + /// A GPU / OS encoder (the default), as opposed to a software encoder + /// reached through the same API (FFmpeg's libx264, ...). + fn is_hardware(&self) -> bool { + true + } + + /// The backend its encoders report. + fn backend(&self) -> EncoderBackend { + EncoderBackend::Hardware(self.name()) + } } -/// Hardware encoders usable on this machine (none yet). -pub fn probe() -> Vec> { - let mut found: Vec> = Vec::new(); - #[cfg(target_os = "linux")] - if let Some(f) = vaapi::probe() { - found.push(Box::new(f)); - } - #[cfg(windows)] - if let Some(f) = media_foundation::probe() { - found.push(Box::new(f)); +/// Encoder factories usable on this machine: FFmpeg's backends that passed +/// their self-test, then MediaCodec (Android). +pub fn probe() -> Vec> { + #[allow(unused_mut)] + let mut found: Vec> = Vec::new(); + #[cfg(feature = "ffmpeg")] + for factory in crate::ffmpeg::FfmpegFactory::available() { + found.push(Box::new(factory)); } #[cfg(target_os = "android")] if let Some(f) = super::mediacodec::probe() { @@ -40,65 +46,3 @@ pub fn probe() -> Vec> { } found } - -#[cfg(target_os = "linux")] -mod vaapi { - use super::*; - use crate::Error; - - pub struct Vaapi; - - /// TODO: open the DRM render node, query VAProfileH264ConstrainedBaseline / - /// VAProfileH264High / VP8 / VP9 encode entrypoints. - pub fn probe() -> Option { - None - } - - impl HardwareEncoderFactory for Vaapi { - fn name(&self) -> &'static str { - "vaapi" - } - - fn codecs(&self) -> Vec { - Vec::new() - } - - fn create(&self, codec: Codec, _: &EncoderConfig) -> Result> { - Err(Error::CodecUnavailable { - codec, - reason: "VA-API encoding is not implemented".into(), - }) - } - } -} - -#[cfg(windows)] -mod media_foundation { - use super::*; - use crate::Error; - - pub struct MediaFoundation; - - /// TODO: enumerate hardware H.264 encoder MFTs (`MFTEnumEx` with - /// `MFT_ENUM_FLAG_HARDWARE`). - pub fn probe() -> Option { - None - } - - impl HardwareEncoderFactory for MediaFoundation { - fn name(&self) -> &'static str { - "mediafoundation" - } - - fn codecs(&self) -> Vec { - Vec::new() - } - - fn create(&self, codec: Codec, _: &EncoderConfig) -> Result> { - Err(Error::CodecUnavailable { - codec, - reason: "Media Foundation encoding is not implemented".into(), - }) - } - } -} diff --git a/crates/voelin-media/src/codec/mediacodec.rs b/crates/voelin-media/src/codec/mediacodec.rs index f5f941b..0cd9df5 100644 --- a/crates/voelin-media/src/codec/mediacodec.rs +++ b/crates/voelin-media/src/codec/mediacodec.rs @@ -24,7 +24,7 @@ use ndk::media::media_codec::{ use ndk::media::media_format::MediaFormat; use tracing::{debug, info}; -use super::hw::HardwareEncoderFactory; +use super::hw::EncoderFactory; use super::image_layout::{ COLOR_FORMAT_FLEXIBLE, COLOR_FORMAT_I420, COLOR_FORMAT_NV12, ImageLayout, }; @@ -56,6 +56,7 @@ fn mime(codec: Codec) -> &'static str { Codec::Vp9 => "video/x-vnd.on2.vp9", Codec::H264 => "video/avc", Codec::Av1 => "video/av01", + Codec::H265 => "video/hevc", } } @@ -145,7 +146,7 @@ pub struct MediaCodecFactory { codecs: Vec, } -impl HardwareEncoderFactory for MediaCodecFactory { +impl EncoderFactory for MediaCodecFactory { fn name(&self) -> &'static str { NAME } diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index e407a1c..5c4b634 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -7,7 +7,9 @@ //! - [`h264`] (feature `openh264`): H.264 with Cisco's prebuilt OpenH264, //! loaded at runtime //! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d -//! - [`hw`]: hardware encoders (VA-API, Media Foundation); not implemented yet +//! - [`hw`]: encoder factories found at runtime: FFmpeg's hardware and +//! software encoders ([`crate::ffmpeg`], feature `ffmpeg`) and, on Android, +//! MediaCodec //! - `mediacodec` (Android): the device's MediaCodec encoders and decoders //! (hardware, or Google's software VP8 / VP9 / H.264) @@ -28,17 +30,19 @@ pub mod mediacodec; #[cfg(feature = "vpx")] pub mod vpx; -/// Video codecs TeamSpeak 6 streams use. +/// Video codecs of streams: the four TeamSpeak 6 uses, and HEVC for peers +/// that negotiate it (offered last, hardware encoders only). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Codec { Vp8, Vp9, H264, Av1, + H265, } impl Codec { - pub const ALL: [Codec; 4] = [Codec::Vp8, Codec::Vp9, Codec::H264, Codec::Av1]; + pub const ALL: [Codec; 5] = [Codec::Vp8, Codec::Vp9, Codec::H264, Codec::Av1, Codec::H265]; /// Name as in SDP (`a=rtpmap: /90000`). pub fn name(self) -> &'static str { @@ -47,6 +51,7 @@ impl Codec { Codec::Vp9 => "VP9", Codec::H264 => "H264", Codec::Av1 => "AV1", + Codec::H265 => "H265", } } } @@ -69,6 +74,7 @@ impl FromStr for Codec { "vp9" => Ok(Codec::Vp9), "h264" | "h.264" | "avc" => Ok(Codec::H264), "av1" | "av1x" => Ok(Codec::Av1), + "h265" | "h.265" | "hevc" => Ok(Codec::H265), _ => Err(Error::Convert(format!("unknown codec {s:?}"))), } } @@ -82,6 +88,7 @@ impl From for str0m::format::Codec { Codec::Vp9 => str0m::format::Codec::Vp9, Codec::H264 => str0m::format::Codec::H264, Codec::Av1 => str0m::format::Codec::Av1, + Codec::H265 => str0m::format::Codec::H265, } } } @@ -96,6 +103,7 @@ impl TryFrom for Codec { str0m::format::Codec::Vp9 => Ok(Codec::Vp9), str0m::format::Codec::H264 => Ok(Codec::H264), str0m::format::Codec::Av1 => Ok(Codec::Av1), + str0m::format::Codec::H265 => Ok(Codec::H265), other => Err(Error::Convert(format!("not a video codec: {other:?}"))), } } @@ -114,6 +122,16 @@ pub enum ContentHint { Motion, } +/// H.264 profile of the encoder output. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum H264Profile { + /// Constrained High (what TeamSpeak clients decode): High without + /// B-frames. + #[default] + ConstrainedHigh, + ConstrainedBaseline, +} + /// Encoder settings. The resolution follows the frames: the first frame and /// every size change start a new keyframe. #[derive(Clone, Debug, PartialEq, Eq)] @@ -131,8 +149,12 @@ pub struct EncoderConfig { pub threads: u32, /// A fixed speed / quality trade-off in the backend's own terms (libvpx /// `cpu-used`); `None` lets the encoder adapt it to how long frames take - /// to encode compared to the frame interval. + /// to encode compared to the frame interval. FFmpeg backends: the x264 + /// preset index (0 ultrafast .. 9 placebo), the NVENC preset `p1`..`p7`, + /// the SVT-AV1 preset, rav1e's speed, libaom's `cpu-used`. pub speed: Option, + /// H.264 only. + pub h264_profile: H264Profile, } impl Default for EncoderConfig { @@ -144,6 +166,7 @@ impl Default for EncoderConfig { content: ContentHint::Screen, threads: 0, speed: None, + h264_profile: H264Profile::default(), } } } @@ -244,29 +267,143 @@ pub trait VideoDecoder: Send { fn decode(&mut self, data: &[u8]) -> Result>; } -/// Implementations behind [`VideoEncoder`], in the streamer's order of -/// preference. +/// Implementations behind [`VideoEncoder`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EncoderBackend { - /// An OS / GPU encoder (see [`hw`]). + /// An OS / GPU encoder of its own API (Android's `mediacodec`, see + /// [`hw`]). Hardware(&'static str), + /// An FFmpeg encoder by its FFmpeg name (`h264_vaapi`, `libx264`, see + /// [`crate::ffmpeg`]), hardware or software. + Ffmpeg(&'static str), Libvpx, OpenH264, } +impl EncoderBackend { + /// The name in settings (`stream.encoder_backend`) and logs. + pub fn name(self) -> &'static str { + match self { + EncoderBackend::Hardware(name) | EncoderBackend::Ffmpeg(name) => name, + EncoderBackend::Libvpx => "libvpx", + EncoderBackend::OpenH264 => "openh264", + } + } +} + +impl fmt::Display for EncoderBackend { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// Which encoders to use (settings `stream.hardware_acceleration` and +/// `stream.encoder_backend`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EncoderPreference { + /// Use hardware encoders when [`backend`](Self::backend) is `Auto`. + pub hardware: bool, + pub backend: BackendChoice, +} + +impl Default for EncoderPreference { + fn default() -> Self { + Self { hardware: true, backend: BackendChoice::Auto } + } +} + +/// `stream.encoder_backend`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum BackendChoice { + /// Hardware first (if enabled), then software. + #[default] + Auto, + /// Software encoders only. + Software, + /// This backend ([`EncoderBackend::name`]) for the codecs it encodes; + /// the automatic order for the others and as fallback. + Named(String), +} + +impl FromStr for BackendChoice { + type Err = std::convert::Infallible; + + fn from_str(s: &str) -> std::result::Result { + Ok(match s.trim() { + "" | "auto" => BackendChoice::Auto, + "software" => BackendChoice::Software, + name => BackendChoice::Named(name.to_owned()), + }) + } +} + +impl fmt::Display for BackendChoice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BackendChoice::Auto => f.write_str("auto"), + BackendChoice::Software => f.write_str("software"), + BackendChoice::Named(name) => f.write_str(name), + } + } +} + +/// One encoder backend in [`Codecs::report`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EncoderInfo { + /// [`EncoderBackend::name`]. + pub name: String, + /// The API or library (`VA-API`, `NVENC`, `x264`, `libvpx`, ...). + pub api: String, + pub codec: Codec, + pub hardware: bool, + /// Usable (passed its self-test), or why not. + pub status: std::result::Result<(), String>, + /// Position among the encoders of its codec under the current + /// preference (0: used first); `None` if not used. + pub rank: Option, +} + +/// Every encoder backend this build knows, what works here and why the +/// rest does not (for the UI and `voelinctl stream encoders`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EncoderReport { + /// The FFmpeg libraries in use (release, version, path), or why none. + pub ffmpeg: std::result::Result, + /// Whether captured DMA-BUFs can go to a VA-API encoder without a copy, + /// or why not. + pub zero_copy: std::result::Result<(), String>, + pub encoders: Vec, +} + fn unavailable(codec: Codec, reason: impl Into) -> Error { Error::CodecUnavailable { codec, reason: reason.into() } } +/// Order of codecs among hardware encoders: H.264 (every viewer decodes +/// it), AV1, VP9, VP8, and HEVC last (only for peers that take nothing +/// else). +const HARDWARE_ORDER: [Codec; 5] = [Codec::H264, Codec::Av1, Codec::Vp9, Codec::Vp8, Codec::H265]; + +/// An encoder backend in the base order (before the preference applies). +struct Candidate { + codec: Codec, + backend: EncoderBackend, + hardware: bool, +} + /// The codecs this build and machine can use, and factories for them. /// /// Viewer order ([`Codecs::decoders`]): VP9 > VP8 > AV1 > H.264. Streamer -/// order ([`Codecs::encoders`]): hardware > VP8 (libvpx) > H.264 (OpenH264) -/// > VP9 (libvpx, costly in software). +/// order ([`Codecs::encoders`]) under the default [`EncoderPreference`]: +/// hardware (H.264, AV1, VP9, VP8, HEVC; FFmpeg's or MediaCodec) > VP8 +/// (libvpx) > H.264 (x264 and OpenH264 through FFmpeg, then Cisco's +/// OpenH264) > VP9 (libvpx, costly in software) > AV1 (SVT-AV1, rav1e, +/// libaom through FFmpeg). pub struct Codecs { - hardware: Vec>, + factories: Vec>, #[cfg(feature = "openh264")] openh264: Option, + preference: EncoderPreference, } impl Default for Codecs { @@ -280,18 +417,21 @@ impl fmt::Debug for Codecs { f.debug_struct("Codecs") .field("decoders", &self.decoders()) .field("encoders", &self.encoders()) + .field("preference", &self.preference) .finish() } } impl Codecs { - /// Software codecs compiled in, plus whatever hardware encoders - /// [`hw::probe`] finds. H.264 needs [`Codecs::with_openh264`]. + /// Software codecs compiled in, plus the encoders [`hw::probe`] finds + /// (FFmpeg's that passed their self-test, MediaCodec). H.264 through + /// Cisco's library needs [`Codecs::with_openh264`]. pub fn new() -> Self { Self { - hardware: hw::probe(), + factories: hw::probe(), #[cfg(feature = "openh264")] openh264: None, + preference: EncoderPreference::default(), } } @@ -307,6 +447,21 @@ impl Codecs { self.openh264.as_ref() } + /// Use `preference` for [`encoders`](Self::encoders) and + /// [`new_encoder`](Self::new_encoder). + pub fn with_preference(mut self, preference: EncoderPreference) -> Self { + self.preference = preference; + self + } + + pub fn set_preference(&mut self, preference: EncoderPreference) { + self.preference = preference; + } + + pub fn preference(&self) -> &EncoderPreference { + &self.preference + } + fn has_openh264(&self) -> bool { #[cfg(feature = "openh264")] return self.openh264.is_some(); @@ -335,6 +490,7 @@ impl Codecs { #[cfg(not(feature = "av1"))] return Err(unavailable(codec, "built without the `av1` feature")); } + Codec::H265 => Err(unavailable(codec, "no HEVC decoder")), } } @@ -343,28 +499,59 @@ impl Codecs { VIEWER_PREFERENCE.into_iter().filter(|&c| self.check_decoder(c).is_ok()).collect() } - /// Encoders in the streamer's order of preference. - pub fn encoders(&self) -> Vec<(Codec, EncoderBackend)> { + /// Every usable encoder in the base order, before the preference. + fn candidates(&self) -> Vec { let mut list = Vec::new(); - for factory in &self.hardware { - for codec in factory.codecs() { - list.push((codec, EncoderBackend::Hardware(factory.name()))); + let factories = |codec: Codec, hardware: bool, list: &mut Vec| { + for f in self.factories.iter().filter(|f| f.is_hardware() == hardware) { + if f.codecs().contains(&codec) { + list.push(Candidate { codec, backend: f.backend(), hardware }); + } } + }; + for codec in HARDWARE_ORDER { + factories(codec, true, &mut list); } #[cfg(feature = "vpx")] if vpx::check(Codec::Vp8, true).is_ok() { - list.push((Codec::Vp8, EncoderBackend::Libvpx)); + list.push(Candidate { codec: Codec::Vp8, backend: EncoderBackend::Libvpx, hardware: false }); } + factories(Codec::H264, false, &mut list); if self.has_openh264() { - list.push((Codec::H264, EncoderBackend::OpenH264)); + let backend = EncoderBackend::OpenH264; + list.push(Candidate { codec: Codec::H264, backend, hardware: false }); } #[cfg(feature = "vpx")] if vpx::check(Codec::Vp9, true).is_ok() { - list.push((Codec::Vp9, EncoderBackend::Libvpx)); + list.push(Candidate { codec: Codec::Vp9, backend: EncoderBackend::Libvpx, hardware: false }); + } + for codec in [Codec::Av1, Codec::H265, Codec::Vp8, Codec::Vp9] { + factories(codec, false, &mut list); } list } + /// Encoders in the streamer's order of preference. + pub fn encoders(&self) -> Vec<(Codec, EncoderBackend)> { + self.encoders_for(&self.preference) + } + + /// Encoders in the order `preference` gives. + pub fn encoders_for(&self, preference: &EncoderPreference) -> Vec<(Codec, EncoderBackend)> { + let all = self.candidates(); + let automatic = |c: &Candidate| preference.hardware || !c.hardware; + let chosen: Vec<&Candidate> = match &preference.backend { + BackendChoice::Auto => all.iter().filter(|c| automatic(c)).collect(), + BackendChoice::Software => all.iter().filter(|c| !c.hardware).collect(), + BackendChoice::Named(name) => { + let named = all.iter().filter(|c| c.backend.name() == name); + let rest = all.iter().filter(|c| c.backend.name() != name && automatic(c)); + named.chain(rest).collect() + } + }; + chosen.into_iter().map(|c| (c.codec, c.backend)).collect() + } + /// Encodable codecs in the streamer's order of preference, without /// duplicates (for the offer). pub fn encoder_codecs(&self) -> Vec { @@ -403,16 +590,26 @@ impl Codecs { &self, codec: Codec, config: EncoderConfig, + ) -> Result> { + self.new_encoder_preferring(codec, config, &self.preference) + } + + /// As [`new_encoder`](Self::new_encoder) with another preference. + pub fn new_encoder_preferring( + &self, + codec: Codec, + config: EncoderConfig, + preference: &EncoderPreference, ) -> Result> { let mut last_error = None; - for (c, backend) in self.encoders() { + for (c, backend) in self.encoders_for(preference) { if c != codec { continue; } match self.new_encoder_with(codec, backend, config.clone()) { Ok(encoder) => return Ok(encoder), Err(e) => { - tracing::warn!(%codec, ?backend, "encoder backend failed: {e}"); + tracing::warn!(%codec, %backend, "encoder backend failed: {e}"); last_error = Some(e); } } @@ -428,12 +625,12 @@ impl Codecs { config: EncoderConfig, ) -> Result> { match backend { - EncoderBackend::Hardware(name) => { + EncoderBackend::Hardware(_) | EncoderBackend::Ffmpeg(_) => { let factory = self - .hardware + .factories .iter() - .find(|f| f.name() == name) - .ok_or_else(|| unavailable(codec, format!("no hardware encoder {name}")))?; + .find(|f| f.backend() == backend) + .ok_or_else(|| unavailable(codec, format!("no encoder {backend} here")))?; factory.create(codec, &config) } #[cfg(feature = "vpx")] @@ -444,7 +641,7 @@ impl Codecs { None => Err(unavailable(codec, "the OpenH264 library is not loaded")), }, #[allow(unreachable_patterns)] - _ => Err(unavailable(codec, format!("{backend:?} cannot encode it in this build"))), + _ => Err(unavailable(codec, format!("{backend} cannot encode it in this build"))), } } @@ -452,6 +649,81 @@ impl Codecs { pub fn pick_encoder(&self, accepted: &[Codec]) -> Option { self.encoder_codecs().into_iter().find(|c| accepted.contains(c)) } + + /// Every encoder backend this build knows, with what works here and why + /// the rest does not, and each one's rank under the current preference. + pub fn report(&self) -> EncoderReport { + let order = self.encoders(); + let rank = |codec: Codec, backend: EncoderBackend| { + order.iter().filter(|(c, _)| *c == codec).position(|(_, b)| *b == backend) + }; + let mut encoders = Vec::new(); + let mut add = |backend: EncoderBackend, api: &str, codec, hardware, status| { + encoders.push(EncoderInfo { + name: backend.name().to_owned(), + api: api.to_owned(), + codec, + hardware, + rank: rank(codec, backend), + status, + }); + }; + for f in &self.factories { + if matches!(f.backend(), EncoderBackend::Hardware(_)) { + for codec in f.codecs() { + add(f.backend(), f.name(), codec, f.is_hardware(), Ok(())); + } + } + } + #[cfg(feature = "ffmpeg")] + for status in crate::ffmpeg::probe() { + let spec = status.spec; + let backend = EncoderBackend::Ffmpeg(spec.name); + add(backend, spec.api, spec.codec, spec.is_hardware(), status.available.clone()); + } + for codec in [Codec::Vp8, Codec::Vp9] { + #[cfg(feature = "vpx")] + let status = vpx::check(codec, true).map_err(|e| e.to_string()); + #[cfg(not(feature = "vpx"))] + let status = Err("built without the `vpx` feature".to_owned()); + add(EncoderBackend::Libvpx, "libvpx", codec, false, status); + } + let status = if self.has_openh264() { + Ok(()) + } else if cfg!(feature = "openh264") { + Err("Cisco's OpenH264 library is not loaded".to_owned()) + } else { + Err("built without the `openh264` feature".to_owned()) + }; + add(EncoderBackend::OpenH264, "OpenH264 (Cisco)", Codec::H264, false, status); + #[cfg(feature = "ffmpeg")] + let (ffmpeg, zero_copy) = match crate::ffmpeg::Ffmpeg::get() { + Ok(ffmpeg) => { + let info = ffmpeg.info(); + let text = format!( + "FFmpeg {} (libavcodec {}, libavutil {}) from {}", + info.release, + info.avcodec, + info.avutil, + info.path.display() + ); + let vaapi = encoders.iter().any(|e| e.name.ends_with("_vaapi") && e.status.is_ok()); + let zero_copy = match (&info.dmabuf_import, vaapi) { + (Err(e), _) => Err(e.clone()), + (Ok(()), false) => Err("no working VA-API encoder".to_owned()), + (Ok(()), true) => Ok(()), + }; + (Ok(text), zero_copy) + } + Err(e) => (Err(e.to_owned()), Err("FFmpeg is not loaded".to_owned())), + }; + #[cfg(not(feature = "ffmpeg"))] + let (ffmpeg, zero_copy) = ( + Err("built without the `ffmpeg` feature".to_owned()), + Err("built without the `ffmpeg` feature".to_owned()), + ); + EncoderReport { ffmpeg, zero_copy, encoders } + } } #[cfg(test)] diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs new file mode 100644 index 0000000..8dae0c9 --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -0,0 +1,1199 @@ +//! Video encoders through FFmpeg: the backends, their realtime settings, the +//! encoder session and the startup self-test. +//! +//! Every backend is configured for live streaming: no B-frames, no +//! lookahead, keyframes only at the start and on request (an "infinite" +//! GOP, forced IDR), constant bitrate. The bitrate changes on the running +//! encoder where FFmpeg's wrapper applies it (x264, NVENC, Quick Sync); +//! elsewhere at the next keyframe, or at once when it drops below half +//! (congestion). Frame and packet buffers are allocated once per session +//! and reused; VA-API surfaces come from a pool. +#![allow(unsafe_code)] + +use std::collections::VecDeque; +use std::ffi::c_int; +use std::sync::OnceLock; +use std::time::Duration; + +use super::layout::{self, HwFramesFields}; +use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; +use super::{Ffmpeg, take_log}; +use crate::codec::hw::EncoderFactory; +use crate::codec::{ + Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, H264Profile, + VideoEncoder, +}; +use crate::convert; +use crate::frame::{FrameData, VideoFrame}; +use crate::{Error, Result}; + +/// How a backend takes frames. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Input { + /// Planar YUV 4:2:0 in system memory. + Yuv420p, + /// NV12 in system memory. + Nv12, + /// NV12 uploaded into a VA-API surface pool (or DMA-BUFs mapped to + /// surfaces). + Vaapi, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BackendKind { + /// A GPU or OS encoder. + Hardware, + /// A software encoder that FFmpeg wraps (x264, SVT-AV1, ...). + Software, +} + +/// One FFmpeg encoder this crate knows how to drive. +#[derive(Debug, PartialEq, Eq)] +pub struct BackendSpec { + /// FFmpeg's encoder name, also the name in settings + /// (`stream.encoder_backend`). + pub name: &'static str, + pub codec: Codec, + /// The API or library behind it, for the UI. + pub api: &'static str, + pub kind: BackendKind, + pub input: Input, + /// FFmpeg applies bitrate changes to the running encoder. + pub dynamic_bitrate: bool, + /// Keyframe interval that means "only on request" for this wrapper. + pub infinite_gop: i64, +} + +const INFINITE: i64 = 1 << 30; + +macro_rules! backend { + ($name:literal, $codec:ident, $api:literal, $kind:ident, $input:ident, $dynamic:literal, $gop:expr) => { + BackendSpec { + name: $name, + codec: Codec::$codec, + api: $api, + kind: BackendKind::$kind, + input: Input::$input, + dynamic_bitrate: $dynamic, + infinite_gop: $gop, + } + }; +} + +/// Every backend, in order of preference within its codec and kind. The +/// ones FFmpeg or the platform lacks fail the probe and are skipped. +pub static BACKENDS: &[BackendSpec] = &[ + // H.264 + backend!("h264_nvenc", H264, "NVENC", Hardware, Yuv420p, true, INFINITE), + backend!("h264_amf", H264, "AMF", Hardware, Nv12, false, 0), + backend!("h264_vaapi", H264, "VA-API", Hardware, Vaapi, false, INFINITE), + backend!("h264_qsv", H264, "Quick Sync", Hardware, Nv12, true, 65535), + backend!("h264_videotoolbox", H264, "VideoToolbox", Hardware, Nv12, false, 0), + backend!("h264_mf", H264, "Media Foundation", Hardware, Nv12, false, INFINITE), + backend!("libx264", H264, "x264", Software, Yuv420p, true, INFINITE), + backend!("libopenh264", H264, "OpenH264", Software, Yuv420p, false, INFINITE), + // HEVC (offered last: only used when a viewer takes nothing else) + backend!("hevc_nvenc", H265, "NVENC", Hardware, Yuv420p, true, INFINITE), + backend!("hevc_amf", H265, "AMF", Hardware, Nv12, false, 0), + backend!("hevc_vaapi", H265, "VA-API", Hardware, Vaapi, false, INFINITE), + backend!("hevc_qsv", H265, "Quick Sync", Hardware, Nv12, true, 65535), + backend!("hevc_videotoolbox", H265, "VideoToolbox", Hardware, Nv12, false, 0), + backend!("hevc_mf", H265, "Media Foundation", Hardware, Nv12, false, INFINITE), + // AV1 + backend!("av1_nvenc", Av1, "NVENC", Hardware, Yuv420p, true, INFINITE), + backend!("av1_amf", Av1, "AMF", Hardware, Nv12, false, 0), + backend!("av1_vaapi", Av1, "VA-API", Hardware, Vaapi, false, INFINITE), + backend!("av1_qsv", Av1, "Quick Sync", Hardware, Nv12, true, 65535), + backend!("libsvtav1", Av1, "SVT-AV1", Software, Yuv420p, false, INFINITE), + backend!("librav1e", Av1, "rav1e", Software, Yuv420p, false, INFINITE), + backend!("libaom-av1", Av1, "libaom", Software, Yuv420p, false, INFINITE), + // VP9 and VP8 (software VP8 / VP9 is libvpx, used directly) + backend!("vp9_vaapi", Vp9, "VA-API", Hardware, Vaapi, false, INFINITE), + backend!("vp9_qsv", Vp9, "Quick Sync", Hardware, Nv12, true, 65535), + backend!("vp8_vaapi", Vp8, "VA-API", Hardware, Vaapi, false, INFINITE), +]; + +impl BackendSpec { + pub fn by_name(name: &str) -> Option<&'static BackendSpec> { + BACKENDS.iter().find(|b| b.name == name) + } + + pub fn is_hardware(&self) -> bool { + self.kind == BackendKind::Hardware + } + + fn is_vaapi(&self) -> bool { + self.input == Input::Vaapi + } + + fn family(&self) -> &'static str { + self.name.rsplit('_').next().unwrap_or(self.name) + } +} + +/// Where an option is set. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Target { + /// `AVCodecContext` (generic options). + Codec, + /// The encoder's private options (`priv_data`). + Private, +} + +/// One option with alternative values (tried in order: older releases +/// know other names), optional unless `required`. +struct Setting { + target: Target, + name: &'static str, + values: Vec, + required: bool, +} + +fn opt(name: &'static str, values: &[&str]) -> Setting { + Setting { + target: Target::Private, + name, + values: values.iter().map(|v| (*v).to_owned()).collect(), + required: false, + } +} + +fn generic(name: &'static str, value: impl ToString) -> Setting { + Setting { target: Target::Codec, name, values: vec![value.to_string()], required: false } +} + +/// libx264 presets, fastest first (`EncoderConfig::speed` indexes them). +const X264_PRESETS: [&str; 10] = [ + "ultrafast", + "superfast", + "veryfast", + "faster", + "fast", + "medium", + "slow", + "slower", + "veryslow", + "placebo", +]; + +/// `FF_PROFILE_H264_HIGH` and `FF_PROFILE_H264_CONSTRAINED_BASELINE`. +const PROFILE_H264_HIGH: i64 = 100; +const PROFILE_H264_CONSTRAINED_BASELINE: i64 = 66 | 1 << 9; + +/// 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 { + let screen = config.content == ContentHint::Screen; + let baseline = config.h264_profile == H264Profile::ConstrainedBaseline; + let h264 = spec.codec == Codec::H264; + let generic_profile = if baseline { PROFILE_H264_CONSTRAINED_BASELINE } else { PROFILE_H264_HIGH }; + let mut list = Vec::new(); + match spec.family() { + "nvenc" => { + let preset = config.speed.map(|s| format!("p{}", s.clamp(1, 7))); + let mut presets = preset.into_iter().collect::>(); + presets.extend(["p2".into(), "llhp".into()]); + list.push(Setting { values: presets, ..opt("preset", &[]) }); + list.push(opt("tune", &["ull", "ll"])); + list.push(opt("rc", &["cbr"])); + list.push(opt("zerolatency", &["1"])); + list.push(opt("delay", &["0"])); + list.push(opt("rc-lookahead", &["0"])); + list.push(opt("forced-idr", &["1"])); + list.push(opt("no-scenecut", &["1"])); + list.push(opt("b_ref_mode", &["disabled"])); + if h264 { + list.push(opt("profile", if baseline { &["baseline"] } else { &["high"] })); + } + } + "qsv" => { + list.push(opt("preset", &["veryfast"])); + list.push(opt("async_depth", &["1"])); + list.push(opt("look_ahead", &["0"])); + list.push(opt("look_ahead_depth", &["0"])); + list.push(opt("forced_idr", &["1"])); + list.push(opt("low_delay_brc", &["1"])); + list.push(opt("scenario", if screen { &["displayremoting"] } else { &["videoconference"] })); + if h264 { + list.push(opt("profile", if baseline { &["baseline"] } else { &["high"] })); + } + } + "amf" => { + list.push(opt("usage", &["ultralowlatency", "lowlatency"])); + list.push(opt("quality", &["speed"])); + list.push(opt("rc", &["cbr"])); + list.push(opt("header_insertion_mode", &["idr", "key", "gop"])); + list.push(opt("latency", &["1"])); + if h264 { + list.push(opt( + "profile", + if baseline { + &["constrained_baseline", "main"] + } else { + &["constrained_high", "high"] + }, + )); + } + } + "vaapi" => { + list.push(opt("rc_mode", &["CBR"])); + list.push(opt("async_depth", &["1"])); + if low_power { + list.push(Setting { required: true, ..opt("low_power", &["1"]) }); + } + if h264 { + list.push(generic("profile", generic_profile)); + } + } + "videotoolbox" => { + list.push(opt("realtime", &["1"])); + list.push(opt("prio_speed", &["1"])); + list.push(opt("allow_sw", &["0"])); + if h264 { + list.push(opt( + "profile", + if baseline { + &["constrained_baseline", "baseline"] + } else { + &["constrained_high", "high"] + }, + )); + } + } + "mf" => { + list.push(opt("hw_encoding", &["1"])); + list.push(opt("rate_control", &["cbr"])); + list.push(opt( + "scenario", + if screen { &["display_remoting"] } else { &["video_conference"] }, + )); + if h264 { + list.push(generic("profile", generic_profile)); + } + } + _ => match spec.name { + "libx264" => { + let preset = config.speed.map_or("veryfast", |s| { + X264_PRESETS[s.clamp(0, X264_PRESETS.len() as i32 - 1) as usize] + }); + list.push(Setting { required: true, ..opt("preset", &[preset]) }); + list.push(opt("tune", &["zerolatency"])); + list.push(opt("profile", if baseline { &["baseline"] } else { &["high"] })); + list.push(opt("forced-idr", &["1"])); + list.push(opt("x264-params", &["scenecut=0"])); + } + "libopenh264" => { + list.push(generic("profile", generic_profile)); + list.push(opt("allow_skip_frames", &["1"])); + list.push(opt("rc_mode", &["bitrate"])); + } + "libsvtav1" => { + let preset = config.speed.unwrap_or(10).to_string(); + list.push(Setting { values: vec![preset], ..opt("preset", &[]) }); + list.push(opt("svtav1-params", &["pred-struct=1:lookahead=0:scd=0", "pred-struct=1"])); + } + "librav1e" => { + let speed = config.speed.unwrap_or(10).to_string(); + list.push(Setting { values: vec![speed], ..opt("speed", &[]) }); + list.push(opt("rav1e-params", &["low_latency=true"])); + } + "libaom-av1" => { + let cpu_used = config.speed.unwrap_or(8).to_string(); + list.push(opt("usage", &["realtime"])); + list.push(Setting { values: vec![cpu_used], ..opt("cpu-used", &[]) }); + list.push(opt("lag-in-frames", &["0"])); + list.push(opt("row-mt", &["1"])); + list.push(opt("end-usage", &["cbr"])); + list.push(opt("aq-mode", &["3"])); + list.push(opt("enable-tpl-model", &["0"])); + if screen { + list.push(opt("tune-content", &["screen"])); + } + } + _ => {} + }, + } + list +} + +/// The process's VA-API device: `VOELIN_VAAPI_DEVICE`, or the first DRM +/// render node. +struct Device(Ptr); + +// SAFETY: an AVBufferRef of an AVHWDeviceContext, never freed; FFmpeg's +// VA-API device may be used from several threads (libva locks per display). +unsafe impl Send for Device {} +unsafe impl Sync for Device {} + +/// The DRM render node for VA-API. +pub fn vaapi_device_path() -> Option { + if let Some(path) = std::env::var_os("VOELIN_VAAPI_DEVICE") { + return Some(path.to_string_lossy().into_owned()); + } + let mut nodes: Vec = std::fs::read_dir("/dev/dri") + .ok()? + .flatten() + .map(|e| e.path().to_string_lossy().into_owned()) + .filter(|p| p.rsplit('/').next().is_some_and(|n| n.starts_with("renderD"))) + .collect(); + nodes.sort(); + nodes.into_iter().next() +} + +fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { + static DEVICE: OnceLock> = OnceLock::new(); + DEVICE + .get_or_init(|| { + let path = vaapi_device_path().ok_or("no DRM render node (/dev/dri/renderD*)")?; + let api = &ffmpeg.api; + let name = cstr("vaapi"); + // SAFETY: a C string. + let kind = unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) }; + if kind <= 0 { + return Err("FFmpeg has no VA-API support".into()); + } + let mut device = std::ptr::null_mut(); + let c_path = cstr(&path); + // SAFETY: out pointer and C strings are valid; no options. + let ret = unsafe { + (api.av_hwdevice_ctx_create)(&mut device, kind, c_path.as_ptr(), std::ptr::null_mut(), 0) + }; + if ret < 0 { + return Err(format!("VA-API device {path}: {}{}", api.error_text(ret), log_suffix())); + } + Ok(Device(device)) + }) + .as_ref() + .map(|d| d.0) + .map_err(Clone::clone) +} + +/// FFmpeg's recent messages, appended to an error. +fn log_suffix() -> String { + let log = take_log(); + if log.is_empty() { String::new() } else { format!(" ({})", log.join("; ")) } +} + +/// Maps output packets back to the frames' 90 kHz timestamps. +struct Timestamps { + pending: VecDeque<(i64, u64)>, +} + +impl Timestamps { + fn new() -> Self { + Self { pending: VecDeque::with_capacity(64) } + } + + fn push(&mut self, pts: i64, pts_90khz: u64) { + if self.pending.len() == self.pending.capacity() { + self.pending.pop_front(); + } + self.pending.push_back((pts, pts_90khz)); + } + + fn take(&mut self, pts: i64) -> Option { + while let Some(&(p, t)) = self.pending.front() { + if p > pts { + break; + } + self.pending.pop_front(); + if p == pts { + return Some(t); + } + } + None + } +} + +/// An open encoder for one size and frame rate. +struct Session { + ctx: Ptr, + width: u32, + height: u32, + fps: u32, + bitrate: u32, + /// Frame in system memory, filled per frame (reused). + sw: Ptr, + /// VA-API: the surface pool and the frame that takes a surface. + pool: Ptr, + hw: Ptr, + packet: Ptr, + last_pts: Option, + timestamps: Timestamps, + nv12: bool, +} + +// 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 {} + +impl Drop for Session { + fn drop(&mut self) { + let api = &Ffmpeg::get().expect("a session exists only with FFmpeg").api; + // SAFETY: each pointer is NULL or owned by this session. + unsafe { + (api.av_frame_free)(&mut self.sw); + (api.av_frame_free)(&mut self.hw); + (api.av_packet_free)(&mut self.packet); + (api.avcodec_free_context)(&mut self.ctx); + if !self.pool.is_null() { + (api.av_buffer_unref)(&mut self.pool); + } + } + } +} + +/// When to recreate the session. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Reinit { + No, + /// With the next keyframe (bitrate changes the wrapper cannot apply). + AtKeyframe, + /// Before the next frame. + Now, +} + +/// An encoder of one [`BackendSpec`]. +pub struct FfmpegEncoder { + ffmpeg: &'static Ffmpeg, + spec: &'static BackendSpec, + config: EncoderConfig, + session: Option, + reinit: Reinit, + /// VA-API only offers the low-power entry point for this codec. + low_power: bool, +} + +impl FfmpegEncoder { + /// An encoder of backend `name` (nothing is opened until the first + /// frame, whose size it takes). + pub fn new(name: &str, config: EncoderConfig) -> Result { + let spec = BackendSpec::by_name(name).ok_or_else(|| Error::CodecUnavailable { + codec: Codec::H264, + reason: format!("unknown FFmpeg encoder {name}"), + })?; + let ffmpeg = Ffmpeg::get() + .map_err(|e| Error::CodecUnavailable { codec: spec.codec, reason: e.to_owned() })?; + Ok(Self { ffmpeg, spec, config, session: None, reinit: Reinit::No, low_power: false }) + } + + pub fn spec(&self) -> &'static BackendSpec { + self.spec + } + + fn error(&self, what: &str, code: c_int) -> Error { + Error::Encoder { + codec: self.spec.codec, + message: format!( + "{} {what}: {}{}", + self.spec.name, + self.ffmpeg.api.error_text(code), + log_suffix() + ), + } + } + + fn unavailable(&self, reason: String) -> Error { + Error::CodecUnavailable { codec: self.spec.codec, reason } + } + + fn set_option(&self, obj: Ptr, name: &str, value: &str) -> c_int { + let (name, value) = (cstr(name), cstr(value)); + // SAFETY: an AVClass-enabled object and two C strings. + unsafe { (self.ffmpeg.api.av_opt_set)(obj, name.as_ptr(), value.as_ptr(), 0) } + } + + fn set_int(&self, obj: Ptr, name: &str, value: i64) -> c_int { + let name = cstr(name); + // SAFETY: an AVClass-enabled object and a C string. + unsafe { (self.ffmpeg.api.av_opt_set_int)(obj, name.as_ptr(), value, 0) } + } + + /// Apply one setting; an optional one that this release does not know + /// (or does not accept) is skipped. + fn apply(&self, ctx: Ptr, private: Ptr, setting: &Setting) -> Result<()> { + let obj = match setting.target { + Target::Codec => ctx, + Target::Private if private.is_null() => return Ok(()), + Target::Private => private, + }; + let mut last = sys::OPTION_NOT_FOUND; + for value in &setting.values { + last = self.set_option(obj, setting.name, value); + if last >= 0 { + return Ok(()); + } + } + if setting.required { + return Err(self.error(&format!("option {}", setting.name), last)); + } + if last != sys::OPTION_NOT_FOUND { + tracing::debug!( + backend = self.spec.name, + option = setting.name, + "not accepted: {}", + self.ffmpeg.api.error_text(last) + ); + } + 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)) + } + + /// Open a session for `width` x `height`. + fn open(&mut self, width: u32, height: u32) -> Result { + match self.open_with(width, height, self.low_power) { + Err(e) if self.spec.is_vaapi() && !self.low_power => { + // Some GPUs only have the low-power entry point for a codec. + match self.open_with(width, height, true) { + Ok(session) => { + self.low_power = true; + Ok(session) + } + Err(_) => Err(e), + } + } + result => result, + } + } + + fn open_with(&self, width: u32, height: u32, low_power: bool) -> Result { + let api = &self.ffmpeg.api; + let pix = self.ffmpeg.pix; + let name = cstr(self.spec.name); + // SAFETY: a C string; returns a static codec or NULL. + let codec = unsafe { (api.avcodec_find_encoder_by_name)(name.as_ptr()) }; + if codec.is_null() { + return Err(self.unavailable(format!("{} is not in this FFmpeg build", self.spec.name))); + } + // SAFETY: allocates a context with the codec's private options. + let ctx = unsafe { (api.avcodec_alloc_context3)(codec) }; + if ctx.is_null() { + return Err(self.unavailable("avcodec_alloc_context3 failed".into())); + } + let fps = self.config.fps.max(1); + let bitrate = self.config.bitrate_bps.max(1); + let mut session = Session { + ctx, + width, + height, + fps, + bitrate, + sw: std::ptr::null_mut(), + pool: std::ptr::null_mut(), + hw: std::ptr::null_mut(), + packet: std::ptr::null_mut(), + last_pts: None, + timestamps: Timestamps::new(), + nv12: self.spec.input != Input::Yuv420p, + }; + // SAFETY: `ctx` is a live codec context; the first child is its + // private options object (NULL if the codec has none). + let private = unsafe { (api.av_opt_child_next)(ctx, std::ptr::null_mut()) }; + let (w, h) = (width as c_int, height as c_int); + let sw_format = if session.nv12 { pix.nv12 } else { pix.yuv420p }; + let format = match self.spec.input { + Input::Vaapi => pix.vaapi.ok_or_else(|| self.unavailable("no VA-API pixel format".into()))?, + _ => sw_format, + }; + let size = cstr("video_size"); + let pixel_format = cstr("pixel_format"); + let time_base = cstr("time_base"); + // SAFETY: typed option setters on a live context with C strings. + let ret = unsafe { + let mut ret = (api.av_opt_set_image_size)(ctx, size.as_ptr(), w, h, 0); + if ret >= 0 { + ret = (api.av_opt_set_pixel_fmt)(ctx, pixel_format.as_ptr(), format, 0); + } + if ret >= 0 { + let tb = Rational { num: 1, den: fps as c_int }; + ret = (api.av_opt_set_q)(ctx, time_base.as_ptr(), tb, 0); + } + ret + }; + if ret < 0 { + return Err(self.error("size, format and time base", ret)); + } + let gop = self.config.keyframe_interval.map_or(self.spec.infinite_gop, i64::from); + let mut list = vec![ + generic("b", bitrate), + generic("maxrate", bitrate), + generic("bufsize", bitrate), + generic("g", gop), + generic("bf", 0), + generic("colorspace", "smpte170m"), + generic("color_primaries", "smpte170m"), + generic("color_trc", "smpte170m"), + generic("color_range", "tv"), + ]; + if !self.spec.is_hardware() { + list.push(generic("threads", self.config.threads_for(width, height))); + } + 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)?; + 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. + unsafe { + let reference = (api.av_buffer_ref)(session.pool); + layout::write::(ctx, offset, reference); + } + } + // SAFETY: a configured context and its codec; no options dictionary. + let ret = unsafe { (api.avcodec_open2)(ctx, codec, std::ptr::null_mut()) }; + if ret < 0 { + return Err(self.error("open", ret)); + } + // Buffers for the whole session. + // SAFETY: allocations; the head fields are set before + // av_frame_get_buffer as documented. + unsafe { + session.packet = (api.av_packet_alloc)(); + session.sw = (api.av_frame_alloc)(); + if session.packet.is_null() || session.sw.is_null() { + return Err(self.unavailable("out of memory".into())); + } + let head = session.sw.cast::(); + (*head).width = w; + (*head).height = h; + (*head).format = sw_format; + let ret = (api.av_frame_get_buffer)(session.sw, 0); + if ret < 0 { + return Err(self.error("frame buffer", ret)); + } + if self.spec.is_vaapi() { + session.hw = (api.av_frame_alloc)(); + if session.hw.is_null() { + return Err(self.unavailable("out of memory".into())); + } + } + } + tracing::debug!( + backend = self.spec.name, + width, + height, + fps, + bitrate, + low_power, + "FFmpeg encoder opened" + ); + Ok(session) + } + + /// A VA-API surface pool (NV12) for `width` x `height`. + fn vaapi_pool(&self, width: u32, height: u32) -> Result { + let api = &self.ffmpeg.api; + let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?; + let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; + // SAFETY: `device` is a live device reference. + let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; + if pool.is_null() { + return Err(self.unavailable("av_hwframe_ctx_alloc failed".into())); + } + // SAFETY: `pool` was just allocated on `device`. + let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } { + Ok(f) => f, + Err(e) => { + // SAFETY: allocated above. + unsafe { (api.av_buffer_unref)(&mut pool) }; + return Err(self.unavailable(e)); + } + }; + // SAFETY: the fields were located and checked on this very context; + // setting them before av_hwframe_ctx_init is what FFmpeg expects. + let ret = unsafe { + let ctx = (*pool.cast::()).data.cast::(); + layout::write::(ctx, fields.format, vaapi); + layout::write::(ctx, fields.sw_format, self.ffmpeg.pix.nv12); + layout::write::(ctx, fields.width, width as c_int); + layout::write::(ctx, fields.height, height as c_int); + // Surfaces are allocated on demand and recycled by the pool. + layout::write::(ctx, fields.initial_pool_size, 0); + (api.av_hwframe_ctx_init)(pool) + }; + if ret < 0 { + // SAFETY: allocated above. + unsafe { (api.av_buffer_unref)(&mut pool) }; + return Err(self.error("VA-API surface pool", ret)); + } + Ok(pool) + } + + /// Copy the I420 picture into the session's frame (cropped to the coded + /// size; NV12 interleaved where the backend wants it). + fn fill(&self, session: &Session, frame: &VideoFrame) -> Result<()> { + let FrameData::I420 { y, u, v } = &frame.data else { + unreachable!("converted to I420 before"); + }; + let api = &self.ffmpeg.api; + // SAFETY: the frame was allocated by av_frame_get_buffer for the + // session size and format; make_writable keeps that and only swaps + // buffers the encoder still references. + let ret = unsafe { (api.av_frame_make_writable)(session.sw) }; + if ret < 0 { + return Err(self.error("frame buffer", ret)); + } + let (w, h) = (session.width as usize, session.height as usize); + let (cw, ch) = (w / 2, h / 2); + // SAFETY: planes of the session's frame: `linesize` bytes per row, + // `h` (luma) or `h / 2` (chroma) rows, at least `w` (or the chroma + // width) bytes each, owned by the frame (writable, see above). + unsafe { + let head = &*session.sw.cast::(); + let plane = |i: usize, rows: usize| { + let stride = head.linesize[i] as usize; + (std::slice::from_raw_parts_mut(head.data[i], stride * rows), stride) + }; + let (dst, stride) = plane(0, h); + for row in 0..h { + dst[row * stride..][..w].copy_from_slice(y.row(row, w)); + } + if session.nv12 { + let (dst, stride) = plane(1, ch); + for row in 0..ch { + let out = &mut dst[row * stride..][..cw * 2]; + let (u_row, v_row) = (u.row(row, cw), v.row(row, cw)); + for ((pair, &u), &v) in out.chunks_exact_mut(2).zip(u_row).zip(v_row) { + pair[0] = u; + pair[1] = v; + } + } + } else { + for (i, src) in [(1, u), (2, v)] { + let (dst, stride) = plane(i, ch); + for row in 0..ch { + dst[row * stride..][..cw].copy_from_slice(src.row(row, cw)); + } + } + } + } + Ok(()) + } + + /// Receive every packet that is ready. + fn drain( + &self, + session: &mut Session, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result { + let api = &self.ffmpeg.api; + let mut keyframe = false; + loop { + // SAFETY: a live context and packet. + let ret = unsafe { (api.avcodec_receive_packet)(session.ctx, session.packet) }; + if ret == sys::EAGAIN || ret == sys::EOF { + return Ok(keyframe); + } + if ret < 0 { + return Err(self.error("receive", ret)); + } + // SAFETY: a packet just filled by the encoder: `data` holds + // `size` bytes until av_packet_unref. + unsafe { + let head = &*session.packet.cast::(); + let key = head.flags & sys::PKT_FLAG_KEY != 0; + keyframe |= key; + let pts_90khz = session.timestamps.take(head.pts).unwrap_or_else(|| { + (head.pts.max(0) as u64) * 90_000 / u64::from(session.fps) + }); + if !head.data.is_null() && head.size > 0 { + let data = std::slice::from_raw_parts(head.data, head.size as usize); + out(EncodedChunk { data, keyframe: key, pts_90khz }); + } + (api.av_packet_unref)(session.packet); + } + } + } + + /// Send one frame (or NULL to flush), draining packets as the encoder + /// asks. + fn send( + &self, + session: &mut Session, + frame: Ptr, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result { + let api = &self.ffmpeg.api; + let mut keyframe = false; + loop { + // SAFETY: a live context; `frame` is NULL or a live frame. + let ret = unsafe { (api.avcodec_send_frame)(session.ctx, frame) }; + if ret == sys::EAGAIN { + keyframe |= self.drain(session, out)?; + continue; + } + if ret < 0 && ret != sys::EOF { + return Err(self.error("send", ret)); + } + break; + } + keyframe |= self.drain(session, out)?; + Ok(keyframe) + } + + fn encode_i420( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let (w, h) = Self::coded_size(frame.width, frame.height); + let mut force = force_keyframe; + let reopen = match &self.session { + None => true, + Some(s) => { + (s.width, s.height) != (w, h) + || self.reinit == Reinit::Now + || (self.reinit == Reinit::AtKeyframe && force) + } + }; + if reopen { + // One session at a time (hardware encoders have few). + self.session = None; + self.session = Some(self.open(w, h)?); + self.reinit = Reinit::No; + force = true; + } + let mut session = self.session.take().expect("opened above"); + let result = self.encode_in(&mut session, frame, force, out); + self.session = Some(session); + result + } + + fn encode_in( + &self, + session: &mut Session, + frame: &VideoFrame, + force: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let api = &self.ffmpeg.api; + self.fill(session, frame)?; + // Frame numbers at the session's rate, strictly increasing. + let exact = frame.timestamp.as_secs_f64() * f64::from(session.fps); + let mut pts = exact.round() as i64; + if let Some(last) = session.last_pts + && pts <= last + { + pts = last + 1; + } + session.last_pts = Some(pts); + session.timestamps.push(pts, frame.pts_90khz()); + let fields = self.ffmpeg.frame; + let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; + let input = if session.hw.is_null() { + session.sw + } else { + // SAFETY: `hw` is our frame (unreferenced after each send); the + // pool is the session's; transfer copies the planes into the + // surface. + unsafe { + let ret = (api.av_hwframe_get_buffer)(session.pool, session.hw, 0); + if ret < 0 { + return Err(self.error("VA-API surface", ret)); + } + let ret = (api.av_hwframe_transfer_data)(session.hw, session.sw, 0); + if ret < 0 { + (api.av_frame_unref)(session.hw); + return Err(self.error("VA-API upload", ret)); + } + } + session.hw + }; + // SAFETY: offsets checked at load for this release's AVFrame. + unsafe { + layout::write::(input, fields.pts, pts); + layout::write::(input, fields.pict_type, pict_type); + } + let result = self.send(session, input, out); + if !session.hw.is_null() { + // The encoder holds its own reference; the surface returns to the + // pool once it is done with it. + // SAFETY: our frame. + unsafe { (api.av_frame_unref)(session.hw) }; + } + 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)> { + 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| { + packets += 1; + keyframe |= chunk.keyframe; + }); + drop(session); + flushed?; + Ok((packets, keyframe)) + } +} + +impl VideoEncoder for FfmpegEncoder { + fn codec(&self) -> Codec { + self.spec.codec + } + + fn backend(&self) -> EncoderBackend { + EncoderBackend::Ffmpeg(self.spec.name) + } + + fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result> { + let mut frames = Vec::new(); + self.encode_with(frame, force_keyframe, &mut |f| { + frames.push(EncodedFrame { + data: f.data.to_vec(), + keyframe: f.keyframe, + pts_90khz: f.pts_90khz, + }); + })?; + Ok(frames) + } + + /// Copies the picture into the session's reused frame (or VA-API + /// surface) and hands out FFmpeg's packet buffer. + fn encode_with( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let i420 = convert::to_i420(frame)?; + self.encode_i420(&i420, force_keyframe, out) + } + + fn set_bitrate(&mut self, bps: u32) -> Result<()> { + let bps = bps.max(1); + self.config.bitrate_bps = bps; + let Some((ctx, running)) = self.session.as_ref().map(|s| (s.ctx, s.bitrate)) else { + return Ok(()); + }; + if running == bps { + return Ok(()); + } + if self.spec.dynamic_bitrate { + // The wrapper compares these with its running configuration + // before each frame and reconfigures the encoder. + for name in ["b", "maxrate", "bufsize"] { + let ret = self.set_int(ctx, name, i64::from(bps)); + if ret < 0 { + return Err(self.error(name, ret)); + } + } + if let Some(session) = &mut self.session { + session.bitrate = bps; + } + } else if u64::from(bps) * 2 < u64::from(running) { + // Congestion: waiting for a keyframe would keep overshooting. + self.reinit = Reinit::Now; + } else { + self.reinit = self.reinit.max(Reinit::AtKeyframe); + } + Ok(()) + } + + /// The time base is the frame rate, fixed per session: a new rate opens + /// a new session (a keyframe). + fn set_fps(&mut self, fps: u32) -> Result<()> { + let fps = fps.max(1); + self.config.fps = fps; + if self.session.as_ref().is_some_and(|s| s.fps != fps) { + self.reinit = Reinit::Now; + } + Ok(()) + } +} + +/// A gradient test picture. +fn test_frame(width: u32, height: u32) -> VideoFrame { + let mut frame = VideoFrame::black_i420(width, height); + if let FrameData::I420 { y, .. } = &mut frame.data { + for (i, px) in y.data.iter_mut().enumerate() { + *px = 16 + ((i % width as usize) * 200 / width as usize) as u8; + } + } + frame.with_timestamp(Duration::ZERO) +} + +/// A backend and the result of its self-test. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BackendStatus { + pub spec: &'static BackendSpec, + /// `Ok` if it encoded the test frame, else why not. + pub available: std::result::Result<(), String>, +} + +/// Size of the self-test frame. +const TEST_SIZE: (u32, u32) = (320, 240); + +fn test_backend(spec: &'static BackendSpec) -> std::result::Result<(), 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(()), + Err(Error::CodecUnavailable { reason, .. }) => Err(reason), + Err(e) => Err(e.to_string()), + } +} + +/// Whether FFmpeg has `name` at all (cheap, before any self-test). +fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool { + let name = cstr(name); + // SAFETY: a C string; returns a static codec or NULL. + !unsafe { (ffmpeg.api.avcodec_find_encoder_by_name)(name.as_ptr()) }.is_null() +} + +/// Every backend with its self-test result (run once per process, the +/// backends in parallel). Empty without FFmpeg. +pub fn probe() -> &'static [BackendStatus] { + static PROBE: OnceLock> = OnceLock::new(); + PROBE.get_or_init(|| { + let Ok(ffmpeg) = Ffmpeg::get() else { return Vec::new() }; + 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) + }) + .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())), + }, + }) + .collect() + }); + 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}"), + } + } + statuses + }) +} + +/// Creates encoders of one backend that passed its self-test. +pub struct FfmpegFactory { + spec: &'static BackendSpec, +} + +impl FfmpegFactory { + /// Factories of the available backends, in [`BACKENDS`] order. + pub fn available() -> Vec { + probe() + .iter() + .filter(|s| s.available.is_ok()) + .map(|s| FfmpegFactory { spec: s.spec }) + .collect() + } + + pub fn spec(&self) -> &'static BackendSpec { + self.spec + } +} + +impl EncoderFactory for FfmpegFactory { + fn name(&self) -> &'static str { + self.spec.name + } + + fn codecs(&self) -> Vec { + vec![self.spec.codec] + } + + fn create(&self, codec: Codec, config: &EncoderConfig) -> Result> { + if codec != self.spec.codec { + return Err(Error::CodecUnavailable { + codec, + reason: format!("{} encodes {}", self.spec.name, self.spec.codec), + }); + } + Ok(Box::new(FfmpegEncoder::new(self.spec.name, config.clone())?)) + } + + fn is_hardware(&self) -> bool { + self.spec.is_hardware() + } + + fn backend(&self) -> EncoderBackend { + EncoderBackend::Ffmpeg(self.spec.name) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backend_table() { + for (i, spec) in BACKENDS.iter().enumerate() { + assert!(BACKENDS[..i].iter().all(|b| b.name != spec.name), "{} twice", spec.name); + assert_eq!(BackendSpec::by_name(spec.name), Some(spec)); + // VA-API needs the hardware frame pool; nothing else does. + assert_eq!(spec.is_vaapi(), spec.name.ends_with("_vaapi"), "{}", spec.name); + assert_eq!(spec.is_hardware(), !spec.name.starts_with("lib"), "{}", spec.name); + } + assert_eq!(BackendSpec::by_name("h264_vaapi").unwrap().family(), "vaapi"); + assert_eq!(BackendSpec::by_name("libx264").unwrap().family(), "libx264"); + } + + #[test] + fn timestamps_follow_packets() { + let mut t = Timestamps::new(); + t.push(0, 0); + t.push(1, 3000); + t.push(3, 9000); + assert_eq!(t.take(1), Some(3000), "an older entry is skipped"); + assert_eq!(t.take(2), None); + assert_eq!(t.take(3), Some(9000)); + for i in 0..100 { + t.push(i, i as u64); + } + assert_eq!(t.pending.len(), 64, "bounded"); + } + + #[test] + fn settings_per_backend() { + let config = EncoderConfig::default(); + let names = |spec: &str, low_power| -> Vec<&'static str> { + settings(BackendSpec::by_name(spec).unwrap(), &config, low_power) + .iter() + .map(|s| s.name) + .collect() + }; + assert!(names("libx264", false).contains(&"tune")); + assert!(names("h264_nvenc", false).contains(&"forced-idr")); + assert!(!names("h264_vaapi", false).contains(&"low_power")); + assert!(names("h264_vaapi", true).contains(&"low_power")); + assert!(names("libaom-av1", false).contains(&"lag-in-frames")); + let baseline = EncoderConfig { h264_profile: H264Profile::ConstrainedBaseline, ..config }; + let x264 = settings(BackendSpec::by_name("libx264").unwrap(), &baseline, false); + let profile = x264.iter().find(|s| s.name == "profile").unwrap(); + assert_eq!(profile.values, ["baseline"]); + } +} diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs new file mode 100644 index 0000000..9245df0 --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -0,0 +1,411 @@ +//! The struct fields FFmpeg offers no function or AVOption for: where they +//! are in the loaded release, found and checked at runtime. +//! +//! Everything else goes through functions and AVOptions, whose meaning does +//! not depend on the release: the codec context is configured only with +//! `av_opt_set*` (`video_size`, `pixel_format`, `time_base`, `b`, `g`, `bf`, +//! ... and the encoders' private options), frames and packets are allocated +//! by FFmpeg, and only their leading fields are read (`sys::FrameHead`, +//! `sys::PacketHead`: unchanged since FFmpeg 0.9 and 2.1). The rest: +//! +//! | Field | Why | How it is found | Check | +//! |---|---|---|---| +//! | `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 | +//! +//! 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. +#![allow(unsafe_code)] + +use std::ffi::c_int; +use std::mem::{offset_of, size_of}; + +use super::sys::{ + Api, BufferRefHead, FrameHead, NOPTS_VALUE, PICTURE_TYPE_NONE, Ptr, Rational, cstr, +}; + +/// Offsets of `pict_type` and `pts` in `AVFrame`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameFields { + pub pict_type: usize, + pub pts: usize, +} + +/// Up to libavutil 59. +#[repr(C)] +struct FrameWithKeyFrame { + head: FrameHead, + key_frame: c_int, + pict_type: c_int, + sample_aspect_ratio: Rational, + pts: i64, +} + +/// libavutil 60 and later (`key_frame` removed). +#[repr(C)] +struct FrameWithoutKeyFrame { + head: FrameHead, + pict_type: c_int, + sample_aspect_ratio: Rational, + pts: i64, +} + +/// # Safety +/// `base + offset` must lie inside a live object and be aligned for `T`. +pub unsafe fn read(base: Ptr, offset: usize) -> T { + // SAFETY: guaranteed by the caller. + unsafe { base.cast::().add(offset).cast::().read() } +} + +/// # Safety +/// As [`read`], and the object must be ours to write. +pub unsafe fn write(base: Ptr, offset: usize, value: T) { + // SAFETY: guaranteed by the caller. + unsafe { base.cast::().add(offset).cast::().write(value) } +} + +/// Find `pict_type` and `pts` in a frame fresh from `av_frame_alloc`. +pub fn frame_fields(api: &Api) -> Result { + // SAFETY: allocates a frame (or returns NULL). + let mut frame = unsafe { (api.av_frame_alloc)() }; + if frame.is_null() { + return Err("av_frame_alloc failed".into()); + } + let matches = |pict_type: usize, sar: usize, pts: usize| { + // SAFETY: both layouts end with `pts` at 136 bytes (64-bit) or less, + // inside every AVFrame (416 bytes and more); the offsets come from + // `offset_of!` of `repr(C)` structs, so they are aligned. + unsafe { + read::(frame, pict_type) == PICTURE_TYPE_NONE + && read::(frame, sar) == Rational { num: 0, den: 1 } + && read::(frame, pts) == NOPTS_VALUE + } + }; + let with = matches( + offset_of!(FrameWithKeyFrame, pict_type), + offset_of!(FrameWithKeyFrame, sample_aspect_ratio), + offset_of!(FrameWithKeyFrame, pts), + ); + let without = matches( + offset_of!(FrameWithoutKeyFrame, pict_type), + offset_of!(FrameWithoutKeyFrame, sample_aspect_ratio), + offset_of!(FrameWithoutKeyFrame, pts), + ); + // SAFETY: the frame came from av_frame_alloc. + unsafe { (api.av_frame_free)(&mut frame) }; + match (with, without) { + (true, false) => Ok(FrameFields { + pict_type: offset_of!(FrameWithKeyFrame, pict_type), + pts: offset_of!(FrameWithKeyFrame, pts), + }), + (false, true) => Ok(FrameFields { + pict_type: offset_of!(FrameWithoutKeyFrame, pict_type), + pts: offset_of!(FrameWithoutKeyFrame, pts), + }), + _ => Err("unknown AVFrame layout (pict_type / pts not where any known release has them)" + .into()), + } +} + +/// The offset of an AVOption's field in `obj`, if the option exists. +fn option_offset(api: &Api, obj: Ptr, name: &str) -> Option { + let name = cstr(name); + // SAFETY: `obj` is an AVClass-enabled object; the name is a C string. + let option = unsafe { (api.av_opt_find)(obj, name.as_ptr(), std::ptr::null(), 0, 0) }; + if option.is_null() { + return None; + } + // SAFETY: av_opt_find returns a pointer into a static option table. + usize::try_from(unsafe { (*option).offset }).ok() +} + +/// libavcodec 61 and later: `err_recognition`, `hwaccel`, `hwaccel_context`, +/// `hw_frames_ctx`, `hw_device_ctx`, `hwaccel_flags`, `extra_hw_frames`. +#[repr(C)] +struct HwFieldsNew { + err_recognition: c_int, + hwaccel: Ptr, + hwaccel_context: Ptr, + hw_frames_ctx: Ptr, + hw_device_ctx: Ptr, + hwaccel_flags: c_int, + extra_hw_frames: c_int, +} + +/// libavcodec 60: `hw_frames_ctx`, `trailing_padding`, `max_pixels`, +/// `hw_device_ctx`, `hwaccel_flags`. +#[repr(C)] +struct HwFields60 { + hw_frames_ctx: Ptr, + trailing_padding: c_int, + max_pixels: i64, + hw_device_ctx: Ptr, + hwaccel_flags: c_int, +} + +/// libavcodec 58 and 59: as 60 with `sub_text_format` after +/// `hw_frames_ctx`. +#[repr(C)] +struct HwFields59 { + hw_frames_ctx: Ptr, + sub_text_format: c_int, + trailing_padding: c_int, + max_pixels: i64, + hw_device_ctx: Ptr, + hwaccel_flags: c_int, +} + +/// Where `hw_frames_ctx` is in `AVCodecContext`, from the offsets of +/// neighbouring AVOptions, checked in a new context. +pub fn codec_hw_frames(api: &Api) -> Result { + // SAFETY: a generic context (no codec); freed below. + let mut ctx = unsafe { (api.avcodec_alloc_context3)(std::ptr::null_mut()) }; + if ctx.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + let result = locate_hw_frames(api, ctx); + // SAFETY: allocated above. + unsafe { (api.avcodec_free_context)(&mut ctx) }; + result +} + +fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result { + let offset = |name| option_offset(api, ctx, name); + let flags = offset("hwaccel_flags").ok_or("no hwaccel_flags option")?; + let found = 'found: { + // libavcodec 61+: anchored at err_recognition and extra_hw_frames. + if let Some(err) = offset("err_detect") + && let Some(base) = err.checked_sub(offset_of!(HwFieldsNew, err_recognition)) + && base + offset_of!(HwFieldsNew, hwaccel_flags) == flags + && offset("extra_hw_frames") == Some(base + offset_of!(HwFieldsNew, extra_hw_frames)) + { + break 'found base + offset_of!(HwFieldsNew, hw_frames_ctx); + } + // Up to 60: anchored at max_pixels. `sub_text_format` (a field up to + // 59) only matters on 32-bit targets, where the version decides. + // SAFETY: no arguments. + let major = unsafe { (api.avcodec_version)() } >> 16; + if let Some(max_pixels) = offset("max_pixels") { + let (max_off, flags_off, frames_off) = if major < 60 { + ( + offset_of!(HwFields59, max_pixels), + offset_of!(HwFields59, hwaccel_flags), + offset_of!(HwFields59, hw_frames_ctx), + ) + } else { + ( + offset_of!(HwFields60, max_pixels), + offset_of!(HwFields60, hwaccel_flags), + offset_of!(HwFields60, hw_frames_ctx), + ) + }; + if let Some(base) = max_pixels.checked_sub(max_off) + && base + flags_off == flags + { + break 'found base + frames_off; + } + } + return Err("unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into()); + }; + let device = found + size_of::(); + // SAFETY: both offsets lie before `hwaccel_flags`, an option of this + // context, so inside it; pointer-aligned by construction. + let (frames, device) = unsafe { (read::(ctx, found), read::(ctx, device)) }; + if !frames.is_null() || !device.is_null() { + return Err("AVCodecContext.hw_frames_ctx check failed (not NULL in a new context)".into()); + } + Ok(found) +} + +/// Offsets in `AVHWFramesContext`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HwFramesFields { + pub initial_pool_size: usize, + pub format: usize, + pub sw_format: usize, + pub width: usize, + pub height: usize, +} + +/// Up to libavutil 58. +#[repr(C)] +struct HwFramesWithInternal { + av_class: Ptr, + internal: Ptr, + device_ref: Ptr, + device_ctx: Ptr, + hwctx: Ptr, + free: Ptr, + user_opaque: Ptr, + pool: Ptr, + initial_pool_size: c_int, + format: c_int, + sw_format: c_int, + width: c_int, + height: c_int, +} + +/// libavutil 59 and later. +#[repr(C)] +struct HwFramesPublic { + av_class: Ptr, + device_ref: Ptr, + device_ctx: Ptr, + hwctx: Ptr, + free: Ptr, + user_opaque: Ptr, + pool: Ptr, + initial_pool_size: c_int, + format: c_int, + sw_format: c_int, + width: c_int, + height: c_int, +} + +macro_rules! hw_frames_fields { + ($ty:ty) => { + HwFramesFields { + initial_pool_size: offset_of!($ty, initial_pool_size), + format: offset_of!($ty, format), + sw_format: offset_of!($ty, sw_format), + width: offset_of!($ty, width), + height: offset_of!($ty, height), + } + }; +} + +/// The fields of the frames context `frames` (fresh from +/// `av_hwframe_ctx_alloc(device)`; both are `AVBufferRef`s). +/// +/// # Safety +/// `frames` and `device` must be live buffer references of an +/// `AVHWFramesContext` just allocated on the `AVHWDeviceContext` `device`. +pub unsafe fn hw_frames_fields(frames: Ptr, device: Ptr) -> Result { + // SAFETY: guaranteed by the caller; `data` is the leading field pair. + let (ctx, device_ctx) = unsafe { + ( + (*frames.cast::()).data.cast::(), + (*device.cast::()).data.cast::(), + ) + }; + let check = |fields: HwFramesFields, device_at: usize| { + // SAFETY: both layouts lie within the smaller one (the current + // public struct); offsets from `offset_of!` are aligned. + unsafe { + read::(ctx, device_at) == device_ctx + && read::(ctx, fields.format) == -1 + && read::(ctx, fields.sw_format) == -1 + } + }; + let old = hw_frames_fields!(HwFramesWithInternal); + let new = hw_frames_fields!(HwFramesPublic); + match ( + check(old, offset_of!(HwFramesWithInternal, device_ctx)), + check(new, offset_of!(HwFramesPublic, device_ctx)), + ) { + (true, false) => Ok(old), + (false, true) => Ok(new), + _ => Err("unknown AVHWFramesContext layout".into()), + } +} + +/// Offsets of `buf[0]` and `hw_frames_ctx` in `AVFrame`, for importing +/// DMA-BUFs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameRefs { + pub buf: usize, + 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. +fn frame_refs_table(avutil_major: u32) -> Option { + if size_of::() != 8 { + return None; + } + let (buf, hw_frames_ctx) = match avutil_major { + 56 => (288, 480), + 57 | 58 => (224, 392), + 59 => (200, 352), + 60.. => (184, 328), + _ => return None, + }; + Some(FrameRefs { buf, hw_frames_ctx }) +} + +/// [`FrameRefs`] of this release, with `buf[0]` checked on a real frame +/// (`hw_frames_ctx` is checked once a hardware frame exists, see +/// [`check_hw_frames_ctx`]). +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"))?; + // 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. + unsafe { + let mut frame = (api.av_frame_alloc)(); + if frame.is_null() { + return Err("av_frame_alloc failed".into()); + } + let head = frame.cast::(); + (*head).width = 16; + (*head).height = 16; + (*head).format = yuv420p; + let ok = (api.av_frame_get_buffer)(frame, 0) >= 0 && { + let buf: Ptr = read(frame, refs.buf); + let hw: Ptr = read(frame, refs.hw_frames_ctx); + !buf.is_null() && (*buf.cast::()).data == (*head).data[0] && hw.is_null() + }; + (api.av_frame_free)(&mut frame); + if ok { Ok(refs) } else { Err(format!("AVFrame.buf check failed (libavutil {major})")) } + } +} + +/// Whether `frame` (from `av_hwframe_get_buffer(pool, ...)`) references +/// `pool` at `refs.hw_frames_ctx`. +/// +/// # Safety +/// `frame` must be a live AVFrame of this release, `pool` a live buffer +/// reference. +#[allow(dead_code)] // for the DMA-BUF import +pub unsafe fn check_hw_frames_ctx(frame: Ptr, pool: Ptr, refs: FrameRefs) -> bool { + // SAFETY: guaranteed by the caller; the offset is inside AVFrame. + unsafe { + let hw: Ptr = read(frame, refs.hw_frames_ctx); + !hw.is_null() + && (*hw.cast::()).data == (*pool.cast::()).data + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The mirrors give the offsets compiled from FFmpeg's headers + /// (x86-64): 4.4-7.1 `pict_type` 124 / `pts` 136, 8.0 120 / 136; + /// `hw_frames_ctx` 16 bytes before `max_pixels` (4.4-6.1) and 16 before + /// `hwaccel_flags` (7.1, 8.0). + #[cfg(target_pointer_width = "64")] + #[test] + fn mirrors_match_the_headers() { + assert_eq!(offset_of!(FrameWithKeyFrame, pict_type), 124); + assert_eq!(offset_of!(FrameWithKeyFrame, pts), 136); + assert_eq!(offset_of!(FrameWithoutKeyFrame, pict_type), 120); + assert_eq!(offset_of!(FrameWithoutKeyFrame, pts), 136); + assert_eq!(offset_of!(HwFields60, max_pixels) - offset_of!(HwFields60, hw_frames_ctx), 16); + assert_eq!(offset_of!(HwFields59, max_pixels) - offset_of!(HwFields59, hw_frames_ctx), 16); + assert_eq!(offset_of!(HwFields60, hwaccel_flags) - offset_of!(HwFields60, max_pixels), 16); + // 7.1: err_recognition 528, hw_frames_ctx 552, hwaccel_flags 568. + assert_eq!(offset_of!(HwFieldsNew, hw_frames_ctx), 552 - 528); + assert_eq!(offset_of!(HwFieldsNew, hwaccel_flags), 568 - 528); + assert_eq!(offset_of!(HwFramesWithInternal, format), 68); + assert_eq!(offset_of!(HwFramesPublic, format), 60); + assert_eq!(frame_refs_table(58), Some(FrameRefs { buf: 224, hw_frames_ctx: 392 })); + assert_eq!(frame_refs_table(55), None); + } +} diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs new file mode 100644 index 0000000..5830540 --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -0,0 +1,247 @@ +//! FFmpeg, loaded at runtime (feature `ffmpeg`): hardware video encoders +//! (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox) and +//! more software encoders (x264, OpenH264, SVT-AV1, rav1e, libaom). +//! +//! FFmpeg is never linked or shipped: [`Ffmpeg::get`] finds the system's +//! (or `VOELIN_FFMPEG_DIR`'s) libavcodec and libavutil, whatever their major +//! version, and looks up the functions it needs by name ([`sys`]). Without +//! them the software encoders of this crate are used as before. Struct +//! layouts that differ between releases are avoided (AVOptions for every +//! codec setting) or located and checked at runtime ([`layout`]). +//! +//! [`probe`] lists every encoder backend with the result of a self-test (one +//! small frame encoded), so a backend whose driver or GPU is missing is +//! skipped with a reason, without affecting the others. +#![allow(unsafe_code)] + +use std::ffi::{CStr, c_char, c_int}; +use std::path::PathBuf; +use std::sync::{Mutex, OnceLock}; + +pub mod encoder; +mod layout; +pub mod sys; + +pub use encoder::{ + BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe, +}; +pub use sys::Search; + +use self::layout::{FrameFields, FrameRefs}; +use self::sys::{Api, Libs, LogCallback, Ptr, VaList}; + +/// Pixel format numbers of this release (looked up by name). +#[derive(Clone, Copy, Debug)] +pub(crate) struct PixFmts { + pub yuv420p: c_int, + pub nv12: c_int, + pub vaapi: Option, + pub drm_prime: Option, +} + +/// What was loaded, for logs and the UI. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LibraryInfo { + /// libavcodec's file. + pub path: PathBuf, + /// FFmpeg's release (`av_version_info`, e.g. `6.1.1-3ubuntu5`). + pub release: String, + /// `major.minor.micro` of libavcodec and libavutil. + pub avcodec: String, + pub avutil: String, + /// libavformat of the same release was found (for RTMP output later). + pub avformat: bool, + /// Why hardware frame pools (VA-API) cannot be used, if not. + pub hw_frames: Result<(), String>, + /// Why DMA-BUF frames cannot be imported (zero-copy), if not. + pub dmabuf_import: Result<(), String>, +} + +/// Loaded FFmpeg libraries. +pub struct Ffmpeg { + pub(crate) api: Api, + _libs: Libs, + pub(crate) frame: FrameFields, + /// `AVCodecContext.hw_frames_ctx`. + pub(crate) codec_hw_frames: Result, + /// `AVFrame.buf[0]` / `hw_frames_ctx`. + #[allow(dead_code)] // for the DMA-BUF import + pub(crate) frame_refs: Result, + pub(crate) pix: PixFmts, + info: LibraryInfo, +} + +// SAFETY: `Api` holds plain function pointers and `Libs` library handles; +// FFmpeg's functions used here are thread-safe for distinct objects. +unsafe impl Send for Ffmpeg {} +unsafe impl Sync for Ffmpeg {} + +impl std::fmt::Debug for Ffmpeg { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Ffmpeg").field("info", &self.info).finish_non_exhaustive() + } +} + +fn version_text(v: u32) -> String { + format!("{}.{}.{}", v >> 16, (v >> 8) & 0xff, v & 0xff) +} + +impl Ffmpeg { + /// Load FFmpeg from `search`. Prefer [`Ffmpeg::get`], which loads once + /// per process. + pub fn load(search: &Search) -> Result { + let (libs, api) = sys::load(search)?; + let frame = layout::frame_fields(&api)?; + let yuv420p = api.pix_fmt("yuv420p").ok_or("no yuv420p pixel format")?; + let nv12 = api.pix_fmt("nv12").ok_or("no nv12 pixel format")?; + let pix = PixFmts { + yuv420p, + nv12, + vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")), + drm_prime: api.pix_fmt("drm_prime"), + }; + let codec_hw_frames = layout::codec_hw_frames(&api); + let frame_refs = layout::frame_refs(&api, yuv420p); + // SAFETY: no arguments; returns version numbers and a static string. + let (avcodec, avutil, release) = unsafe { + ( + (api.avcodec_version)(), + (api.avutil_version)(), + CStr::from_ptr((api.av_version_info)()).to_string_lossy().into_owned(), + ) + }; + let info = LibraryInfo { + path: libs.path.clone(), + release, + avcodec: version_text(avcodec), + avutil: version_text(avutil), + avformat: libs.avformat.is_some(), + hw_frames: codec_hw_frames.clone().map(|_| ()), + dmabuf_import: match (&codec_hw_frames, &frame_refs, pix.drm_prime) { + (Err(e), _, _) | (_, Err(e), _) => Err(e.clone()), + (_, _, None) => Err("no DRM PRIME pixel format".into()), + _ => Ok(()), + }, + }; + Ok(Self { api, _libs: libs, frame, codec_hw_frames, frame_refs, pix, info }) + } + + /// The process's FFmpeg, loaded on first use from [`Search::from_env`] + /// (`VOELIN_FFMPEG_DIR`), or why there is none. `VOELIN_FFMPEG=0` + /// disables it. + pub fn get() -> Result<&'static Ffmpeg, &'static str> { + static FFMPEG: OnceLock> = OnceLock::new(); + FFMPEG + .get_or_init(|| { + if std::env::var("VOELIN_FFMPEG").is_ok_and(|v| matches!(v.as_str(), "0" | "off")) + { + return Err("disabled by VOELIN_FFMPEG".into()); + } + let loaded = Self::load(&Search::from_env()); + match &loaded { + Ok(ffmpeg) => { + ffmpeg.capture_log(); + tracing::info!( + path = %ffmpeg.info.path.display(), + release = ffmpeg.info.release, + avcodec = ffmpeg.info.avcodec, + "FFmpeg loaded" + ); + } + Err(e) => tracing::info!("FFmpeg not used: {e}"), + } + loaded + }) + .as_ref() + .map_err(String::as_str) + } + + pub fn info(&self) -> &LibraryInfo { + &self.info + } + + /// Route FFmpeg's warnings and errors to `tracing` (and to + /// [`take_log`] for error reports) instead of stderr. + fn capture_log(&self) { + let _ = LOG_FORMAT.set(self.api.av_log_format_line2); + // SAFETY: sets a global level and a callback that stays valid (a + // plain function). + unsafe { + (self.api.av_log_set_level)(sys::LOG_WARNING); + (self.api.av_log_set_callback)(Some(log_callback as LogCallback)); + } + } +} + +type FormatLine = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList, *mut c_char, c_int, *mut c_int) -> c_int; + +static LOG_FORMAT: OnceLock = OnceLock::new(); + +/// The last FFmpeg messages (warnings and errors), for error reports. +static LOG: Mutex> = Mutex::new(Vec::new()); + +/// Take the FFmpeg messages logged since the last call (at most 16). +pub fn take_log() -> Vec { + std::mem::take(&mut *LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) +} + +unsafe extern "C" fn log_callback(avcl: Ptr, level: c_int, fmt: *const c_char, vl: VaList) { + if level > sys::LOG_WARNING { + return; + } + let Some(format) = LOG_FORMAT.get() else { return }; + let mut line = [0 as c_char; 512]; + let mut prefix: c_int = 1; + // SAFETY: FFmpeg passes its own arguments through; the buffer and its + // size are valid, and the result is NUL-terminated. + let text = unsafe { + format(avcl, level, fmt, vl, line.as_mut_ptr(), line.len() as c_int, &mut prefix); + CStr::from_ptr(line.as_ptr()) + }; + let text = text.to_string_lossy().trim_end().to_owned(); + if text.is_empty() { + return; + } + if level <= sys::LOG_ERROR { + tracing::debug!(target: "ffmpeg", "{text}"); + } else { + tracing::trace!(target: "ffmpeg", "{text}"); + } + if let Ok(mut log) = LOG.lock() { + if log.len() >= 16 { + log.remove(0); + } + log.push(text); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// With FFmpeg installed (the CI image and this machine have it), every + /// runtime check of the layout passes. + #[test] + fn loads_when_installed() { + let Ok(ffmpeg) = Ffmpeg::get() else { + eprintln!("FFmpeg not installed, skipped"); + return; + }; + let info = ffmpeg.info(); + assert!(!info.release.is_empty()); + assert!(info.avcodec.split('.').count() == 3); + assert!(info.hw_frames.is_ok(), "{info:?}"); + if cfg!(target_pointer_width = "64") { + assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs); + } + } + + #[test] + fn no_ffmpeg_in_an_empty_directory() { + let dir = std::env::temp_dir().join(format!("voelin-no-ffmpeg-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let err = Ffmpeg::load(&Search { dirs: vec![dir.clone()], system: false }).unwrap_err(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(err.contains("no FFmpeg libraries"), "{err}"); + } +} diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs new file mode 100644 index 0000000..d82b4c6 --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -0,0 +1,569 @@ +//! The FFmpeg libraries, found and opened at runtime (`libloading`), and the +//! few functions and struct fields this crate uses. +//! +//! Nothing is linked: every function is looked up by name once, and a +//! library that lacks one is not used. Struct fields are read or written only +//! where FFmpeg offers no function or AVOption for them; see [`super::layout`] +//! for which ones and why that is safe across major versions. +#![allow(unsafe_code)] + +use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void}; +use std::path::{Path, PathBuf}; + +use libloading::Library; + +/// An FFmpeg object behind an opaque pointer (`AVCodecContext *`, ...). +pub type Ptr = *mut c_void; + +/// `va_list` as FFmpeg's log callback receives it and `av_log_format_line2` +/// takes it. On every ABI this crate builds for it is passed as one pointer: +/// a `char *` (Windows, Apple, 32-bit x86), an array that decays to a pointer +/// (x86-64 System V), or a struct larger than 16 bytes passed by reference +/// (AArch64 AAPCS), or a one-word struct in a register (32-bit ARM). It is +/// only ever handed back to FFmpeg, never read. +pub type VaList = *mut c_void; + +/// `AVRational`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Rational { + pub num: c_int, + pub den: c_int, +} + +/// The leading fields of `AVPacket`, unchanged since libavcodec 55 (FFmpeg +/// 2.1): `buf`, `pts`, `dts`, `data`, `size`, `stream_index`, `flags`. +/// Packets are always allocated by `av_packet_alloc`, so the struct is at +/// least this large. +#[repr(C)] +pub struct PacketHead { + pub buf: Ptr, + pub pts: i64, + pub dts: i64, + pub data: *mut u8, + pub size: c_int, + pub stream_index: c_int, + pub flags: c_int, +} + +/// `AV_PKT_FLAG_KEY`. +pub const PKT_FLAG_KEY: c_int = 1; + +/// The number of data pointers of an `AVFrame` (`AV_NUM_DATA_POINTERS`, +/// 8 since libavutil 51). +pub const NUM_DATA_POINTERS: usize = 8; + +/// The leading fields of `AVFrame`, unchanged since libavutil 51 (FFmpeg +/// 0.9): `data[8]`, `linesize[8]`, `extended_data`, `width`, `height`, +/// `nb_samples`, `format`. Frames are always allocated by `av_frame_alloc`. +#[repr(C)] +pub struct FrameHead { + pub data: [*mut u8; NUM_DATA_POINTERS], + pub linesize: [c_int; NUM_DATA_POINTERS], + pub extended_data: *mut *mut u8, + pub width: c_int, + pub height: c_int, + pub nb_samples: c_int, + pub format: c_int, +} + +/// The leading fields of `AVOption` (`name`, `help`, `offset`, `type`), +/// unchanged since FFmpeg 0.5. Only `offset` is read, to locate fields of +/// `AVCodecContext` that have no option of their own (see +/// [`super::layout`]). +#[repr(C)] +pub struct OptionHead { + pub name: *const c_char, + pub help: *const c_char, + pub offset: c_int, + pub kind: c_int, +} + +/// The leading fields of `AVBufferRef` (`buffer`, `data`); `size` changed +/// from `int` to `size_t` in libavutil 57 and is not read. +#[repr(C)] +pub struct BufferRefHead { + pub buffer: Ptr, + pub data: *mut u8, +} + +/// `AVDRMObjectDescriptor` (`libavutil/hwcontext_drm.h`, unchanged since it +/// was added in libavutil 55). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct DrmObject { + pub fd: c_int, + pub size: usize, + pub format_modifier: u64, +} + +/// `AVDRMPlaneDescriptor`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct DrmPlane { + pub object_index: c_int, + pub offset: isize, + pub pitch: isize, +} + +/// `AV_DRM_MAX_PLANES`. +pub const DRM_MAX_PLANES: usize = 4; + +/// `AVDRMLayerDescriptor`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct DrmLayer { + pub format: u32, + pub nb_planes: c_int, + pub planes: [DrmPlane; DRM_MAX_PLANES], +} + +/// `AVDRMFrameDescriptor`: what `data[0]` of an `AV_PIX_FMT_DRM_PRIME` frame +/// points to. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct DrmFrameDescriptor { + pub nb_objects: c_int, + pub objects: [DrmObject; DRM_MAX_PLANES], + pub nb_layers: c_int, + pub layers: [DrmLayer; DRM_MAX_PLANES], +} + +/// `AV_PICTURE_TYPE_NONE` and `AV_PICTURE_TYPE_I`. +pub const PICTURE_TYPE_NONE: c_int = 0; +pub const PICTURE_TYPE_I: c_int = 1; + +/// `AV_NOPTS_VALUE`. +pub const NOPTS_VALUE: i64 = i64::MIN; + +/// `AV_LOG_*` levels. +pub const LOG_QUIET: c_int = -8; +pub const LOG_ERROR: c_int = 16; +pub const LOG_WARNING: c_int = 24; + +/// `AV_HWFRAME_MAP_READ` and `AV_HWFRAME_MAP_DIRECT`. +pub const HWFRAME_MAP_READ: c_int = 1; +pub const HWFRAME_MAP_DIRECT: c_int = 8; + +/// `AVERROR(EAGAIN)`: FFmpeg errors are negated `errno` values of the C +/// library it was built against. +#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd"))] +pub const EAGAIN: c_int = -35; +#[cfg(not(any( + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "openbsd" +)))] +pub const EAGAIN: c_int = -11; + +/// `FFERRTAG(a, b, c, d)`. +const fn err_tag(a: u8, b: u8, c: u8, d: u8) -> c_int { + -((a as c_int) | (b as c_int) << 8 | (c as c_int) << 16 | (d as c_int) << 24) +} + +/// `AVERROR_EOF`. +pub const EOF: c_int = err_tag(b'E', b'O', b'F', b' '); +/// `AVERROR_OPTION_NOT_FOUND`. +pub const OPTION_NOT_FOUND: c_int = err_tag(0xF8, b'O', b'P', b'T'); + +/// Declares the function table: every function, its library, its C +/// signature. `resolve` looks all of them up; a missing one fails the load. +macro_rules! api { + ($($lib:ident { $(fn $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)* })*) => { + /// FFmpeg functions used by this crate. + #[allow(non_snake_case, dead_code)] + pub struct Api { + $($(pub $name: unsafe extern "C" fn($($ty),*) $(-> $ret)?,)*)* + } + + impl Api { + /// # Safety + /// The libraries must be FFmpeg's, so the symbols have the + /// declared signatures. + unsafe fn resolve(libs: &Libs) -> Result { + Ok(Self { + $($($name: unsafe { libs.symbol(Lib::$lib, stringify!($name))? },)*)* + }) + } + } + }; +} + +api! { + Util { + fn avutil_version() -> c_uint; + fn av_version_info() -> *const c_char; + fn av_frame_alloc() -> Ptr; + fn av_frame_free(frame: *mut Ptr); + fn av_frame_get_buffer(frame: Ptr, align: c_int) -> c_int; + fn av_frame_make_writable(frame: Ptr) -> c_int; + fn av_frame_unref(frame: Ptr); + fn av_opt_set(obj: Ptr, name: *const c_char, val: *const c_char, flags: c_int) -> c_int; + fn av_opt_set_int(obj: Ptr, name: *const c_char, val: i64, flags: c_int) -> c_int; + fn av_opt_set_q(obj: Ptr, name: *const c_char, val: Rational, flags: c_int) -> c_int; + fn av_opt_set_image_size(obj: Ptr, name: *const c_char, w: c_int, h: c_int, flags: c_int) -> c_int; + fn av_opt_set_pixel_fmt(obj: Ptr, name: *const c_char, fmt: c_int, flags: c_int) -> c_int; + fn av_opt_find( + obj: Ptr, + name: *const c_char, + unit: *const c_char, + opt_flags: c_int, + search_flags: c_int + ) -> *const OptionHead; + fn av_opt_child_next(obj: Ptr, prev: Ptr) -> Ptr; + fn av_strerror(errnum: c_int, buf: *mut c_char, size: usize) -> c_int; + fn av_get_pix_fmt(name: *const c_char) -> c_int; + fn av_log_set_level(level: c_int); + fn av_log_set_callback(callback: Option); + fn av_log_format_line2( + avcl: Ptr, + level: c_int, + fmt: *const c_char, + vl: VaList, + line: *mut c_char, + size: c_int, + print_prefix: *mut c_int + ) -> c_int; + fn av_buffer_ref(buf: Ptr) -> Ptr; + fn av_buffer_unref(buf: *mut Ptr); + fn av_hwdevice_find_type_by_name(name: *const c_char) -> c_int; + fn av_hwdevice_ctx_create( + device: *mut Ptr, + kind: c_int, + name: *const c_char, + opts: Ptr, + flags: c_int + ) -> c_int; + fn av_hwframe_ctx_alloc(device: Ptr) -> Ptr; + fn av_hwframe_ctx_init(frames: Ptr) -> c_int; + fn av_hwframe_get_buffer(frames: Ptr, frame: Ptr, flags: c_int) -> c_int; + fn av_hwframe_transfer_data(dst: Ptr, src: Ptr, flags: c_int) -> c_int; + fn av_hwframe_map(dst: Ptr, src: Ptr, flags: c_int) -> c_int; + } + + Codec { + fn avcodec_version() -> c_uint; + fn avcodec_find_encoder_by_name(name: *const c_char) -> Ptr; + fn avcodec_alloc_context3(codec: Ptr) -> Ptr; + fn avcodec_free_context(ctx: *mut Ptr); + fn avcodec_open2(ctx: Ptr, codec: Ptr, options: *mut Ptr) -> c_int; + fn avcodec_send_frame(ctx: Ptr, frame: Ptr) -> c_int; + fn avcodec_receive_packet(ctx: Ptr, packet: Ptr) -> c_int; + fn av_packet_alloc() -> Ptr; + fn av_packet_free(packet: *mut Ptr); + fn av_packet_unref(packet: Ptr); + } +} + +/// `void (*)(void *avcl, int level, const char *fmt, va_list vl)`. +pub type LogCallback = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList); + +#[derive(Clone, Copy)] +enum Lib { + Util, + Codec, +} + +/// The opened libraries. Never closed: FFmpeg keeps global state (codec +/// registrations, the log callback) that must outlive every object. +pub struct Libs { + avcodec: Library, + /// libavutil where symbols are not found through libavcodec's handle + /// (Windows: `GetProcAddress` does not search dependencies). + avutil: Option, + /// libavformat, if present (for later use: RTMP output). + pub avformat: Option, + /// Where libavcodec was found. + pub path: PathBuf, +} + +impl Libs { + /// # Safety + /// `T` must be the symbol's actual type. + unsafe fn symbol(&self, lib: Lib, name: &str) -> Result { + let library = match lib { + Lib::Util => self.avutil.as_ref().unwrap_or(&self.avcodec), + Lib::Codec => &self.avcodec, + }; + // SAFETY: the caller guarantees the type; the library stays loaded + // for the life of the process (it is never dropped, see `Libs`). + unsafe { library.get::(name.as_bytes()) } + .map(|s| *s) + .map_err(|e| format!("{} lacks {name}: {e}", self.path.display())) + } +} + +/// Where to look for FFmpeg. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Search { + /// Directories searched first (full paths, newest major first). + pub dirs: Vec, + /// Also the system's library search path (and `ldconfig -p` on Linux, + /// Homebrew and MacPorts on macOS, the executable's directory and `PATH` + /// on Windows). + pub system: bool, +} + +impl Search { + /// `VOELIN_FFMPEG_DIR` (only that directory) if set, else the system. + pub fn from_env() -> Self { + match std::env::var_os("VOELIN_FFMPEG_DIR") { + Some(dir) if !dir.is_empty() => Self { dirs: vec![dir.into()], system: false }, + _ => Self { dirs: Vec::new(), system: true }, + } + } +} + +/// The major version in a library file name: `libavcodec.so.61` → 61, +/// `avcodec-61.dll` → 61, `libavcodec.61.dylib` → 61. +pub fn major_of(name: &str) -> Option { + let name = name.rsplit(['/', '\\']).next()?; + let rest = name.strip_prefix("lib").unwrap_or(name); + let rest = rest.split_once(['.', '-'])?.1; + rest.split(['.', '-']).find_map(|part| part.parse().ok()) +} + +/// Library names (not paths) of `base` to try with the system search, newest +/// first. The range of majors reaches well past today's (62) so newer +/// releases are found without a change here; `ldconfig -p` covers the rest. +fn system_names(base: &str) -> Vec { + const MAJORS: std::ops::RangeInclusive = 54..=80; + let mut names = Vec::new(); + if cfg!(windows) { + names.extend(MAJORS.rev().map(|n| format!("{base}-{n}.dll"))); + names.push(format!("{base}.dll")); + } else if cfg!(target_vendor = "apple") { + names.extend(MAJORS.rev().map(|n| format!("lib{base}.{n}.dylib"))); + names.push(format!("lib{base}.dylib")); + } else { + names.extend(MAJORS.rev().map(|n| format!("lib{base}.so.{n}"))); + names.push(format!("lib{base}.so")); + } + names +} + +/// Full paths of `base` in `dir`, newest major first. +fn files_in(dir: &Path, base: &str) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut found: Vec<(u32, PathBuf)> = entries + .flatten() + .filter_map(|e| { + let name = e.file_name().to_string_lossy().into_owned(); + let matches = (name.starts_with(&format!("lib{base}.")) && name.contains(".so")) + || (name.starts_with(&format!("lib{base}.")) && name.ends_with(".dylib")) + || (name.starts_with(&format!("{base}-")) && name.ends_with(".dll")) + || name == format!("{base}.dll"); + matches.then(|| (major_of(&name).unwrap_or(0), e.path())) + }) + .collect(); + found.sort_by(|a, b| b.0.cmp(&a.0)); + found.into_iter().map(|(_, p)| p).collect() +} + +/// `ldconfig -p` entries of `base` (Linux), newest major first. +#[cfg(target_os = "linux")] +fn ldconfig(base: &str) -> Vec { + let Ok(output) = std::process::Command::new("ldconfig").arg("-p").output() else { + return Vec::new(); + }; + let text = String::from_utf8_lossy(&output.stdout); + let prefix = format!("lib{base}.so"); + let mut found: Vec<(u32, PathBuf)> = text + .lines() + .filter_map(|line| { + let (name, path) = line.trim().split_once(" => ")?; + let name = name.split_whitespace().next()?; + name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path))) + }) + .collect(); + found.sort_by(|a, b| b.0.cmp(&a.0)); + found.into_iter().map(|(_, p)| p).collect() +} + +/// Candidates for `base` (`avcodec`, `avformat`) in search order. +fn candidates(search: &Search, base: &str) -> Vec { + let mut list: Vec = Vec::new(); + for dir in &search.dirs { + list.extend(files_in(dir, base)); + } + if search.system { + if cfg!(target_vendor = "apple") { + for dir in ["/opt/homebrew/lib", "/usr/local/lib", "/opt/local/lib"] { + list.extend(files_in(Path::new(dir), base)); + } + } + if cfg!(windows) + && let Some(dir) = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned)) + { + list.extend(files_in(&dir, base)); + } + list.extend(system_names(base).into_iter().map(PathBuf::from)); + #[cfg(target_os = "linux")] + list.extend(ldconfig(base)); + } + let mut seen = std::collections::HashSet::new(); + list.retain(|p| seen.insert(p.clone())); + list +} + +/// Open one library file or name. +fn open(path: &Path) -> Result { + #[cfg(windows)] + if path.is_absolute() { + use libloading::os::windows::{LOAD_WITH_ALTERED_SEARCH_PATH, Library as WinLibrary}; + // SAFETY: loading runs the library's initialisers; FFmpeg's have no + // preconditions. + return unsafe { WinLibrary::load_with_flags(path, LOAD_WITH_ALTERED_SEARCH_PATH) } + .map(Library::from); + } + // SAFETY: as above. + unsafe { Library::new(path.as_os_str()) } +} + +/// Load libavutil files of `dir` first, so libavcodec's dependencies resolve +/// to them when `dir` is not on the system search path (each file only +/// satisfies its own soname). +fn preload_dependencies(dir: &Path, keep: &mut Vec) { + for base in ["avutil", "swresample"] { + for path in files_in(dir, base) { + if let Ok(lib) = open(&path) { + keep.push(lib); + } + } + } +} + +/// On Windows, the libavutil DLL libavcodec loaded (already in the process). +#[cfg(windows)] +fn loaded_avutil(avcodec: &Path) -> Option { + use libloading::os::windows::Library as WinLibrary; + let mut names: Vec = system_names("avutil").into_iter().map(PathBuf::from).collect(); + if let Some(dir) = avcodec.parent() { + names.splice(0..0, files_in(dir, "avutil")); + } + names.into_iter().find_map(|name| { + let file = name.file_name()?.to_owned(); + WinLibrary::open_already_loaded(file).ok().map(Library::from) + }) +} + +/// Find and open libavcodec (with the libavutil it depends on) and, if +/// present, libavformat, then look up every function. +pub fn load(search: &Search) -> Result<(Libs, Api), String> { + let mut errors = Vec::new(); + let mut preloaded = Vec::new(); + for dir in &search.dirs { + preload_dependencies(dir, &mut preloaded); + } + for path in candidates(search, "avcodec") { + let avcodec = match open(&path) { + Ok(lib) => lib, + Err(e) => { + if path.is_absolute() { + errors.push(format!("{}: {e}", path.display())); + } + continue; + } + }; + #[cfg(windows)] + let avutil = loaded_avutil(&path); + #[cfg(not(windows))] + // dlsym on libavcodec's handle also searches its dependencies, so + // libavutil's functions come from the very library it was built with. + let avutil = None; + let mut libs = Libs { avcodec, avutil, avformat: None, path: path.clone() }; + // SAFETY: the library is libavcodec (found by its file name), whose + // exported functions have the signatures declared in `api!`. + match unsafe { Api::resolve(&libs) } { + Ok(api) => { + // libavformat of the same release: libavformat and libavcodec + // share their major version. + // SAFETY: no arguments; returns a version number. + let major = unsafe { (api.avcodec_version)() } >> 16; + libs.avformat = candidates(search, "avformat") + .into_iter() + .filter(|p| major_of(&p.to_string_lossy()) == Some(major)) + .find_map(|p| open(&p).ok()); + // Keep the preloaded dependencies loaded for good. + std::mem::forget(preloaded); + return Ok((libs, api)); + } + Err(e) => errors.push(e), + } + } + if errors.is_empty() { + let place = if search.system { + "on the system library path".to_owned() + } else { + search.dirs.iter().map(|d| d.display().to_string()).collect::>().join(", ") + }; + Err(format!("no FFmpeg libraries (libavcodec) found {place}")) + } else { + Err(errors.join("; ")) + } +} + +/// A C string for an FFmpeg call (names and option values never contain +/// NUL; one that does is passed as empty). +pub fn cstr(s: &str) -> CString { + CString::new(s).unwrap_or_default() +} + +impl Api { + /// FFmpeg's text for an error code. + pub fn error_text(&self, code: c_int) -> String { + let mut buf = [0 as c_char; 256]; + // SAFETY: the buffer and its size are valid; av_strerror always + // NUL-terminates within it. + unsafe { (self.av_strerror)(code, buf.as_mut_ptr(), buf.len()) }; + // SAFETY: NUL-terminated above. + let text = unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy(); + format!("{text} ({code})") + } + + /// `av_get_pix_fmt(name)`: pixel format numbers moved between majors, so + /// they are always looked up by name. `None` if unknown. + pub fn pix_fmt(&self, name: &str) -> Option { + let name = cstr(name); + // SAFETY: a valid C string. + let fmt = unsafe { (self.av_get_pix_fmt)(name.as_ptr()) }; + (fmt >= 0).then_some(fmt) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn majors_from_file_names() { + assert_eq!(major_of("libavcodec.so.61"), Some(61)); + assert_eq!(major_of("/usr/lib/x86_64-linux-gnu/libavcodec.so.60.31.102"), Some(60)); + assert_eq!(major_of("avcodec-62.dll"), Some(62)); + assert_eq!(major_of("C:\\ffmpeg\\bin\\avcodec-61.dll"), Some(61)); + assert_eq!(major_of("libavcodec.59.dylib"), Some(59)); + assert_eq!(major_of("libavcodec.so"), None); + } + + #[test] + fn system_names_are_newest_first_and_unbounded_below_today() { + let names = system_names("avcodec"); + let majors: Vec = names.iter().filter_map(|n| major_of(n)).collect(); + assert!(majors.windows(2).all(|w| w[0] > w[1])); + assert!(majors.contains(&58) && majors.contains(&62) && majors[0] > 62); + } + + #[test] + fn error_tags() { + assert_eq!(EOF, -0x2046_4F45); + assert_eq!(OPTION_NOT_FOUND, -0x5450_4FF8); + } + + #[test] + fn missing_directory_fails_cleanly() { + let search = Search { dirs: vec!["/nonexistent/voelin-ffmpeg".into()], system: false }; + let err = load(&search).err().expect("nothing there"); + assert!(err.contains("no FFmpeg libraries"), "{err}"); + } +} diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 538625b..6d57eba 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -8,7 +8,8 @@ //! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference //! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264 //! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding, -//! feature `av1`) +//! feature `av1`), and FFmpeg loaded at runtime ([`ffmpeg`], feature +//! `ffmpeg`: hardware encoders, x264, SVT-AV1, ...) //! - [`capture`]: [`ScreenCapture`] and [`AudioCapture`] with a synthetic //! test source, X11 (feature `x11`), the Wayland ScreenCast portal and //! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture @@ -27,6 +28,8 @@ pub mod capture; pub mod codec; pub mod convert; +#[cfg(feature = "ffmpeg")] +pub mod ffmpeg; pub mod frame; pub mod handoff; pub mod pool; @@ -36,8 +39,9 @@ pub mod workers; pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId}; pub use codec::{ - Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, - VideoDecoder, VideoEncoder, + BackendChoice, Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, + EncoderConfig, EncoderInfo, EncoderPreference, EncoderReport, H264Profile, VideoDecoder, + VideoEncoder, }; pub use frame::{ AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, From 8b9ea9ca1d5d4ae05b079ae6cdfaeda5b01c3e1a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 19:30:29 +0000 Subject: [PATCH 2/9] voelin-media: test FFmpeg encoders end to end, fix what that found The self-test and a roundtrip through our own decoders (OpenH264 for H.264, dav1d for AV1) run for every FFmpeg software encoder present: x264, SVT-AV1, rav1e and libaom all decode above 28 dB PSNR with the keyframes where they were asked for. Fixes: SVT-AV1 takes CBR from rc=2 and rejects a maximum rate equal to the target; rav1e refuses a keyframe interval of 2^30 and holds about 20 frames even in low-latency mode, so it is only used when named; a new session flushes the old one so delayed frames are not lost; the first packet of a session counts as a keyframe; FFmpeg's log lines go to the encoder they are about when backends are tested in parallel. Codecs::builtin() gives the compiled-in codecs alone, for tests that check libvpx or OpenH264 specifically. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/src/codec/hw.rs | 6 + crates/voelin-media/src/codec/mod.rs | 101 +++++++- crates/voelin-media/src/ffmpeg/encoder.rs | 103 ++++++--- crates/voelin-media/src/ffmpeg/layout.rs | 13 +- crates/voelin-media/src/ffmpeg/mod.rs | 27 ++- crates/voelin-media/src/ffmpeg/sys.rs | 3 +- crates/voelin-media/tests/codec_roundtrip.rs | 4 +- crates/voelin-media/tests/ffmpeg.rs | 230 +++++++++++++++++++ crates/voelin-media/tests/openh264.rs | 4 +- 9 files changed, 439 insertions(+), 52 deletions(-) create mode 100644 crates/voelin-media/tests/ffmpeg.rs diff --git a/crates/voelin-media/src/codec/hw.rs b/crates/voelin-media/src/codec/hw.rs index 3d80de0..7cedb6d 100644 --- a/crates/voelin-media/src/codec/hw.rs +++ b/crates/voelin-media/src/codec/hw.rs @@ -25,6 +25,12 @@ pub trait EncoderFactory: Send + Sync { true } + /// Whether the automatic choice may use it (not for encoders with a long + /// delay; those are used only when named in the settings). + fn is_automatic(&self) -> bool { + true + } + /// The backend its encoders report. fn backend(&self) -> EncoderBackend { EncoderBackend::Hardware(self.name()) diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 5c4b634..f020003 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -389,6 +389,14 @@ struct Candidate { codec: Codec, backend: EncoderBackend, hardware: bool, + /// See [`hw::EncoderFactory::is_automatic`]. + automatic: bool, +} + +impl Candidate { + fn builtin(codec: Codec, backend: EncoderBackend) -> Self { + Self { codec, backend, hardware: false, automatic: true } + } } /// The codecs this build and machine can use, and factories for them. @@ -435,6 +443,17 @@ impl Codecs { } } + /// Only the codecs compiled into this crate (libvpx, OpenH264 once + /// loaded, dav1d): no FFmpeg or MediaCodec, nothing probed. + pub fn builtin() -> Self { + Self { + factories: Vec::new(), + #[cfg(feature = "openh264")] + openh264: None, + preference: EncoderPreference::default(), + } + } + /// Enable H.264 through a loaded OpenH264 library. #[cfg(feature = "openh264")] pub fn with_openh264(mut self, library: h264::OpenH264) -> Self { @@ -505,7 +524,8 @@ impl Codecs { let factories = |codec: Codec, hardware: bool, list: &mut Vec| { for f in self.factories.iter().filter(|f| f.is_hardware() == hardware) { if f.codecs().contains(&codec) { - list.push(Candidate { codec, backend: f.backend(), hardware }); + let automatic = f.is_automatic(); + list.push(Candidate { codec, backend: f.backend(), hardware, automatic }); } } }; @@ -514,16 +534,15 @@ impl Codecs { } #[cfg(feature = "vpx")] if vpx::check(Codec::Vp8, true).is_ok() { - list.push(Candidate { codec: Codec::Vp8, backend: EncoderBackend::Libvpx, hardware: false }); + list.push(Candidate::builtin(Codec::Vp8, EncoderBackend::Libvpx)); } factories(Codec::H264, false, &mut list); if self.has_openh264() { - let backend = EncoderBackend::OpenH264; - list.push(Candidate { codec: Codec::H264, backend, hardware: false }); + list.push(Candidate::builtin(Codec::H264, EncoderBackend::OpenH264)); } #[cfg(feature = "vpx")] if vpx::check(Codec::Vp9, true).is_ok() { - list.push(Candidate { codec: Codec::Vp9, backend: EncoderBackend::Libvpx, hardware: false }); + list.push(Candidate::builtin(Codec::Vp9, EncoderBackend::Libvpx)); } for codec in [Codec::Av1, Codec::H265, Codec::Vp8, Codec::Vp9] { factories(codec, false, &mut list); @@ -539,10 +558,10 @@ impl Codecs { /// Encoders in the order `preference` gives. pub fn encoders_for(&self, preference: &EncoderPreference) -> Vec<(Codec, EncoderBackend)> { let all = self.candidates(); - let automatic = |c: &Candidate| preference.hardware || !c.hardware; + let automatic = |c: &Candidate| c.automatic && (preference.hardware || !c.hardware); let chosen: Vec<&Candidate> = match &preference.backend { BackendChoice::Auto => all.iter().filter(|c| automatic(c)).collect(), - BackendChoice::Software => all.iter().filter(|c| !c.hardware).collect(), + BackendChoice::Software => all.iter().filter(|c| c.automatic && !c.hardware).collect(), BackendChoice::Named(name) => { let named = all.iter().filter(|c| c.backend.name() == name); let rest = all.iter().filter(|c| c.backend.name() != name && automatic(c)); @@ -753,12 +772,13 @@ mod tests { #[test] fn preference_order() { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); // Without OpenH264, H.264 is neither offered nor accepted. assert!(!codecs.decoders().contains(&Codec::H264)); assert!(codecs.new_decoder(Codec::H264).is_err()); let err = codecs.new_encoder(Codec::H264, EncoderConfig::default()).err().unwrap(); assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}"); + assert!(codecs.new_decoder(Codec::H265).is_err()); #[cfg(feature = "vpx")] { assert_eq!(codecs.decoders()[..2], [Codec::Vp9, Codec::Vp8]); @@ -777,6 +797,71 @@ mod tests { assert!(order.windows(2).all(|w| w[0] < w[1])); } + struct Fake(&'static str, Codec, bool); + + impl hw::EncoderFactory for Fake { + fn name(&self) -> &'static str { + self.0 + } + + fn codecs(&self) -> Vec { + vec![self.1] + } + + fn create(&self, codec: Codec, _: &EncoderConfig) -> Result> { + Err(unavailable(codec, "fake")) + } + + fn is_hardware(&self) -> bool { + self.2 + } + + fn backend(&self) -> EncoderBackend { + EncoderBackend::Ffmpeg(self.0) + } + } + + #[test] + fn encoder_preference() { + let mut codecs = Codecs::builtin(); + codecs.factories = vec![ + Box::new(Fake("x264", Codec::H264, false)), + Box::new(Fake("vp8_gpu", Codec::Vp8, true)), + Box::new(Fake("h264_gpu", Codec::H264, true)), + Box::new(Fake("hevc_gpu", Codec::H265, true)), + Box::new(Fake("av1_sw", Codec::Av1, false)), + ]; + let names = |preference: EncoderPreference| -> Vec<&'static str> { + codecs.encoders_for(&preference).iter().map(|(_, b)| b.name()).collect() + }; + let auto = names(EncoderPreference::default()); + // Hardware in codec order (HEVC last), then software. + assert_eq!(auto[..3], ["h264_gpu", "vp8_gpu", "hevc_gpu"]); + let position = |list: &[&str], name| list.iter().position(|n| *n == name).unwrap(); + assert!(position(&auto, "x264") < position(&auto, "av1_sw")); + #[cfg(feature = "vpx")] + assert!(position(&auto, "libvpx") < position(&auto, "x264"), "VP8 before software H.264"); + let no_hardware = names(EncoderPreference { hardware: false, ..Default::default() }); + assert!(!no_hardware.iter().any(|n| n.ends_with("_gpu"))); + let software = + names(EncoderPreference { hardware: true, backend: "software".parse().unwrap() }); + assert_eq!(software, no_hardware); + // A named backend comes first, even hardware with acceleration off. + let named = + names(EncoderPreference { hardware: false, backend: "hevc_gpu".parse().unwrap() }); + assert_eq!(named[0], "hevc_gpu"); + assert!(!named[1..].iter().any(|n| n.ends_with("_gpu"))); + // The codecs follow the preference. + codecs.set_preference(EncoderPreference::default()); + assert_eq!(codecs.encoder_codecs()[..3], [Codec::H264, Codec::Vp8, Codec::H265]); + // The report ranks what the preference uses. + let report = codecs.report(); + let openh264 = report.encoders.iter().find(|e| e.name == "openh264").unwrap(); + assert!(openh264.status.is_err() && openh264.rank.is_none()); + assert_eq!("auto".parse::().unwrap(), BackendChoice::Auto); + assert_eq!(BackendChoice::Named("h264_vaapi".into()).to_string(), "h264_vaapi"); + } + #[test] fn thread_heuristic() { let config = EncoderConfig { threads: 3, ..EncoderConfig::default() }; diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 8dae0c9..a3251fa 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -105,7 +105,8 @@ pub static BACKENDS: &[BackendSpec] = &[ backend!("av1_vaapi", Av1, "VA-API", Hardware, Vaapi, false, INFINITE), backend!("av1_qsv", Av1, "Quick Sync", Hardware, Nv12, true, 65535), backend!("libsvtav1", Av1, "SVT-AV1", Software, Yuv420p, false, INFINITE), - backend!("librav1e", Av1, "rav1e", Software, Yuv420p, false, INFINITE), + // rav1e refuses a keyframe interval of 2^30. + backend!("librav1e", Av1, "rav1e", Software, Yuv420p, false, 1 << 29), backend!("libaom-av1", Av1, "libaom", Software, Yuv420p, false, INFINITE), // VP9 and VP8 (software VP8 / VP9 is libvpx, used directly) backend!("vp9_vaapi", Vp9, "VA-API", Hardware, Vaapi, false, INFINITE), @@ -122,6 +123,13 @@ impl BackendSpec { self.kind == BackendKind::Hardware } + /// Whether the automatic choice may use it: rav1e holds about 20 frames + /// before its first packet even in its low-latency mode (measured with + /// rav1e 0.7), so it is only used when named in the settings. + pub fn is_automatic(&self) -> bool { + self.name != "librav1e" + } + fn is_vaapi(&self) -> bool { self.input == Input::Vaapi } @@ -186,7 +194,8 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< let screen = config.content == ContentHint::Screen; let baseline = config.h264_profile == H264Profile::ConstrainedBaseline; let h264 = spec.codec == Codec::H264; - let generic_profile = if baseline { PROFILE_H264_CONSTRAINED_BASELINE } else { PROFILE_H264_HIGH }; + let generic_profile = + if baseline { PROFILE_H264_CONSTRAINED_BASELINE } else { PROFILE_H264_HIGH }; let mut list = Vec::new(); match spec.family() { "nvenc" => { @@ -213,7 +222,10 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< list.push(opt("look_ahead_depth", &["0"])); list.push(opt("forced_idr", &["1"])); list.push(opt("low_delay_brc", &["1"])); - list.push(opt("scenario", if screen { &["displayremoting"] } else { &["videoconference"] })); + list.push(opt( + "scenario", + if screen { &["displayremoting"] } else { &["videoconference"] }, + )); if h264 { list.push(opt("profile", if baseline { &["baseline"] } else { &["high"] })); } @@ -290,12 +302,18 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< "libsvtav1" => { let preset = config.speed.unwrap_or(10).to_string(); list.push(Setting { values: vec![preset], ..opt("preset", &[]) }); - list.push(opt("svtav1-params", &["pred-struct=1:lookahead=0:scd=0", "pred-struct=1"])); + list.push(opt( + "svtav1-params", + &["rc=2:pred-struct=1:lookahead=0:scd=0", "rc=2:pred-struct=1"], + )); } "librav1e" => { let speed = config.speed.unwrap_or(10).to_string(); list.push(Setting { values: vec![speed], ..opt("speed", &[]) }); - list.push(opt("rav1e-params", &["low_latency=true"])); + list.push(opt( + "rav1e-params", + &["low_latency=true:rdo_lookahead_frames=1:reservoir_frame_delay=12"], + )); } "libaom-av1" => { let cpu_used = config.speed.unwrap_or(8).to_string(); @@ -356,10 +374,20 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { let c_path = cstr(&path); // SAFETY: out pointer and C strings are valid; no options. let ret = unsafe { - (api.av_hwdevice_ctx_create)(&mut device, kind, c_path.as_ptr(), std::ptr::null_mut(), 0) + (api.av_hwdevice_ctx_create)( + &mut device, + kind, + c_path.as_ptr(), + std::ptr::null_mut(), + 0, + ) }; if ret < 0 { - return Err(format!("VA-API device {path}: {}{}", api.error_text(ret), log_suffix())); + return Err(format!( + "VA-API device {path}: {}{}", + api.error_text(ret), + log_suffix("vaapi") + )); } Ok(Device(device)) }) @@ -369,8 +397,8 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { } /// FFmpeg's recent messages, appended to an error. -fn log_suffix() -> String { - let log = take_log(); +fn log_suffix(context: &str) -> String { + let log = take_log(context); if log.is_empty() { String::new() } else { format!(" ({})", log.join("; ")) } } @@ -419,6 +447,9 @@ struct Session { hw: Ptr, packet: Ptr, last_pts: Option, + /// 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, timestamps: Timestamps, nv12: bool, } @@ -488,7 +519,7 @@ impl FfmpegEncoder { "{} {what}: {}{}", self.spec.name, self.ffmpeg.api.error_text(code), - log_suffix() + log_suffix(self.spec.name) ), } } @@ -587,6 +618,7 @@ impl FfmpegEncoder { hw: std::ptr::null_mut(), packet: std::ptr::null_mut(), last_pts: None, + first_packet: true, timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, }; @@ -596,7 +628,9 @@ impl FfmpegEncoder { let (w, h) = (width as c_int, height as c_int); let sw_format = if session.nv12 { pix.nv12 } else { pix.yuv420p }; let format = match self.spec.input { - Input::Vaapi => pix.vaapi.ok_or_else(|| self.unavailable("no VA-API pixel format".into()))?, + Input::Vaapi => { + pix.vaapi.ok_or_else(|| self.unavailable("no VA-API pixel format".into()))? + } _ => sw_format, }; let size = cstr("video_size"); @@ -620,7 +654,9 @@ impl FfmpegEncoder { let gop = self.config.keyframe_interval.map_or(self.spec.infinite_gop, i64::from); let mut list = vec![ generic("b", bitrate), - generic("maxrate", bitrate), + // 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), generic("g", gop), generic("bf", 0), @@ -691,7 +727,8 @@ impl FfmpegEncoder { fn vaapi_pool(&self, width: u32, height: u32) -> Result { let api = &self.ffmpeg.api; let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?; - let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; + let vaapi = + self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; // SAFETY: `device` is a live device reference. let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; if pool.is_null() { @@ -778,11 +815,7 @@ impl FfmpegEncoder { } /// Receive every packet that is ready. - fn drain( - &self, - session: &mut Session, - out: &mut dyn FnMut(EncodedChunk<'_>), - ) -> Result { + fn drain(&self, session: &mut Session, out: &mut dyn FnMut(EncodedChunk<'_>)) -> Result { let api = &self.ffmpeg.api; let mut keyframe = false; loop { @@ -798,11 +831,13 @@ impl FfmpegEncoder { // `size` bytes until av_packet_unref. unsafe { let head = &*session.packet.cast::(); - let key = head.flags & sys::PKT_FLAG_KEY != 0; + let key = head.flags & sys::PKT_FLAG_KEY != 0 || session.first_packet; + session.first_packet = false; keyframe |= key; - let pts_90khz = session.timestamps.take(head.pts).unwrap_or_else(|| { - (head.pts.max(0) as u64) * 90_000 / u64::from(session.fps) - }); + let pts_90khz = session + .timestamps + .take(head.pts) + .unwrap_or_else(|| (head.pts.max(0) as u64) * 90_000 / u64::from(session.fps)); if !head.data.is_null() && head.size > 0 { let data = std::slice::from_raw_parts(head.data, head.size as usize); out(EncodedChunk { data, keyframe: key, pts_90khz }); @@ -855,8 +890,14 @@ impl FfmpegEncoder { } }; if reopen { - // One session at a time (hardware encoders have few). - self.session = None; + // Frames the old session still holds (encoders with a delay) come + // out first; then one session at a time (hardware encoders have + // few). + if let Some(mut old) = self.session.take() + && let Err(e) = self.send(&mut old, std::ptr::null_mut(), out) + { + tracing::debug!(backend = self.spec.name, "flushing the old session: {e}"); + } self.session = Some(self.open(w, h)?); self.reinit = Reinit::No; force = true; @@ -1080,9 +1121,9 @@ pub fn probe() -> &'static [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())), + Some(handle) => { + handle.join().unwrap_or_else(|_| Err("the self-test panicked".into())) + } }, }) .collect() @@ -1090,7 +1131,9 @@ pub fn probe() -> &'static [BackendStatus] { 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}"), + Err(e) => { + tracing::debug!(backend = status.spec.name, "FFmpeg encoder unusable: {e}") + } } } statuses @@ -1140,6 +1183,10 @@ impl EncoderFactory for FfmpegFactory { self.spec.is_hardware() } + fn is_automatic(&self) -> bool { + self.spec.is_automatic() + } + fn backend(&self) -> EncoderBackend { EncoderBackend::Ffmpeg(self.spec.name) } diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 9245df0..0df7c63 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -105,8 +105,10 @@ pub fn frame_fields(api: &Api) -> Result { pict_type: offset_of!(FrameWithoutKeyFrame, pict_type), pts: offset_of!(FrameWithoutKeyFrame, pts), }), - _ => Err("unknown AVFrame layout (pict_type / pts not where any known release has them)" - .into()), + _ => { + Err("unknown AVFrame layout (pict_type / pts not where any known release has them)" + .into()) + } } } @@ -208,7 +210,9 @@ fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result { break 'found base + frames_off; } } - return Err("unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into()); + return Err( + "unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into() + ); }; let device = found + size_of::(); // SAFETY: both offsets lie before `hwaccel_flags`, an option of this @@ -377,8 +381,7 @@ pub unsafe fn check_hw_frames_ctx(frame: Ptr, pool: Ptr, refs: FrameRefs) -> boo // SAFETY: guaranteed by the caller; the offset is inside AVFrame. unsafe { let hw: Ptr = read(frame, refs.hw_frames_ctx); - !hw.is_null() - && (*hw.cast::()).data == (*pool.cast::()).data + !hw.is_null() && (*hw.cast::()).data == (*pool.cast::()).data } } diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 5830540..47a9162 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -133,8 +133,7 @@ impl Ffmpeg { static FFMPEG: OnceLock> = OnceLock::new(); FFMPEG .get_or_init(|| { - if std::env::var("VOELIN_FFMPEG").is_ok_and(|v| matches!(v.as_str(), "0" | "off")) - { + if std::env::var("VOELIN_FFMPEG").is_ok_and(|v| matches!(v.as_str(), "0" | "off")) { return Err("disabled by VOELIN_FFMPEG".into()); } let loaded = Self::load(&Search::from_env()); @@ -173,16 +172,32 @@ impl Ffmpeg { } } -type FormatLine = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList, *mut c_char, c_int, *mut c_int) -> c_int; +type FormatLine = unsafe extern "C" fn( + Ptr, + c_int, + *const c_char, + VaList, + *mut c_char, + c_int, + *mut c_int, +) -> c_int; static LOG_FORMAT: OnceLock = OnceLock::new(); /// The last FFmpeg messages (warnings and errors), for error reports. static LOG: Mutex> = Mutex::new(Vec::new()); -/// Take the FFmpeg messages logged since the last call (at most 16). -pub fn take_log() -> Vec { - std::mem::take(&mut *LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) +/// Take the FFmpeg messages logged since the last call (at most 16) that +/// are about `context` (an encoder name such as `h264_vaapi`: FFmpeg +/// prefixes its messages with `[h264_vaapi @ 0x...]`) or about nothing in +/// particular. Messages of other encoders (tested in parallel) stay. +pub fn take_log(context: &str) -> Vec { + let mut log = LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let tag = format!("[{context} @"); + let (mine, others): (Vec, Vec) = + log.drain(..).partition(|line| line.contains(&tag) || !line.contains(" @ 0x")); + *log = others; + mine } unsafe extern "C" fn log_callback(avcl: Ptr, level: c_int, fmt: *const c_char, vl: VaList) { diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index d82b4c6..c95bbb2 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -394,7 +394,8 @@ fn candidates(search: &Search, base: &str) -> Vec { } } if cfg!(windows) - && let Some(dir) = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned)) + && let Some(dir) = + std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned)) { list.extend(files_in(&dir, base)); } diff --git a/crates/voelin-media/tests/codec_roundtrip.rs b/crates/voelin-media/tests/codec_roundtrip.rs index c92561d..07ffb06 100644 --- a/crates/voelin-media/tests/codec_roundtrip.rs +++ b/crates/voelin-media/tests/codec_roundtrip.rs @@ -27,7 +27,7 @@ fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str) /// Encode 30 frames of the pattern, force a keyframe midway, lower the /// bitrate, and check every decoded frame. fn roundtrip(codec: Codec) { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); let screen = SyntheticScreen::new(W, H); let config = EncoderConfig { fps: FPS, bitrate_bps: 1_500_000, ..EncoderConfig::default() }; let mut encoder = codecs.new_encoder(codec, config).unwrap(); @@ -69,7 +69,7 @@ fn vp9_synthetic_roundtrip() { /// Frames from the capture thread go through encode / decode in order. #[tokio::test] async fn capture_thread_to_decoder() { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); let mut screen = SyntheticScreen::new(W, H); let options = CaptureOptions { fps: 60, cursor: false, queue: 8 }; let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap(); diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs new file mode 100644 index 0000000..8393ecc --- /dev/null +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -0,0 +1,230 @@ +//! Encoders through the system's FFmpeg (loaded at runtime), decoded with +//! this crate's own decoders: H.264 with Cisco's OpenH264 +//! (`VOELIN_OPENH264_LIB`), AV1 with dav1d (`--features av1`). +//! +//! Skipped without FFmpeg. Hardware backends need their GPU and driver; on a +//! machine without them the self-test reports why and they are skipped. +#![cfg(feature = "ffmpeg")] + +use std::time::Duration; + +use voelin_media::capture::synthetic::SyntheticScreen; +use voelin_media::ffmpeg::{BACKENDS, Ffmpeg, FfmpegEncoder, probe}; +use voelin_media::{ + Codec, Codecs, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, convert, +}; + +const W: u32 = 320; +const H: u32 = 240; + +fn ffmpeg() -> Option<&'static Ffmpeg> { + match Ffmpeg::get() { + Ok(f) => Some(f), + Err(e) => { + eprintln!("FFmpeg not available ({e}), skipped"); + None + } + } +} + +fn decoder(codec: Codec) -> Option> { + match codec { + #[cfg(feature = "openh264")] + Codec::H264 => { + let path = std::env::var_os("VOELIN_OPENH264_LIB")?; + let library = voelin_media::codec::h264::OpenH264::load(path).ok()?; + Some(Box::new(library.decoder().unwrap())) + } + #[cfg(feature = "av1")] + Codec::Av1 => Some(Box::new(voelin_media::codec::av1::Dav1dDecoder::new().unwrap())), + _ => None, + } +} + +/// 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); + 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 codec = encoder.codec(); + let mut decoder = decoder(codec); + let mut keyframes = Vec::new(); + let mut sent = Vec::new(); + let mut decoded = 0; + let mut sources = Vec::new(); + // Frames in until the first packet came out (the encoder's delay). + let mut delay = None; + // Until frame 11 came out (encoders with a delay need more input). + for n in 0..60u32 { + if sources.len() > 11 && sent.len() >= 12 { + break; + } + let frame = screen.frame(u64::from(n), 30); + if n == 5 { + encoder.set_bitrate(800_000).unwrap(); + } + let out = encoder.encode(&frame, n == 8).unwrap(); + sources.push(frame); + if delay.is_none() && !out.is_empty() { + delay = Some(n); + } + for f in &out { + sent.push(f.pts_90khz); + // Encoders with a delay hand out older frames: match by time. + let index = sources.iter().position(|s| s.pts_90khz() == f.pts_90khz).unwrap(); + if f.keyframe { + keyframes.push(index); + } + 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"); + decoded += 1; + } + } + } + eprintln!( + "{name}: {} packets from {} frames (first after {delay:?}), keyframes at {keyframes:?}, decoded {decoded}", + sent.len(), + sources.len() + ); + assert!(sent.len() >= 8, "{name}: only {} packets", sent.len()); + assert_eq!(keyframes.first(), Some(&0), "{name}"); + assert!(keyframes.contains(&8), "{name}: forced keyframe missing: {keyframes:?}"); + assert!(sent.windows(2).all(|w| w[0] < w[1]), "{name}: timestamps {sent:?}"); + assert_eq!(sent[0], 0); + if decoder.is_some() { + assert!(decoded >= 8, "{name}: decoded {decoded}"); + } +} + +fn available(name: &str) -> bool { + probe().iter().any(|s| s.spec.name == name && s.available.is_ok()) +} + +#[test] +fn probe_reports_every_backend() { + let Some(ffmpeg) = ffmpeg() else { return }; + eprintln!("{:?}", ffmpeg.info()); + let statuses = probe(); + assert_eq!(statuses.len(), BACKENDS.len()); + for status in statuses { + eprintln!("{:>18}: {:?}", status.spec.name, status.available); + if let Err(reason) = &status.available { + assert!(!reason.is_empty()); + } + } + // The report lists them with the built-in ones. + let report = Codecs::new().report(); + assert!(report.ffmpeg.is_ok(), "{report:?}"); + assert!(report.encoders.iter().any(|e| e.name == "libvpx")); + for status in statuses { + let info = report.encoders.iter().find(|e| e.name == status.spec.name).unwrap(); + assert_eq!(info.status, status.available); + let automatic = status.available.is_ok() && status.spec.is_automatic(); + assert_eq!(info.rank.is_some(), automatic, "{}", status.spec.name); + } +} + +#[test] +fn software_encoders_roundtrip() { + if ffmpeg().is_none() { + return; + } + let mut tested = Vec::new(); + for name in ["libx264", "libopenh264", "libsvtav1", "librav1e", "libaom-av1"] { + if available(name) { + roundtrip(name); + tested.push(name); + } else { + eprintln!("{name} skipped: not available"); + } + } + eprintln!("tested: {tested:?}"); +} + +#[test] +fn x264_is_constrained_high_and_changes_size() { + if ffmpeg().is_none() || !available("libx264") { + return; + } + let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() }; + let mut encoder = FfmpegEncoder::new("libx264", config).unwrap(); + let screen = SyntheticScreen::new(W, H); + let first = encoder.encode(&screen.frame(0, 30), false).unwrap(); + // profile_idc 100 (High) without B-frames: what TeamSpeak decodes. + let sps = + first[0].data.windows(5).find(|w| w[..4] == [0, 0, 1, 0x67] || w[..4] == [0, 0, 0, 1]); + assert!(sps.is_some()); + let profile = h264_profile(&first[0].data); + assert_eq!(profile, Some(100), "High profile"); + // A new size: a new session, starting with a keyframe. + let small = SyntheticScreen::new(160, 120); + let out = encoder.encode(&small.frame(1, 30), false); + assert!(out.unwrap().iter().any(|f| f.keyframe)); + // Odd sizes are cropped to even ones instead of failing. + let odd = + voelin_media::VideoFrame::black_i420(201, 151).with_timestamp(Duration::from_millis(66)); + assert!(encoder.encode(&odd, false).unwrap().iter().any(|f| f.keyframe)); + // Baseline on request. + let baseline = EncoderConfig { + h264_profile: voelin_media::H264Profile::ConstrainedBaseline, + ..EncoderConfig::default() + }; + let mut encoder = FfmpegEncoder::new("libx264", baseline).unwrap(); + let out = encoder.encode(&screen.frame(0, 30), false).unwrap(); + assert_eq!(h264_profile(&out[0].data), Some(66)); +} + +/// `profile_idc` of the first SPS in an Annex B stream. +fn h264_profile(data: &[u8]) -> Option { + let mut i = 0; + while i + 4 < data.len() { + if data[i..i + 3] == [0, 0, 1] { + if data[i + 3] & 0x1f == 7 { + return data.get(i + 4).copied(); + } + i += 3; + } else { + i += 1; + } + } + None +} + +#[test] +fn codecs_prefer_ffmpeg_h264_over_nothing() { + if ffmpeg().is_none() || !available("libx264") { + return; + } + let codecs = Codecs::new(); + assert!(codecs.encoder_codecs().contains(&Codec::H264)); + let encoder = codecs.new_encoder(Codec::H264, EncoderConfig::default()).unwrap(); + assert!(matches!(encoder.backend(), EncoderBackend::Ffmpeg(_))); + let named = + voelin_media::EncoderPreference { hardware: false, backend: "libx264".parse().unwrap() }; + let encoder = codecs.new_encoder_preferring(Codec::H264, EncoderConfig::default(), &named); + assert_eq!(encoder.unwrap().backend(), EncoderBackend::Ffmpeg("libx264")); +} + +/// Unknown names and hardware without its device fail with a reason, not +/// a panic. +#[test] +fn unusable_backends_fail_cleanly() { + if ffmpeg().is_none() { + return; + } + assert!(FfmpegEncoder::new("no_such_encoder", EncoderConfig::default()).is_err()); + for status in probe().iter().filter(|s| s.available.is_err()) { + let Ok(mut encoder) = FfmpegEncoder::new(status.spec.name, EncoderConfig::default()) else { + continue; + }; + let frame = voelin_media::VideoFrame::black_i420(W, H); + assert!(encoder.encode(&frame, true).is_err(), "{} passed now", status.spec.name); + } +} diff --git a/crates/voelin-media/tests/openh264.rs b/crates/voelin-media/tests/openh264.rs index d89cc0f..20b4c51 100644 --- a/crates/voelin-media/tests/openh264.rs +++ b/crates/voelin-media/tests/openh264.rs @@ -21,7 +21,7 @@ fn missing_library_is_a_clear_error() { assert!(err.to_string().contains("OpenH264 library not found"), "{err}"); // Without a library, H.264 is neither decodable nor encodable. - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); assert!(!codecs.decoders().contains(&Codec::H264)); assert!(!codecs.encoder_codecs().contains(&Codec::H264)); let err = codecs.new_decoder(Codec::H264).err().unwrap(); @@ -52,7 +52,7 @@ fn sps_profile(data: &[u8]) -> Option { } fn roundtrip(library: OpenH264) { - let codecs = Codecs::new().with_openh264(library.clone()); + let codecs = Codecs::builtin().with_openh264(library.clone()); assert_eq!(codecs.decoders().last(), Some(&Codec::H264)); assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264))); From 6e5e138ccae1f5271b1f35d23fe5d11655346b7b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 00:33:16 +0000 Subject: [PATCH 3/9] Encode each layer once per codec its viewers chose (WIP) Offers list the stream codec first, then the codecs of hardware encoders, VP8 through libvpx and HEVC last; software encoders other than VP8 are only ever the stream codec, so no answer starts an expensive one. The streamer's peer reports the codec each answer chose, the session sends video only to viewers of its codec and tells the encoders through LayerFeedback which codecs are needed. Each layer's encoder thread keeps one encoder per such codec, made when a viewer needs it and dropped when none does; the stream codec is skipped while nobody takes it. The H.264 profile-level-id is computed from macroblocks per second, frame size and bitrate (Table A-1), at least 3.1 as before. Streamer takes an encoder preference (hardware on/off, auto / software / a named backend) that reconfigure can change live. HEVC is negotiable (str0m packetizes it) and only offered when a hardware encoder has it. Work in progress: committed early so it cannot be lost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 1 + crates/voelin-core/src/media.rs | 501 +++++++++++++++++++++++---- crates/voelin-core/src/stream.rs | 18 + crates/voelin-media/src/codec/mod.rs | 23 +- crates/voelin-stream/src/feedback.rs | 36 +- crates/voelin-stream/src/h264.rs | 131 +++++++ crates/voelin-stream/src/lib.rs | 2 + crates/voelin-stream/src/peer.rs | 91 ++++- crates/voelin-stream/src/session.rs | 49 ++- crates/voelin-ui/src/video.rs | 44 ++- 10 files changed, 799 insertions(+), 97 deletions(-) create mode 100644 crates/voelin-stream/src/h264.rs diff --git a/Cargo.lock b/Cargo.lock index 515ee26..cf15994 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9169,6 +9169,7 @@ dependencies = [ "bzip2", "criterion", "dav1d", + "libloading", "libvpx-native-sys", "memmap2", "ndk 0.9.0", diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3d338d1..b84dd46 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -48,6 +48,7 @@ use voelin_media::{ AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, FrameRef, VideoEncoder, VideoFrame, }; +pub use voelin_media::{EncoderBackend, EncoderPreference}; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, @@ -95,6 +96,7 @@ pub fn media_codec(codec: VideoCodec) -> Codec { VideoCodec::Vp9 => Codec::Vp9, VideoCodec::H264 => Codec::H264, VideoCodec::Av1 => Codec::Av1, + VideoCodec::H265 => Codec::H265, } } @@ -105,6 +107,7 @@ pub fn video_codec(codec: Codec) -> VideoCodec { Codec::Vp9 => VideoCodec::Vp9, Codec::H264 => VideoCodec::H264, Codec::Av1 => VideoCodec::Av1, + Codec::H265 => VideoCodec::H265, } } @@ -116,16 +119,77 @@ pub fn stream_codec(codecs: &Codecs, config: &PeerConfig) -> Option { } /// `config` adjusted to what `codecs` can do: viewers accept only codecs we -/// decode, and a streamer offers only the codec it encodes (every viewer -/// gets the same frames, and a viewer picks from the offer). +/// decode; a streamer offers its stream codec ([`stream_codec`]) first, then +/// [`offer_codecs`]. Viewers answer with the first they decode, and the +/// [`Streamer`] encodes each layer once per codec its viewers chose. pub fn peer_config(codecs: &Codecs, mut config: PeerConfig) -> PeerConfig { config.accept_video_codecs = codecs.decoders().into_iter().map(video_codec).collect(); if let Some(codec) = stream_codec(codecs, &config) { - config.video_codecs = vec![video_codec(codec)]; + config.video_codecs = offer_codecs(codecs, codec).into_iter().map(video_codec).collect(); } config } +/// What a streamer with `primary` as its stream codec offers, in order: +/// `primary`, the codecs of hardware encoders, VP8 through libvpx (every +/// TeamSpeak client decodes it), and HEVC last (for peers that take nothing +/// else). Other software encoders are only ever the stream codec, so no +/// viewer's answer starts one of them on top of it. +pub fn offer_codecs(codecs: &Codecs, primary: Codec) -> Vec { + let mut offer = vec![primary]; + let mut hevc = false; + for (codec, backend) in codecs.encoders() { + let cheap = codecs.is_hardware(backend) + || (codec == Codec::Vp8 && backend == voelin_media::EncoderBackend::Libvpx); + if !cheap || offer.contains(&codec) { + continue; + } + if codec == Codec::H265 { + hevc = true; + } else { + offer.push(codec); + } + } + if hevc && primary != Codec::H265 { + offer.push(Codec::H265); + } + offer +} + +/// The encoder preference of the settings `stream.hardware_acceleration` +/// and `stream.encoder_backend`. +pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media::EncoderPreference { + use crate::settings::{STREAM_ENCODER_BACKEND, STREAM_HARDWARE_ACCELERATION}; + voelin_media::EncoderPreference { + hardware: settings.get(&STREAM_HARDWARE_ACCELERATION), + backend: settings.get(&STREAM_ENCODER_BACKEND).parse().unwrap_or_default(), + } +} + +/// The stream codec: `configured` if we can encode it, else the first codec +/// of the encoder preference (hardware first when enabled; VP8 through +/// libvpx without hardware), never HEVC (offered last only). Put it first in +/// `PeerConfig::video_codecs` before [`peer_config`]. +pub fn preferred_codec(codecs: &Codecs, configured: Option) -> Option { + let encodable = codecs.encoder_codecs(); + configured + .filter(|c| encodable.contains(c)) + .or_else(|| encodable.into_iter().find(|c| *c != Codec::H265)) +} + +/// The codec of the setting `stream.codec`; `None` for `auto` (see +/// [`preferred_codec`]). +pub fn configured_codec(settings: &crate::settings::Settings) -> Option { + use crate::settings::{CodecChoice, STREAM_CODEC}; + match settings.get(&STREAM_CODEC) { + CodecChoice::Auto => None, + CodecChoice::Vp8 => Some(Codec::Vp8), + CodecChoice::Vp9 => Some(Codec::Vp9), + CodecChoice::H264 => Some(Codec::H264), + CodecChoice::Av1 => Some(Codec::Av1), + } +} + /// Monitors and windows of this session's capture backend. The portal (on /// Wayland) lists a single entry: its own dialog picks. pub fn screen_sources() -> Result, MediaError> { @@ -166,6 +230,19 @@ pub trait MediaSink: Send + Sync { let _ = layer; None } + + /// Send one video frame encoded in `codec`: it goes to the viewers whose + /// answer chose `codec`. + fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool { + let _ = codec; + self.send(frame) + } + + /// Adds to `out` the video codecs the viewers chose; none (the default) + /// means only the stream codec is sent. + fn video_codecs(&self, out: &mut Vec) { + let _ = out; + } } impl MediaSink for StreamSink { @@ -173,6 +250,18 @@ impl MediaSink for StreamSink { StreamSink::send(self, frame) } + fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool { + StreamSink::send_video(self, frame, video_codec(codec)) + } + + fn video_codecs(&self, out: &mut Vec) { + for codec in VideoCodec::ALL { + if self.has_video_codec(codec) { + out.push(media_codec(codec)); + } + } + } + fn take_keyframe_request(&self) -> bool { StreamSink::take_keyframe_request(self) } @@ -247,6 +336,8 @@ pub struct StreamerConfig { pub bitrate_kbps: u32, /// The codec of our offer, see [`stream_codec`]. pub codec: Codec, + /// Which encoders to use ([`encoder_preference`] of the settings). + pub encoder: EncoderPreference, /// Capture and send system audio (a sine tone with the test pattern). pub audio: bool, pub cursor: bool, @@ -270,6 +361,7 @@ impl Default for StreamerConfig { fps: 30, bitrate_kbps: 4608, codec: Codec::Vp8, + encoder: EncoderPreference::default(), audio: true, cursor: true, synthetic_size: (1280, 720), @@ -302,6 +394,9 @@ pub struct StreamerConfigUpdate { pub bitrate_kbps: Option, /// Another codec: new encoders, starting with keyframes. pub codec: Option, + /// Other encoders (hardware on or off, another backend): new encoders + /// for every codec, starting with keyframes. + pub encoder: Option, /// Another set of layers (`Some(vec![])`: back to a single layer). Layers /// keep their encoder when their id stays; new ids get new encoders. pub layers: Option>, @@ -330,6 +425,11 @@ pub struct LayerStats { pub threads: u32, /// The encoder's speed setting (libvpx `cpu-used`), if it has one. pub speed: Option, + /// The encoder of the stream codec (`libvpx`, `h264_vaapi`, ...). + pub backend: Option, + /// The codecs this layer is encoded in: the stream codec, and those + /// viewers chose instead (each with its own encoder). + pub codecs: Vec, } /// What a [`Streamer`] has done so far. Rates are over the last second. @@ -391,6 +491,9 @@ struct Layer { target: AtomicU64, /// `cpu-used`, or `i64::MIN`. speed: AtomicI64, + /// The stream codec's encoder and every codec encoded (for stats). + backend: Mutex>, + codecs: Mutex>, } impl Layer { @@ -414,6 +517,8 @@ impl Layer { size: AtomicU64::new(0), target: AtomicU64::new(spec.bitrate), speed: AtomicI64::new(i64::MIN), + backend: Mutex::new(None), + codecs: Mutex::new(Vec::new()), } } @@ -439,6 +544,7 @@ struct Settings { fps: u32, bitrate_kbps: u32, codec: Codec, + encoder: EncoderPreference, layers: Vec, } @@ -486,6 +592,11 @@ struct Shared { keyframes: Mutex, settings: Mutex>, rates: Mutex, + /// For encoders of the codecs viewers chose besides the stream codec, + /// created by the encoder threads when a viewer needs one. + encoders: Mutex>, + /// Bumped when `encoders` changes: those encoders are made again. + encoders_generation: AtomicU64, } impl Shared { @@ -536,21 +647,28 @@ fn cores() -> u32 { voelin_media::codec::encoder_cpus() } -fn new_encoder( - codecs: &Codecs, - codec: Codec, - spec: &LayerSpec, - fps: u32, - threads: u32, -) -> Result, MediaError> { - let config = EncoderConfig { +fn encoder_config(spec: &LayerSpec, fps: u32, threads: u32) -> EncoderConfig { + EncoderConfig { fps: layer_fps(spec, fps), bitrate_bps: spec.bitrate.clamp(1, u64::from(u32::MAX)) as u32, content: ContentHint::Screen, threads, ..EncoderConfig::default() - }; - Ok(codecs.new_encoder(codec, config)?) + } +} + +fn new_encoder( + codecs: &Codecs, + codec: Codec, + preference: &EncoderPreference, + spec: &LayerSpec, + fps: u32, + threads: u32, +) -> Result, MediaError> { + let config = encoder_config(spec, fps, threads); + let encoder = codecs.new_encoder_preferring(codec, config, preference)?; + debug!(layer = spec.id, %codec, backend = %encoder.backend(), "video encoder"); + Ok(encoder) } /// Capture and encoding for our stream. Frames are captured from the start @@ -598,9 +716,10 @@ impl Streamer { let split = thread_split(&layers, cores()); let mut ready = Vec::new(); for (spec, threads) in layers.iter().zip(split) { - let encoder = new_encoder(codecs, config.codec, spec, fps, threads)?; + let encoder = new_encoder(codecs, config.codec, &config.encoder, spec, fps, threads)?; ready.push((Arc::new(Layer::new(spec, fps, threads)), encoder)); } + *lock(&shared.encoders) = Some((codecs.clone(), config.encoder.clone())); for (layer, encoder) in ready { streamer.spawn_encoder(layer, encoder)?; } @@ -608,6 +727,7 @@ impl Streamer { fps, bitrate_kbps: config.bitrate_kbps, codec: config.codec, + encoder: config.encoder.clone(), layers: config.layers.clone(), }); streamer.threads.push(spawn("voelin-stream-stats", { @@ -674,11 +794,13 @@ impl Streamer { Ok(()) } - /// Change frame rate, bitrate, codec or layers while streaming, without - /// restarting the capture; applies from the next frame. A new codec - /// gets new encoders, which start with a keyframe; new layers get new - /// encoders; removed layers stop. Fails without changing anything if an - /// encoder cannot be created. + /// Change frame rate, bitrate, codec, encoders or layers while + /// streaming, without restarting the capture; applies from the next + /// frame. A new codec or encoder preference gets new encoders (the + /// stream codec's at once, those of codecs viewers chose on their next + /// frame), which start with a keyframe; new layers get new encoders; + /// removed layers stop. Fails without changing anything if an encoder + /// cannot be created. pub fn reconfigure( &self, codecs: &Codecs, @@ -691,11 +813,12 @@ impl Streamer { fps: update.fps.unwrap_or(settings.fps).max(1), bitrate_kbps: update.bitrate_kbps.unwrap_or(settings.bitrate_kbps), codec: update.codec.unwrap_or(settings.codec), + encoder: update.encoder.unwrap_or_else(|| settings.encoder.clone()), layers: update.layers.unwrap_or_else(|| settings.layers.clone()), }; let specs = next.effective_layers(); check_layers(&specs)?; - let codec_changed = next.codec != old_codec; + let codec_changed = next.codec != old_codec || next.encoder != settings.encoder; let current: Vec> = lock(&self.shared.layers).clone(); // Create every encoder before changing anything. let split = thread_split(&specs, cores()); @@ -703,9 +826,14 @@ impl Streamer { for (spec, &threads) in specs.iter().zip(&split) { let existing = current.iter().any(|l| l.id == spec.id); if !existing || codec_changed { - created.push((spec.id, new_encoder(codecs, next.codec, spec, next.fps, threads)?)); + let encoder = new_encoder(codecs, next.codec, &next.encoder, spec, next.fps, threads)?; + created.push((spec.id, encoder)); } } + if codec_changed { + *lock(&self.shared.encoders) = Some((codecs.clone(), next.encoder.clone())); + self.shared.encoders_generation.fetch_add(1, Ordering::Relaxed); + } self.shared.fps.store(next.fps, Ordering::Relaxed); let mut layers = Vec::with_capacity(specs.len()); for (spec, &threads) in specs.iter().zip(&split) { @@ -819,6 +947,8 @@ impl Streamer { bitrate: l.target.load(Ordering::Relaxed), threads: l.threads, speed: (speed != i64::MIN).then_some(speed as i32), + backend: *lock(&l.backend), + codecs: lock(&l.codecs).clone(), } }) .collect(); @@ -1067,35 +1197,166 @@ impl Drop for Ingest { } } -/// One layer's encoder thread. -fn encode_loop(shared: &Shared, layer: &Layer, mut encoder: Box) { - // A requested keyframe the encoder has not produced yet (rate control - // may skip a frame). - let mut keyframe_due = false; +/// One encoder of a layer: its keyframe and bitrate state. +struct LayerEncoder { + codec: Codec, + /// `None`: creating it failed (not retried until it is needed anew). + encoder: Option>, + /// A requested keyframe the encoder has not produced yet (rate control + /// may skip a frame). + keyframe_due: bool, + /// The bitrate and frame rate it was last set to. + bitrate: u64, + fps: u32, +} + +impl LayerEncoder { + fn new(encoder: Box, fps: u32) -> Self { + Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps } + } + + /// Encode `frame` and hand the frames to `sink`; follows the layer's + /// target bitrate and frame rate first. + fn encode( + &mut self, + shared: &Shared, + layer: &Layer, + sink: &dyn MediaSink, + frame: &VideoFrame, + requested: bool, + target: u64, + ) { + let codec = self.codec; + let Some(encoder) = &mut self.encoder else { return }; + if target.abs_diff(self.bitrate) * 100 > self.bitrate { + match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) { + Ok(()) => self.bitrate = target, + Err(e) => warn!(layer = layer.id, %codec, "cannot change the bitrate: {e}"), + } + } + let want_fps = layer.fps.load(Ordering::Relaxed); + if want_fps != self.fps && encoder.set_fps(want_fps).is_ok() { + self.fps = want_fps; + } + let force = requested || self.keyframe_due; + let mut produced_keyframe = false; + let result = encoder.encode_with(frame, force, &mut |chunk| { + produced_keyframe |= chunk.keyframe; + let encoded = EncodedFrame { + kind: MediaKind::Video, + time: MediaTime::from_90khz(chunk.pts_90khz), + // The one allocation per encoded frame. + data: Arc::from(chunk.data), + layer: layer.id, + keyframe: chunk.keyframe, + }; + if sink.send_video(encoded, codec) { + layer.frames.fetch_add(1, Ordering::Relaxed); + layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed); + layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed); + shared.video_frames.fetch_add(1, Ordering::Relaxed); + } + }); + match result { + Ok(()) => self.keyframe_due = force && !produced_keyframe, + Err(e) => { + warn!(layer = layer.id, %codec, "video encoding failed: {e}"); + self.keyframe_due = force; + shared.set_error(e); + } + } + } +} + +/// An encoder of `codec` for `layer` (a codec a viewer chose), with the +/// streamer's current codecs and preference. +fn extra_encoder(shared: &Shared, layer: &Layer, codec: Codec) -> Option> { + let guard = lock(&shared.encoders); + let (codecs, preference) = guard.as_ref()?; + let spec = lock(&layer.spec).clone(); + let config = encoder_config(&spec, layer.fps.load(Ordering::Relaxed), layer.threads); + match codecs.new_encoder_preferring(codec, config, preference) { + Ok(encoder) => { + debug!(layer = layer.id, %codec, backend = %encoder.backend(), "encoder for viewers"); + Some(encoder) + } + Err(e) => { + warn!(layer = layer.id, %codec, "no encoder for viewers of this codec: {e}"); + None + } + } +} + +/// One layer's encoder thread: the stream codec's encoder, plus one per +/// other codec the sink's viewers chose (created when a viewer needs it, +/// dropped when none does). +fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { + let fps = layer.fps.load(Ordering::Relaxed); + let mut primary = LayerEncoder::new(encoder, fps); + // The first frame is a keyframe anyway; no need to insist. + primary.keyframe_due = false; + primary.bitrate = layer.bitrate.load(Ordering::Relaxed); + *lock(&layer.backend) = primary.encoder.as_ref().map(|e| e.backend()); + let mut extra: Vec = Vec::new(); + let mut wanted: Vec = Vec::new(); + let mut generation = shared.encoders_generation.load(Ordering::Relaxed); + // Whether the stream codec was encoded for the last frame. + let mut primary_on = true; // The last picture, and when it came: a static screen sends no frames, // so keyframe requests are answered by encoding it again. let mut last: Option<(Arc, Instant)> = None; - let mut bitrate = layer.bitrate.load(Ordering::Relaxed); - let mut fps = layer.fps.load(Ordering::Relaxed); - layer.speed.store(encoder.speed().map_or(i64::MIN, i64::from), Ordering::Relaxed); + layer.speed.store( + primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from), + Ordering::Relaxed, + ); while !shared.stopped() && !layer.stopped() { let frame = layer.inbox.wait_timeout(POLL); if let Some(next) = lock(&layer.next_encoder).take() { // Another codec: its first frame is a keyframe anyway. - encoder = next; - bitrate = 0; - keyframe_due = true; + *lock(&layer.backend) = Some(next.backend()); + primary = LayerEncoder::new(next, primary.fps); } let Some(sink) = shared.sink() else { continue }; shared.poll_keyframes(&*sink); + // The codecs viewers chose; none known: the stream codec. + wanted.clear(); + sink.video_codecs(&mut wanted); + let now = shared.encoders_generation.load(Ordering::Relaxed); + if now != generation { + generation = now; + extra.clear(); + } + extra.retain(|e| wanted.contains(&e.codec)); + for &codec in &wanted { + if codec != primary.codec && !extra.iter().any(|e| e.codec == codec) { + let fps = layer.fps.load(Ordering::Relaxed); + extra.push(match extra_encoder(shared, layer, codec) { + Some(encoder) => LayerEncoder::new(encoder, fps), + None => LayerEncoder { codec, encoder: None, keyframe_due: false, bitrate: 0, fps }, + }); + } + } + let primary_wanted = wanted.is_empty() || wanted.contains(&primary.codec); + if primary_wanted && !primary_on { + // Frames were skipped: the next one must stand alone. + primary.keyframe_due = true; + } + primary_on = primary_wanted; + { + let mut codecs = lock(&layer.codecs); + codecs.clear(); + codecs.extend(primary_on.then_some(primary.codec)); + codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec)); + } let requested = layer.keyframe.swap(false, Ordering::Relaxed); - let force = requested || keyframe_due; + let due = primary_on && primary.keyframe_due + || extra.iter().any(|e| e.keyframe_due && e.encoder.is_some()); let frame = match frame { Some(frame) => { last = Some((frame.clone(), Instant::now())); frame } - None if force => { + None if requested || due => { let Some((frame, at)) = &last else { layer.keyframe.store(requested, Ordering::Relaxed); continue; @@ -1112,50 +1373,21 @@ fn encode_loop(shared: &Shared, layer: &Layer, mut encoder: Box max, }; let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap); - if target.abs_diff(bitrate) * 100 > bitrate { - match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) { - Ok(()) => { - bitrate = target; - layer.target.store(target, Ordering::Relaxed); - } - Err(e) => warn!(layer = layer.id, "cannot change the bitrate: {e}"), - } - } - let want_fps = layer.fps.load(Ordering::Relaxed); - if want_fps != fps && encoder.set_fps(want_fps).is_ok() { - fps = want_fps; - } let started = Instant::now(); - let mut produced_keyframe = false; - let result = encoder.encode_with(&frame, force, &mut |chunk| { - produced_keyframe |= chunk.keyframe; - let encoded = EncodedFrame { - kind: MediaKind::Video, - time: MediaTime::from_90khz(chunk.pts_90khz), - // The one allocation per encoded frame. - data: Arc::from(chunk.data), - layer: layer.id, - keyframe: chunk.keyframe, - }; - if sink.send(encoded) { - layer.frames.fetch_add(1, Ordering::Relaxed); - layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed); - layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed); - shared.video_frames.fetch_add(1, Ordering::Relaxed); - } - }); + if primary_on { + primary.encode(shared, layer, &*sink, &frame, requested, target); + layer.target.store(primary.bitrate, Ordering::Relaxed); + } + for encoder in &mut extra { + encoder.encode(shared, layer, &*sink, &frame, requested, target); + } layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); layer.encoded.fetch_add(1, Ordering::Relaxed); layer.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed); - layer.speed.store(encoder.speed().map_or(i64::MIN, i64::from), Ordering::Relaxed); - match result { - Ok(()) => keyframe_due = force && !produced_keyframe, - Err(e) => { - warn!(layer = layer.id, "video encoding failed: {e}"); - keyframe_due = force; - shared.set_error(e); - } - } + layer.speed.store( + primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from), + Ordering::Relaxed, + ); } } @@ -1410,6 +1642,11 @@ pub fn is_keyframe(codec: Codec, data: &[u8]) -> bool { Codec::Vp9 => vp9_is_keyframe(data), Codec::H264 => h264_nal_types(data).any(|t| t == 5 || t == 7), Codec::Av1 => av1_has_sequence_header(data).unwrap_or(true), + // IRAP pictures (16-23) or a VPS / SPS in front of one. + Codec::H265 => data + .windows(4) + .filter_map(|w| (w[..3] == [0, 0, 1]).then_some((w[3] >> 1) & 0x3f)) + .any(|t| (16..=23).contains(&t) || t == 32 || t == 33), } } @@ -1871,6 +2108,10 @@ mod tests { assert!(is_keyframe(Codec::Av1, &[0x12, 0x00, 0x0a, 0x01, 0xff])); assert!(!is_keyframe(Codec::Av1, &[0x12, 0x00, 0x32, 0x01, 0xff])); assert!(is_keyframe(Codec::Av1, &[0x12, 0x05]), "truncated: let the decoder try"); + // HEVC: a VPS (type 32) or an IDR (19) starts one, a trailing picture not. + assert!(is_keyframe(Codec::H265, &[0, 0, 1, 0x40, 0x01])); + assert!(is_keyframe(Codec::H265, &[0, 0, 0, 1, 0x26, 0x01])); + assert!(!is_keyframe(Codec::H265, &[0, 0, 1, 0x02, 0x01])); } #[test] @@ -1886,14 +2127,122 @@ mod tests { #[cfg(feature = "media-desktop")] #[test] fn peer_config_follows_codecs() { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); let config = peer_config(&codecs, PeerConfig::default()); assert_eq!(config.video_codecs, [VideoCodec::Vp8]); assert!(config.accept_video_codecs.contains(&VideoCodec::Vp8)); assert!(!config.accept_video_codecs.contains(&VideoCodec::H264), "no OpenH264 loaded"); assert_eq!(stream_codec(&codecs, &config), Some(Codec::Vp8)); - let h264_only = PeerConfig { video_codecs: vec![VideoCodec::H264], ..config }; + let h264_only = PeerConfig { video_codecs: vec![VideoCodec::H264], ..config.clone() }; assert_eq!(stream_codec(&codecs, &h264_only), None); + // VP9 as the stream codec: VP8 (cheap) is offered after it, nothing + // else in software. + let vp9 = PeerConfig { video_codecs: vec![VideoCodec::Vp9], ..config }; + let vp9 = peer_config(&codecs, vp9); + assert_eq!(vp9.video_codecs, [VideoCodec::Vp9, VideoCodec::Vp8]); + assert_eq!(stream_codec(&codecs, &vp9), Some(Codec::Vp9)); + // With FFmpeg's software encoders, still only VP8 besides the stream + // codec. + let all = Codecs::new(); + let offer = offer_codecs(&all, Codec::Vp8); + for codec in &offer[1..] { + let backend = all.encoders().into_iter().find(|(c, _)| c == codec).unwrap().1; + assert!(all.is_hardware(backend), "{codec} offered in software"); + } + if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) { + assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]); + } + } + + /// A sink whose viewers chose `codecs`; keeps every video frame with its + /// codec. + #[derive(Default)] + struct CodecSink { + codecs: Mutex>, + frames: Mutex>, + keyframe: AtomicBool, + } + + impl MediaSink for CodecSink { + fn send(&self, _: EncodedFrame) -> bool { + true + } + + fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool { + lock(&self.frames).push((codec, frame)); + true + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } + + fn video_codecs(&self, out: &mut Vec) { + out.extend(lock(&self.codecs).iter()); + } + } + + /// Viewers that chose another codec get their own encoder per layer, + /// made when they come and dropped when they go; the stream codec is + /// skipped while nobody takes it. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn an_encoder_per_codec_viewers_chose() { + let codecs = Codecs::builtin(); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (160, 120), + audio: false, + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let sink = Arc::new(CodecSink::default()); + streamer.attach(sink.clone()); + let wait_for = |codec: Codec, count: usize| { + let sink = sink.clone(); + async move { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let n = lock(&sink.frames).iter().filter(|(c, _)| *c == codec).count(); + if n >= count { + return; + } + assert!(Instant::now() < deadline, "no {codec} frames"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } + }; + // Nobody chose yet: the stream codec. + wait_for(Codec::Vp8, 3).await; + // A VP9 viewer as well. + *lock(&sink.codecs) = vec![Codec::Vp8, Codec::Vp9]; + wait_for(Codec::Vp9, 5).await; + assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp8, Codec::Vp9]); + let vp9: Vec = + lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp9).map(|(_, f)| f.clone()).collect(); + assert!(is_keyframe(Codec::Vp9, &vp9[0].data), "the first VP9 frame is a keyframe"); + let mut decoder = codecs.new_decoder(Codec::Vp9).unwrap(); + for frame in &vp9 { + let picture = decoder.decode(&frame.data).unwrap().expect("a picture"); + assert_eq!((picture.width, picture.height), (160, 120)); + } + // Only VP9 viewers left: VP8 stops. + *lock(&sink.codecs) = vec![Codec::Vp9]; + tokio::time::sleep(Duration::from_millis(300)).await; + let before = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count(); + wait_for(Codec::Vp9, vp9.len() + 10).await; + let after = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count(); + assert_eq!(before, after, "VP8 is not encoded for nobody"); + assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp9]); + assert_eq!(streamer.stats().layers[0].backend, Some(EncoderBackend::Libvpx)); + // Another encoder preference: new encoders, the stream goes on. + let update = StreamerConfigUpdate { + encoder: Some(EncoderPreference { hardware: false, ..EncoderPreference::default() }), + ..StreamerConfigUpdate::default() + }; + streamer.reconfigure(&codecs, update).unwrap(); + let count = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp9).count(); + wait_for(Codec::Vp9, count + 5).await; } /// The test pattern through VP8 and back, without a network: pictures diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index fffde7c..8ef8cd9 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -77,6 +77,18 @@ impl StreamSink { self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok() } + /// Send one video frame encoded in `codec`: only viewers whose answer + /// chose `codec` get it. + pub fn send_video(&self, frame: EncodedFrame, codec: VideoCodec) -> bool { + self.live.load(Ordering::Relaxed) + && self.tx.send(StreamInput::VideoFrame(frame, codec)).is_ok() + } + + /// Whether a viewer's answer chose `codec`. + pub fn has_video_codec(&self, codec: VideoCodec) -> bool { + self.feedback.has_codec(codec) + } + /// Whether a viewer asked for a keyframe of any layer since the last /// call (or [`take_layer_keyframes`](Self::take_layer_keyframes)). pub fn take_keyframe_request(&self) -> bool { @@ -141,6 +153,8 @@ pub(crate) enum StreamInput { /// SRTP profile order of new connections. SrtpProfiles(Vec), Frame(EncodedFrame), + /// A video frame for the viewers that chose its codec. + VideoFrame(EncodedFrame, VideoCodec), Notification(StreamNotification), RequestFailed(Request, String), /// Clients on the server: channel and `client_is_streaming`. @@ -268,6 +282,10 @@ impl StreamTask { self.streams.write_frame(&frame); Ok(()) } + StreamInput::VideoFrame(frame, codec) => { + self.streams.write_frame_in(&frame, Some(codec)); + Ok(()) + } StreamInput::Notification(n) => { self.streams.handle_notification(n).await; Ok(()) diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index f020003..70a6c59 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -14,6 +14,7 @@ //! (hardware, or Google's software VP8 / VP9 / H.264) use std::fmt; +use std::sync::Arc; use std::str::FromStr; use crate::frame::VideoFrame; @@ -406,9 +407,10 @@ impl Candidate { /// hardware (H.264, AV1, VP9, VP8, HEVC; FFmpeg's or MediaCodec) > VP8 /// (libvpx) > H.264 (x264 and OpenH264 through FFmpeg, then Cisco's /// OpenH264) > VP9 (libvpx, costly in software) > AV1 (SVT-AV1, rav1e, -/// libaom through FFmpeg). +/// libaom through FFmpeg). Cheap to clone: the factories are shared. +#[derive(Clone)] pub struct Codecs { - factories: Vec>, + factories: Vec>, #[cfg(feature = "openh264")] openh264: Option, preference: EncoderPreference, @@ -436,7 +438,7 @@ impl Codecs { /// Cisco's library needs [`Codecs::with_openh264`]. pub fn new() -> Self { Self { - factories: hw::probe(), + factories: hw::probe().into_iter().map(Arc::from).collect(), #[cfg(feature = "openh264")] openh264: None, preference: EncoderPreference::default(), @@ -481,6 +483,11 @@ impl Codecs { &self.preference } + /// Whether `backend` is a hardware encoder here. + pub fn is_hardware(&self, backend: EncoderBackend) -> bool { + self.factories.iter().any(|f| f.backend() == backend && f.is_hardware()) + } + fn has_openh264(&self) -> bool { #[cfg(feature = "openh264")] return self.openh264.is_some(); @@ -825,11 +832,11 @@ mod tests { fn encoder_preference() { let mut codecs = Codecs::builtin(); codecs.factories = vec![ - Box::new(Fake("x264", Codec::H264, false)), - Box::new(Fake("vp8_gpu", Codec::Vp8, true)), - Box::new(Fake("h264_gpu", Codec::H264, true)), - Box::new(Fake("hevc_gpu", Codec::H265, true)), - Box::new(Fake("av1_sw", Codec::Av1, false)), + Arc::new(Fake("x264", Codec::H264, false)), + Arc::new(Fake("vp8_gpu", Codec::Vp8, true)), + Arc::new(Fake("h264_gpu", Codec::H264, true)), + Arc::new(Fake("hevc_gpu", Codec::H265, true)), + Arc::new(Fake("av1_sw", Codec::Av1, false)), ]; let names = |preference: EncoderPreference| -> Vec<&'static str> { codecs.encoders_for(&preference).iter().map(|(_, b)| b.name()).collect() diff --git a/crates/voelin-stream/src/feedback.rs b/crates/voelin-stream/src/feedback.rs index 159e56b..57d6f12 100644 --- a/crates/voelin-stream/src/feedback.rs +++ b/crates/voelin-stream/src/feedback.rs @@ -1,5 +1,6 @@ //! Feedback from the stream sessions to the encoders of our stream's layers: -//! keyframe requests and bitrate targets per [`LayerId`]. +//! keyframe requests and bitrate targets per [`LayerId`], and the video +//! codecs the viewers negotiated. //! //! [`LayerFeedback`] is shared between the stream session (which writes) and //! encoder threads (which read every frame). Both sides only use atomics; @@ -9,9 +10,10 @@ use std::array; use std::sync::OnceLock; -use std::sync::atomic::{AtomicU16, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU64, Ordering}; use crate::layer::{LayerId, LayerSet}; +use crate::peer::VideoCodec; /// Words of the keyframe bitmap: one bit per layer id. const WORDS: usize = (LayerId::MAX as usize + 1) / 64; @@ -30,6 +32,8 @@ pub struct LayerFeedback { top: AtomicU16, /// Bitrate targets (bit/s, 0: none) in chunks of [`CHUNK`] layer ids. bitrates: Box<[OnceLock>]>, + /// [`VideoCodec::bit`]s of the codecs connected viewers negotiated. + codecs: AtomicU8, } impl Default for LayerFeedback { @@ -51,6 +55,7 @@ impl LayerFeedback { summary: array::from_fn(|_| AtomicU64::new(0)), top: AtomicU16::new(0), bitrates: (0..=LayerId::MAX as usize / CHUNK).map(|_| OnceLock::new()).collect(), + codecs: AtomicU8::new(0), } } @@ -122,6 +127,22 @@ impl LayerFeedback { let bitrate = chunk[usize::from(layer) % CHUNK].load(Ordering::Relaxed); (bitrate != 0).then_some(bitrate) } + + /// The video codecs the viewers negotiated. + pub fn set_codecs(&self, codecs: impl IntoIterator) { + let bits = codecs.into_iter().fold(0, |bits, c| bits | c.bit()); + self.codecs.store(bits, Ordering::Relaxed); + } + + /// Whether a viewer negotiated `codec`. + pub fn has_codec(&self, codec: VideoCodec) -> bool { + self.codecs.load(Ordering::Relaxed) & codec.bit() != 0 + } + + /// Whether any viewer negotiated a codec yet. + pub fn has_codecs(&self) -> bool { + self.codecs.load(Ordering::Relaxed) != 0 + } } #[cfg(test)] @@ -160,4 +181,15 @@ mod tests { f.set_bitrate(3, None); assert_eq!(f.bitrate(3), None); } + + #[test] + fn codecs() { + let f = LayerFeedback::new(); + assert!(!f.has_codecs()); + f.set_codecs([VideoCodec::Vp8, VideoCodec::H265, VideoCodec::Vp8]); + assert!(f.has_codec(VideoCodec::Vp8) && f.has_codec(VideoCodec::H265)); + assert!(!f.has_codec(VideoCodec::H264)); + f.set_codecs([]); + assert!(!f.has_codecs()); + } } diff --git a/crates/voelin-stream/src/h264.rs b/crates/voelin-stream/src/h264.rs new file mode 100644 index 0000000..090633c --- /dev/null +++ b/crates/voelin-stream/src/h264.rs @@ -0,0 +1,131 @@ +//! H.264 `profile-level-id` for the offer: the profile our encoders produce +//! and the level the stream's size, frame rate and bitrate need (ITU-T +//! H.264 Table A-1), instead of a fixed level. + +/// Profile of our H.264 streams. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum H264Profile { + /// Constrained High (`profile_idc` 100, `constraint_set4` and `5`): what + /// TeamSpeak clients decode. + #[default] + ConstrainedHigh, + /// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`). + ConstrainedBaseline, +} + +/// Level limits: `level_idc`, macroblocks per second, macroblocks per frame, +/// bitrate in kbit/s (Baseline; High allows 1.25 times that). +const LEVELS: [(u8, 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 (`level_idc`, e.g. 31 for 3.1) whose limits hold +/// `width` x `height` at `fps` and `bitrate` bit/s; the highest level +/// defined if none does (the stream is sent anyway: decoders mostly take +/// more than their level). +pub fn level_idc(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate: u64) -> u8 { + 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, + }; + 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 + && bitrate <= max_kbps * factor + }) + .map_or(LEVELS[LEVELS.len() - 1].0, |l| l.0) +} + +/// `profile-level-id` (`a=fmtp`, three bytes: `profile_idc`, +/// `profile-iop`, `level_idc`) for `profile` at `level_idc`. +pub fn profile_level_id(profile: H264Profile, level_idc: u8) -> u32 { + let (profile_idc, iop) = match profile { + H264Profile::ConstrainedHigh => (0x64, 0x0c), + H264Profile::ConstrainedBaseline => (0x42, 0xe0), + }; + (profile_idc << 16) | (iop << 8) | u32::from(level_idc) +} + +/// The level TeamSpeak offers (3.1): our offers never go below it, so the +/// offer official clients know stays the same for small streams. +pub const MIN_OFFER_LEVEL: u8 = 31; + +/// `profile-level-id` for a stream of this size, frame rate and bitrate, +/// at least level 3.1. +pub fn offer_profile_level_id( + profile: H264Profile, + width: u32, + height: u32, + fps: u32, + bitrate: u64, +) -> u32 { + let level = level_idc(profile, width, height, fps, bitrate).max(MIN_OFFER_LEVEL); + profile_level_id(profile, level) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HIGH: H264Profile = H264Profile::ConstrainedHigh; + + #[test] + fn levels_from_macroblocks_per_second() { + // 720p30: 3600 MBs per frame, 108000 per second: exactly 3.1. + assert_eq!(level_idc(HIGH, 1280, 720, 30, 4_000_000), 31); + // 720p60 needs 3.2, 1080p30 4.0, 1080p60 4.2. + assert_eq!(level_idc(HIGH, 1280, 720, 60, 4_000_000), 32); + assert_eq!(level_idc(HIGH, 1920, 1080, 30, 8_000_000), 40); + assert_eq!(level_idc(HIGH, 1920, 1080, 60, 8_000_000), 42); + // 1440p60: 14400 MBs per frame, more than 4.2's 8704: 5.1. + assert_eq!(level_idc(HIGH, 2560, 1440, 60, 10_000_000), 51); + // 4K120 needs 6.0 (and any size or rate beyond all: the top level). + assert_eq!(level_idc(HIGH, 3840, 2160, 120, 10_000_000), 60); + assert_eq!(level_idc(HIGH, 16384, 16384, 240, 10_000_000), 62); + // Small streams: low levels. + assert_eq!(level_idc(HIGH, 320, 240, 15, 200_000), 12); + // The bitrate counts too: 1080p30 at 30 Mbit/s is beyond 4.0 (25 + // Mbit/s in High). + assert_eq!(level_idc(HIGH, 1920, 1080, 30, 30_000_000), 41); + // Baseline has the lower bitrate limit. + let baseline = H264Profile::ConstrainedBaseline; + assert_eq!(level_idc(baseline, 1920, 1080, 30, 22_000_000), 41); + assert_eq!(level_idc(HIGH, 1920, 1080, 30, 22_000_000), 40); + // A very wide frame is limited by sqrt(8 * MaxFS). + assert_eq!(level_idc(HIGH, 4096, 64, 1, 100_000), 40); + } + + #[test] + fn profile_level_ids() { + assert_eq!(profile_level_id(HIGH, 31), 0x640c1f); + assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f); + assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f); + assert_eq!(offer_profile_level_id(HIGH, 1920, 1080, 60, 8_000_000), 0x640c2a); + } +} diff --git a/crates/voelin-stream/src/lib.rs b/crates/voelin-stream/src/lib.rs index 5e84b43..55ff6c8 100644 --- a/crates/voelin-stream/src/lib.rs +++ b/crates/voelin-stream/src/lib.rs @@ -12,6 +12,7 @@ pub mod discovery; pub mod dtls; pub mod feedback; +pub mod h264; pub mod layer; pub mod peer; pub mod proto; @@ -23,6 +24,7 @@ pub mod stun; pub use discovery::{ClientState, StreamLookup}; pub use dtls::SrtpProfile; pub use feedback::LayerFeedback; +pub use h264::H264Profile; pub use layer::{LayerId, LayerSet, LayerSpec}; pub use peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec}; pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup}; diff --git a/crates/voelin-stream/src/peer.rs b/crates/voelin-stream/src/peer.rs index f87bbef..e1e99e9 100644 --- a/crates/voelin-stream/src/peer.rs +++ b/crates/voelin-stream/src/peer.rs @@ -32,6 +32,7 @@ use tokio::sync::{mpsc, oneshot}; use tracing::{debug, trace, warn}; use crate::dtls::{self, NegotiatedProfile, SrtpProfile}; +use crate::h264::{self, H264Profile}; use crate::layer::LayerSpec; use crate::stun; @@ -46,10 +47,12 @@ pub enum VideoCodec { Vp9, H264, Av1, + /// HEVC: offered last, for peers that take nothing else. + H265, } impl VideoCodec { - pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1]; + pub const ALL: [Self; 5] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1, Self::H265]; pub fn from_codec(c: Codec) -> Option { match c { @@ -57,6 +60,7 @@ impl VideoCodec { Codec::Vp9 => Some(Self::Vp9), Codec::H264 => Some(Self::H264), Codec::Av1 => Some(Self::Av1), + Codec::H265 => Some(Self::H265), _ => None, } } @@ -72,8 +76,20 @@ impl VideoCodec { Self::Vp9 => "VP9", Self::H264 => "H264", Self::Av1 => "AV1", + Self::H265 => "H265", } } + + /// Bit of this codec in a set of codecs ([`crate::LayerFeedback`]). + pub fn bit(self) -> u8 { + 1 << Self::ALL.iter().position(|c| *c == self).unwrap_or(0) + } +} + +impl std::fmt::Display for VideoCodec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.sdp_name()) + } } #[derive(Clone, Debug)] @@ -107,6 +123,10 @@ pub struct PeerConfig { /// simulcast leaves the peer unable to send video. Official TeamSpeak /// viewers get a plain offer and one layer at a time. pub simulcast: bool, + /// H.264 `profile-level-id` of the offer: Constrained High at the level + /// the stream needs ([`set_h264_format`](Self::set_h264_format)); level + /// 3.1 by default. + pub h264_profile_level_id: u32, } impl Default for PeerConfig { @@ -121,6 +141,7 @@ impl Default for PeerConfig { srtp_profiles: SrtpProfile::DEFAULT_ORDER.to_vec(), bandwidth_estimation: true, simulcast: false, + h264_profile_level_id: H264_CONSTRAINED_HIGH, } } } @@ -134,6 +155,21 @@ impl PeerConfig { ..Self::default() } } + + /// Offer H.264 in `profile` at the level a `width` x `height` stream at + /// `fps` and `bitrate` bit/s needs (at least 3.1, see + /// [`crate::h264::offer_profile_level_id`]). + pub fn set_h264_format( + &mut self, + profile: H264Profile, + width: u32, + height: u32, + fps: u32, + bitrate: u64, + ) { + self.h264_profile_level_id = + h264::offer_profile_level_id(profile, width, height, fps, bitrate); + } } #[derive(Debug, thiserror::Error)] @@ -190,6 +226,9 @@ pub enum PeerEvent { /// The answer accepted RID simulcast: video goes out per layer with /// these RIDs ([`Peer::write_rid`]). Simulcast(Vec), + /// The video codec the answer chose (streamer side): the viewer's first + /// one. Video written to this peer must be in it. + VideoCodec(VideoCodec), /// The connection is gone. Closed, } @@ -422,11 +461,12 @@ fn build_rtc( 112.into(), Some(113.into()), true, - H264_CONSTRAINED_HIGH, + config.h264_profile_level_id, ); c } VideoCodec::Av1 => rtc_config.enable_av1(true), + VideoCodec::H265 => rtc_config.enable_h265(true), }; } dtls::build_rtc(rtc_config, &config.srtp_profiles) @@ -798,6 +838,18 @@ impl Task { let _ = self.events.send(PeerEvent::Simulcast(rids.clone())); } } + // The codec video is written in (see `find_writer`). + if let Some((mid, pt)) = self.find_writer(MediaKind::Video) { + self.writers.insert(MediaKind::Video, (mid, pt)); + let codec = self.rtc.writer(mid).and_then(|w| { + let params = w.payload_params().find(|p| p.pt() == pt)?; + VideoCodec::from_codec(params.spec().codec) + }); + if let Some(codec) = codec { + debug!(%codec, "the answer chose"); + let _ = self.events.send(PeerEvent::VideoCodec(codec)); + } + } Ok(()) } @@ -872,6 +924,41 @@ mod tests { assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); } + /// Several codecs offered: the streamer learns which one each viewer's + /// answer chose; H.264 carries the level the stream needs. + #[tokio::test] + async fn streamer_learns_the_answered_codec() { + let mut streamer = PeerConfig { + video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264, VideoCodec::H265], + ..PeerConfig::loopback() + }; + streamer.set_h264_format(H264Profile::ConstrainedHigh, 1920, 1080, 60, 8_000_000); + let (mut peer, offer) = Peer::offer(&streamer, "s").await.unwrap(); + assert!(offer.contains("profile-level-id=640c2a"), "{offer}"); + assert!(offer.contains("H265/90000"), "{offer}"); + let viewers = [ + (vec![VideoCodec::Vp8, VideoCodec::H264], VideoCodec::Vp8), + (vec![VideoCodec::H264], VideoCodec::H264), + (vec![VideoCodec::H265], VideoCodec::H265), + ]; + for (accept, expected) in viewers { + let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap(); + let config = PeerConfig { accept_video_codecs: accept, ..PeerConfig::loopback() }; + let (_viewer, answer) = Peer::answer(&config, &offer).await.unwrap(); + streamer_peer.accept_answer(&answer).await.unwrap(); + let codec = loop { + match streamer_peer.next_event().await.unwrap() { + PeerEvent::VideoCodec(codec) => break codec, + PeerEvent::Closed => panic!("closed"), + _ => {} + } + }; + assert_eq!(codec, expected); + } + peer.close(); + while peer.next_event().await.is_some() {} + } + /// The SDP lines that make up the media description (not the random ids, /// ports, credentials and fingerprints). fn media_lines(sdp: &str) -> Vec<&str> { diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 0fbe12f..a46f8ea 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -40,7 +40,7 @@ use crate::discovery::{ClientState, Discovery, StreamLookup}; use crate::dtls::SrtpProfile; use crate::feedback::LayerFeedback; use crate::layer::{LayerId, LayerSet, LayerSpec}; -use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent}; +use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec}; use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup}; use crate::signal::Signal; use crate::source::EncodedFrame; @@ -146,6 +146,9 @@ pub struct ViewerInfo { pub estimate: Option, /// The SRTP profile of the connection, once DTLS is done. pub srtp_profile: Option, + /// The video codec the viewer's answer chose (it gets video in that + /// codec). + pub codec: Option, } /// What happens to our own stream. @@ -542,6 +545,8 @@ struct ViewerSlot { /// The latest bandwidth estimate of the connection (bit/s). estimate: Option, srtp_profile: Option, + /// The video codec its answer chose. + codec: Option, } impl ViewerSlot { @@ -554,6 +559,7 @@ impl ViewerSlot { rids: None, estimate: None, srtp_profile: None, + codec: None, } } @@ -648,6 +654,7 @@ impl StreamerSession { layer: (v.peer.is_some() && v.rids.is_none()).then_some(v.choice.layer), estimate: v.estimate, srtp_profile: v.srtp_profile, + codec: v.codec, }) .collect() } @@ -792,6 +799,7 @@ impl StreamerSession { slot.peer = Some(peer); slot.state = ViewerState::Connecting; slot.choice = LayerChoice::new(layer); + slot.codec = None; slot.rids = None; slot.estimate = None; slot.srtp_profile = None; @@ -930,6 +938,18 @@ impl StreamerSession { /// Send an encoded frame: audio to every connected viewer, video to the /// viewers of its layer (with its RID to peers with RID simulcast). pub fn write_frame(&mut self, frame: &EncodedFrame, out: &mut Outbox) { + self.write_frame_in(frame, None, out); + } + + /// [`write_frame`](Self::write_frame) for video encoded in `codec` + /// (`None`: whatever the viewers negotiated): only viewers whose answer + /// chose that codec get it. + pub fn write_frame_in( + &mut self, + frame: &EncodedFrame, + codec: Option, + out: &mut Outbox, + ) { let (kind, time, layer) = (frame.kind, frame.time, frame.layer); let rid = match kind { MediaKind::Video => self.layers.index(layer).and_then(|i| self.layers.rids[i]), @@ -944,6 +964,11 @@ impl StreamerSession { peer.write(kind, time, frame.data.clone()); continue; } + if let (Some(codec), Some(negotiated)) = (codec, slot.codec) + && codec != negotiated + { + continue; + } match &slot.rids { Some(rids) => { if let Some(rid) = rid @@ -1062,6 +1087,11 @@ impl StreamerSession { slot.rids = Some(rids); } } + PeerEvent::VideoCodec(codec) => { + debug!(viewer = viewer.0, %codec, "viewer's video codec"); + slot.codec = Some(codec); + self.emit_viewers(out); + } PeerEvent::Media(_) | PeerEvent::LayerMedia { .. } => {} PeerEvent::Closed => { // The viewer may ask for a new offer (`reconnect`); it stays @@ -1173,6 +1203,11 @@ impl StreamerSession { } fn emit_viewers(&mut self, out: &mut Outbox) { + // Every change of the viewers comes through here: the encoders learn + // which codecs are needed now. + self.feedback.set_codecs( + self.viewers.values().filter(|v| v.peer.is_some()).filter_map(|v| v.codec), + ); self.last_viewers_event = Some(Instant::now()); out.event(StreamEvent::Streamer(StreamerEvent::Viewers(self.viewers()))); } @@ -1409,7 +1444,8 @@ impl ViewerSession { PeerEvent::KeyframeRequest | PeerEvent::LayerKeyframeRequest(_) | PeerEvent::BitrateEstimate(_) - | PeerEvent::Simulcast(_) => {} + | PeerEvent::Simulcast(_) + | PeerEvent::VideoCodec(_) => {} PeerEvent::Closed => { if self.peer.take().is_none() { return; @@ -1524,8 +1560,15 @@ impl Streams { /// Send an encoded frame of our stream: audio to every connected viewer, /// video to the viewers of its layer. pub fn write_frame(&mut self, frame: &EncodedFrame) { + self.write_frame_in(frame, None); + } + + /// [`write_frame`](Self::write_frame) of video encoded in `codec`: to + /// the viewers that negotiated it (see + /// [`StreamerSession::write_frame_in`]). + pub fn write_frame_in(&mut self, frame: &EncodedFrame, codec: Option) { if let Some(s) = self.streamer.as_mut().filter(|s| !s.is_ended()) { - s.write_frame(frame, &mut self.out); + s.write_frame_in(frame, codec, &mut self.out); } } diff --git a/crates/voelin-ui/src/video.rs b/crates/voelin-ui/src/video.rs index 35632e1..cb1debb 100644 --- a/crates/voelin-ui/src/video.rs +++ b/crates/voelin-ui/src/video.rs @@ -11,9 +11,10 @@ use slint::{Image, Rgba8Pixel, SharedPixelBuffer}; use tokio::runtime::Handle; use tracing::warn; use voelin_core::media::voelin_media::capture::SourceId; -use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert}; +use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert}; use voelin_core::media::{ - self, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, stream_codec, + self, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, + preferred_codec, stream_codec, }; use voelin_core::stream::PeerConfig; use voelin_core::{Engine, StreamSink}; @@ -56,6 +57,10 @@ pub(crate) struct Video { openh264_dir: PathBuf, #[cfg(not(target_os = "android"))] h264: openh264::State, + /// Which encoders to use and the configured stream codec (`None`: + /// automatic), from the settings. + encoder: EncoderPreference, + codec: Option, /// Sources of the share dialog, by index. sources: Vec<(SourceId, String)>, } @@ -67,6 +72,8 @@ impl Video { #[allow(unused_mut, reason = "set_h264 does nothing on Android")] let mut video = Self { codecs: Arc::new(Codecs::new()), + encoder: EncoderPreference::default(), + codec: None, #[cfg(not(target_os = "android"))] openh264_dir: data_dir.join("openh264"), #[cfg(not(target_os = "android"))] @@ -78,11 +85,34 @@ impl Video { video } - /// `base` with the codecs this machine can encode and decode. - pub fn peer_config(&self, base: PeerConfig) -> PeerConfig { + /// `base` with the codecs this machine can encode and decode: the stream + /// codec (configured, or the encoder preference's first) offered first. + pub fn peer_config(&self, mut base: PeerConfig) -> PeerConfig { + if let Some(codec) = preferred_codec(&self.codecs, self.codec) { + base.video_codecs = vec![media::video_codec(codec)]; + } peer_config(&self.codecs, base) } + /// Use other encoders (`stream.hardware_acceleration`, + /// `stream.encoder_backend`) and stream codec (`stream.codec`, `None`: + /// automatic). A running share follows through + /// `Streamer::reconfigure` with `StreamerConfigUpdate::encoder`. + #[allow(dead_code, reason = "for the settings page")] + pub fn set_encoder_preference(&mut self, encoder: EncoderPreference, codec: Option) { + let mut codecs = (*self.codecs).clone(); + codecs.set_preference(encoder.clone()); + self.codecs = Arc::new(codecs); + self.encoder = encoder; + self.codec = codec; + } + + /// Every encoder backend, what works and why the rest does not. + #[allow(dead_code, reason = "for the integrations page")] + pub fn encoder_report(&self) -> EncoderReport { + self.codecs.report() + } + /// Whether H.264 works, and a line for the settings page. pub fn h264_status(&self) -> (bool, String) { #[cfg(target_os = "android")] @@ -109,7 +139,7 @@ impl Video { use openh264::State; if !enabled { self.h264 = State::Off; - self.codecs = Arc::new(Codecs::new()); + self.codecs = Arc::new(Codecs::new().with_preference(self.encoder.clone())); return; } if matches!(self.h264, State::Loaded(_) | State::Downloading) { @@ -125,7 +155,8 @@ impl Video { #[cfg(not(target_os = "android"))] fn loaded(&mut self, library: openh264::OpenH264) { self.h264 = openh264::State::Loaded(library.path().to_owned()); - self.codecs = Arc::new(Codecs::new().with_openh264(library)); + self.codecs = + Arc::new(Codecs::new().with_openh264(library).with_preference(self.encoder.clone())); } /// Download Cisco's OpenH264 (only on the user's request). `done` runs @@ -229,6 +260,7 @@ impl Video { fps: options.fps, bitrate_kbps: options.bitrate_kbps, codec, + encoder: self.encoder.clone(), audio: options.audio, restore_token: options.restore_token, ..StreamerConfig::default() From 2927100b202510624ad6484e49c4cf0a23813a99 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 00:56:41 +0000 Subject: [PATCH 4/9] voelinctl: list the video encoders, bench and stream with any of them `voelinctl stream encoders` prints the FFmpeg libraries found, every encoder backend with its self-test result or why it cannot be used, and the order the streamer tries them in (--encoder / --no-hardware rank as the settings would). `stream bench` and `stream start` take --encoder, --no-hardware and a --codec that defaults to the named encoder's codec or the choice's first; they print the backend in use. `stream start` feeds a FrameSource, which does not tell codecs apart, so it offers its stream codec alone; with the test pattern the H.264 level follows its size, rate and bitrate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-core/src/media.rs | 14 ++- crates/voelin-media/src/codec/mod.rs | 2 +- crates/voelin-media/src/ffmpeg/encoder.rs | 1 + crates/voelin-stream/src/session.rs | 5 +- tools/voelinctl/src/bench.rs | 110 +++++++++++++++++++--- tools/voelinctl/src/stream.rs | 69 ++++++++++++-- 6 files changed, 171 insertions(+), 30 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index d639daf..245b4c0 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -1002,7 +1002,8 @@ impl Streamer { for (spec, &threads) in specs.iter().zip(&split) { let existing = current.iter().any(|l| l.id == spec.id); if !existing || codec_changed { - let encoder = new_encoder(codecs, next.codec, &next.encoder, spec, next.fps, threads)?; + let encoder = + new_encoder(codecs, next.codec, &next.encoder, spec, next.fps, threads)?; created.push((spec.id, encoder)); } } @@ -1696,7 +1697,9 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box) { let fps = layer.fps.load(Ordering::Relaxed); extra.push(match extra_encoder(shared, layer, codec) { Some(encoder) => LayerEncoder::new(encoder, fps), - None => LayerEncoder { codec, encoder: None, keyframe_due: false, bitrate: 0, fps }, + None => { + LayerEncoder { codec, encoder: None, keyframe_due: false, bitrate: 0, fps } + } }); } } @@ -2553,8 +2556,11 @@ mod tests { *lock(&sink.codecs) = vec![Codec::Vp8, Codec::Vp9]; wait_for(Codec::Vp9, 5).await; assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp8, Codec::Vp9]); - let vp9: Vec = - lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp9).map(|(_, f)| f.clone()).collect(); + let vp9: Vec = lock(&sink.frames) + .iter() + .filter(|(c, _)| *c == Codec::Vp9) + .map(|(_, f)| f.clone()) + .collect(); assert!(is_keyframe(Codec::Vp9, &vp9[0].data), "the first VP9 frame is a keyframe"); let mut decoder = codecs.new_decoder(Codec::Vp9).unwrap(); for frame in &vp9 { diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 70a6c59..138f2e7 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -14,8 +14,8 @@ //! (hardware, or Google's software VP8 / VP9 / H.264) use std::fmt; -use std::sync::Arc; use std::str::FromStr; +use std::sync::Arc; use crate::frame::VideoFrame; use crate::{Error, Result}; diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index a3251fa..4b13d4e 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -1089,6 +1089,7 @@ fn test_backend(spec: &'static BackendSpec) -> std::result::Result<(), String> { Ok((_, false)) => Err("the test frame did not come out as a keyframe".into()), Ok(_) => Ok(()), Err(Error::CodecUnavailable { reason, .. }) => Err(reason), + Err(Error::Encoder { message, .. }) => Err(message), Err(e) => Err(e.to_string()), } } diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index a46f8ea..c4b03af 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -1205,9 +1205,8 @@ impl StreamerSession { fn emit_viewers(&mut self, out: &mut Outbox) { // Every change of the viewers comes through here: the encoders learn // which codecs are needed now. - self.feedback.set_codecs( - self.viewers.values().filter(|v| v.peer.is_some()).filter_map(|v| v.codec), - ); + self.feedback + .set_codecs(self.viewers.values().filter(|v| v.peer.is_some()).filter_map(|v| v.codec)); self.last_viewers_event = Some(Instant::now()); out.event(StreamEvent::Streamer(StreamerEvent::Viewers(self.viewers()))); } diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index 50227b5..b902a10 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -12,7 +12,7 @@ use clap::{Args, Subcommand}; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::capture::synthetic::Pattern; use voelin_core::media::voelin_media::{Codec, Codecs}; -use voelin_core::media::{MediaSink, Streamer, StreamerConfig}; +use voelin_core::media::{EncoderPreference, MediaSink, Streamer, StreamerConfig, preferred_codec}; use voelin_stream::{EncodedFrame, LayerId, LayerSet, LayerSpec, MediaKind}; use crate::alloc; @@ -29,6 +29,24 @@ enum StreamTool { /// test pattern without a server; print per-stage and per-layer numbers /// and heap allocations per frame. Bench(BenchArgs), + /// List the video encoders: the FFmpeg libraries found, every backend + /// with its self-test result (or why it cannot be used), and the order + /// the streamer would use them in. + Encoders(EncodersArgs), +} + +#[derive(Args, Debug)] +struct EncodersArgs { + /// Encoder choice to rank by: `auto`, `software` or a backend name (as + /// the setting `stream.encoder_backend`). + #[arg(long, default_value = "auto")] + encoder: String, + /// Rank without hardware encoders (`stream.hardware_acceleration` off). + #[arg(long)] + no_hardware: bool, + /// Cisco's OpenH264 library, to list it as well. + #[arg(long)] + openh264: Option, } #[derive(Args, Debug)] @@ -43,9 +61,17 @@ struct BenchArgs { /// as real screen content) or `simple` (a flat background). #[arg(long, default_value = "desktop")] pattern: String, - /// Video codec: vp8, vp9 or h264 (needs --openh264). - #[arg(long, default_value = "vp8")] - codec: String, + /// Video codec: vp8, vp9, h264, av1 or h265 [default: the codec of + /// --encoder if named, else the first the encoder choice gives]. + #[arg(long)] + codec: Option, + /// Encoder: `auto`, `software` or a backend name from `voelinctl stream + /// encoders` (`h264_vaapi`, `libx264`, `libsvtav1`, ...). + #[arg(long, default_value = "auto")] + encoder: String, + /// No hardware encoders unless named with --encoder. + #[arg(long)] + no_hardware: bool, /// A simulcast layer, e.g. `scale=0.5,bitrate=1500k,fps=15` (keys: id, /// scale, size=WxH, fps, bitrate, max, min, rid; bitrates in bit/s with /// k/M suffixes); repeatable. Without it: one layer at --bitrate. @@ -68,9 +94,60 @@ struct BenchArgs { pub fn run(args: StreamToolArgs) -> Result<()> { match args.command { StreamTool::Bench(args) => bench(args), + StreamTool::Encoders(args) => encoders(args), } } +/// `Codecs` with the encoder choice of the arguments. +fn codecs_for(encoder: &str, no_hardware: bool, openh264: Option<&PathBuf>) -> Result { + let preference = + EncoderPreference { hardware: !no_hardware, backend: encoder.parse().unwrap_or_default() }; + let mut codecs = Codecs::new().with_preference(preference); + if let Some(path) = openh264 { + let library = voelin_core::media::voelin_media::codec::h264::OpenH264::load(path) + .context("OpenH264")?; + codecs = codecs.with_openh264(library); + } + Ok(codecs) +} + +fn encoders(args: EncodersArgs) -> Result<()> { + let codecs = codecs_for(&args.encoder, args.no_hardware, args.openh264.as_ref())?; + let report = codecs.report(); + match &report.ffmpeg { + Ok(text) => println!("{text}"), + Err(e) => println!("FFmpeg: not used ({e})"), + } + match &report.zero_copy { + Ok(()) => println!("zero-copy DMA-BUF import: available"), + Err(e) => println!("zero-copy DMA-BUF import: no ({e})"), + } + println!(); + println!("{:<18} {:<5} {:<17} {:<8} {:<5} status", "encoder", "codec", "api", "kind", "rank"); + let mut list = report.encoders.clone(); + // Usable ones first, in the order the streamer tries them per codec. + list.sort_by_key(|e| (e.status.is_err(), e.rank.unwrap_or(usize::MAX), e.codec.name())); + for e in &list { + let status = match &e.status { + Ok(()) if e.rank.is_none() => "ok (only when named)".to_owned(), + Ok(()) => "ok".to_owned(), + Err(reason) => reason.clone(), + }; + println!( + "{:<18} {:<5} {:<17} {:<8} {:<5} {status}", + e.name, + e.codec.name(), + e.api, + if e.hardware { "hardware" } else { "software" }, + e.rank.map_or("-".to_owned(), |r| r.to_string()), + ); + } + let order: Vec = + codecs.encoders().iter().map(|(codec, backend)| format!("{codec} {backend}")).collect(); + println!("\nstreamer order: {}", order.join(", ")); + Ok(()) +} + /// Frames and bytes the sink got for one layer. #[derive(Default)] struct LayerCount { @@ -220,13 +297,18 @@ fn bench(args: BenchArgs) -> Result<()> { "simple" => Pattern::Simple, other => bail!("unknown pattern {other:?}: desktop or simple"), }; - let codec: Codec = args.codec.parse().map_err(|e| anyhow::anyhow!("{e}"))?; - let mut codecs = Codecs::new(); - if let Some(path) = &args.openh264 { - let library = voelin_core::media::voelin_media::codec::h264::OpenH264::load(path) - .context("OpenH264")?; - codecs = codecs.with_openh264(library); - } + let codecs = codecs_for(&args.encoder, args.no_hardware, args.openh264.as_ref())?; + let codec: Codec = match &args.codec { + Some(codec) => codec.parse().map_err(|e| anyhow::anyhow!("{e}"))?, + None => { + // The named encoder's codec, else the first of the choice. + let named = codecs.encoders().into_iter().find(|(_, b)| b.name() == args.encoder); + match named { + Some((codec, _)) => codec, + None => preferred_codec(&codecs, None).context("no video encoder")?, + } + } + }; let layers = args .layers .iter() @@ -242,6 +324,7 @@ fn bench(args: BenchArgs) -> Result<()> { fps: args.fps, bitrate_kbps: args.bitrate, codec, + encoder: codecs.preference().clone(), audio: false, layers: layers.clone(), ..StreamerConfig::default() @@ -253,10 +336,13 @@ fn bench(args: BenchArgs) -> Result<()> { keyframe: AtomicBool::new(true), }); streamer.attach(sink.clone()); + let backend = streamer.stats().layers.first().and_then(|l| l.backend); println!( - "{width}x{height} {} test pattern at {} fps, {codec}, {} layer(s), {} s after {} s warm-up", + "{width}x{height} {} test pattern at {} fps, {codec} ({}), {} layer(s), {} s after {} s \ + warm-up", args.pattern, args.fps, + backend.map_or("?".to_owned(), |b| b.to_string()), ids.len(), args.seconds, args.warmup diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index bf65c55..e882a6f 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -16,14 +16,14 @@ use tsclientlib::{ClientId, Connection, MessageHandle, StreamItem}; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert}; use voelin_core::media::{ - CaptureBackend, EncodedSource, Latest, Streamer, StreamerConfig, VideoPipeline, peer_config, - stream_codec, + CaptureBackend, EncodedSource, EncoderPreference, Latest, Streamer, StreamerConfig, + VideoPipeline, peer_config, preferred_codec, stream_codec, video_codec, }; use voelin_model::ServerFlavor; use voelin_stream::{ - ClientState, EndReason, FrameSource, LayerId, LayerSpec, MediaKind, Output, PeerConfig, - Request, SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup, StreamerEvent, - StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent, + ClientState, EndReason, FrameSource, H264Profile, LayerId, LayerSpec, MediaKind, Output, + PeerConfig, Request, SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup, + StreamerEvent, StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent, }; #[derive(Args, Debug, Clone)] @@ -96,6 +96,17 @@ pub enum StreamCommand { /// bitrate, no encoder) instead of capturing. #[arg(long, conflicts_with_all = ["source", "synthetic"])] placeholder: bool, + /// Video codec: vp8, vp9, h264, av1 [default: the first the encoder + /// choice gives: hardware first, else VP8]. + #[arg(long)] + codec: Option, + /// Encoder: `auto`, `software` or a backend name from `voelinctl + /// stream encoders`. + #[arg(long, default_value = "auto")] + encoder: String, + /// No hardware encoders unless named with --encoder. + #[arg(long)] + no_hardware: bool, }, /// List the streams in our channel. List { @@ -141,19 +152,54 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { if !args.srtp.is_empty() { config.srtp_profiles = parse_srtp(&args.srtp)?; } - if let StreamCommand::Start { simulcast, placeholder, .. } = &args.command { + let mut codecs = Codecs::new(); + if let StreamCommand::Start { + simulcast, + placeholder, + codec, + encoder, + no_hardware, + synthetic, + size, + fps, + bitrate, + .. + } = &args.command + { config.simulcast = *simulcast; + codecs.set_preference(EncoderPreference { + hardware: !no_hardware, + backend: encoder.parse().unwrap_or_default(), + }); if *placeholder { // The placeholder frames are VP8. config.video_codecs = vec![VideoCodec::Vp8]; + } else { + let configured = match codec { + Some(codec) => Some(codec.parse().map_err(|e| anyhow::anyhow!("{e}"))?), + None => None, + }; + if let Some(codec) = preferred_codec(&codecs, configured) { + config.video_codecs = vec![video_codec(codec)]; + } + if *synthetic { + let (w, h) = parse_size(size)?; + let bitrate = u64::from(*bitrate) * 1000; + config.set_h264_format(H264Profile::ConstrainedHigh, w, h, *fps, bitrate); + } } } // Offer the codec we encode, accept what we decode. - let codecs = Arc::new(Codecs::new()); - let config = match &args.command { + let codecs = Arc::new(codecs); + let mut config = match &args.command { StreamCommand::Start { placeholder: true, .. } => config, _ => peer_config(&codecs, config), }; + if matches!(args.command, StreamCommand::Start { .. }) { + // Frames go out through a `FrameSource`, which does not tell codecs + // apart: offer the stream codec alone. + config.video_codecs.truncate(1); + } let codec = stream_codec(&codecs, &config); let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() }; driver.sync_clients(con)?; @@ -169,8 +215,8 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { bitrate, no_audio, layers, - simulcast: _, placeholder, + .. } => { let mut layers = layers.clone(); number_layers(&mut layers); @@ -203,13 +249,16 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { fps: *fps, bitrate_kbps: *bitrate, codec, + encoder: codecs.preference().clone(), audio: !no_audio, synthetic_size: parse_size(size)?, layers: layers.clone(), ..StreamerConfig::default() }; let streamer = Streamer::start(&codecs, config).await.context("capture")?; - println!("capturing with {} ({codec})", streamer.backend()); + let backend = streamer.stats().layers.first().and_then(|l| l.backend); + let backend = backend.map_or("?".to_owned(), |b| b.to_string()); + println!("capturing with {} ({codec} through {backend})", streamer.backend()); if let Some(e) = streamer.audio_error() { println!("audio: {e}"); } From fec23905d66afc16436fc50d6d84720c2fc859f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:02:36 +0000 Subject: [PATCH 5/9] voelin-media: DMA-BUF import into VA-API encoders, up to the GPU conversion FfmpegEncoder::encode_dmabuf maps a DRM PRIME frame onto a VA-API surface (av_hwframe_map) that the encoder reads without a copy. It needs AVFrame.buf[0] and AVFrame.hw_frames_ctx, which have no accessor: their offsets come from a table per libavutil major, buf[0] is checked on a real frame at load and hw_frames_ctx on the encoder's first surface. Only NV12 buffers are taken: screen capture delivers RGB, which needs a colour conversion on the GPU (VA-API video processing) that is not implemented; anything else is refused as unavailable so the caller maps the buffer as before. On the capture side, FrameSink::accepts_dmabuf / dmabuf let the portal hand a buffer over before mapping it (and pass tiled ones through). No sink accepts yet, and the portal still negotiates LINEAR buffers only. The encoder ends its stream when dropped (SVT-AV1 logs an error otherwise). Untested on a GPU: this machine has no render node. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/src/capture/mod.rs | 48 ++++++ crates/voelin-media/src/capture/portal.rs | 39 ++++- crates/voelin-media/src/ffmpeg/encoder.rs | 189 ++++++++++++++++++++-- crates/voelin-media/src/ffmpeg/layout.rs | 1 - crates/voelin-media/src/ffmpeg/mod.rs | 1 - crates/voelin-media/src/ffmpeg/sys.rs | 2 + crates/voelin-media/tests/ffmpeg.rs | 27 ++++ 7 files changed, 286 insertions(+), 21 deletions(-) diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index f37ee4d..b4ccc1a 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -110,6 +110,54 @@ pub trait FrameSink: Send { /// One frame. Its pixels are only valid during the call. Returns /// `false` when no more frames are wanted; the backend then stops. fn frame(&mut self, frame: FrameRef<'_>) -> bool; + + /// Whether the sink takes frames that are still in a DMA-BUF (GPU + /// memory) through [`dmabuf`](Self::dmabuf), e.g. for a VA-API encoder + /// that imports them without a copy + /// (`ffmpeg::FfmpegEncoder::encode_dmabuf`). Backends that capture into + /// DMA-BUFs (the portal) then offer the buffer before mapping it. + fn accepts_dmabuf(&self) -> bool { + false + } + + /// A frame in a DMA-BUF, valid during the call. `None`: not taken, the + /// backend maps it and calls [`frame`](Self::frame); `Some(more)` as the + /// result of `frame`. + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + let _ = frame; + None + } +} + +/// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`. +pub const fn drm_fourcc(code: &[u8; 4]) -> u32 { + code[0] as u32 | (code[1] as u32) << 8 | (code[2] as u32) << 16 | (code[3] as u32) << 24 +} + +/// `DRM_FORMAT_MOD_LINEAR`. +pub const DRM_MOD_LINEAR: u64 = 0; +/// `DRM_FORMAT_MOD_INVALID`: the driver's implicit layout. +pub const DRM_MOD_INVALID: u64 = 0x00ff_ffff_ffff_ffff; + +/// A captured frame still in a DMA-BUF: one buffer object (a file +/// descriptor borrowed for the call) with one plane per `planes` entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DmaBufRef { + pub width: u32, + pub height: u32, + /// As [`VideoFrame::timestamp`]. + pub timestamp: Duration, + /// DRM format (`drm_fourcc(b"XR24")` for BGRx, `b"NV12"`, ...). + pub fourcc: u32, + /// DRM format modifier (tiling); [`DRM_MOD_LINEAR`] for rows in memory + /// order. + pub modifier: u64, + pub fd: i32, + /// Size of the buffer object in bytes. + pub size: usize, + /// `(offset, stride)` of each plane in the buffer object. + pub planes: [(usize, usize); 4], + pub plane_count: usize, } /// Keeps frames of a source for a frame-rate cap, by their timestamps, so diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index ea42eab..7fecbd2 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -34,7 +34,8 @@ use tracing::{debug, warn}; use crate::capture::dmabuf::DmaBufMap; use crate::capture::pw::{PwThread, pod, serialize}; use crate::capture::{ - BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId, + BoxFuture, CaptureOptions, CaptureSource, DRM_MOD_LINEAR, DmaBufRef, FrameSink, QueueSink, + ScreenCapture, SourceId, drm_fourcc, }; use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::FrameReceiver; @@ -524,8 +525,8 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { } let Some(mut buffer) = stream.dequeue_buffer() else { return }; let Some(format) = state.format else { return }; - if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) { - // Tiled: the CPU cannot read it (we never offer that). + if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) && !state.sink.accepts_dmabuf() { + // Tiled: the CPU cannot read it (we only offer LINEAR). return; } let timestamp = state.started.elapsed(); @@ -564,6 +565,38 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { state.logged = Some(is_dmabuf); debug!(dmabuf = is_dmabuf, "screen capture buffers"); } + // A sink that imports DMA-BUFs (a VA-API encoder) gets the buffer as it + // is, without a mapping or copy. + if is_dmabuf && state.sink.accepts_dmabuf() { + let raw = data.as_raw(); + let fourcc = match format.format { + VideoFormat::BGRx => drm_fourcc(b"XR24"), + VideoFormat::BGRA => drm_fourcc(b"AR24"), + VideoFormat::RGBx => drm_fourcc(b"XB24"), + _ => drm_fourcc(b"AB24"), + }; + let frame = DmaBufRef { + width: format.width, + height: format.height, + timestamp, + fourcc, + modifier: format.modifier.map_or(DRM_MOD_LINEAR, |m| m as u64), + fd: data.fd(), + size: (raw.mapoffset + raw.maxsize) as usize, + planes: [(raw.mapoffset as usize + offset, stride), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + }; + if let Some(more) = state.sink.dmabuf(&frame) { + if !more && let Some(mainloop) = state.mainloop.upgrade() { + mainloop.quit(); + } + return; + } + } + if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) { + // Tiled and not taken as it is: nothing the CPU can read. + return; + } let started = Instant::now(); let more = if is_dmabuf { let raw = data.as_raw(); diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 4b13d4e..cdd1918 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -18,6 +18,7 @@ use std::time::Duration; use super::layout::{self, HwFramesFields}; use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; use super::{Ffmpeg, take_log}; +use crate::capture::{DmaBufRef, drm_fourcc}; use crate::codec::hw::EncoderFactory; use crate::codec::{ Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, H264Profile, @@ -493,6 +494,8 @@ pub struct FfmpegEncoder { reinit: Reinit, /// VA-API only offers the low-power entry point for this codec. low_power: bool, + /// `AVFrame.hw_frames_ctx` was checked on a surface of this encoder. + dmabuf_checked: bool, } impl FfmpegEncoder { @@ -505,7 +508,15 @@ impl FfmpegEncoder { })?; let ffmpeg = Ffmpeg::get() .map_err(|e| Error::CodecUnavailable { codec: spec.codec, reason: e.to_owned() })?; - Ok(Self { ffmpeg, spec, config, session: None, reinit: Reinit::No, low_power: false }) + Ok(Self { + ffmpeg, + spec, + config, + session: None, + reinit: Reinit::No, + low_power: false, + dmabuf_checked: false, + }) } pub fn spec(&self) -> &'static BackendSpec { @@ -873,13 +884,16 @@ impl FfmpegEncoder { Ok(keyframe) } - fn encode_i420( + /// The session for a `width` x `height` frame, opened anew when the size + /// changed or a reinit is due; whether the frame must be a keyframe. + fn prepare( &mut self, - frame: &VideoFrame, + width: u32, + height: u32, force_keyframe: bool, out: &mut dyn FnMut(EncodedChunk<'_>), - ) -> Result<()> { - let (w, h) = Self::coded_size(frame.width, frame.height); + ) -> Result<(Session, bool)> { + let (w, h) = Self::coded_size(width, height); let mut force = force_keyframe; let reopen = match &self.session { None => true, @@ -902,12 +916,154 @@ impl FfmpegEncoder { self.reinit = Reinit::No; force = true; } - let mut session = self.session.take().expect("opened above"); + Ok((self.session.take().expect("opened above"), force)) + } + + fn encode_i420( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; let result = self.encode_in(&mut session, frame, force, out); self.session = Some(session); 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. + /// + /// 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). + pub fn encode_dmabuf( + &mut self, + frame: &DmaBufRef, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + 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(), + )); + } + if Self::coded_size(frame.width, frame.height) != (frame.width, frame.height) { + return Err(self.unavailable("odd frame size".into())); + } + 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); + 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, + force: bool, + refs: layout::FrameRefs, + drm_prime: c_int, + vaapi: c_int, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let api = &self.ffmpeg.api; + if !self.dmabuf_checked { + // The table's AVFrame.hw_frames_ctx must be where FFmpeg puts + // the pool of a surface it allocates. + // SAFETY: `hw` is our frame, the pool the session's. + let ok = unsafe { + let ret = (api.av_hwframe_get_buffer)(session.pool, session.hw, 0); + let ok = ret >= 0 && layout::check_hw_frames_ctx(session.hw, session.pool, refs); + (api.av_frame_unref)(session.hw); + ok + }; + if !ok { + return Err(self.unavailable("AVFrame.hw_frames_ctx check failed".into())); + } + self.dmabuf_checked = true; + } + let mut descriptor = + sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() }; + descriptor.objects[0] = + sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier }; + descriptor.layers[0].format = frame.fourcc; + descriptor.layers[0].nb_planes = frame.plane_count as c_int; + for (plane, &(offset, pitch)) in + descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count]) + { + *plane = + sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; + } + 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 + // hw_frames_ctx offset; av_frame_free / av_frame_unref release both. + unsafe { + let mut buffer = (api.av_buffer_allocz)(std::mem::size_of::()); + let mut src = (api.av_frame_alloc)(); + if buffer.is_null() || src.is_null() { + (api.av_buffer_unref)(&mut buffer); + (api.av_frame_free)(&mut src); + return Err(self.unavailable("out of memory".into())); + } + let data = (*buffer.cast::()).data; + data.cast::().write(descriptor); + let head = src.cast::(); + (*head).format = drm_prime; + (*head).width = frame.width as c_int; + (*head).height = frame.height as c_int; + (*head).data[0] = data; + layout::write::(src, refs.buf, buffer); + let dst = session.hw; + (*dst.cast::()).format = vaapi; + layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(session.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(|_| ()) + } + } + + /// The pts of a frame taken at `timestamp`: frame numbers at the + /// session's rate (its time base), strictly increasing; remembered with + /// the 90 kHz time for the packets. + fn stamp(&self, session: &mut Session, timestamp: Duration, pts_90khz: u64) -> i64 { + let exact = timestamp.as_secs_f64() * f64::from(session.fps); + let mut pts = exact.round() as i64; + if let Some(last) = session.last_pts + && pts <= last + { + pts = last + 1; + } + session.last_pts = Some(pts); + session.timestamps.push(pts, pts_90khz); + pts + } + fn encode_in( &self, session: &mut Session, @@ -917,16 +1073,7 @@ impl FfmpegEncoder { ) -> Result<()> { let api = &self.ffmpeg.api; self.fill(session, frame)?; - // Frame numbers at the session's rate, strictly increasing. - let exact = frame.timestamp.as_secs_f64() * f64::from(session.fps); - let mut pts = exact.round() as i64; - if let Some(last) = session.last_pts - && pts <= last - { - pts = last + 1; - } - session.last_pts = Some(pts); - session.timestamps.push(pts, frame.pts_90khz()); + let pts = self.stamp(session, frame.timestamp, frame.pts_90khz()); let fields = self.ffmpeg.frame; let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; let input = if session.hw.is_null() { @@ -984,6 +1131,16 @@ impl FfmpegEncoder { } } +impl Drop for FfmpegEncoder { + /// Ends the stream properly (SVT-AV1 complains otherwise); the frames + /// still inside are dropped. + fn drop(&mut self) { + if let Some(mut session) = self.session.take() { + let _ = self.send(&mut session, std::ptr::null_mut(), &mut |_| {}); + } + } +} + impl VideoEncoder for FfmpegEncoder { fn codec(&self) -> Codec { self.spec.codec diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 0df7c63..3947825 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -376,7 +376,6 @@ pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result { /// # Safety /// `frame` must be a live AVFrame of this release, `pool` a live buffer /// reference. -#[allow(dead_code)] // for the DMA-BUF import pub unsafe fn check_hw_frames_ctx(frame: Ptr, pool: Ptr, refs: FrameRefs) -> bool { // SAFETY: guaranteed by the caller; the offset is inside AVFrame. unsafe { diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 47a9162..e565fff 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -65,7 +65,6 @@ pub struct Ffmpeg { /// `AVCodecContext.hw_frames_ctx`. pub(crate) codec_hw_frames: Result, /// `AVFrame.buf[0]` / `hw_frames_ctx`. - #[allow(dead_code)] // for the DMA-BUF import pub(crate) frame_refs: Result, pub(crate) pix: PixFmts, info: LibraryInfo, diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index c95bbb2..8d6f8ce 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -227,6 +227,8 @@ api! { ) -> c_int; fn av_buffer_ref(buf: Ptr) -> Ptr; fn av_buffer_unref(buf: *mut Ptr); + // `size` is an `int` up to libavutil 56: passed in the same register. + fn av_buffer_allocz(size: usize) -> Ptr; fn av_hwdevice_find_type_by_name(name: *const c_char) -> c_int; fn av_hwdevice_ctx_create( device: *mut Ptr, diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index 8393ecc..f495408 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -228,3 +228,30 @@ fn unusable_backends_fail_cleanly() { assert!(encoder.encode(&frame, true).is_err(), "{} passed now", status.spec.name); } } + +/// DMA-BUF import is for VA-API encoders and NV12 buffers; anything else is +/// refused as unavailable, so the caller maps the buffer instead. +#[cfg(target_os = "linux")] +#[test] +fn dmabuf_import_is_refused_cleanly() { + use voelin_media::capture::{DRM_MOD_LINEAR, DmaBufRef, drm_fourcc}; + if ffmpeg().is_none() { + return; + } + let frame = DmaBufRef { + width: W, + height: H, + timestamp: Duration::ZERO, + fourcc: drm_fourcc(b"XR24"), + modifier: DRM_MOD_LINEAR, + fd: -1, + 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 mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap(); + let err = encoder.encode_dmabuf(&frame, true, &mut |_| {}).unwrap_err(); + assert!(matches!(err, voelin_media::Error::CodecUnavailable { .. }), "{name}: {err}"); + } +} From d769ab8910b58fea126fdc1770f44453ab84b7b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:10:26 +0000 Subject: [PATCH 6/9] docs: FFmpeg encoders, per-viewer codecs, how to install FFmpeg docs/media.md: how FFmpeg is found (VOELIN_FFMPEG_DIR, VOELIN_FFMPEG, any major version), which struct fields are read and how they are checked, the backends and their realtime settings, runtime bitrate and size changes, buffers, what is zero-copy and what is missing (the GPU colour conversion), installing FFmpeg per OS, the offer with several codecs and an encoder per codec viewers chose, the computed H.264 level, the new API, voelinctl, licenses and what was tested how. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- CHANGELOG.md | 7 ++ docs/architecture.md | 2 +- docs/media.md | 209 +++++++++++++++++++++++++++++++++++++++---- 3 files changed, 199 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d616d4a..55af48f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,13 @@ The first release is in preparation. them, through the `tsgw` gateway or own ServerQuery credentials. - TeamSpeak 6 streams: watching and sharing screens with sound (VP8, VP9, optional H.264 through Cisco's OpenH264, AV1 decoding). +- Hardware video encoders (VA-API, NVENC, Quick Sync, AMF, Media + Foundation, VideoToolbox) and more software ones (x264, SVT-AV1, libaom) + through an installed FFmpeg, loaded at runtime; each is tested at start + and skipped with a reason if it does not work. Viewers that answer with + another offered codec get their own encoder. Settings: + `stream.hardware_acceleration`, `stream.encoder_backend`, `stream.codec`; + `voelinctl stream encoders` lists what works. - `tsgw`: companion gateway for server admins (presence, channel chat relay, history). - Chat history: messages are kept on the device and, with a gateway, what diff --git a/docs/architecture.md b/docs/architecture.md index 271c46c..216a348 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,7 +71,7 @@ fuzz/ cargo-fuzz targets | `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport | | `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6; `media` module (capture → encoder → stream, stream → decoder) | done | | `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) | -| `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | done (desktop hardware encoders planned; MediaCodec not run on a device yet) | +| `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | done (desktop hardware encoders through FFmpeg loaded at runtime, not run on a GPU yet; MediaCodec not run on a device yet) | | `voelin-platform` | Global hotkeys, notifications, paths, crash reports, notices | done | | `voelin-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture); see [android.md](android.md) | builds, not yet run on a device | diff --git a/docs/media.md b/docs/media.md index 3445db8..a99bea6 100644 --- a/docs/media.md +++ b/docs/media.md @@ -20,7 +20,11 @@ MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received | `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | | `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time) | | `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | -| `Codecs` | `new()`, `with_openh264(lib)`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order), `new_decoder(codec)`, `new_encoder(codec, config)`, `pick_encoder(&accepted)` | +| `Codecs` | `new()` (probes FFmpeg / MediaCodec once per process), `builtin()` (compiled-in codecs only), `with_openh264(lib)`, `with_preference(EncoderPreference)` / `set_preference`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order under the preference), `encoders_for(&pref)`, `new_decoder(codec)`, `new_encoder(codec, config)`, `new_encoder_preferring(codec, config, &pref)`, `new_encoder_with(codec, backend, config)`, `pick_encoder(&accepted)`, `is_hardware(backend)`, `report()`; cheap to clone | +| `EncoderPreference { hardware, backend: BackendChoice }` | settings `stream.hardware_acceleration` and `stream.encoder_backend` (`auto`, `software`, or a backend name such as `h264_vaapi`, `libx264`, `libvpx`, `openh264`) | +| `EncoderReport { ffmpeg, zero_copy, encoders: Vec }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference | +| `EncoderBackend` | `Libvpx`, `OpenH264`, `Ffmpeg("h264_vaapi")`, `Hardware("mediacodec")`; `name()` is the settings spelling | +| `ffmpeg::{Ffmpeg, probe, FfmpegEncoder, BACKENDS}` | FFmpeg loaded at runtime (feature `ffmpeg`), see [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) | | `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user | | `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool` | | `FramePacer` | frame-rate cap by timestamps, evenly spaced | @@ -51,7 +55,7 @@ while let Some(frame) = frames.recv().await { Feature `media` of voelin-core builds the module with whatever voelin-media backends are enabled (on Android: MediaCodec and the app's capture source); -`media-desktop` adds voelin-media's default backends (libvpx, OpenH264, X11, +`media-desktop` adds voelin-media's default backends (libvpx, OpenH264, FFmpeg, X11, PipeWire). The desktop app and voelinctl use `media-desktop`, the Android app `media`. Codecs are always chosen through `Codecs`, so each build uses its own. @@ -94,16 +98,29 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder `max_bitrate`), else its configured bitrate; libvpx changes it in place without a keyframe. - `Streamer::reconfigure(&codecs, StreamerConfigUpdate { fps, bitrate_kbps, - codec, layers, audio_sources })` applies from the next frame without restarting the + codec, encoder, layers, audio_sources })` applies from the next frame without restarting the capture: encoders are created first (an error changes nothing), layers keep their encoder when their id stays, new ids get threads, removed ones - stop, a new codec swaps every encoder (first frame a keyframe), and the + stop, a new codec or encoder preference (`encoder`: hardware on/off, another + backend) swaps every encoder (first frame a keyframe), and the frame-rate cap reaches the capture backend (X11 and the test pattern retime, the portal renegotiates the rate with the compositor). +- One encoder per codec viewers chose: the offer lists several codecs (see + `peer_config` below), the streamer's peer reports the codec each answer + chose (`PeerEvent::VideoCodec`), and the session sends a video frame only + to viewers of its codec (`StreamerSession::write_frame_in`) and tells the + encoders which codecs are wanted (`LayerFeedback::set_codecs`, + `MediaSink::video_codecs`). Each layer's encoder thread keeps the stream + codec's encoder and makes one more per other wanted codec when a viewer + needs it (with the streamer's current `Codecs` and preference), drops it + when none does, and skips the stream codec while nobody takes it; frames + go out through `MediaSink::send_video(frame, codec)`. Sinks that do not + tell codecs apart (`EncodedSource`, a `FrameSource`) get the stream codec + only, so their offers must list it alone (`voelinctl stream start` does). - `stats()`: `StreamerStats` with capture fps, convert time and threads, dropped frames, codec, and per layer (`LayerStats`) size, frames, - keyframes, dropped, fps, kbit/s, encode time, target bitrate, threads - and encoder speed; the audio mix's level and limiter gain, and per audio + keyframes, dropped, fps, kbit/s, encode time, target bitrate, threads, + encoder speed, the stream codec's `backend` and the `codecs` encoded; the audio mix's level and limiter gain, and per audio source (`AudioSourceStats`) level, state, latency, underruns and why it captures nothing, if so. Counters are atomics; rates are computed once a second, and a one-line summary is logged every 5 s at debug level @@ -112,8 +129,20 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder WGC), `Portal`, `X11`, `Wlroots`; `name()` / `FromStr` use the settings spellings `auto`, `portal`, `x11`, `wlroots`. - `peer_config(&codecs, config)` makes a viewer accept only what we decode - and a streamer offer only the codec it encodes (VP8 unless changed): all - viewers get the same frames, and a viewer picks from the offer. + and a streamer offer its stream codec (the first of `config.video_codecs` + it can encode) followed by `offer_codecs`: the codecs of hardware + encoders, VP8 through libvpx (every TeamSpeak client decodes it), and HEVC + last. Other software encoders (x264, SVT-AV1, libvpx VP9, ...) are only + ever the stream codec, so a viewer's answer never starts an expensive + second encoder. Answers keep the offer's order, so viewers take the stream + codec when they decode it. `preferred_codec(&codecs, configured)` picks the + stream codec: `stream.codec` if encodable, else the preference's first + (hardware first when enabled, VP8 in software; never HEVC); + `encoder_preference(&settings)` and `configured_codec(&settings)` read the + settings. H.264 is offered as Constrained High at the level the stream + needs (`PeerConfig::set_h264_format(profile, width, height, fps, bitrate)`: + macroblocks per second and per frame, and bitrate, per H.264 Table A-1; + never below 3.1, the level offered before). - `VideoPipeline` decodes on its own thread. It starts at a keyframe, and after a lost frame (`contiguous == false`, a lagging frame bus, a queue longer than 30 frames) or a decoder error it skips to the next keyframe, @@ -195,16 +224,142 @@ e.g. calls). ## Codecs Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with -hardware > VP8 (libvpx) > H.264 (OpenH264) > VP9 (libvpx, expensive in -software). `Codecs` filters both lists by what is compiled in and loaded. +hardware (H.264 > AV1 > VP9 > VP8 > HEVC) > VP8 (libvpx) > H.264 (x264 and +OpenH264 through FFmpeg, then Cisco's OpenH264) > VP9 (libvpx, expensive in +software) > AV1 (SVT-AV1, libaom through FFmpeg). `Codecs` filters both lists +by what is compiled in, loaded and passed its self-test, and applies the +`EncoderPreference`: `auto` (hardware first unless +`stream.hardware_acceleration` is off), `software` (no hardware), or a named +backend first for the codecs it encodes (even hardware with acceleration +off), the automatic order after it. | Backend | Feature | Encode | Decode | Library | |---|---|---|---|---| | libvpx | `vpx` (default) | VP8, VP9 | VP8, VP9 | system libvpx (1.14 tested), dynamically linked; bindings from `libvpx-native-sys` (pre-generated, no bindgen) | | OpenH264 | `openh264` (default) | H.264 Constrained High / Baseline | H.264 | Cisco's prebuilt binary, loaded at runtime | | dav1d | `av1` | – | AV1 | system libdav1d >= 1.3 (1.4.1 tested) | -| hardware | – | not yet | – | `codec::hw::HardwareEncoderFactory`; VA-API and Media Foundation stubs report nothing (TODO) | -| MediaCodec (Android) | – | H.264, VP8, VP9 | VP8, VP9, H.264, AV1 | the device's default codec per type through the NDK (`ndk` crate); a hardware encoder factory named `mediacodec` | +| FFmpeg | `ffmpeg` (default; off on Android) | H.264, HEVC, AV1, VP9, VP8 in hardware; H.264 (x264, OpenH264), AV1 (SVT-AV1, libaom, rav1e) in software | – | the system's (or `VOELIN_FFMPEG_DIR`'s) libavcodec / libavutil, any major version, loaded at runtime; see below | +| MediaCodec (Android) | – | H.264, VP8, VP9 | VP8, VP9, H.264, AV1 | the device's default codec per type through the NDK (`ndk` crate); an encoder factory named `mediacodec` | + +HEVC (`Codec::H265`): str0m packetizes and depacketizes H.265, so it can be +negotiated; it is offered last and only when a hardware encoder has it, i.e. +used only by a peer that takes none of the other codecs. There is no HEVC +decoder, so viewers never accept it. + +### FFmpeg encoders, loaded at runtime + +`crate::ffmpeg` (feature `ffmpeg`) uses whatever FFmpeg is installed; it is +never linked or shipped. Without it, or when a backend fails its self-test, +the software encoders above are used as before. + +- Finding it: `VOELIN_FFMPEG_DIR` (only that directory; its libavutil and + libswresample are loaded first so libavcodec's dependencies resolve + there), else the system: `libavcodec.so.N` for N from 80 down to 54 and + `libavcodec.so`, then whatever `ldconfig -p` lists (Linux); + `avcodec-N.dll` next to the executable or on `PATH` (Windows); + `libavcodec.N.dylib` on the library path, Homebrew (`/opt/homebrew/lib`, + `/usr/local/lib`) and MacPorts (`/opt/local/lib`) (macOS). No version is + refused. libavutil's functions come from the libavutil libavcodec itself + loaded (through its handle; on Windows the already loaded DLL), so the two + always match; libavformat of the same major is opened if present (for RTMP + output later). `VOELIN_FFMPEG=0` disables FFmpeg. Only functions are + looked up by name (`sys.rs`); FFmpeg's warnings and errors go to + `tracing` (target `ffmpeg`) and into the self-test's failure reasons. +- ABI across major versions: every codec setting goes through AVOptions + (`av_opt_set*`: `video_size`, `pixel_format`, `time_base`, `b`, + `maxrate`, `bufsize`, `g`, `bf`, `threads`, colour properties, `profile` + and each encoder's private options), frames and packets are allocated by + FFmpeg, and of `AVFrame` / `AVPacket` only the leading fields are read or + written (`data[8]`, `linesize[8]`, `width`, `height`, `format`; `pts`, + `data`, `size`, `flags`), unchanged since FFmpeg 0.9 / 2.1. Fields without + an accessor are found and checked at runtime (`layout.rs`): + `AVFrame.pict_type` and `pts` (after `format`, with or without + `key_frame`, which libavutil 60 removed; a fresh frame must read NONE, + {0, 1}, `AV_NOPTS_VALUE` in exactly one layout), `AVCodecContext.hw_frames_ctx` + (for VA-API; located from the offsets `av_opt_find` reports for its + neighbours `hwaccel_flags` and `err_detect` / `extra_hw_frames` (libavcodec + 61+) or `max_pixels` (up to 60), and NULL in a new context), + `AVHWFramesContext` `format`, `sw_format`, `width`, `height`, + `initial_pool_size` (with or without `internal`, which libavutil 59 + removed; `device_ctx` and both formats checked in a new context), and for + the DMA-BUF import `AVFrame.buf[0]` and `hw_frames_ctx` (a table per + libavutil major 56-60 on 64-bit, newer majors tried with the newest entry; + `buf[0]` checked on a real frame at load, `hw_frames_ctx` on the first + surface). The layouts were compiled from the headers of FFmpeg 4.4, 5.1, + 6.1, 7.1 and 8.0. A failed check disables only what needs the field + (VA-API, or the import) and says why (`LibraryInfo::hw_frames`, + `dmabuf_import`, the report). +- Backends (`ffmpeg::BACKENDS`, FFmpeg's encoder names, also the names in + `stream.encoder_backend`): H.264 `h264_nvenc`, `h264_amf`, `h264_vaapi`, + `h264_qsv`, `h264_videotoolbox`, `h264_mf`, software `libx264`, + `libopenh264`; HEVC `hevc_nvenc`, `hevc_amf`, `hevc_vaapi`, `hevc_qsv`, + `hevc_videotoolbox`, `hevc_mf`; AV1 `av1_nvenc`, `av1_amf`, `av1_vaapi`, + `av1_qsv`, software `libsvtav1`, `librav1e`, `libaom-av1`; VP9 + `vp9_vaapi`, `vp9_qsv`; VP8 `vp8_vaapi`. `ffmpeg::probe()` runs each one + present in the build once per process (in parallel): one 320x240 frame, + forced keyframe, flushed; a backend that gives no keyframe packet is + skipped with FFmpeg's reason ("Cannot load libcuda.so.1", "no DRM render + node", "not in this FFmpeg build", ...). rav1e holds about 20 frames + before its first packet even in low-latency mode (measured, rav1e 0.7), so + it is used only when named. +- Realtime settings: no B-frames, no lookahead, keyframes only at the start + and on request (a GOP of 2^30 frames, or what each wrapper takes as + unlimited: 65535 for Quick Sync, 0 for AMF and VideoToolbox, 2^29 for + rav1e; `keyframe_interval` if set) with forced IDR (`pict_type` I, + `forced-idr`), CBR (`maxrate` = `b`, a one-second buffer; SVT-AV1 `rc=2`), + time base 1/fps (hardware rate control budgets per frame from it; pts are + frame numbers from the capture timestamps), BT.601 limited range. Per + family: x264 `veryfast` (`EncoderConfig::speed` picks another preset), + `zerolatency`, no scene cuts; NVENC `p2` (`llhp` on old releases), tune + `ull`, `zerolatency`, `delay 0`; Quick Sync `veryfast`, `async_depth 1`, + `low_delay_brc`, scenario display remoting; AMF usage `ultralowlatency`, + quality `speed`, SPS/PPS with every IDR; VA-API `rc_mode CBR`, + `async_depth 1`, `low_power` retried when the normal entry point fails; + VideoToolbox `realtime`, `prio_speed`; Media Foundation hardware MFT, + scenario display remoting; SVT-AV1 preset 10, `pred-struct=1` (low + delay), no lookahead or scene detection; libaom `usage realtime`, + `cpu-used 8`, `lag-in-frames 0`, `row-mt`, screen tuning. H.264 is High + without B-frames (Constrained High, what TeamSpeak decodes) or Constrained + Baseline (`EncoderConfig::h264_profile`). Options a release does not know + are skipped; alternatives are tried in order. +- Runtime changes: x264, NVENC and Quick Sync take bitrate changes on the + running encoder (FFmpeg's wrappers compare `b` / `maxrate` / `bufsize` + before each frame); the others reopen at the next keyframe, or at once + when the target falls below half (congestion). A new frame rate or size + opens a new session (keyframe); the old one is flushed first, so frames an + encoder with a delay still held come out. +- Buffers: per session one software `AVFrame` (`av_frame_get_buffer`, + written after `av_frame_make_writable`, NV12 interleaved where the backend + wants it) and one `AVPacket`, reused; packets are handed out borrowed + (`encode_with`). VA-API frames come from a surface pool + (`av_hwframe_ctx_init`, surfaces allocated on demand and recycled) filled + with `av_hwframe_transfer_data`; the device is `VOELIN_VAAPI_DEVICE` or the + first `/dev/dri/renderD*`, shared by all encoders. Odd sizes are cropped to + even ones. The streamer's steady state is 1.1 heap allocations per encoded + frame with x264 or SVT-AV1, as with libvpx (`voelinctl stream bench`). +- Zero-copy (Linux): `FfmpegEncoder::encode_dmabuf(&DmaBufRef, ...)` maps a + DRM PRIME frame onto a VA-API surface (`av_hwframe_map`) that the encoder + reads without a copy, for NV12 buffers. Screen capture delivers RGB + (BGRx), which needs a colour conversion on the GPU first (VA-API video + processing); that step is not implemented, so RGB buffers are refused and + mapped for the CPU path as before. The capture side has the hook + (`FrameSink::accepts_dmabuf` / `dmabuf`: the portal offers a buffer before + mapping it and would pass tiled ones through), but no sink accepts yet + and the portal still negotiates LINEAR buffers only; offering tiled + modifiers needs the encoder's import modifiers. Untested on a GPU. + +Installing FFmpeg (runtime libraries only, no `-dev` packages): + +| OS | | +|---|---| +| Debian / Ubuntu | `apt install libavcodec60` (Ubuntu 24.04; Debian 12: `libavcodec59`); VA-API drivers: `intel-media-va-driver` / `mesa-va-drivers`; NVENC needs the NVIDIA driver (`libcuda.so.1`); x264 comes with Ubuntu's libavcodec | +| Fedora | `dnf install ffmpeg-libs` from RPM Fusion (Fedora's own `ffmpeg-free` lacks x264 and some hardware encoders) | +| Arch | `pacman -S ffmpeg` | +| Windows | a shared build (e.g. gyan.dev or BtbN "shared"): put `avcodec-*.dll`, `avutil-*.dll` and their neighbours next to the executable, on `PATH`, or in `VOELIN_FFMPEG_DIR` | +| macOS | `brew install ffmpeg` (VideoToolbox is always there) | + +`voelinctl stream encoders` lists what was found, every backend's self-test +result and the order the streamer uses them in. On Android, `codec::mediacodec` uses byte-buffer mode on both sides, so it takes and returns `VideoFrame`s like the software codecs. Encoders get NV12 @@ -240,8 +395,9 @@ change the bitrate at runtime. The other modules with `unsafe` code, each with SAFETY comments: the X11 and wlroots shared-memory mappings (`capture/x11/shm.rs`, `capture/wlroots.rs`), the DMA-BUF mapping and sync ioctl (`capture/dmabuf.rs`), the lifetime-erased job of the worker pool -(`workers.rs`), the `Arc` raw pointers of the handoff (`handoff.rs`), and -the `Send` wrapper in `codec/mediacodec.rs`. +(`workers.rs`), the `Arc` raw pointers of the handoff (`handoff.rs`), the +`Send` wrapper in `codec/mediacodec.rs`, and the FFmpeg bindings +(`ffmpeg/sys.rs`, `layout.rs`, `mod.rs`, `encoder.rs`). The OpenH264 encoder has no safe runtime bitrate change in the `openh264` crate, so `set_bitrate` recreates it (the next frame is an IDR). It enables @@ -342,6 +498,9 @@ their own (x11rb reply buffers; the Android provider hands owned frames). ```sh # The real pipeline on the test pattern, no server: voelinctl stream bench --res 1920x1080 --fps 60 --codec vp8 --seconds 10 +# Any encoder (see `voelinctl stream encoders`); --no-hardware for software: +voelinctl stream bench --res 1280x720 --encoder libx264 +voelinctl stream bench --res 1280x720 --encoder h264_vaapi voelinctl stream bench --res 2560x1440 --fps 30 \ --layer scale=1,bitrate=6M --layer scale=0.5,bitrate=1500k,fps=30 \ --layer size=640x360,bitrate=400k,fps=15 @@ -390,14 +549,18 @@ Linux (Debian/Ubuntu packages): `libvpx-dev` (feature `vpx`), PipeWire bindings run bindgen), `pkg-config`, and `libdav1d-dev` for `--features av1`. X11 capture is pure Rust (x11rb) and needs no packages. Tests of X11 capture need an X server: `xvfb`, run with `xvfb-run -a cargo -test -p voelin-media` (skipped without `DISPLAY`). +test -p voelin-media` (skipped without `DISPLAY`). FFmpeg needs nothing at +build time (feature `ffmpeg` only adds `libloading`); its tests run with the +runtime libraries installed (`libavcodec60` on Ubuntu 24.04) and are +skipped without them; `VOELIN_OPENH264_LIB` lets them decode x264's output +with Cisco's OpenH264, `--features av1` AV1 with dav1d. Windows: libvpx is not found through pkg-config there. Install it (e.g. `vcpkg install libvpx:x64-windows`) and set `VPX_LIB_DIR`, `VPX_INCLUDE_DIR` and `VPX_VERSION`, or build without the `vpx` feature. The Windows capture code is type-checked on Linux (`cargo clippy -p voelin-media --target -x86_64-pc-windows-gnu --no-default-features --features openh264`) but has not -run on Windows yet. +x86_64-pc-windows-gnu --no-default-features --features openh264,ffmpeg`) but +has not run on Windows yet. ## Licenses @@ -414,6 +577,8 @@ run on Windows yet. | `criterion` | Apache-2.0 OR MIT | benchmarks only (dev-dependency) | | `ashpd`, `pipewire`, `libspa` / libpipewire | MIT | libpipewire is dynamic | | `windows-capture`, `wasapi`, `windows` | MIT (`windows`: MIT OR Apache-2.0) | Windows only | +| FFmpeg (libavcodec, libavutil, libavformat) | LGPL-2.1+ (GPL-2+ in builds with x264 and other GPL parts) | the user's installed libraries, loaded at runtime; never linked or shipped | +| `libloading` | ISC | opens FFmpeg (and OpenH264, through the `openh264` crate) | | `bzip2` / `libbz2-rs-sys` | MIT OR Apache-2.0 / bzip2-1.0.6 | unpacks the OpenH264 download; `bzip2-1.0.6` is allowed in `deny.toml` | ## Verification status @@ -434,7 +599,15 @@ run on Windows yet. | Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested | | Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) | | Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only | -| Hardware encoders | – | stubs | +| FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-8.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04) | +| FFmpeg software encoders → our decoders: x264 → OpenH264, SVT-AV1 / rav1e / libaom → dav1d (PSNR > 28 dB, keyframes at start and on request, timestamps, bitrate change, size change, odd sizes, Constrained High / Baseline) | `tests/ffmpeg.rs` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested | +| Self-test failures (NVENC without CUDA, Quick Sync without a session, VA-API without a render node, encoders not in the build) | `tests/ffmpeg.rs`, `voelinctl stream encoders` | tested: each fails alone with FFmpeg's reason | +| Encoder preference (auto, software, named, hardware off), report ranks | `codec::tests::encoder_preference` | tested | +| An encoder per codec viewers chose (made, dropped, stream codec skipped, preference change) | `voelin-core` `media::tests::an_encoder_per_codec_viewers_chose` | tested | +| Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) | +| x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame | +| Hardware encoders (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox), DMA-BUF import | – | compile only (no GPU here); the Windows code type-checks for `x86_64-pc-windows-gnu` | +| Several codecs against official TeamSpeak viewers | – | not tested live | | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | | Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `voelin-core` `stream::tests::test_pattern_through_stream_tasks` | tested | | Stream audio (RTP time → jitter buffer ids, volume, end) | `voelin-core` `audio::tests::stream_audio_with_volume`, stream task test | tested | From c4021b9859836fa54bbde4f797b61a8f6e9e5064 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:12:15 +0000 Subject: [PATCH 7/9] voelin-core: live test of a viewer that answers another codec Against the TeamSpeak 6 dev server: the streamer offers VP9 (its stream codec) and VP8, a viewer that decodes only VP8 answers VP8 and decodes pictures from the encoder made for it, and the VP9 encoder, wanted by nobody, idles. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-core/tests/media_live.rs | 79 +++++++++++++++++++++++++- docs/media.md | 3 +- 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/voelin-core/tests/media_live.rs b/crates/voelin-core/tests/media_live.rs index 3226768..f27ec7f 100644 --- a/crates/voelin-core/tests/media_live.rs +++ b/crates/voelin-core/tests/media_live.rs @@ -14,7 +14,7 @@ use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::capture::synthetic::RECT_COLOR; use voelin_core::media::voelin_media::{Codec, Codecs, convert}; use voelin_core::media::{Streamer, StreamerConfig, Viewer, peer_config, stream_codec}; -use voelin_core::stream::{PeerConfig, StreamSetup}; +use voelin_core::stream::{PeerConfig, StreamSetup, VideoCodec}; use voelin_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState}; fn live() -> bool { @@ -177,3 +177,80 @@ async fn ts6_test_pattern_decoded() { engine.send(Command::CloseSession { session: 2 }); tokio::time::sleep(Duration::from_millis(500)).await; } + +/// The streamer's offer lists VP9 (its stream codec) and VP8; a viewer that +/// only decodes VP8 answers VP8 and gets VP8 pictures from an encoder made +/// for it, while the VP9 encoder, wanted by nobody, idles. +#[tokio::test(flavor = "multi_thread")] +async fn ts6_viewer_gets_the_codec_it_chose() { + if !live() { + eprintln!("skipped: set VOELIN_LIVE=1 with the dev servers running"); + return; + } + let engine = Engine::start(); + let mut events = engine.subscribe(); + let codecs = Arc::new(Codecs::builtin()); + let vp9_first = PeerConfig { video_codecs: vec![VideoCodec::Vp9], ..PeerConfig::loopback() }; + let streamer_peer = peer_config(&codecs, vp9_first); + assert_eq!(streamer_peer.video_codecs, [VideoCodec::Vp9, VideoCodec::Vp8]); + let codec = stream_codec(&codecs, &streamer_peer).expect("an encoder"); + assert_eq!(codec, Codec::Vp9); + let viewer_peer = + PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() }; + let tag = std::process::id() % 10_000; + connect(&engine, &mut events, 1, &format!("c-streamer-{tag}"), streamer_peer).await; + connect(&engine, &mut events, 2, &format!("c-viewer-{tag}"), viewer_peer).await; + + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (320, 180), + bitrate_kbps: 1000, + codec, + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let setup = StreamSetup { name: format!("codecs {tag}"), ..Default::default() }; + engine.send(Command::StartStream { session: 1, setup, auto_accept: true }); + let mut live = None; + let mut listed = Vec::new(); + let (id, sink) = wait_for(&mut events, "stream live and in the viewer's list", |e| { + match e { + Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => { + live = Some((id.clone(), sink.clone())); + } + Event::StreamsChanged { session: 2, streams } => { + listed = streams.iter().map(|s| s.id.clone()).collect(); + } + _ => {} + } + live.clone().filter(|(id, _)| listed.contains(id)) + }) + .await; + streamer.attach(Arc::new(sink)); + let (tx, pictures) = std_mpsc::channel(); + let viewer = Viewer::start(&engine, 2, &id, codecs, move |picture| { + let _ = tx.send(picture); + }); + engine.send(Command::WatchStream { session: 2, stream_id: id.clone() }); + let decoded = tokio::task::spawn_blocking(move || { + let mut decoded = 0; + while decoded < 30 { + let picture = pictures.recv_timeout(Duration::from_secs(15)).expect("no picture"); + assert_eq!((picture.width, picture.height), (320, 180)); + decoded += 1; + } + decoded + }) + .await + .unwrap(); + let sent = streamer.stats(); + eprintln!("decoded {decoded}, sent {sent:?}"); + assert_eq!(sent.layers[0].codecs, [Codec::Vp8], "only the codec a viewer chose"); + assert!(viewer.stats().error.is_none()); + engine.send(Command::StopStream { session: 1 }); + drop(viewer); + drop(streamer); + engine.send(Command::CloseSession { session: 1 }); + engine.send(Command::CloseSession { session: 2 }); + tokio::time::sleep(Duration::from_millis(500)).await; +} diff --git a/docs/media.md b/docs/media.md index a99bea6..958e23c 100644 --- a/docs/media.md +++ b/docs/media.md @@ -607,7 +607,8 @@ has not run on Windows yet. | Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) | | x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame | | Hardware encoders (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox), DMA-BUF import | – | compile only (no GPU here); the Windows code type-checks for `x86_64-pc-windows-gnu` | -| Several codecs against official TeamSpeak viewers | – | not tested live | +| Offer [VP9, VP8], a viewer that decodes only VP8 → its own VP8 encoder, VP9 idle, pictures decoded | `voelin-core/tests/media_live.rs` `ts6_viewer_gets_the_codec_it_chose` (`VOELIN_LIVE=1`) | tested against the TeamSpeak 6 dev server (our client on both ends) | +| Several codecs against official TeamSpeak viewers | – | not tested (no official client here) | | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | | Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `voelin-core` `stream::tests::test_pattern_through_stream_tasks` | tested | | Stream audio (RTP time → jitter buffer ids, volume, end) | `voelin-core` `audio::tests::stream_audio_with_volume`, stream task test | tested | From 9cdc336c2d67328c01bb74066036c6edf8653035 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:13:44 +0000 Subject: [PATCH 8/9] voelin-media: bitrate increases reach encoders that cannot change it running VA-API, AMF, SVT-AV1 and the other wrappers without a live bitrate change applied a new target only at the next keyframe, so a still screen kept the bandwidth estimate's low start value for good. An increase of half or more now reopens the session (a keyframe) once it is five seconds old; smaller ones still wait for a keyframe, drops below half apply at once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/src/ffmpeg/encoder.rs | 22 +++++++++++++++++-- crates/voelin-media/tests/ffmpeg.rs | 26 +++++++++++++++++++++++ docs/media.md | 6 ++++-- 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index cdd1918..53a3bfb 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -13,7 +13,7 @@ use std::collections::VecDeque; use std::ffi::c_int; use std::sync::OnceLock; -use std::time::Duration; +use std::time::{Duration, Instant}; use super::layout::{self, HwFramesFields}; use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; @@ -451,6 +451,9 @@ struct Session { /// 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, + /// When it was opened (bitrate increases reopen at most every + /// [`REOPEN_FOR_BITRATE`]). + opened: Instant, timestamps: Timestamps, nv12: bool, } @@ -475,6 +478,11 @@ impl Drop for Session { } } +/// How long a session runs before a bitrate increase of half or more +/// reopens it (a keyframe) on backends that cannot change the bitrate +/// running; smaller increases wait for the next keyframe. +const REOPEN_FOR_BITRATE: Duration = Duration::from_secs(5); + /// When to recreate the session. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] enum Reinit { @@ -630,6 +638,7 @@ impl FfmpegEncoder { packet: std::ptr::null_mut(), last_pts: None, first_packet: true, + opened: Instant::now(), timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, }; @@ -1177,7 +1186,9 @@ impl VideoEncoder for FfmpegEncoder { fn set_bitrate(&mut self, bps: u32) -> Result<()> { let bps = bps.max(1); self.config.bitrate_bps = bps; - let Some((ctx, running)) = self.session.as_ref().map(|s| (s.ctx, s.bitrate)) else { + let Some((ctx, running, opened)) = + self.session.as_ref().map(|s| (s.ctx, s.bitrate, s.opened)) + else { return Ok(()); }; if running == bps { @@ -1198,6 +1209,13 @@ impl VideoEncoder for FfmpegEncoder { } else if u64::from(bps) * 2 < u64::from(running) { // Congestion: waiting for a keyframe would keep overshooting. self.reinit = Reinit::Now; + } else if u64::from(bps) * 2 > u64::from(running) * 3 + && opened.elapsed() >= REOPEN_FOR_BITRATE + { + // Much more room (the estimate ramping up after the start): a + // screen that never asks for a keyframe would otherwise keep + // the start bitrate. + self.reinit = Reinit::Now; } else { self.reinit = self.reinit.max(Reinit::AtKeyframe); } diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index f495408..a3d34e7 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -229,6 +229,32 @@ fn unusable_backends_fail_cleanly() { } } +/// A backend whose wrapper cannot change the bitrate running (libaom here, +/// VA-API alike) waits for the next keyframe, but reopens at once when the +/// target falls below half. +#[test] +fn bitrate_changes_without_live_reconfiguration() { + if ffmpeg().is_none() || !available("libaom-av1") { + return; + } + let screen = SyntheticScreen::new(W, H); + let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() }; + let mut encoder = FfmpegEncoder::new("libaom-av1", config).unwrap(); + let mut key = |encoder: &mut FfmpegEncoder, n: u64, force: bool| { + encoder.encode(&screen.frame(n, 30), force).unwrap().iter().any(|f| f.keyframe) + }; + assert!(key(&mut encoder, 0, false)); + assert!(!key(&mut encoder, 1, false)); + encoder.set_bitrate(800_000).unwrap(); + assert!(!key(&mut encoder, 2, false), "a small change waits for a keyframe"); + encoder.set_bitrate(300_000).unwrap(); + assert!(key(&mut encoder, 3, false), "congestion: at once"); + encoder.set_bitrate(400_000).unwrap(); + assert!(!key(&mut encoder, 4, false)); + assert!(key(&mut encoder, 5, true)); + 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. #[cfg(target_os = "linux")] diff --git a/docs/media.md b/docs/media.md index 958e23c..ca8a600 100644 --- a/docs/media.md +++ b/docs/media.md @@ -324,8 +324,10 @@ the software encoders above are used as before. are skipped; alternatives are tried in order. - Runtime changes: x264, NVENC and Quick Sync take bitrate changes on the running encoder (FFmpeg's wrappers compare `b` / `maxrate` / `bufsize` - before each frame); the others reopen at the next keyframe, or at once - when the target falls below half (congestion). A new frame rate or size + before each frame); the others reopen at the next keyframe, at once + when the target falls below half (congestion), and when it rose by half + or more and the session is 5 s old (the estimate ramping up after the + start would otherwise never reach the encoder). A new frame rate or size opens a new session (keyframe); the old one is flushed first, so frames an encoder with a delay still held come out. - Buffers: per session one software `AVFrame` (`av_frame_get_buffer`, From c08584175eff894294d1fa39905eb4cf11d395f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:23:35 +0000 Subject: [PATCH 9/9] voelin-media: drop a needless mut in the FFmpeg bitrate test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/tests/ffmpeg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index a3d34e7..4f8e2ad 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -240,7 +240,7 @@ fn bitrate_changes_without_live_reconfiguration() { let screen = SyntheticScreen::new(W, H); let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() }; let mut encoder = FfmpegEncoder::new("libaom-av1", config).unwrap(); - let mut key = |encoder: &mut FfmpegEncoder, n: u64, force: bool| { + let key = |encoder: &mut FfmpegEncoder, n: u64, force: bool| { encoder.encode(&screen.frame(n, 30), force).unwrap().iter().any(|f| f.keyframe) }; assert!(key(&mut encoder, 0, false));