From badfb328a02f579ee5bb34743c2bf72f13149fd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 19:15:38 +0000 Subject: [PATCH] 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,