From 66a2b8329bbf39b43851f2da548dd3b4c2e9d58a Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 22:59:03 +0300 Subject: [PATCH 1/9] Decode with FFmpeg at runtime: hardware first, then software Watching an official client's stream failed partly because the app decoded too little: no AV1 (the official client prefers it on modern GPUs), and H.264 only with Cisco's OpenH264 downloaded. FFmpeg, already loaded at runtime for the encoders, now decodes too, never linked or shipped: the platform's hardware decoders through FFmpeg's hwaccel API (VA-API and NVDEC on Linux, D3D11VA and DXVA2 on Windows, VideoToolbox on macOS) for AV1, HEVC, VP9, H.264 and VP8, then FFmpeg's software ones (dav1d, libaom, its own HEVC, VP9, H.264, VP8). Hardware decoders get AVCodecContext.hw_device_ctx, located next to hw_frames_ctx from the AVOption offsets of its neighbours and checked in a new context like the encoders' fields; FFmpeg's default get_format then picks the device's surfaces. Pictures are copied out of the GPU into a frame of our own and into the caller's VideoFrame through the new VideoDecoder::decode_into, both reused, so a running decoder allocates nothing per picture on our side. Slice threads only and dav1d with a frame delay of one keep the latency at zero. A self-test per decoder, run once per process in parallel with the encoders' probe, decodes a three-frame clip of each codec made by our own encoders (src/ffmpeg/clips): each picture at once, at its size, above 30 dB against the test picture, and on the GPU for a hardware decoder, since FFmpeg silently decodes in software when the GPU lacks the codec (VP8 on AMD). Codecs now orders a ladder per codec (decoders_for): hardware, FFmpeg's software decoders, then the built-in libvpx, OpenH264 and dav1d, under a DecoderPreference like the encoders'; decoders() lists every codec one of them decodes, best first (AV1, HEVC, VP9, H.264, VP8). The report lists the decoders too. Tested here (RX 7900 GRE, FFmpeg 9.0.1): VA-API decodes AV1, HEVC, VP9 and H.264 on the GPU, and every encoder of the machine decodes with every decoder of its codec above 36 dB. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/src/codec/hw.rs | 39 +- crates/voelin-media/src/codec/mod.rs | 316 ++++++- crates/voelin-media/src/ffmpeg/clips/av1.bin | Bin 0 -> 512 bytes crates/voelin-media/src/ffmpeg/clips/h264.bin | Bin 0 -> 1433 bytes crates/voelin-media/src/ffmpeg/clips/hevc.bin | Bin 0 -> 2712 bytes crates/voelin-media/src/ffmpeg/clips/vp8.bin | Bin 0 -> 1203 bytes crates/voelin-media/src/ffmpeg/clips/vp9.bin | Bin 0 -> 4073 bytes crates/voelin-media/src/ffmpeg/decoder.rs | 836 ++++++++++++++++++ crates/voelin-media/src/ffmpeg/encoder.rs | 10 +- crates/voelin-media/src/ffmpeg/layout.rs | 47 +- crates/voelin-media/src/ffmpeg/mod.rs | 25 +- crates/voelin-media/src/ffmpeg/sys.rs | 12 + crates/voelin-media/src/frame.rs | 62 +- crates/voelin-media/src/lib.rs | 6 +- crates/voelin-media/tests/ffmpeg_decoders.rs | 241 +++++ crates/voelin-media/tests/openh264.rs | 3 +- 16 files changed, 1524 insertions(+), 73 deletions(-) create mode 100644 crates/voelin-media/src/ffmpeg/clips/av1.bin create mode 100644 crates/voelin-media/src/ffmpeg/clips/h264.bin create mode 100644 crates/voelin-media/src/ffmpeg/clips/hevc.bin create mode 100644 crates/voelin-media/src/ffmpeg/clips/vp8.bin create mode 100644 crates/voelin-media/src/ffmpeg/clips/vp9.bin create mode 100644 crates/voelin-media/src/ffmpeg/decoder.rs create mode 100644 crates/voelin-media/tests/ffmpeg_decoders.rs diff --git a/crates/voelin-media/src/codec/hw.rs b/crates/voelin-media/src/codec/hw.rs index 7cedb6d..2cb5f78 100644 --- a/crates/voelin-media/src/codec/hw.rs +++ b/crates/voelin-media/src/codec/hw.rs @@ -1,13 +1,17 @@ -//! Encoder factories found at runtime. +//! Encoder and decoder factories found at runtime. //! //! - 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`]). +//! that passed its self-test ([`crate::ffmpeg::probe`]). Decoders likewise: +//! VA-API, NVDEC, D3D11VA, DXVA2 and VideoToolbox, then dav1d and FFmpeg's +//! own ([`crate::ffmpeg::decoder::probe`]). //! - Android: MediaCodec ([`super::mediacodec`]). use crate::Result; -use crate::codec::{Codec, EncoderBackend, EncoderConfig, VideoEncoder}; +use crate::codec::{ + Codec, DecoderBackend, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, +}; /// Creates encoders of one backend. pub trait EncoderFactory: Send + Sync { @@ -52,3 +56,32 @@ pub fn probe() -> Vec> { } found } + +/// Creates decoders of one backend for one codec: FFmpeg's, or one an +/// application adds ([`Codecs::with_decoder`](super::Codecs::with_decoder)). +pub trait DecoderFactory: Send + Sync { + /// The backend its decoders are (for the ladder, logs and settings). + fn backend(&self) -> DecoderBackend; + + fn codec(&self) -> Codec; + + /// The API or library behind it (`VA-API`, `dav1d`, ...), for the UI. + fn api(&self) -> &'static str; + + /// A GPU decoder: left out when hardware decoding is off. + fn is_hardware(&self) -> bool; + + fn create(&self) -> Result>; +} + +/// Decoder factories usable on this machine: FFmpeg's decoders that passed +/// their self-test, hardware first. +pub fn probe_decoders() -> Vec> { + #[allow(unused_mut)] + let mut found: Vec> = Vec::new(); + #[cfg(feature = "ffmpeg")] + for factory in crate::ffmpeg::decoder::FfmpegDecoderFactory::available() { + found.push(Box::new(factory)); + } + found +} diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 914ed3b..b2c2035 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -7,11 +7,16 @@ //! - [`h264`] (feature `openh264`): H.264 with Cisco's prebuilt OpenH264, //! loaded at runtime //! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d -//! - [`hw`]: encoder factories found at runtime: FFmpeg's hardware and -//! software encoders ([`crate::ffmpeg`], feature `ffmpeg`) and, on Android, -//! MediaCodec +//! - [`hw`]: encoder and decoder factories found at runtime: FFmpeg's +//! hardware and software encoders and decoders ([`crate::ffmpeg`], feature +//! `ffmpeg`) and, on Android, MediaCodec encoders //! - `mediacodec` (Android): the device's MediaCodec encoders and decoders //! (hardware, or Google's software VP8 / VP9 / H.264) +//! +//! A viewer decodes each codec with the best decoder that works here and +//! falls back to the next one ([`Codecs::decoders_for`]): hardware (FFmpeg's +//! hwaccels, MediaCodec), then FFmpeg's software decoders, then the built-in +//! libvpx, OpenH264 and dav1d. use std::fmt; use std::str::FromStr; @@ -110,8 +115,12 @@ impl TryFrom for Codec { } } -/// Order in which a viewer accepts codecs: VP9 > VP8 > AV1 > H.264. -pub const VIEWER_PREFERENCE: [Codec; 4] = [Codec::Vp9, Codec::Vp8, Codec::Av1, Codec::H264]; +/// Order in which a viewer accepts codecs, best first: AV1 > HEVC > VP9 > +/// H.264 > VP8 (the best compression first, the codec every client has +/// last). Answers follow the offer's order, so this ranks what a viewer +/// asks for when it chooses, and what [`Codecs::decoders`] lists. +pub const VIEWER_PREFERENCE: [Codec; 5] = + [Codec::Av1, Codec::H265, Codec::Vp9, Codec::H264, Codec::Vp8]; /// What the encoder should optimise for. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -292,6 +301,23 @@ pub trait VideoDecoder: Send { /// Decode one complete frame (a depacketized RTP frame). Returns the /// picture if one is ready; its timestamp is zero. fn decode(&mut self, data: &[u8]) -> Result>; + + /// Like [`decode`](Self::decode), into `out`: `true` if a picture is + /// there, else `out` is unchanged. Decoders that can reuse `out`'s + /// buffers do (FFmpeg's), so a caller that keeps passing the same frame + /// gets its pictures without allocations. + fn decode_into(&mut self, data: &[u8], out: &mut VideoFrame) -> Result { + let picture = self.decode(data)?; + Ok(picture.map(|p| *out = p).is_some()) + } + + /// Whether frames after a lost one still decode to a picture (what is + /// missing concealed until the next keyframe), so that a viewer keeps + /// decoding instead of waiting for a keyframe: FFmpeg's H.264 and HEVC + /// decoders. The others fail, or show garbage, on a missing reference. + fn conceals_errors(&self) -> bool { + false + } } /// Implementations behind [`VideoEncoder`]. @@ -324,6 +350,45 @@ impl fmt::Display for EncoderBackend { } } +/// Implementations behind [`VideoDecoder`], as [`Codecs::decoders_for`] +/// orders them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum DecoderBackend { + /// An OS / GPU decoder of its own API (Android's `mediacodec`), or one + /// an application adds ([`Codecs::with_decoder`]). + Hardware(&'static str), + /// An FFmpeg decoder by its name in `ffmpeg::DECODERS`: in hardware + /// (`h264_vaapi`, FFmpeg's names of its hwaccels) or in software + /// (`h264`, `libdav1d`). + Ffmpeg(&'static str), + Libvpx, + OpenH264, + Dav1d, +} + +impl DecoderBackend { + /// The name in settings (`stream.decoder_backend`) and logs. + pub fn name(self) -> &'static str { + match self { + DecoderBackend::Hardware(name) | DecoderBackend::Ffmpeg(name) => name, + DecoderBackend::Libvpx => "libvpx", + DecoderBackend::OpenH264 => "openh264", + DecoderBackend::Dav1d => "dav1d", + } + } +} + +impl fmt::Display for DecoderBackend { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// Which decoders to use (settings `stream.hardware_decoding` and +/// `stream.decoder_backend`): the choices of the encoders, `hardware` for +/// GPU decoders and `backend` naming a [`DecoderBackend::name`]. +pub type DecoderPreference = EncoderPreference; + /// Which encoders to use (settings `stream.hardware_acceleration` and /// `stream.encoder_backend`). #[derive(Clone, Debug, PartialEq, Eq)] @@ -390,8 +455,12 @@ pub struct EncoderInfo { 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`). +/// One decoder backend in [`Codecs::report`]: as [`EncoderInfo`], its +/// `rank` the position in its codec's ladder ([`Codecs::decoders_for`]). +pub type DecoderInfo = EncoderInfo; + +/// Every encoder and decoder 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. @@ -400,6 +469,7 @@ pub struct EncoderReport { /// or why not. pub zero_copy: std::result::Result<(), String>, pub encoders: Vec, + pub decoders: Vec, } fn unavailable(codec: Codec, reason: impl Into) -> Error { @@ -430,7 +500,9 @@ impl Candidate { /// The codecs this build and machine can use, and factories for them. /// -/// Viewer order ([`Codecs::decoders`]): VP9 > VP8 > AV1 > H.264. Streamer +/// Viewer order ([`Codecs::decoders`]): AV1 > HEVC > VP9 > H.264 > VP8, each +/// codec with its ladder of decoders ([`Codecs::decoders_for`]) under the +/// [`DecoderPreference`]. Streamer /// 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 @@ -439,9 +511,11 @@ impl Candidate { #[derive(Clone)] pub struct Codecs { factories: Vec>, + decoder_factories: Vec>, #[cfg(feature = "openh264")] openh264: Option, preference: EncoderPreference, + decoder_preference: DecoderPreference, } impl Default for Codecs { @@ -456,34 +530,67 @@ impl fmt::Debug for Codecs { .field("decoders", &self.decoders()) .field("encoders", &self.encoders()) .field("preference", &self.preference) + .field("decoder_preference", &self.decoder_preference) .finish() } } impl Codecs { /// 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`]. + /// (FFmpeg's that passed their self-test, MediaCodec) and the decoders + /// [`hw::probe_decoders`] finds (FFmpeg's), both probed at once. H.264 + /// through Cisco's library needs [`Codecs::with_openh264`]. pub fn new() -> Self { + let (factories, decoder_factories) = std::thread::scope(|scope| { + let decoders = scope.spawn(hw::probe_decoders); + (hw::probe(), decoders.join().unwrap_or_default()) + }); Self { - factories: hw::probe().into_iter().map(Arc::from).collect(), + factories: factories.into_iter().map(Arc::from).collect(), + decoder_factories: decoder_factories.into_iter().map(Arc::from).collect(), #[cfg(feature = "openh264")] openh264: None, preference: EncoderPreference::default(), + decoder_preference: DecoderPreference::default(), } } /// Only the codecs compiled into this crate (libvpx, OpenH264 once - /// loaded, dav1d): no FFmpeg or MediaCodec, nothing probed. + /// loaded, dav1d): no FFmpeg or MediaCodec encoders, no FFmpeg decoders, + /// nothing probed. pub fn builtin() -> Self { Self { factories: Vec::new(), + decoder_factories: Vec::new(), #[cfg(feature = "openh264")] openh264: None, preference: EncoderPreference::default(), + decoder_preference: DecoderPreference::default(), } } + /// Decode `factory`'s codec with it first (a decoder of the embedding + /// application, or a test's). + pub fn with_decoder(mut self, factory: Arc) -> Self { + self.decoder_factories.insert(0, factory); + self + } + + /// Use `preference` for [`decoders_for`](Self::decoders_for) and + /// [`new_decoder`](Self::new_decoder). + pub fn with_decoder_preference(mut self, preference: DecoderPreference) -> Self { + self.decoder_preference = preference; + self + } + + pub fn set_decoder_preference(&mut self, preference: DecoderPreference) { + self.decoder_preference = preference; + } + + pub fn decoder_preference(&self) -> &DecoderPreference { + &self.decoder_preference + } + /// Enable H.264 through a loaded OpenH264 library. #[cfg(feature = "openh264")] pub fn with_openh264(mut self, library: h264::OpenH264) -> Self { @@ -525,32 +632,74 @@ impl Codecs { /// Whether `codec` can be decoded, or why not. pub fn check_decoder(&self, codec: Codec) -> Result<()> { - #[cfg(target_os = "android")] - if mediacodec::check_decoder(codec).is_ok() { + if !self.decoders_for(codec).is_empty() { return Ok(()); } - match codec { - Codec::Vp8 | Codec::Vp9 => { - #[cfg(feature = "vpx")] - return vpx::check(codec, false); - #[cfg(not(feature = "vpx"))] - return Err(unavailable(codec, "built without the `vpx` feature")); - } - Codec::H264 if self.has_openh264() => Ok(()), - Codec::H264 => Err(unavailable(codec, "the OpenH264 library is not loaded")), - Codec::Av1 => { - #[cfg(feature = "av1")] - return Ok(()); - #[cfg(not(feature = "av1"))] - return Err(unavailable(codec, "built without the `av1` feature")); - } - Codec::H265 => Err(unavailable(codec, "no HEVC decoder")), + if !self.decoder_candidates(codec).is_empty() { + let choice = &self.decoder_preference; + return Err(unavailable(codec, format!("its decoders are not used ({choice:?})"))); } + let builtin = match codec { + Codec::Vp8 | Codec::Vp9 if cfg!(feature = "vpx") => "libvpx has no decoder for it", + Codec::Vp8 | Codec::Vp9 => "built without the `vpx` feature", + Codec::H264 => "the OpenH264 library is not loaded", + Codec::Av1 => "built without the `av1` feature (dav1d)", + Codec::H265 => "nothing built in decodes it", + }; + Err(unavailable(codec, format!("no FFmpeg decoder works here, and {builtin}"))) } - /// Decodable codecs in the viewer's order of preference. + /// Decodable codecs in the viewer's order of preference + /// ([`VIEWER_PREFERENCE`]): those with at least one decoder. pub fn decoders(&self) -> Vec { - VIEWER_PREFERENCE.into_iter().filter(|&c| self.check_decoder(c).is_ok()).collect() + VIEWER_PREFERENCE.into_iter().filter(|&c| !self.decoders_for(c).is_empty()).collect() + } + + /// Every decoder of `codec` here and whether it is a GPU one: the + /// platform's (MediaCodec), the factories (an application's, then + /// FFmpeg's hardware and software decoders), then the built-in ones. + fn decoder_candidates(&self, codec: Codec) -> Vec<(DecoderBackend, bool)> { + let mut list = Vec::new(); + // The device's codecs (hardware, or Google's software ones): Android + // has no others, so hardware decoding off does not leave them out. + #[cfg(target_os = "android")] + if mediacodec::check_decoder(codec).is_ok() { + list.push((DecoderBackend::Hardware("mediacodec"), false)); + } + for f in self.decoder_factories.iter().filter(|f| f.codec() == codec) { + list.push((f.backend(), f.is_hardware())); + } + match codec { + #[cfg(feature = "vpx")] + Codec::Vp8 | Codec::Vp9 if vpx::check(codec, false).is_ok() => { + list.push((DecoderBackend::Libvpx, false)); + } + Codec::H264 if self.has_openh264() => list.push((DecoderBackend::OpenH264, false)), + #[cfg(feature = "av1")] + Codec::Av1 => list.push((DecoderBackend::Dav1d, false)), + _ => {} + } + list + } + + /// The decoders of `codec` in the order a viewer tries them, its ladder: + /// hardware first (unless the [`DecoderPreference`] turns it off), then + /// FFmpeg's software decoders, then the built-in libvpx, OpenH264 and + /// dav1d; a backend named in the preference before all of them. + pub fn decoders_for(&self, codec: Codec) -> Vec { + let all = self.decoder_candidates(codec); + let preference = &self.decoder_preference; + let automatic = |c: &&(DecoderBackend, bool)| preference.hardware || !c.1; + let chosen: Vec<&(DecoderBackend, bool)> = match &preference.backend { + BackendChoice::Auto => all.iter().filter(automatic).collect(), + BackendChoice::Software => all.iter().filter(|c| !c.1).collect(), + BackendChoice::Named(name) => { + let named = all.iter().filter(|c| c.0.name() == name); + let rest = all.iter().filter(|c| c.0.name() != name).filter(automatic); + named.chain(rest).collect() + } + }; + chosen.into_iter().map(|c| c.0).collect() } /// Every usable encoder in the base order, before the preference. @@ -618,24 +767,51 @@ impl Codecs { codecs } + /// A decoder for `codec`: the first of its ladder + /// ([`decoders_for`](Self::decoders_for)) that opens. pub fn new_decoder(&self, codec: Codec) -> Result> { + self.check_decoder(codec)?; + let mut last_error = None; + for backend in self.decoders_for(codec) { + match self.new_decoder_with(codec, backend) { + Ok(decoder) => return Ok(decoder), + Err(e) => { + tracing::warn!(%codec, %backend, "decoder failed to open: {e}"); + last_error = Some(e); + } + } + } + Err(last_error.unwrap_or_else(|| unavailable(codec, "no decoder in this build"))) + } + + /// A decoder from a specific backend. + pub fn new_decoder_with( + &self, + codec: Codec, + backend: DecoderBackend, + ) -> Result> { #[cfg(target_os = "android")] - if mediacodec::check_decoder(codec).is_ok() { + if backend == DecoderBackend::Hardware("mediacodec") { return Ok(Box::new(mediacodec::MediaCodecDecoder::new(codec)?)); } - self.check_decoder(codec)?; - match codec { + if let Some(factory) = + self.decoder_factories.iter().find(|f| f.backend() == backend && f.codec() == codec) + { + return factory.create(); + } + match backend { #[cfg(feature = "vpx")] - Codec::Vp8 | Codec::Vp9 => Ok(Box::new(vpx::VpxDecoder::new(codec)?)), + DecoderBackend::Libvpx if matches!(codec, Codec::Vp8 | Codec::Vp9) => { + Ok(Box::new(vpx::VpxDecoder::new(codec)?)) + } #[cfg(feature = "openh264")] - Codec::H264 => match &self.openh264 { + DecoderBackend::OpenH264 if codec == Codec::H264 => match &self.openh264 { Some(lib) => Ok(Box::new(lib.decoder()?)), None => Err(unavailable(codec, "the OpenH264 library is not loaded")), }, #[cfg(feature = "av1")] - Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)), - #[allow(unreachable_patterns)] - _ => Err(unavailable(codec, "no decoder in this build")), + DecoderBackend::Dav1d if codec == Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)), + _ => Err(unavailable(codec, format!("no decoder {backend} for it here"))), } } @@ -776,7 +952,65 @@ impl Codecs { Err("built without the `ffmpeg` feature".to_owned()), Err("built without the `ffmpeg` feature".to_owned()), ); - EncoderReport { ffmpeg, zero_copy, encoders } + EncoderReport { ffmpeg, zero_copy, encoders, decoders: self.decoder_report() } + } + + /// Every decoder this build knows, with what works here and why the + /// rest does not, and each one's place in its codec's ladder. + fn decoder_report(&self) -> Vec { + let ladders: Vec<(Codec, Vec)> = + Codec::ALL.into_iter().map(|c| (c, self.decoders_for(c))).collect(); + let mut decoders = Vec::new(); + let mut add = |backend: DecoderBackend, api: &str, codec, hardware, status| { + let ladder = ladders.iter().find(|(c, _)| *c == codec).map(|(_, l)| l); + decoders.push(DecoderInfo { + name: backend.name().to_owned(), + api: api.to_owned(), + codec, + hardware, + rank: ladder.and_then(|l| l.iter().position(|b| *b == backend)), + status, + }); + }; + #[cfg(target_os = "android")] + for codec in Codec::ALL { + if mediacodec::check_decoder(codec).is_ok() { + add(DecoderBackend::Hardware("mediacodec"), "MediaCodec", codec, true, Ok(())); + } + } + for f in &self.decoder_factories { + if !matches!(f.backend(), DecoderBackend::Ffmpeg(_)) { + add(f.backend(), f.api(), f.codec(), f.is_hardware(), Ok(())); + } + } + #[cfg(feature = "ffmpeg")] + for status in crate::ffmpeg::decoder::probe() { + let spec = status.spec; + let backend = DecoderBackend::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, false).map_err(|e| e.to_string()); + #[cfg(not(feature = "vpx"))] + let status = Err("built without the `vpx` feature".to_owned()); + add(DecoderBackend::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(DecoderBackend::OpenH264, "OpenH264 (Cisco)", Codec::H264, false, status); + let status = if cfg!(feature = "av1") { + Ok(()) + } else { + Err("built without the `av1` feature".to_owned()) + }; + add(DecoderBackend::Dav1d, "dav1d", Codec::Av1, false, status); + decoders } } diff --git a/crates/voelin-media/src/ffmpeg/clips/av1.bin b/crates/voelin-media/src/ffmpeg/clips/av1.bin new file mode 100644 index 0000000000000000000000000000000000000000..965cb40bc81ed902b968c85053067fb1676acaca GIT binary patch literal 512 zcmV+b0{{IH0RR9B4gdfE3_Sn50v!-wU|>KR5D);60FZIV925Wmf)GK5KqBgafB?HP z6vDiP+`CFakb8S{C62fZ?51tfr)=7Ex+F}`9xvE%X7eMbh-gPOM6o#5G&-9e_Ua|# zn9RUL+>MmHquTftDs*QLCO{6@ayP3v>dLk?$Gl1?0NUf zVCDGnXvMq`fBFbfXjF!emqL3wQ~uydF;%L=^vTC0>|?a)mp(Y%`6GX?VhHRFqTxtR z7?;c15AB)Q`K(0=@pbJ2o8C&8g4BYr2M#wkJI2Us4G&=bd@ae?!Xh z_{r3|g%foWC9Vr<`_2wLbiX2dVH|2C`+8L(!yGc=mCxj2iO?g!ZvX%Q8Wk`EKtz&B zB!C2hiYTC<02pD%1Q-G$(|~{gn`3k>3Kqh*?utmgysgr`fH-pjDeKT83<6LFhiw(l z>~#b_%=sKchI`#+--RaClfOteB zPyhe`0ch?xFaQ7m0R{!2S(J+?5$r{;mUS7_AL^-1Oks9oHZv|UE-^4MATJ7GA=SLdSz}gEio;6Wo{_|00)4B)&Kwl06+l*000930Du4h00Cu)fI|Q4m`CxS znj3f6=h=vlb?Gs^vlubU6b$9HC<9-NjfXB6j<$N)4uvp5IFyzn{D)lxZ;C3H^Y&%IYmnAku|4Y z*TzUVl-Ucl}Y!|U8tuzRL}VF~S5>Av0b8pUX{#7iy*ipL6y zzTp3@fVCJoA{eh73rddF9a+~`o}j(DDrWN^#vlMjJ22+nJBd?Ln#f07r#fCcR+Gn- z@-i!6*bpt)Yj*!~nlh7qu)ypuZ0${qeYhHNSExK4zzjq|yc)!}IixVh73A$iJSukF0Db-`@PF-p|E07anelI})+PXl9)I(s(o7Lya1_4~ z8#`Rq=dil3zpTX=dQ@DRy3UnMyqKvmHpBxcFz7;Cn%vnFd}u% z)%oe=(|Wyg+;Pad@w5r_J3FVto%=`IYOXmg5xAi_obzczV*$lA6z0;+BpG4o nLr0TH3k?3%BMq;jfswdhE+*^^@$=CR0}Ep`cd`{jBKMRy9>RQM literal 0 HcmV?d00001 diff --git a/crates/voelin-media/src/ffmpeg/clips/hevc.bin b/crates/voelin-media/src/ffmpeg/clips/hevc.bin new file mode 100644 index 0000000000000000000000000000000000000000..d93d6ae3207881c16cae30177543172e3e1932c5 GIT binary patch literal 2712 zcmV;J3TO4i0ssI20003%0Sp2E{{dhC00RK90009300RI&EDQhu0{{d700RJdKmY&$ z0YU)*0bl?C0|2l900RI30{}mu3J4DtB)KFhS|*^tz`%e200RJk000jJ00001L;=8e zz=;3=00AZeuPV||$6nBq5$aOC9qu%=g?AN%YdjDNQ!jZB_Fg&*3a7{RaPdwM4m^@A z<+I?O#=9skggn+O0IKP5&To-d{zK5eFR1oR}P3!3FtImE_LmXcvIh_!@DR-cFzVYxetSVt;s$vckN9RtN<-G+H2H28Cr{LQ z-%|e=U{jqGY)vY_s-}G(Cj4W5>dwHyc)@h77lEu8&G6I_XqwJ1pW+l=7 zU$NrliOvr3!S=7|N0!V17q&crlkJGNF{1M6#;S`<(m#reQs1|yIZ=Mu#bjf$tudt? z9{fM`K~DPrCCn0O(}rM-AbXw4IvTIfS&8s0e>#<9Iw(!S{zeVxt+PK(8Uj(Hy2L^JT} zch2$6J7Ba}@ttP>KD-s&cG-8}W){1EKeu}ht?v(87WLTk9$laP|M+Edn>#dY&9^lH z^2KlEoMow3M1>LU4vqXeP6)*3LrTFKRs5O?l%Ud>C`iQTLrTFKRz<*o0RR9100033 z0nh-K(2B!8|NGr$Q_!c0j#f0Pe~a+^!qzjuedc+-j?ZB<7M1~(qNSA9<%ezSL&jKN zAE$?VYHO)-SLfo0bs>`di?*)qs)Q>ZHJ|n7fE4<0$I%T)7zkT!J*YPCj!^MM2Z-L6 zQ$$#uUMza()6e<^oBxq7)PJYuU$wV-3NY8Jy)Ty?O>0;mHJqC9RknP{->9)7oZ9o-8j{VyRZ25q|Lv$ z8^aq&V%E!SzqKSv_ys>ZHc@5k>T#k#Z`2_|E_BZ%BW$*RK2Fgn3t{Y2Sk{kTpU<|f zucLe<)}4fXxB@F_P2V4?5*F8p6y@%c3^29nA#`AVr;bAK4Q*pNMjA zhUHbi+nP6s>|;@kqHd5#1^@s6000330nh;#(CT;rCtr~58hvJuYV-cCqD7gvafp^7 z`=W}a4ABLm?x?#JWkT4~^PrnwYB-W@fcwgQq7t`0K2k^}$9FMAtx@Q}C%{r1lEFkb z(=cEjCRQZMkirTAtM;2VXbZCAK9D3U=sdUXoTOllUDai2(m#AE#_WUw2C=1UzaN$_ znSxVJT09Eg!|iV==Dg0yC43>r|L3hJZIs^A`hapD1~J2(?Q-eiORkO627frPT#lew z)N>Qc>vD`c!p}h1lNY~QwX)u854ax7Oj4#xit*t_U$mH3^md{kbkhg>1s#ZB=ggmvl)^KmmkEp8Tp_v)NFjf9OF)Owg6a}5hIG`Rd9*n(wx9)=4byt*dW}s zDyjUxo5GYHGQ`D@*t;q?GoHbvl+Q@n@p2;^PR1>{7){8Ie~)Pl5t`}R4YRz<)+3bnP5~Xyg+E#h>Is@uR_HOo%Rg-y3sLOqR!w*06I$n3N#X zhtAGU8m5L>Tfbw7%9lt4)*2&LK_6sApaa|QYmrprT7}pUgyvwV;Hj=n-b;+29b)x=mj8wCXE1MuNjqkf|#c`~LBB5#gd zNBN!*ulY}dPXh-@U{SeM<9%L#c4(i(SsZCUrFQO8C4yP%-h2O4Y>Cizz{dd%2Ea>T>jJ%b4iq8nslM zX2=2{7PNGX@=vpd1sqJ&+$|-0IW@|M(fGWlLPtoXASeLCg>9@pA7y*~EeQ}l zS>-G*#p-8!AWkX3Bi6ypaW6e0SR_sbo#C?XXsn4>O=Rpz$H2hl#n==i8Nm&`-J0&3 z*)`w|fZUMSq^T{P@-RuUpbIh$uO9Q6Gj<9s=*Kw+Ys7Y0VI0LA7G?a_l3EL6*QrCQqQr@3q9Mq`yIaTYSsUbL3WKvZLx`;O$NHH+Y;T45mj`}eLz zl<9TZw{=IOnT7U^8ne+f7AjVZSvZo;TX|gidjrSXa%Mdyd1-aR(dKd@+;Bu^W3SE+ z`EMsi%Plck=ZmLA0`JJ}X2%3>YU^#hejQ=7?hcQ<)kHg6ZXu7KqHG z{z4-EKvjj@VSaJ2|5ZG86$(1~OThVu*XIMh_ex|u`*ZP2uIWh({!0%&-b@J%!PO8j zy(+_)_{FflerKnP%rJlP6P@!pC-9Me$*CJ7SFQ}Q>1IdI|9OBt`R+m1RpdA#s!k>Fg(EOl|qQ)1v@{{PTr4PJ9WRZB7d^LZ2Xf zC}&XxFw!lxL|Ida-dMcUAXpC66MmUsdhh#wuX$;!0GXYMzJElJ{y(qThY(bFt$H+n zKj=Wb*s+S1oI36jYplj}7CyP(q?oDrpK{x&rZ}Y)7-I3YURLioz+pR@%P6zFyqm&3)Sb z#T|eVV~)Q}DFTvtq%9sh75}*%twErd Sjk>+sU8t1BNY}d184REv0VKQt literal 0 HcmV?d00001 diff --git a/crates/voelin-media/src/ffmpeg/clips/vp8.bin b/crates/voelin-media/src/ffmpeg/clips/vp8.bin new file mode 100644 index 0000000000000000000000000000000000000000..27ff8f55a0fc237dec84b6800c3a4078d6bdafb4 GIT binary patch literal 1203 zcmb1UW?-0L%rKWx%YpF&gC&qBqr#)3<8nsDfm0#xfx&&xMgC`Aai7p%U|(C>H~pLa zjrUvFf5yN6_y52Bum6{STr76q^`G$%$G^KD{2l&%{KNi6Sw(&SFZ=a1_t-z=-~XKv z-|+wc{IUX*ixcnd{j1Q!(EMD3ZIXPk<dZTCn}+ zDa@YyJLjA_-hbjGTjnyqqzMMqYIBz`rt&IqYh*G+y!D!WcwWpaU2gVGnYSFo0xmIl zyG=E3x7m3mN{m0{@|Fgjg^Sw)_tmd9^pLQf?01P_Q`-dAzAM60x36b^rpXM~weeO{ z(YCJ-{v1_E_~vWv!E{Q>LCiY9FYMkP`58-idK+!8fzYCa_L1X%M=&)c4_ey;8B(=9?yOfr>L8&HyU~Iuqm$ zpc0)jG$ok~s*BP5bn&nOSm{EzxBU+M`@eMI|Cfi?SIm!1<4u+S|KH>O`jutI7ysO4 z{{R1rr%qthfpb6muUve!+sQH9GlW+>qTkTRIP{&V$)vf)YJ$Z7Wg)bVF@9L#JvRii~(fO=i^tMlv7Onr$U&yy!x_xTddgoePX-k+{Uh@ zCfP@q34c7{uB38BHnJywn$Ff$k1SgDbUhW2&b$`l{o8InbeXOj{qePq4qvDbU|hVL_!rX^ndwK22h zPZ7{nIx4YW{nl$f+qnFlUzDoJ5*JsU!;8NrUFQ7pM0ui67SB$GXB!PpR+KyJWME)0 z&hByn13<6W4tqg}65*-W{NI2hh;c8bo6`Yl#%Uiv{cZEPs!U=^fW(FDaPESj^aO21~ z&cb&~dt0=e-lq0R72e(8RdU(aAyoSB{T~l`*4VJvUtMxZuYYsa{{J7fx~)T>D&N@o z#daNk0aMxc9g2S*us9!@gUvocg z@2sy&YVYX1Q<8~wy0$Ay=(x_^siG_S&PDFl(hicHv$-rJZ1Kv;LWiRyvYmM|64&yW zE^Mn|IJxi5hj-5%e0W#+O%|PJ9Nxmeyt*U&&+Bf9b(Y?L3gza``{B5)>;K%sq~b>h zYfDxv+W$NzV$P2Z@v&MO>wjJsQ@7LHxcTDAi<;Zye5QQevF*3K#A4>?#J9o|GXRv! BKZ*bV literal 0 HcmV?d00001 diff --git a/crates/voelin-media/src/ffmpeg/clips/vp9.bin b/crates/voelin-media/src/ffmpeg/clips/vp9.bin new file mode 100644 index 0000000000000000000000000000000000000000..39302de364984724ce97753ed528e00b379f5236 GIT binary patch literal 4073 zcmZ{ncRU>XyT=F7Yoe@Zi`XEnl86>jlPJ*+QKGXBB9;(kEsGE(qDz$M2@#1FWR>V$ zh#tN7%@V7xx_6y>PR{+^*S&vz=QYo~W}f=~JcD2WfDp|PRe%}CfTNm=dt##u&Ug6nG_ z;9VAnQc0kH41@c08S(``C4+m&*SP7&p|~~^zY)0iKs@*5>5$f*v^2i0sz>_;uCVCk zsuvcJ&aI}2N+a7X0l^n>@)7Q!axyWj$6^#M%ljdFk3#(sf~n@5VrK zm__LqhW+5#3$>PE1%nr(acVYFq#!f@_{XPO`4yhdrhOB6)iE+j3y>$tS2`%22eY8r z$2z@R-Yn%#x~+=!E}Q1ahK-x3y4#0G<1w|Otn+YbrsA_D>su~uGi`qe>(IJ1c>gGc zmt-gCX=dNxrt3dNvBetmsU-SDh#W{7WDaywT@zuKci@rKN-;|i&gGHIg)?9o-%7|Z zADA99b*OS;w$s)y=uu6b?Vje@1K1`>xt#YvAj)ABE}~0|Ko671PDveGlwRd>3**XI z&YmCmGS4E{D|puZ_*w{HlawPKcJJ3{O>Pp~ANM@@lU#n-P$T~Arq$ncf}RS`$vkNp zoV#1`;R$VN-bQZI{>b5CaXNt9?*N-zR&aN@2Hsa-gW9ONg3K}I1V$8WUCA273b!dT zG#=H|H*K(=Fy&Y+r&Q-;HwEh(KF`CKlEw^^f7;vbDGGt3E+imzNK)30fd21{^8{EE zjNl?sn@C0_u~4QYuHH`(=D6W5YwQ~qc>t5O?fgt^u>^eP-t@b06LN)zzfwLnUczhn|x~Yzd=D0Jybgcg#84CFz)oTppGQkcedL6G8VS0L?zJn*~{9;;f*wy|Z=xg);PtgI1d1ob%y=z8YtE76!BT zbvLOIVk0FK!KU%e!iA&xv z7G$uolw$Z`;&o-{zb%S1adrjqzVRQjUUg0yM~NsjJqp4PW4&a}LK3^s$&A~(D8R`f z97p&(SN2fpXF6165J%9bum7|sOHbDyt{6{1ZkrGYJA1gVN{jZL)z<7AOuD0KD&5av zmIJxvZ<5KHbQr51F|?68R1uilS$+kwqMECN9{$uj^dJyU4x1cjXL^xqXAFe8<57lK zZh@%KmlNa$0!?Dl8@C7egV{&H^~Oi!BFD5FYexAV36PRTWzr;ogo1>ym8qt4s|I{X zE^mB2AZ6wUy=)86lnorGM?os80z#;96^>sjou6=A&N)$9M~Eir9p%&NdzQOEFK@sn z(ka560vV5aXqk?Hr$GRemkvNS0+JUA+r>#o3?%-O$~2~`;yb}FZ#nW;7uy2V%Rh!{ zv};blia|dhI&Lcv1y?}n>_+FKd>=IeZ@yN$Uj3W0YZ@P{w}VIw+nm6uLE6jfzbsqI{rz z36NuCvgIiPQ2Y>jQF(iNW4mkJ^zrj=)vyJXUw3~D8ltX0j~Dd3A=he~H|(jQ_U@Xh zoKNydG{7hD46`g>dB$_p8ItVQ0-GyZEby#6gOag}=LWW>D^t=*_gJn!IMcm9C^v=C z7ujL8VjFg!D?YF9=YZk*Ef3%MR>ih#>yw8DsIjk?>t^LN3d!=f_0`p}n{NwKiEw>Q z@t*p~Xf2BMqw@qVl53TjfT*Cesn1NB0r|1s$&-SXoefX?@Pp+{E+1|xBzLZtfNYE3 z><(Ww`ktAnY-mSw+GAF*EMKK%eNOLROaf~E#6&lRs?|q%F3D9E29_NSWMN_0b}~Lq zXZjnjV>G^K%t?~I>PL5D)d3ye)-toaO4q5X@Uekm|Se$NOs&DV@d* zP?HwX#o(rQCAnH)5$@M-#0@&s_u;;nh%Lt++0c^>cr1kydRc-Q%y?AS_4`u zwl5+~!)P_O=6x98*9Rdgk#0(TJtY=PHfHO4m8D-EAA0?cZ@-&089tCWdW3P5Q{TR{ zBF*Hjk(rWX9qZimQ^TYpinc$5{35?W!MRqXEVq0)-Fym}c>`rio*f;jz~_BFKh)48 z0(B*;^G255|8PCyIz`=utUUjiZ(F`po_}hni)|BAaLRDQuihg8yA#bt^0>L_yjb~~ zI=gY>5fGZLG#jL^zOzkMo>fGX+54grs+?YTrGuBs?X(!o`IjDO8LCc7h?Yw?4`h~m z)?k5rs|n~LUI7VgDm^5FIQUig&9OXC_NyYk|?N}l{YSPvhHrkLjv z;4L+8V6DTK86n@_MP|g5MYnvCk&g-E$agS^zdkH$sEl1;d0Ur592AL>JV2WT?6n)* z|Eu)q3Yoi7Pqf&9Mn)g=V6By^jbWmNEn+3U;!JEvf78Ac|(8-+)R-BX|yS@Jf{9+ERBTNM^dx8)mdU<0sIMg?MSJ|)?&L>_a8 zJ=pPQt@RR1CNX~j)lk+|u=O7^)_zu^B8aiRQbzRCt|i3XI7`U4D#&Q0(>Do0YEO@( zR&6h6EeI{(U6suuBy4$es%x=ZbH`w zYu>&Z)Z_V^@1M8YZ%%s97+mbG3n0nTdo`;Lq>@<$>vtElVJ`IiZ_&(XZ_2Iftf|p* z%gLgo3FiJwN}uxp%o>smVtO3*ii;@(119EJc57+YoT~gduc=RUs5Vm zc)m5MpD%@KGGI3ru%#RW9Lwb{tL3MznK}eY@V&rdPRbnAV}!_|QUI>T*>PE9N_C<- zB+qhr1$iXuU4*!L*%)%a#UBJ|3W3h|7F)Xq=#AO-2HAl|W{p51VjLmJD`Zb@C)#|k zAaQZi{(;XHbvW=}HubhCfr0HB=_b%YE5r@pZ{}2gyPwal;U(S{B!9r_d_Qd(y9S|| z=&*gQFiY;neLt_!cte+r$cpgOSn}A@j0o8Bn#Hvh5zcwUMKm6Gh_pntCh#jk zHcLl*OK&UW8xvY)A2NAt;EDMo7Bz_gE&NDF;!doqdM0A#@&nHd{F^`D-=T9kh!m!x zMWhF7@;&^Q1b!SIJ4F%$Rp-Vly{kXdzvx&NG&(s9R@_GOmP|#jq?wPVe8l0Q*Gsfk z{ntm%cHBc3-`wlp8TaZr=GP_0rg*8mXn5Y4LGS8>g;MvxE=kTCaLZXoa3{A_MB@~r z{n!mSVEkNyI00WMQe)>1y-$chn~_hxAGpxJ{Xnjl&nv%6K3HBLxOkE+cCbW?8gz2w zJsae{>-1iy)GiV2MOr|LkRldCo-=K`dyitliKk3i{lSmk1FbE@S~#K+wr)z2X8hfX z7POv5@g&M1OQ>G!j>dn#`1YtIheMC$uMpwxDgmj5-C&1vnkqzY?Qf~<4aKd@d_Mbk zNS3GQfn-ga$C*9c4KfSJ@!(ob3XXhNw(tZZ_GpU~HD|qIKht?yU4YjEY)R7YWgHSc zfd&7OwwBDTg`bwSi8Rh>258*Zv5yep9C$Jg%7DETqD|af19&~8X94P5r3?$mO+&Rw zqE>azJo-}S8(H#qd-4Q*Z{;|b+9<+8`fqBiAuEY6uz!C& zg@s@z{91NpK$rCwsvmAnF>zu;f7a3t>IPq83>1j_r$H_$u!)aL)6KKzDgNRADkAP_ zx++#L;kE3itHg}GXUmOzL>cpl^KZ2D>tOW6131tBKf<#(S>9r$=Q(W`S{;AhTgfN`GsGOVyZI0o*#P%_2aMu0cabn>zeANv`YTOhFb1OTjV^){mlWV^N*8`;|B=3QW!#A6QAu|*g8m>M(} z&V@ru_R+%rI!H%7mZvH#*sqcQzIASa`iNO}?uq7#g)2a#o;HtloF9!}rmB4eopDU- z3CL)L19BLSs-9~L)RM`Mf7(Vu7g?<2`8Edea=!1Pzuba&xWawoNPl+}pe zPqvm$vGpn5wEgF)ySUXCwpGy7T{s)B|9=Fl{(l6^;jQuQkg5ZR$6Ps&lvN+kxvx4{ zd$Pt8@z!b!pG#E Yvv*dzFRLlWFF{xbjowQg^q9o`7Z3C2QUCw| literal 0 HcmV?d00001 diff --git a/crates/voelin-media/src/ffmpeg/decoder.rs b/crates/voelin-media/src/ffmpeg/decoder.rs new file mode 100644 index 0000000..96df38e --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/decoder.rs @@ -0,0 +1,836 @@ +//! Video decoders through FFmpeg: the platform's hardware decoders first +//! (VA-API and, with NVIDIA's driver, NVDEC on Linux; D3D11VA and DXVA2 on +//! Windows; VideoToolbox on macOS), then FFmpeg's software decoders (dav1d +//! and libaom for AV1, FFmpeg's own HEVC, VP9, H.264 and VP8), each checked +//! by a self-test. +//! +//! Hardware decoding goes through FFmpeg's hwaccel API: FFmpeg's own decoder +//! (`av1`, `h264`, ...) with `AVCodecContext.hw_device_ctx` set (located +//! at load, see [`super::layout`]), so that its default `get_format` picks +//! the device's surfaces. Pictures are copied out of the GPU +//! (`av_hwframe_transfer_data`) into a frame of our own, reused, and from +//! there into the caller's [`VideoFrame`] (NV12), whose buffers are reused +//! as well ([`VideoDecoder::decode_into`]): a running decoder allocates +//! nothing per picture on our side. Software decoders give I420 (or NV12). +//! +//! Every decoder is set up for live video: slice threads only (frame +//! threads hold one frame per thread before the first picture comes out), +//! dav1d with a frame delay of one, so each frame's picture comes out of +//! the call that decoded it. +//! +//! [`probe`] runs every decoder once per process (in parallel) on a short +//! clip of its codec: three frames of a test picture encoded by this crate's +//! own encoders (`clips/`). Each frame must give its picture at once, at its +//! size and close to the test picture (PSNR), and a hardware decoder must +//! have decoded on the GPU: FFmpeg silently decodes in software when the +//! GPU lacks the codec (VP8 on AMD), which the self-test reports as +//! unusable, since FFmpeg's software decoder follows in the ladder anyway. +#![allow(unsafe_code)] + +use std::ffi::c_int; +use std::sync::{Mutex, OnceLock, PoisonError}; +use std::time::{Duration, Instant}; + +use super::Ffmpeg; +use super::encoder::{Device, log_suffix, vaapi_device}; +use super::layout; +use super::sys::{EAGAIN, EOF, FrameHead, OPTION_NOT_FOUND, PacketHead, Ptr, cstr}; +use crate::codec::hw::DecoderFactory; +use crate::codec::{Codec, DecoderBackend, VideoDecoder}; +use crate::convert; +use crate::frame::{FrameData, FrameRef, PixelsRef, PlaneRef, VideoFrame, chroma_size}; +use crate::{Error, Result}; + +/// One FFmpeg decoder this crate drives. +#[derive(Debug, PartialEq, Eq)] +pub struct DecoderSpec { + /// The name in settings (`stream.decoder_backend`) and logs: FFmpeg's + /// name of the hardware acceleration (`h264_vaapi`, `av1_nvdec`), or of + /// the decoder in software (`hevc`, `libdav1d`). + pub name: &'static str, + pub codec: Codec, + /// FFmpeg's decoder. + pub decoder: &'static str, + /// For hardware decoding: FFmpeg's device type (`vaapi`, `d3d11va`, ...) + /// and the pixel format of its pictures (`vaapi`, `d3d11`, ...). + pub hardware: Option<(&'static str, &'static str)>, + /// The API or library, for the UI. + pub api: &'static str, +} + +macro_rules! hardware { + ($name:literal, $codec:ident, $decoder:literal, $device:literal, $format:literal, $api:literal) => { + DecoderSpec { + name: $name, + codec: Codec::$codec, + decoder: $decoder, + hardware: Some(($device, $format)), + api: $api, + } + }; +} + +macro_rules! software { + ($name:literal, $codec:ident, $api:literal) => { + DecoderSpec { name: $name, codec: Codec::$codec, decoder: $name, hardware: None, api: $api } + }; +} + +/// Every decoder of this platform, best first within its codec: hardware, +/// then software. The ones FFmpeg or the machine lacks fail the probe and +/// are skipped. +pub static DECODERS: &[DecoderSpec] = &[ + #[cfg(target_os = "linux")] + hardware!("av1_vaapi", Av1, "av1", "vaapi", "vaapi", "VA-API"), + #[cfg(target_os = "linux")] + hardware!("hevc_vaapi", H265, "hevc", "vaapi", "vaapi", "VA-API"), + #[cfg(target_os = "linux")] + hardware!("vp9_vaapi", Vp9, "vp9", "vaapi", "vaapi", "VA-API"), + #[cfg(target_os = "linux")] + hardware!("h264_vaapi", H264, "h264", "vaapi", "vaapi", "VA-API"), + #[cfg(target_os = "linux")] + hardware!("vp8_vaapi", Vp8, "vp8", "vaapi", "vaapi", "VA-API"), + // NVIDIA's driver has no VA-API of its own. + #[cfg(target_os = "linux")] + hardware!("av1_nvdec", Av1, "av1", "cuda", "cuda", "NVDEC"), + #[cfg(target_os = "linux")] + hardware!("hevc_nvdec", H265, "hevc", "cuda", "cuda", "NVDEC"), + #[cfg(target_os = "linux")] + hardware!("vp9_nvdec", Vp9, "vp9", "cuda", "cuda", "NVDEC"), + #[cfg(target_os = "linux")] + hardware!("h264_nvdec", H264, "h264", "cuda", "cuda", "NVDEC"), + #[cfg(target_os = "linux")] + hardware!("vp8_nvdec", Vp8, "vp8", "cuda", "cuda", "NVDEC"), + // Every GPU vendor's; DXVA2 for systems without Direct3D 11 video. + #[cfg(windows)] + hardware!("av1_d3d11va", Av1, "av1", "d3d11va", "d3d11", "D3D11VA"), + #[cfg(windows)] + hardware!("hevc_d3d11va", H265, "hevc", "d3d11va", "d3d11", "D3D11VA"), + #[cfg(windows)] + hardware!("vp9_d3d11va", Vp9, "vp9", "d3d11va", "d3d11", "D3D11VA"), + #[cfg(windows)] + hardware!("h264_d3d11va", H264, "h264", "d3d11va", "d3d11", "D3D11VA"), + #[cfg(windows)] + hardware!("av1_dxva2", Av1, "av1", "dxva2", "dxva2_vld", "DXVA2"), + #[cfg(windows)] + hardware!("hevc_dxva2", H265, "hevc", "dxva2", "dxva2_vld", "DXVA2"), + #[cfg(windows)] + hardware!("vp9_dxva2", Vp9, "vp9", "dxva2", "dxva2_vld", "DXVA2"), + #[cfg(windows)] + hardware!("h264_dxva2", H264, "h264", "dxva2", "dxva2_vld", "DXVA2"), + #[cfg(target_vendor = "apple")] + hardware!("av1_videotoolbox", Av1, "av1", "videotoolbox", "videotoolbox_vld", "VideoToolbox"), + #[cfg(target_vendor = "apple")] + hardware!( + "hevc_videotoolbox", + H265, + "hevc", + "videotoolbox", + "videotoolbox_vld", + "VideoToolbox" + ), + #[cfg(target_vendor = "apple")] + hardware!("vp9_videotoolbox", Vp9, "vp9", "videotoolbox", "videotoolbox_vld", "VideoToolbox"), + #[cfg(target_vendor = "apple")] + hardware!( + "h264_videotoolbox", + H264, + "h264", + "videotoolbox", + "videotoolbox_vld", + "VideoToolbox" + ), + // FFmpeg's native AV1 decoder decodes in hardware only. + software!("libdav1d", Av1, "dav1d"), + software!("libaom-av1", Av1, "libaom"), + software!("hevc", H265, "FFmpeg"), + software!("vp9", Vp9, "FFmpeg"), + software!("h264", H264, "FFmpeg"), + software!("vp8", Vp8, "FFmpeg"), +]; + +impl DecoderSpec { + pub fn by_name(name: &str) -> Option<&'static DecoderSpec> { + DECODERS.iter().find(|d| d.name == name) + } + + pub fn is_hardware(&self) -> bool { + self.hardware.is_some() + } +} + +/// The process's device of FFmpeg type `kind` (its default one), shared by +/// all decoders; VA-API's is the encoders' (`VOELIN_VAAPI_DEVICE`, or the +/// first render node). +fn hw_device(ffmpeg: &Ffmpeg, kind: &'static str) -> std::result::Result { + if kind == "vaapi" { + return vaapi_device(ffmpeg); + } + type Devices = Vec<(&'static str, std::result::Result)>; + static DEVICES: Mutex = Mutex::new(Vec::new()); + let mut devices = DEVICES.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((_, device)) = devices.iter().find(|(k, _)| *k == kind) { + return device.as_ref().map(|d| d.0).map_err(Clone::clone); + } + let api = &ffmpeg.api; + let name = cstr(kind); + // SAFETY: a C string. + let id = unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) }; + let created = if id <= 0 { + Err(format!("FFmpeg has no {kind} support")) + } else { + let mut device = std::ptr::null_mut(); + // SAFETY: a valid out pointer; the type's default device, no options. + let ret = unsafe { + (api.av_hwdevice_ctx_create)(&mut device, id, std::ptr::null(), std::ptr::null_mut(), 0) + }; + if ret < 0 { + Err(format!("{kind} device: {}{}", api.error_text(ret), log_suffix(kind))) + } else { + Ok(Device(device)) + } + }; + let result = created.as_ref().map(|d| d.0).map_err(Clone::clone); + devices.push((kind, created)); + result +} + +/// Threads of a software decoder: slice (or dav1d's tile and row) threads, +/// which add no delay. +fn decoder_threads() -> usize { + std::thread::available_parallelism().map_or(1, |n| n.get().min(8)) +} + +/// A decoder of one [`DecoderSpec`]; see the [module docs](self). +pub struct FfmpegDecoder { + ffmpeg: &'static Ffmpeg, + spec: &'static DecoderSpec, + ctx: Ptr, + packet: Ptr, + /// The decoder's pictures. + frame: Ptr, + /// Hardware pictures are copied here from the GPU (reused). + download: Ptr, + /// The pixel format of the device's pictures. + hw_format: Option, + yuvj420p: Option, + gpu_pictures: u64, + cpu_pictures: u64, +} + +// SAFETY: the FFmpeg objects belong to this decoder alone and are used from +// one thread at a time (`&mut self`); FFmpeg's decoders have no thread +// affinity. +unsafe impl Send for FfmpegDecoder {} + +impl FfmpegDecoder { + /// A decoder of `spec`, opened at once (on its device for hardware + /// decoding). + pub fn new(spec: &'static DecoderSpec) -> Result { + let unavailable = |reason: String| Error::CodecUnavailable { codec: spec.codec, reason }; + let ffmpeg = Ffmpeg::get().map_err(|e| unavailable(e.to_owned()))?; + let api = &ffmpeg.api; + // Filled in one by one; Drop frees what was made. + let mut this = Self { + ffmpeg, + spec, + ctx: std::ptr::null_mut(), + packet: std::ptr::null_mut(), + frame: std::ptr::null_mut(), + download: std::ptr::null_mut(), + hw_format: None, + yuvj420p: api.pix_fmt("yuvj420p"), + gpu_pictures: 0, + cpu_pictures: 0, + }; + let name = cstr(spec.decoder); + // SAFETY: a C string; returns a static codec or NULL. + let codec = unsafe { (api.avcodec_find_decoder_by_name)(name.as_ptr()) }; + if codec.is_null() { + return Err(unavailable(format!("{} is not in this FFmpeg build", spec.decoder))); + } + // SAFETY: allocates a context with the decoder's private options. + this.ctx = unsafe { (api.avcodec_alloc_context3)(codec) }; + if this.ctx.is_null() { + return Err(unavailable("avcodec_alloc_context3 failed".into())); + } + // SAFETY: `ctx` is a live codec context; the first child is its + // private options object (NULL if the decoder has none). + let private = unsafe { (api.av_opt_child_next)(this.ctx, std::ptr::null_mut()) }; + // A hardware decoder's work is on the GPU. + let threads = if spec.is_hardware() { 1 } else { decoder_threads() }; + this.set(this.ctx, "threads", &threads.to_string()); + this.set(this.ctx, "thread_type", "slice"); + if spec.decoder == "libdav1d" + && this.set(private, "max_frame_delay", "1") == OPTION_NOT_FOUND + { + // Before FFmpeg 5.0. + this.set(private, "framethreads", "1"); + } + if let Some((kind, format)) = spec.hardware { + let device = hw_device(ffmpeg, kind).map_err(unavailable)?; + let offset = ffmpeg.codec_hw_device.clone().map_err(unavailable)?; + let format = + api.pix_fmt(format).ok_or_else(|| unavailable(format!("no {format} format")))?; + this.hw_format = Some(format); + // SAFETY: `device` is a live device reference; `offset` is + // AVCodecContext.hw_device_ctx (located and checked at load), + // which takes the new reference and frees it with the context. + unsafe { + let reference = (api.av_buffer_ref)(device); + if reference.is_null() { + return Err(unavailable("out of memory".into())); + } + layout::write::(this.ctx, offset, reference); + } + } + // SAFETY: a configured context and its codec; no options dictionary. + let ret = unsafe { (api.avcodec_open2)(this.ctx, codec, std::ptr::null_mut()) }; + if ret < 0 { + return Err(this.error("open", ret)); + } + // SAFETY: allocations, checked below. + unsafe { + this.packet = (api.av_packet_alloc)(); + this.frame = (api.av_frame_alloc)(); + this.download = (api.av_frame_alloc)(); + } + if this.packet.is_null() || this.frame.is_null() || this.download.is_null() { + return Err(unavailable("out of memory".into())); + } + Ok(this) + } + + pub fn spec(&self) -> &'static DecoderSpec { + self.spec + } + + /// Pictures decoded on the GPU so far. + pub fn gpu_pictures(&self) -> u64 { + self.gpu_pictures + } + + /// Pictures decoded in software so far (by a hardware decoder: the GPU + /// did not take the stream, and FFmpeg decoded it itself). + pub fn cpu_pictures(&self) -> u64 { + self.cpu_pictures + } + + /// Set an option of `obj` (the context, or its private options) by name; + /// one this release does not know is skipped. + fn set(&self, obj: Ptr, name: &str, value: &str) -> c_int { + if obj.is_null() { + return OPTION_NOT_FOUND; + } + 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 error(&self, what: &str, code: c_int) -> Error { + self.failed(format!( + "{what}: {}{}", + self.ffmpeg.api.error_text(code), + log_suffix(self.spec.decoder) + )) + } + + fn failed(&self, message: String) -> Error { + Error::Decoder { codec: self.spec.codec, message: format!("{} {message}", self.spec.name) } + } + + /// Hand `data` to the decoder. The packet points at it only during the + /// call: it is not reference-counted, so FFmpeg copies the data into a + /// padded buffer of its own. + fn send(&mut self, data: &[u8], size: c_int) -> c_int { + let packet = self.packet.cast::(); + // SAFETY: our packet (from av_packet_alloc, so at least as large as + // its leading fields); emptied again before `data` goes away. + unsafe { + (*packet).data = data.as_ptr().cast_mut(); + (*packet).size = size; + let ret = (self.ffmpeg.api.avcodec_send_packet)(self.ctx, self.packet); + (*packet).data = std::ptr::null_mut(); + (*packet).size = 0; + ret + } + } + + /// Take every picture that is ready; the last one ends up in `out`. + fn receive(&mut self, out: &mut VideoFrame) -> Result { + let mut got = false; + loop { + // SAFETY: a live context and our frame. + let ret = unsafe { (self.ffmpeg.api.avcodec_receive_frame)(self.ctx, self.frame) }; + if ret == EAGAIN || ret == EOF { + return Ok(got); + } + if ret < 0 { + return Err(self.error("decoding", ret)); + } + let copied = self.copy_picture(out); + // SAFETY: our frame; its buffers go back to the decoder. + unsafe { (self.ffmpeg.api.av_frame_unref)(self.frame) }; + copied?; + got = true; + } + } + + /// The decoded picture into `out`: from the GPU through the download + /// frame, or straight from FFmpeg's buffers. + fn copy_picture(&mut self, out: &mut VideoFrame) -> Result<()> { + let api = &self.ffmpeg.api; + let head = self.frame.cast::(); + // SAFETY: a frame the decoder just filled. + let (format, width, height) = unsafe { ((*head).format, (*head).width, (*head).height) }; + let source = if Some(format) == self.hw_format { + let download = self.download.cast::(); + // SAFETY: the download frame is ours: its leading fields are set + // before av_frame_get_buffer as documented, and its buffers are + // referenced by nothing else, so they are writable. + unsafe { + if (*download).data[0].is_null() + || ((*download).width, (*download).height) != (width, height) + { + (api.av_frame_unref)(self.download); + (*download).width = width; + (*download).height = height; + (*download).format = self.ffmpeg.pix.nv12; + let ret = (api.av_frame_get_buffer)(self.download, 0); + if ret < 0 { + return Err(self.error("picture buffer", ret)); + } + } + let ret = (api.av_hwframe_transfer_data)(self.download, self.frame, 0); + if ret < 0 { + return Err(self.error("copy from the GPU", ret)); + } + } + self.gpu_pictures += 1; + self.download + } else { + self.cpu_pictures += 1; + self.frame + }; + // SAFETY: `source` holds a picture until it is unreferenced, after + // this copy. + unsafe { self.view(source) }?.copy_to(out); + Ok(()) + } + + /// The picture in `frame`, borrowed. + /// + /// # Safety + /// `frame` must hold a picture that stays as it is while the view is + /// used. + unsafe fn view(&self, frame: Ptr) -> Result> { + // SAFETY: guaranteed by the caller. + let head = unsafe { &*frame.cast::() }; + let (Ok(width), Ok(height)) = (u32::try_from(head.width), u32::try_from(head.height)) + else { + return Err(self.failed("gave a picture of no size".into())); + }; + if width == 0 || height == 0 { + return Err(self.failed("gave a picture of no size".into())); + } + let (w, h) = (width as usize, height as usize); + let (cw, ch) = chroma_size(width, height); + let plane = |i: usize, bytes: usize, rows: usize| -> Result> { + let stride = usize::try_from(head.linesize[i]).unwrap_or(0); + if head.data[i].is_null() || stride < bytes { + return Err(self.failed(format!("gave plane {i} with a line size of {stride}"))); + } + // SAFETY: FFmpeg's planes hold `linesize` bytes for every row of + // the picture but the last, which holds at least the row. + let data = + unsafe { std::slice::from_raw_parts(head.data[i], stride * (rows - 1) + bytes) }; + Ok(PlaneRef::new(data, stride)) + }; + let pix = self.ffmpeg.pix; + let pixels = if head.format == pix.yuv420p || Some(head.format) == self.yuvj420p { + PixelsRef::I420 { y: plane(0, w, h)?, u: plane(1, cw, ch)?, v: plane(2, cw, ch)? } + } else if head.format == pix.nv12 { + PixelsRef::Nv12 { y: plane(0, w, h)?, uv: plane(1, cw * 2, ch)? } + } else { + return Err(self.failed(format!( + "gave pictures in {} (only 8-bit 4:2:0 is supported)", + self.ffmpeg.api.pix_fmt_name(head.format) + ))); + }; + Ok(FrameRef { width, height, timestamp: Duration::ZERO, pixels }) + } +} + +impl Drop for FfmpegDecoder { + fn drop(&mut self) { + let api = &self.ffmpeg.api; + // SAFETY: each pointer is NULL or owned by this decoder; the context + // frees its device reference. + unsafe { + (api.av_packet_free)(&mut self.packet); + (api.av_frame_free)(&mut self.frame); + (api.av_frame_free)(&mut self.download); + (api.avcodec_free_context)(&mut self.ctx); + } + } +} + +impl VideoDecoder for FfmpegDecoder { + fn codec(&self) -> Codec { + self.spec.codec + } + + fn decode(&mut self, data: &[u8]) -> Result> { + let mut picture = VideoFrame::black_i420(0, 0); + Ok(self.decode_into(data, &mut picture)?.then_some(picture)) + } + + /// FFmpeg's H.264 decoder conceals what a lost frame left missing (from + /// the previous picture), and its HEVC decoder makes up missing + /// references; VP8, VP9 and AV1 fail on them or show garbage. + fn conceals_errors(&self) -> bool { + matches!(self.spec.codec, Codec::H264 | Codec::H265) + } + + fn decode_into(&mut self, data: &[u8], out: &mut VideoFrame) -> Result { + if data.is_empty() { + return Ok(false); + } + let size = + c_int::try_from(data.len()).map_err(|_| self.failed("frame too large".into()))?; + let mut got = false; + let mut ret = self.send(data, size); + if ret == EAGAIN { + // Pictures have to be taken out before more data goes in. + got |= self.receive(out)?; + ret = self.send(data, size); + } + if ret < 0 { + return Err(self.error("decoding", ret)); + } + got |= self.receive(out)?; + Ok(got) + } +} + +/// Creates decoders of one [`DecoderSpec`] that passed its self-test. +pub struct FfmpegDecoderFactory(pub &'static DecoderSpec); + +impl FfmpegDecoderFactory { + /// Factories of the decoders that passed their self-test, in + /// [`DECODERS`] order (hardware first). + pub fn available() -> Vec { + probe() + .iter() + .filter(|s| s.available.is_ok()) + .map(|s| FfmpegDecoderFactory(s.spec)) + .collect() + } +} + +impl DecoderFactory for FfmpegDecoderFactory { + fn backend(&self) -> DecoderBackend { + DecoderBackend::Ffmpeg(self.0.name) + } + + fn codec(&self) -> Codec { + self.0.codec + } + + fn api(&self) -> &'static str { + self.0.api + } + + fn is_hardware(&self) -> bool { + self.0.is_hardware() + } + + fn create(&self) -> Result> { + Ok(Box::new(FfmpegDecoder::new(self.0)?)) + } +} + +/// Size of the self-test clips: one every hardware decoder takes (NVDEC +/// wants at least 144x144 for HEVC), and a multiple of what AV1 encoders +/// pad to (64x16 on RDNA3), so that the AV1 clip declares exactly this. +pub(crate) const CLIP_SIZE: (u32, u32) = (320, 240); + +/// Frames per clip: a keyframe and two that predict from it. +const CLIP_FRAMES: usize = 3; + +/// How close a decoded clip picture must be to [`clip_picture`]; the clips +/// decode at well over 40 dB. +const CLIP_PSNR: f64 = 30.0; + +/// The self-test clip of `codec`: [`CLIP_FRAMES`] frames of +/// [`clip_picture`] encoded by this crate's encoders (see +/// `write_self_test_clips` in the tests), each as a little-endian `u32` +/// length and the frame as a stream carries it (Annex B for H.264 and HEVC, +/// a temporal unit of OBUs for AV1). +fn clip(codec: Codec) -> &'static [u8] { + match codec { + Codec::Av1 => include_bytes!("clips/av1.bin"), + Codec::H265 => include_bytes!("clips/hevc.bin"), + Codec::Vp9 => include_bytes!("clips/vp9.bin"), + Codec::H264 => include_bytes!("clips/h264.bin"), + Codec::Vp8 => include_bytes!("clips/vp8.bin"), + } +} + +fn clip_frames(codec: Codec) -> impl Iterator { + let mut rest = clip(codec); + std::iter::from_fn(move || { + let (length, tail) = rest.split_first_chunk::<4>()?; + let (frame, tail) = tail.split_at_checked(u32::from_le_bytes(*length) as usize)?; + rest = tail; + Some(frame) + }) +} + +/// Frame `n` of the self-test clips: a luma ramp, chroma ramps the other +/// way, and a bright square that moves 24 pixels per frame. +fn clip_picture(n: usize) -> VideoFrame { + let (width, height) = CLIP_SIZE; + let (w, h) = (width as usize, height as usize); + let mut frame = VideoFrame::black_i420(width, height); + let FrameData::I420 { y, u, v } = &mut frame.data else { unreachable!("black_i420") }; + let left = 32 + 24 * n; + for row in 0..h { + for col in 0..w { + let square = (left..left + 64).contains(&col) && (64..128).contains(&row); + y.data[row * w + col] = if square { 235 } else { 16 + (col * 200 / w) as u8 }; + } + } + let (cw, ch) = (w / 2, h / 2); + for row in 0..ch { + for col in 0..cw { + u.data[row * cw + col] = 64 + (row * 128 / ch) as u8; + v.data[row * cw + col] = 192 - (col * 128 / cw) as u8; + } + } + frame.with_timestamp(Duration::from_millis(33 * n as u64)) +} + +/// Decode `spec`'s clip: every frame's picture at once, at its size, close +/// to the test picture; on the GPU for a hardware decoder. +fn test_decoder(spec: &'static DecoderSpec) -> std::result::Result<(), String> { + let reason = |e: Error| match e { + Error::CodecUnavailable { reason, .. } => reason, + Error::Decoder { message, .. } => message, + e => e.to_string(), + }; + let mut decoder = FfmpegDecoder::new(spec).map_err(reason)?; + let mut picture = VideoFrame::black_i420(0, 0); + let mut frames = 0; + for (n, data) in clip_frames(spec.codec).enumerate() { + if !decoder.decode_into(data, &mut picture).map_err(reason)? { + return Err(format!("no picture from frame {n} of the self-test clip")); + } + if (picture.width, picture.height) != CLIP_SIZE { + let (w, h) = CLIP_SIZE; + return Err(format!( + "frame {n} decoded at {}x{} instead of {w}x{h}", + picture.width, picture.height + )); + } + let psnr = convert::psnr(&clip_picture(n), &picture).map_err(|e| e.to_string())?; + if psnr < CLIP_PSNR { + return Err(format!("frame {n} decoded wrong (PSNR {psnr:.1} dB)")); + } + frames += 1; + } + if frames != CLIP_FRAMES { + return Err(format!("the {} self-test clip has {frames} frames", spec.codec)); + } + if spec.is_hardware() && decoder.cpu_pictures > 0 { + return Err(format!( + "the GPU does not decode {} here (FFmpeg fell back to software){}", + spec.codec, + log_suffix(spec.decoder) + )); + } + Ok(()) +} + +/// Why `spec` cannot work here before trying it, if that is known: not in +/// this FFmpeg build, or (NVDEC) no NVIDIA GPU, whose driver would spend +/// its initialisation failing. +fn absent(ffmpeg: &Ffmpeg, spec: &DecoderSpec) -> Option { + let api = &ffmpeg.api; + let name = cstr(spec.decoder); + // SAFETY: a C string; returns a static codec or NULL. + if unsafe { (api.avcodec_find_decoder_by_name)(name.as_ptr()) }.is_null() { + return Some(format!("{} is not in this FFmpeg build", spec.decoder)); + } + let (kind, _) = spec.hardware?; + let name = cstr(kind); + // SAFETY: a C string. + if unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) } <= 0 { + return Some(format!("FFmpeg has no {kind} support")); + } + #[cfg(target_os = "linux")] + if kind == "cuda" { + use super::encoder::{drm_vendors, vendor}; + let vendors = drm_vendors(); + if !vendors.is_empty() + && !vendors.contains(&vendor::NVIDIA) + && !std::path::Path::new("/dev/nvidiactl").exists() + { + return Some("no NVIDIA GPU in this machine".into()); + } + } + None +} + +/// A decoder and the result of its self-test. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DecoderStatus { + pub spec: &'static DecoderSpec, + /// `Ok` if it decoded the self-test clip, else why not. + pub available: std::result::Result<(), String>, + /// How long its self-test took (they run in parallel). + pub took: Duration, +} + +/// Every decoder of [`DECODERS`] with its self-test result (run once per +/// process, the decoders in parallel). Empty without FFmpeg. +pub fn probe() -> &'static [DecoderStatus] { + static PROBE: OnceLock> = OnceLock::new(); + PROBE.get_or_init(|| { + let Ok(ffmpeg) = Ffmpeg::get() else { return Vec::new() }; + let started = Instant::now(); + let statuses: Vec = std::thread::scope(|scope| { + let tests: Vec<_> = DECODERS + .iter() + .map(|spec| { + let absent = absent(ffmpeg, spec); + let test = absent.is_none().then(|| { + scope.spawn(move || { + let started = Instant::now(); + (test_decoder(spec), started.elapsed()) + }) + }); + (spec, absent, test) + }) + .collect(); + tests + .into_iter() + .map(|(spec, absent, test)| { + let (available, took) = match test { + None => (Err(absent.unwrap_or_default()), Duration::ZERO), + Some(handle) => handle.join().unwrap_or_else(|_| { + (Err("the self-test panicked".into()), Duration::ZERO) + }), + }; + DecoderStatus { spec, available, took } + }) + .collect() + }); + for status in &statuses { + match &status.available { + Ok(()) => tracing::info!( + decoder = status.spec.name, + ms = status.took.as_millis() as u64, + "FFmpeg decoder available" + ), + Err(e) => tracing::debug!( + decoder = status.spec.name, + ms = status.took.as_millis() as u64, + "FFmpeg decoder unusable: {e}" + ), + } + } + tracing::info!( + ms = started.elapsed().as_millis() as u64, + tested = statuses.iter().filter(|s| !s.took.is_zero()).count(), + "FFmpeg decoders probed" + ); + statuses + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::codec::{Codecs, EncoderConfig}; + + #[test] + fn decoder_table() { + for (i, spec) in DECODERS.iter().enumerate() { + assert!(DECODERS[..i].iter().all(|d| d.name != spec.name), "{} twice", spec.name); + assert_eq!(DecoderSpec::by_name(spec.name), Some(spec)); + // Hardware first within a codec, so the probe's order is the + // ladder's. + let later_hardware = + DECODERS[i..].iter().any(|d| d.codec == spec.codec && d.is_hardware()); + assert!(spec.is_hardware() || !later_hardware, "{} before hardware", spec.name); + } + assert!(DecoderSpec::by_name("h264").is_some_and(|d| !d.is_hardware())); + } + + /// The clips hold [`CLIP_FRAMES`] frames each, the first a keyframe. + #[test] + fn clips_are_complete() { + for codec in Codec::ALL { + let frames: Vec<&[u8]> = clip_frames(codec).collect(); + assert_eq!(frames.len(), CLIP_FRAMES, "{codec}"); + assert!(frames.iter().all(|f| !f.is_empty()), "{codec}"); + } + } + + /// libvpx, always built in on the desktop, decodes the VP8 and VP9 clips + /// to the test picture: the clips and [`clip_picture`] belong together. + #[cfg(feature = "vpx")] + #[test] + fn clips_match_the_test_picture() { + for codec in [Codec::Vp8, Codec::Vp9] { + let mut decoder = crate::codec::vpx::VpxDecoder::new(codec).unwrap(); + for (n, data) in clip_frames(codec).enumerate() { + let picture = decoder.decode(data).unwrap().expect("a picture per frame"); + let psnr = convert::psnr(&clip_picture(n), &picture).unwrap(); + assert!(psnr > 40.0, "{codec} frame {n}: {psnr:.1} dB"); + } + } + } + + /// Writes the self-test clips (`src/ffmpeg/clips/*.bin`) with the best + /// encoder of each codec this machine has: run again only when + /// [`clip_picture`] changes. Needs an encoder of every codec (HEVC is + /// encoded in hardware only). + #[test] + #[ignore = "writes the decoders' self-test clips"] + fn write_self_test_clips() { + let codecs = Codecs::new(); + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ffmpeg/clips"); + for codec in Codec::ALL { + // A high bitrate for a high PSNR, the keyframe dominating. + let config = + EncoderConfig { fps: 30, bitrate_bps: 2_000_000, ..EncoderConfig::default() }; + let mut encoder = codecs.new_encoder(codec, config).unwrap(); + let mut clip = Vec::new(); + let mut frames = 0; + // Hardware encoders may hold a frame or two. + for n in 0..CLIP_FRAMES + 8 { + let source = clip_picture(n.min(CLIP_FRAMES - 1)); + let source = source.with_timestamp(Duration::from_millis(33 * n as u64)); + for packet in encoder.encode(&source, n == 0).unwrap() { + if frames < CLIP_FRAMES { + let index = (packet.pts_90khz / 2970) as usize; + assert_eq!(index, frames, "{codec}: packets out of order"); + assert_eq!(packet.keyframe, frames == 0, "{codec} frame {frames}"); + clip.extend_from_slice(&(packet.data.len() as u32).to_le_bytes()); + clip.extend_from_slice(&packet.data); + frames += 1; + } + } + } + assert_eq!(frames, CLIP_FRAMES, "{codec}"); + let name = match codec { + Codec::H265 => "hevc".to_owned(), + c => c.name().to_ascii_lowercase(), + }; + std::fs::write(dir.join(format!("{name}.bin")), &clip).unwrap(); + eprintln!("{codec}: {} bytes from {}", clip.len(), encoder.backend()); + } + } +} diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 7fc088e..1afe3bc 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -393,7 +393,7 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< /// The process's VA-API device: `VOELIN_VAAPI_DEVICE`, or the first DRM /// render node. -struct Device(Ptr); +pub(super) struct Device(pub(super) Ptr); // SAFETY: an AVBufferRef of an AVHWDeviceContext, never freed; FFmpeg's // VA-API device may be used from several threads (libva locks per display). @@ -415,7 +415,7 @@ pub fn vaapi_device_path() -> Option { nodes.into_iter().next() } -fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { +pub(super) fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { static DEVICE: OnceLock> = OnceLock::new(); DEVICE .get_or_init(|| { @@ -518,7 +518,7 @@ pub(crate) fn vaapi_pool( } /// FFmpeg's recent messages, appended to an error. -fn log_suffix(context: &str) -> String { +pub(super) fn log_suffix(context: &str) -> String { let log = take_log(context); if log.is_empty() { String::new() } else { format!(" ({})", log.join("; ")) } } @@ -1618,7 +1618,7 @@ fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool { /// PCI vendor of a GPU, as `/sys/class/drm/*/device/vendor` gives it. #[cfg(target_os = "linux")] -mod vendor { +pub(super) mod vendor { pub const AMD: u32 = 0x1002; pub const NVIDIA: u32 = 0x10de; pub const INTEL: u32 = 0x8086; @@ -1628,7 +1628,7 @@ mod vendor { /// `/sys/class/drm` says nothing (a container without it, say), which is /// taken as "unknown" and skips nothing. #[cfg(target_os = "linux")] -fn drm_vendors() -> &'static [u32] { +pub(super) fn drm_vendors() -> &'static [u32] { static VENDORS: OnceLock> = OnceLock::new(); VENDORS.get_or_init(|| { let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() }; diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 087bca9..81cd66c 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -11,7 +11,7 @@ //! | 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 | +//! | `AVCodecContext.hw_frames_ctx`, `hw_device_ctx` | VA-API input frames; the device of hardware decoders | next to fields that have AVOptions, whose offsets `av_opt_find` reports: `hw_frames_ctx`, `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or `hw_frames_ctx` two fields before `max_pixels` and `hw_device_ctx` right after it (up to 60) | the neighbours' option offsets must match the layout, and both fields 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-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | //! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout | @@ -168,68 +168,74 @@ struct HwFields59 { 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 { +/// Where `hw_frames_ctx` and `hw_device_ctx` are in `AVCodecContext`, from +/// the offsets of neighbouring AVOptions, checked in a new context: the +/// frame pool of VA-API encoders, and the device hardware decoders decode +/// on. +pub fn codec_hw_fields(api: &Api) -> Result<(usize, usize), String> { // 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); + let result = locate_hw_fields(api, ctx); // SAFETY: allocated above. unsafe { (api.avcodec_free_context)(&mut ctx) }; result } -fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result { +fn locate_hw_fields(api: &Api, ctx: Ptr) -> Result<(usize, usize), String> { let offset = |name| option_offset(api, ctx, name); let flags = offset("hwaccel_flags").ok_or("no hwaccel_flags option")?; - let found = 'found: { + let (found, device) = '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); + break 'found ( + base + offset_of!(HwFieldsNew, hw_frames_ctx), + base + offset_of!(HwFieldsNew, hw_device_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 { + let (max_off, flags_off, frames_off, device_off) = if major < 60 { ( offset_of!(HwFields59, max_pixels), offset_of!(HwFields59, hwaccel_flags), offset_of!(HwFields59, hw_frames_ctx), + offset_of!(HwFields59, hw_device_ctx), ) } else { ( offset_of!(HwFields60, max_pixels), offset_of!(HwFields60, hwaccel_flags), offset_of!(HwFields60, hw_frames_ctx), + offset_of!(HwFields60, hw_device_ctx), ) }; if let Some(base) = max_pixels.checked_sub(max_off) && base + flags_off == flags { - break 'found base + frames_off; + break 'found (base + frames_off, base + device_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() { + let (frames, device_ref) = unsafe { (read::(ctx, found), read::(ctx, device)) }; + if !frames.is_null() || !device_ref.is_null() { return Err("AVCodecContext.hw_frames_ctx check failed (not NULL in a new context)".into()); } - Ok(found) + Ok((found, device)) } /// Where `sample_fmt` is in `AVCodecContext`, from the offsets of the @@ -578,6 +584,19 @@ mod tests { 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); + // `hw_device_ctx` right before `hwaccel_flags` in every layout. + assert_eq!( + offset_of!(HwFields60, hwaccel_flags) - offset_of!(HwFields60, hw_device_ctx), + 8 + ); + assert_eq!( + offset_of!(HwFields59, hwaccel_flags) - offset_of!(HwFields59, hw_device_ctx), + 8 + ); + assert_eq!( + offset_of!(HwFieldsNew, hwaccel_flags) - offset_of!(HwFieldsNew, hw_device_ctx), + 8 + ); // 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); diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 7839d11..88eefc1 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -1,6 +1,8 @@ //! 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). +//! more software encoders (x264, OpenH264, SVT-AV1, rav1e, libaom); video +//! decoders, in hardware (VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox) and +//! in software (dav1d, FFmpeg's own), see [`decoder`]. //! //! FFmpeg is never linked or shipped: [`Ffmpeg::get`] finds the system's //! (or `VOELIN_FFMPEG_DIR`'s) libavcodec and libavutil, whatever their major @@ -11,7 +13,8 @@ //! //! [`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. +//! skipped with a reason, without affecting the others; +//! [`decoder::probe`] does the same for decoders (a short clip decoded). #![allow(unsafe_code)] use std::ffi::{CStr, c_char, c_int}; @@ -20,6 +23,7 @@ use std::sync::{Mutex, OnceLock}; pub mod audio; pub mod avio; +pub mod decoder; pub mod encoder; mod gpu; mod layout; @@ -29,6 +33,7 @@ mod vpp; pub(crate) use gpu::Surface; pub use gpu::{GpuConverter, GpuLayer}; +pub use decoder::{DECODERS, DecoderSpec, DecoderStatus, FfmpegDecoder}; pub use encoder::{ BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe, }; @@ -82,6 +87,8 @@ pub struct Ffmpeg { pub(crate) frame: FrameFields, /// `AVCodecContext.hw_frames_ctx`. pub(crate) codec_hw_frames: Result, + /// `AVCodecContext.hw_device_ctx`, for hardware decoders. + pub(crate) codec_hw_device: Result, /// `AVFrame.buf[0]` / `hw_frames_ctx`. pub(crate) frame_refs: Result, /// `AVCodecContext.sample_fmt`, for the AAC encoder of RTMP output. @@ -122,7 +129,9 @@ impl Ffmpeg { drm_prime: api.pix_fmt("drm_prime"), bgr0: api.pix_fmt("bgr0"), }; - let codec_hw_frames = layout::codec_hw_frames(&api); + let hw_fields = layout::codec_hw_fields(&api); + let codec_hw_frames = hw_fields.clone().map(|(frames, _)| frames); + let codec_hw_device = hw_fields.map(|(_, device)| device); let frame_refs = layout::frame_refs(&api, yuv420p); let codec_sample_fmt = layout::codec_sample_fmt(&api); let io = libs.format_api().and_then(|format| { @@ -159,6 +168,7 @@ impl Ffmpeg { _libs: libs, frame, codec_hw_frames, + codec_hw_device, frame_refs, codec_sample_fmt, io, @@ -292,6 +302,15 @@ mod tests { if cfg!(target_pointer_width = "64") { assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs); } + // `hw_device_ctx`, where FFmpeg 9's headers put it (libavcodec 63: + // `hw_frames_ctx` 552, `hw_device_ctx` 560 on x86-64). + let (frames, device) = (ffmpeg.codec_hw_frames.clone(), ffmpeg.codec_hw_device.clone()); + // SAFETY: no arguments. + if cfg!(target_pointer_width = "64") + && unsafe { (ffmpeg.api.avcodec_version)() } >> 16 == 63 + { + assert_eq!((frames, device), (Ok(552), Ok(560))); + } } /// `AVIOContext.error` is where the headers of the installed releases diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index d409282..6a6fef3 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -226,6 +226,7 @@ api! { 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_get_pix_fmt_name(fmt: c_int) -> *const c_char; fn av_log_set_level(level: c_int); fn av_log_set_callback(callback: Option); fn av_log_format_line2( @@ -617,6 +618,17 @@ impl Api { let fmt = unsafe { (self.av_get_pix_fmt)(name.as_ptr()) }; (fmt >= 0).then_some(fmt) } + + /// The name of pixel format `fmt` (for messages). + pub fn pix_fmt_name(&self, fmt: c_int) -> String { + // SAFETY: returns a static string, or NULL for an unknown format. + let name = unsafe { (self.av_get_pix_fmt_name)(fmt) }; + if name.is_null() { + return format!("pixel format {fmt}"); + } + // SAFETY: a NUL-terminated static string. + unsafe { CStr::from_ptr(name) }.to_string_lossy().into_owned() + } } #[cfg(test)] diff --git a/crates/voelin-media/src/frame.rs b/crates/voelin-media/src/frame.rs index b329bd2..b029433 100644 --- a/crates/voelin-media/src/frame.rs +++ b/crates/voelin-media/src/frame.rs @@ -89,11 +89,19 @@ impl<'a> PlaneRef<'a> { /// A tightly packed copy of `width` x `rows` bytes. fn to_plane(self, width: usize, rows: usize) -> Plane { - let mut data = Vec::with_capacity(width * rows); + let mut plane = Plane::new(Vec::with_capacity(width * rows), width); + self.copy_into(&mut plane, width, rows); + plane + } + + /// As [`to_plane`](Self::to_plane), into `dst`'s buffer (which only + /// grows). + fn copy_into(self, dst: &mut Plane, width: usize, rows: usize) { + dst.data.clear(); for y in 0..rows { - data.extend_from_slice(self.row(y, width)); + dst.data.extend_from_slice(self.row(y, width)); } - Plane::new(data, width) + dst.stride = width; } } @@ -179,6 +187,33 @@ impl FrameRef<'_> { }; VideoFrame { width: self.width, height: self.height, timestamp: self.timestamp, data } } + + /// As [`to_frame`](Self::to_frame), into `out`: its buffers are reused + /// when it has this pixel format, so copying frames of one size into the + /// same `out` allocates nothing after the first. + pub fn copy_to(&self, out: &mut VideoFrame) { + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + match (self.pixels, &mut out.data) { + (PixelsRef::I420 { y, u, v }, FrameData::I420 { y: oy, u: ou, v: ov }) => { + y.copy_into(oy, w, h); + u.copy_into(ou, cw, ch); + v.copy_into(ov, cw, ch); + } + (PixelsRef::Nv12 { y, uv }, FrameData::Nv12 { y: oy, uv: ouv }) => { + y.copy_into(oy, w, h); + uv.copy_into(ouv, cw * 2, ch); + } + (PixelsRef::Bgra(p), FrameData::Bgra(o)) | (PixelsRef::Rgba(p), FrameData::Rgba(o)) => { + p.copy_into(o, w * 4, h); + } + _ => { + *out = self.to_frame(); + return; + } + } + (out.width, out.height, out.timestamp) = (self.width, self.height, self.timestamp); + } } /// The pixels of a [`VideoFrame`]. @@ -395,4 +430,25 @@ mod tests { assert!(short.validate().is_err()); assert_eq!(VideoFrame::black_i420(5, 3).view().format(), PixelFormat::I420); } + + #[test] + fn copies_reuse_the_destination() { + let source = VideoFrame::black_i420(33, 17).with_timestamp(Duration::from_millis(7)); + let mut out = VideoFrame::from_bgra(1, 1, 4, vec![0; 4]).unwrap(); + source.view().copy_to(&mut out); + assert_eq!(out, source, "another format: replaced"); + let FrameData::I420 { y, .. } = &out.data else { panic!("not I420") }; + let buffer = y.data.as_ptr(); + let smaller = VideoFrame::black_i420(20, 10); + smaller.view().copy_to(&mut out); + assert_eq!(out, smaller); + let FrameData::I420 { y, .. } = &out.data else { panic!("not I420") }; + assert_eq!(y.data.as_ptr(), buffer, "the same buffer"); + let nv12 = FrameRef { + pixels: PixelsRef::Nv12 { y: PlaneRef::new(&[1; 4], 2), uv: PlaneRef::new(&[2; 2], 2) }, + ..VideoFrame::black_i420(2, 2).view() + }; + nv12.copy_to(&mut out); + assert_eq!(out, nv12.to_frame()); + } } diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index b74516b..dbe0fc2 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -44,9 +44,9 @@ pub mod workers; pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId}; pub use codec::{ - BackendChoice, Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, - EncoderConfig, EncoderInfo, EncoderPreference, EncoderReport, H264Profile, VideoDecoder, - VideoEncoder, + BackendChoice, Codec, Codecs, ContentHint, DecoderBackend, DecoderInfo, DecoderPreference, + EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, EncoderInfo, EncoderPreference, + EncoderReport, H264Profile, VideoDecoder, VideoEncoder, }; pub use frame::{ AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame, diff --git a/crates/voelin-media/tests/ffmpeg_decoders.rs b/crates/voelin-media/tests/ffmpeg_decoders.rs new file mode 100644 index 0000000..85199e6 --- /dev/null +++ b/crates/voelin-media/tests/ffmpeg_decoders.rs @@ -0,0 +1,241 @@ +//! Decoders through the system's FFmpeg (loaded at runtime): the probe, the +//! ladder of each codec, every encoder of this machine against every decoder +//! of its codec, VA-API decoding on the GPU, and the codecs a viewer accepts +//! with and without FFmpeg. +//! +//! Skipped without FFmpeg. Hardware decoders need their GPU and driver; on a +//! machine without them the self-test reports why and they are skipped. +#![cfg(feature = "ffmpeg")] + +use std::time::{Duration, Instant}; + +use voelin_media::capture::synthetic::SyntheticScreen; +use voelin_media::ffmpeg::{DECODERS, DecoderSpec, Ffmpeg, FfmpegDecoder, decoder}; +use voelin_media::{ + Codec, Codecs, DecoderBackend, EncodedFrame, EncoderConfig, EncoderPreference, VideoDecoder, + VideoFrame, convert, +}; + +fn ffmpeg() -> Option<&'static Ffmpeg> { + match Ffmpeg::get() { + Ok(f) => Some(f), + Err(e) => { + eprintln!("FFmpeg not available ({e}), skipped"); + None + } + } +} + +fn available(name: &str) -> bool { + decoder::probe().iter().any(|s| s.spec.name == name && s.available.is_ok()) +} + +#[test] +fn probe_reports_every_decoder() { + if ffmpeg().is_none() { + return; + } + let statuses = decoder::probe(); + assert_eq!(statuses.len(), DECODERS.len()); + for status in statuses { + eprintln!( + "{:>18}: {:?} ({} ms)", + status.spec.name, + status.available, + status.took.as_millis() + ); + if let Err(reason) = &status.available { + assert!(!reason.is_empty()); + } + } + // The report lists them with the built-in ones, ranked by the ladder. + let codecs = Codecs::new(); + let report = codecs.report(); + assert!(report.decoders.iter().any(|d| d.name == "libvpx")); + for status in statuses { + let info = report.decoders.iter().find(|d| d.name == status.spec.name).unwrap(); + assert_eq!(info.status, status.available); + assert_eq!(info.rank.is_some(), status.available.is_ok(), "{}", status.spec.name); + } + for codec in Codec::ALL { + let ladder: Vec = + codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect(); + eprintln!("{codec}: {}", ladder.join(" > ")); + } + eprintln!("viewer accepts: {:?}", codecs.decoders()); + // FFmpeg's software decoders are in every build: a viewer takes every + // codec but AV1 (which needs dav1d or libaom in FFmpeg) with them. + for (name, codec) in [("h264", Codec::H264), ("hevc", Codec::H265), ("vp9", Codec::Vp9)] { + if available(name) { + assert!(codecs.decoders().contains(&codec), "{codec}"); + } + } +} + +/// `frames` of the moving test pattern at `w` x `h` through `encoder`'s +/// best backend (`backend` named first), with a keyframe at the start. +fn encode(codec: Codec, backend: &str, w: u32, h: u32, frames: u64) -> Vec<(EncodedFrame, u64)> { + let codecs = Codecs::new(); + let screen = SyntheticScreen::new(w, h); + let config = EncoderConfig { fps: 30, bitrate_bps: 2_000_000, ..EncoderConfig::default() }; + let preference = EncoderPreference { hardware: true, backend: backend.parse().unwrap() }; + let mut encoder = codecs.new_encoder_preferring(codec, config, &preference).unwrap(); + let mut out = Vec::new(); + let mut sources = Vec::new(); + for n in 0..frames + 8 { + let frame = screen.frame(n.min(frames - 1), 30); + let frame = frame.with_timestamp(Duration::from_millis(33 * n)); + sources.push(frame.pts_90khz()); + for f in encoder.encode(&frame, n == 0).unwrap() { + let index = sources.iter().position(|&p| p == f.pts_90khz).unwrap() as u64; + if out.len() < frames as usize { + out.push((f, index.min(frames - 1))); + } + } + } + out +} + +/// Decodes `stream` with `decoder`: the PSNR of every picture against the +/// pattern frame it came from, or why it failed. +fn decode( + decoder: &mut dyn VideoDecoder, + stream: &[(EncodedFrame, u64)], + screen: &SyntheticScreen, +) -> Result<(usize, f64), String> { + let mut picture = VideoFrame::black_i420(0, 0); + let mut worst = f64::INFINITY; + let mut decoded = 0; + for (frame, index) in stream { + if decoder.decode_into(&frame.data, &mut picture).map_err(|e| e.to_string())? { + let source = screen.frame(*index, 30); + let source = if (picture.width, picture.height) == (source.width, source.height) { + source + } else { + // Cropped to the encoder's alignment (AV1 in hardware). + let mut view = source.view(); + (view.width, view.height) = (picture.width, picture.height); + view.to_frame() + }; + worst = worst.min(convert::psnr(&source, &picture).map_err(|e| e.to_string())?); + decoded += 1; + } + } + Ok((decoded, worst)) +} + +/// Every encoder this machine has, through every decoder of its codec +/// (hardware, FFmpeg's software ones, the built-in ones): every frame +/// decodes, PSNR above 28 dB against the pattern, as `tests/ffmpeg.rs` +/// checks the encoders. +#[test] +fn every_encoder_decodes_with_every_decoder() { + if ffmpeg().is_none() { + return; + } + let codecs = Codecs::new(); + let (w, h) = (320, 240); + let screen = SyntheticScreen::new(w, h); + let mut table = Vec::new(); + let mut failed = Vec::new(); + for (codec, encoder) in codecs.encoders() { + let stream = encode(codec, encoder.name(), w, h, 12); + for backend in codecs.decoders_for(codec) { + let mut decoder = codecs.new_decoder_with(codec, backend).unwrap(); + match decode(&mut *decoder, &stream, &screen) { + Ok((decoded, psnr)) if decoded == stream.len() && psnr > 28.0 => { + table.push(format!("{codec:<4} {encoder:<12} -> {backend:<12} {psnr:5.1} dB")); + } + Ok((decoded, psnr)) => failed.push(format!( + "{encoder} -> {backend}: {decoded} of {} pictures, PSNR {psnr:.1} dB", + stream.len() + )), + Err(e) => failed.push(format!("{encoder} -> {backend}: {e}")), + } + } + } + eprintln!("{}", table.join("\n")); + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// The VA-API decoders that passed their self-test decode on the GPU: every +/// picture of a stream comes out of a VA-API surface, none from FFmpeg's +/// software path; at 1920x1080 too (1088 coded rows, cropped). Skipped +/// where no VA-API decoder works. +#[cfg(target_os = "linux")] +#[test] +fn vaapi_decodes_on_the_gpu() { + if ffmpeg().is_none() { + return; + } + let names: Vec<&str> = + DECODERS.iter().map(|d| d.name).filter(|n| n.ends_with("_vaapi") && available(n)).collect(); + if names.is_empty() { + eprintln!("no usable VA-API decoder, skipped"); + return; + } + let codecs = Codecs::new(); + for name in &names { + let spec = DecoderSpec::by_name(name).unwrap(); + if codecs.encoders().iter().all(|(c, _)| *c != spec.codec) { + eprintln!("{name}: nothing here encodes {}, skipped", spec.codec); + continue; + } + for (w, h) in [(320, 240), (1920, 1080)] { + let stream = encode(spec.codec, "auto", w, h, 10); + let mut decoder = FfmpegDecoder::new(spec).unwrap(); + let screen = SyntheticScreen::new(w, h); + let started = Instant::now(); + let (decoded, psnr) = decode(&mut decoder, &stream, &screen).unwrap(); + eprintln!( + "{name} {w}x{h}: {decoded} pictures, {} on the GPU, PSNR {psnr:.1} dB, {:.1} ms each", + decoder.gpu_pictures(), + started.elapsed().as_secs_f64() * 1000.0 / decoded.max(1) as f64 + ); + assert_eq!(decoded, stream.len(), "{name}"); + assert_eq!(decoder.gpu_pictures(), decoded as u64, "{name}: not on the GPU"); + assert_eq!(decoder.cpu_pictures(), 0, "{name}"); + assert!(psnr > 28.0, "{name}: {psnr:.1} dB"); + } + } +} + +/// What a viewer accepts with FFmpeg and without (`VOELIN_FFMPEG=0`, in a +/// child process: FFmpeg is loaded once per process). +#[test] +fn decoders_with_and_without_ffmpeg() { + let without = std::env::var("VOELIN_FFMPEG").is_ok_and(|v| v == "0"); + let codecs = Codecs::new(); + let decoders = codecs.decoders(); + eprintln!("VOELIN_FFMPEG={without}: {decoders:?}"); + if without { + // Only the built-in decoders: libvpx (and dav1d with `av1`). + assert!(Ffmpeg::get().is_err()); + assert!(decoder::probe().is_empty()); + assert!(!decoders.contains(&Codec::H265) && !decoders.contains(&Codec::H264)); + assert_eq!(decoders.contains(&Codec::Av1), cfg!(feature = "av1")); + #[cfg(feature = "vpx")] + assert_eq!(decoders[decoders.len() - 2..], [Codec::Vp9, Codec::Vp8]); + let ladder = codecs.decoders_for(Codec::Vp9); + assert!(ladder.iter().all(|b| !matches!(b, DecoderBackend::Ffmpeg(_))), "{ladder:?}"); + return; + } + if ffmpeg().is_some() { + // The software decoders of every FFmpeg build. + for codec in [Codec::H265, Codec::Vp9, Codec::H264, Codec::Vp8] { + assert!(decoders.contains(&codec), "{codec}: {decoders:?}"); + } + // The viewer's order: best first. + let order: Vec = decoders + .iter() + .map(|c| voelin_media::codec::VIEWER_PREFERENCE.iter().position(|p| p == c).unwrap()) + .collect(); + assert!(order.windows(2).all(|w| w[0] < w[1]), "{decoders:?}"); + } + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "decoders_with_and_without_ffmpeg", "--nocapture"]) + .env("VOELIN_FFMPEG", "0") + .status() + .unwrap(); + assert!(child.success(), "without FFmpeg: {child}"); +} diff --git a/crates/voelin-media/tests/openh264.rs b/crates/voelin-media/tests/openh264.rs index 20b4c51..2ef097f 100644 --- a/crates/voelin-media/tests/openh264.rs +++ b/crates/voelin-media/tests/openh264.rs @@ -53,7 +53,8 @@ fn sps_profile(data: &[u8]) -> Option { fn roundtrip(library: OpenH264) { let codecs = Codecs::builtin().with_openh264(library.clone()); - assert_eq!(codecs.decoders().last(), Some(&Codec::H264)); + assert!(codecs.decoders().contains(&Codec::H264)); + assert_eq!(codecs.decoders_for(Codec::H264), [voelin_media::DecoderBackend::OpenH264]); assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264))); let screen = SyntheticScreen::new(320, 240); From 289e7d4e6bac428cbffaa85de27c49cdc10ac581 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:02:48 +0300 Subject: [PATCH 2/9] Fall back to the next decoder at runtime; recover from losses A watched stream now decodes with the best decoder of its codec and, when it fails, with the next of the codec's ladder, without ending the watch: three failures in a row (errors, or ten frames without a picture) replace it, the keyframe that failed starts the next one at once, and otherwise a keyframe is asked for. Each switch is logged with its reason, and DecodeStats tells the decoder in use. The official client's H.264 has B-frames and rare keyframes, and the pipeline dropped every frame after a loss or an error until the next keyframe, which such an encoder seldom sends. Decoders that conceal what a loss leaves missing (FFmpeg's H.264 and HEVC) now go on decoding while a keyframe is asked for; the others still skip to it. Whenever one is wanted it is asked for again every half second until it comes, also while no frame arrives, instead of once per skipped frame. Pictures come from a small pool and go to the callback as Arc: decoders write into a free one (decode_into), and a consumer that converts and drops each picture, as the app does, costs no allocations. Settings stream.hardware_decoding and stream.decoder_backend choose the decoders like the encoder settings (decoder_preference); the app applies them when they change, to streams watched from then on. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 380 +++++++++++++++++++++++++---- crates/voelin-core/src/settings.rs | 25 +- crates/voelin-ui/src/app.rs | 10 +- crates/voelin-ui/src/video.rs | 40 ++- tools/voelinctl/src/stream.rs | 4 +- 5 files changed, 404 insertions(+), 55 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 3e56420..711f308 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -16,8 +16,11 @@ //! sink allows. [`Streamer::reconfigure`] changes frame rate, bitrate, //! codec, layers and audio sources while streaming. //! - [`VideoPipeline`] decodes the video of a watched stream on its own -//! thread and hands every picture to a callback. After lost frames or -//! decoder errors it skips to the next keyframe and asks for one. +//! thread with the best decoder of its codec, falling back to the next +//! one when a decoder fails, and hands every picture to a callback. After +//! lost frames it asks for a keyframe; decoders that conceal what is +//! missing (FFmpeg's H.264 and HEVC) go on decoding meanwhile, the others +//! skip to it. //! - [`Viewer`] is a [`VideoPipeline`] fed from [`Engine::subscribe_frames`]. //! The stream's audio needs nothing here: the session plays it //! ([`Command::SetStreamVolume`]). @@ -59,7 +62,7 @@ use voelin_media::{ Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder, VideoFrame, }; -pub use voelin_media::{EncoderBackend, EncoderPreference}; +pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference}; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, @@ -79,6 +82,17 @@ const OPUS_BITRATE: i32 = 128_000; pub const MAX_QUEUED: usize = 30; /// Keyframe requests while waiting for one are at least this far apart. const KEYFRAME_RETRY: Duration = Duration::from_millis(500); +/// Failures in a row (errors, or [`FRAMES_WITHOUT_PICTURE`] frames that +/// gave none) after which a decoder is replaced by the next one of its +/// codec's ladder. +const DECODER_FAILURES: u32 = 3; +/// Frames a decoder may take without giving a picture before that counts +/// as a failure (and a keyframe is asked for): decoders of streams with +/// B-frames hold a few. +const FRAMES_WITHOUT_PICTURE: u32 = 10; +/// Decoded pictures a [`VideoPipeline`] recycles; while the consumer holds +/// them all, more are made. +const PICTURE_POOL: usize = 4; /// The decoding rates of [`DecodeStats`] cover at least this long. const RATE_WINDOW: Duration = Duration::from_millis(500); @@ -188,6 +202,16 @@ pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media: } } +/// The decoder preference of the settings `stream.hardware_decoding` and +/// `stream.decoder_backend` (for `Codecs::with_decoder_preference`). +pub fn decoder_preference(settings: &crate::settings::Settings) -> DecoderPreference { + use crate::settings::{STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING}; + DecoderPreference { + hardware: settings.get(&STREAM_HARDWARE_DECODING), + backend: settings.get(&STREAM_DECODER_BACKEND).parse().unwrap_or_default(), + } +} + /// The stream codec: `configured` if we can encode it, else the first codec /// of the encoder preference (hardware first when enabled; VP8 through /// libvpx without hardware) that every TeamSpeak client decodes @@ -2422,6 +2446,9 @@ pub struct DecodeStats { pub skipped: u64, pub keyframe_requests: u64, pub codec: Option, + /// The decoder in use ([`Codecs::decoders_for`]: the first of the + /// codec's that works). + pub decoder: Option, pub width: u32, pub height: u32, /// The last error (no decoder for the codec, decoding failed). @@ -2500,12 +2527,14 @@ pub struct VideoPipeline { } impl VideoPipeline { - /// `on_frame` gets every decoded picture on the decoding thread; - /// `request_keyframe` is called when the decoder needs one (at most - /// every half second). + /// `on_frame` gets every decoded picture on the decoding thread, from a + /// pool: a picture comes back to it once the consumer drops it, so a + /// consumer that converts and drops each one costs no allocations. + /// `request_keyframe` is called when the decoder needs one (every half + /// second until one comes). pub fn new( codecs: Arc, - on_frame: impl FnMut(VideoFrame) + Send + 'static, + on_frame: impl FnMut(Arc) + Send + 'static, request_keyframe: impl Fn() + Send + 'static, ) -> Self { let queue = Arc::new(DecodeQueue::default()); @@ -2556,16 +2585,100 @@ impl Drop for VideoPipeline { } } +/// The decoder of a [`VideoPipeline`] and the rest of its codec's ladder. +struct ActiveDecoder { + codec: Codec, + backend: DecoderBackend, + decoder: Box, + /// The codec's other decoders, best first, still to try. + rest: VecDeque, + /// Failures since the last picture. + failures: u32, + /// Frames taken since the last picture or failure. + without_picture: u32, +} + +impl ActiveDecoder { + /// The first decoder of `codec`'s ladder that opens. + fn start(codecs: &Codecs, codec: Codec) -> Result { + let mut rest: VecDeque = codecs.decoders_for(codec).into(); + let (backend, decoder) = Self::open_next(codecs, codec, &mut rest).map_err(|e| { + e.unwrap_or_else(|| { + codecs + .check_decoder(codec) + .err() + .map_or_else(|| format!("no decoder for {codec}"), |e| e.to_string()) + }) + })?; + Ok(Self { codec, backend, decoder, rest, failures: 0, without_picture: 0 }) + } + + /// The next decoder of `rest` that opens; the last error if none did. + fn open_next( + codecs: &Codecs, + codec: Codec, + rest: &mut VecDeque, + ) -> Result<(DecoderBackend, Box), Option> { + let mut error = None; + while let Some(backend) = rest.pop_front() { + match codecs.new_decoder_with(codec, backend) { + Ok(decoder) => return Ok((backend, decoder)), + Err(e) => { + warn!(%codec, %backend, "the decoder does not open: {e}"); + error = Some(e.to_string()); + } + } + } + Err(error) + } + + /// Replace the decoder by the next one of the ladder, after `reason`; + /// `false` (keeping this one) if there is none. + fn fall_back(&mut self, codecs: &Codecs, reason: &str) -> bool { + (self.failures, self.without_picture) = (0, 0); + let (codec, failed) = (self.codec, self.backend); + match Self::open_next(codecs, codec, &mut self.rest) { + Ok((backend, decoder)) => { + warn!(%codec, %failed, %backend, "the decoder failed ({reason}); trying the next"); + (self.backend, self.decoder) = (backend, decoder); + true + } + Err(_) => { + warn!(%codec, %failed, "the decoder fails ({reason}), and no other is left"); + false + } + } + } +} + +/// A pooled picture nobody else holds, to decode into: one the consumer +/// gave back, else a new one (when the pool is full, the oldest is left to +/// whoever holds it). +fn free_picture(pictures: &mut Vec>) -> usize { + if let Some(i) = pictures.iter_mut().position(|p| Arc::get_mut(p).is_some()) { + return i; + } + if pictures.len() >= PICTURE_POOL { + pictures.remove(0); + } + pictures.push(Arc::new(VideoFrame::black_i420(0, 0))); + pictures.len() - 1 +} + fn decode_loop( queue: &DecodeQueue, codecs: &Codecs, - mut on_frame: impl FnMut(VideoFrame), + mut on_frame: impl FnMut(Arc), request_keyframe: impl Fn(), ) { - let mut decoder: Option<(Codec, Box)> = None; + let mut active: Option = None; // Start at a keyframe; the streamer sends one when a viewer connects. let mut waiting = true; + // A keyframe is wanted (after a loss, or an error of a decoder that goes + // on), asked for until one decodes. + let mut wanted = false; let mut last_request: Option = None; + let mut pictures: Vec> = Vec::with_capacity(PICTURE_POOL); let mut request = |stats: &Mutex| { if last_request.is_none_or(|t| t.elapsed() >= KEYFRAME_RETRY) { last_request = Some(Instant::now()); @@ -2575,19 +2688,22 @@ fn decode_loop( }; let set_error = |message: String| lock(&queue.stats).error = Some(message); loop { - let (frame, lost) = { + let next = { let mut state = lock(&queue.state); - loop { - if state.closed { - return; - } - if let Some(frame) = state.frames.pop_front() { - break (frame, std::mem::take(&mut state.lost)); - } + if state.frames.is_empty() && !state.closed { state = queue.cond.wait_timeout(state, POLL).unwrap_or_else(PoisonError::into_inner).0; } + if state.closed { + return; + } + state.frames.pop_front().map(|frame| (frame, std::mem::take(&mut state.lost))) }; + // Asked for again while none comes, even while no frame does. + if (waiting || wanted) && active.is_some() { + request(&queue.stats); + } + let Some((frame, lost)) = next else { continue }; let codec = match Codec::try_from(frame.codec) { Ok(codec) => codec, Err(e) => { @@ -2595,51 +2711,95 @@ fn decode_loop( continue; } }; - if decoder.as_ref().is_none_or(|(c, _)| *c != codec) { - match codecs.new_decoder(codec) { - Ok(d) => { - decoder = Some((codec, d)); + if active.as_ref().is_none_or(|a| a.codec != codec) { + match ActiveDecoder::start(codecs, codec) { + Ok(started) => { + let mut stats = lock(&queue.stats); + (stats.codec, stats.decoder) = (Some(codec), Some(started.backend)); + drop(stats); + active = Some(started); waiting = true; - lock(&queue.stats).codec = Some(codec); } Err(e) => { - if decoder.is_some() || lock(&queue.stats).error.is_none() { + if active.is_some() || lock(&queue.stats).error.is_none() { warn!("no decoder for the stream: {e}"); } - decoder = None; - set_error(e.to_string()); + active = None; + set_error(e); continue; } } } + let Some(dec) = &mut active else { continue }; if lost || !frame.contiguous { - waiting = true; + // A decoder that conceals the loss goes on; the others would + // fail, or show garbage, until a keyframe. + if dec.decoder.conceals_errors() { + wanted = true; + } else { + waiting = true; + } } + let keyframe = is_keyframe(codec, &frame.data); if waiting { - if !is_keyframe(codec, &frame.data) { + if !keyframe { lock(&queue.stats).skipped += 1; request(&queue.stats); continue; } waiting = false; } - let Some((_, dec)) = &mut decoder else { continue }; - match dec.decode(&frame.data) { - Ok(Some(picture)) => { - { - let mut stats = lock(&queue.stats); - stats.decoded += 1; - (stats.width, stats.height) = (picture.width, picture.height); + loop { + let slot = free_picture(&mut pictures); + let picture = Arc::get_mut(&mut pictures[slot]).expect("a free picture"); + let failure = match dec.decoder.decode_into(&frame.data, picture) { + Ok(true) => { + (dec.failures, dec.without_picture) = (0, 0); + wanted &= !keyframe; + { + let mut stats = lock(&queue.stats); + stats.decoded += 1; + (stats.width, stats.height) = (picture.width, picture.height); + } + on_frame(pictures[slot].clone()); + None } - on_frame(picture); + Ok(false) => { + // Decoders with a delay (B-frames) give it a few frames + // later; one that gives nothing gets keyframes to try. + dec.without_picture += 1; + (dec.without_picture >= FRAMES_WITHOUT_PICTURE).then(|| { + dec.without_picture = 0; + wanted = true; + request(&queue.stats); + format!("no picture from {FRAMES_WITHOUT_PICTURE} frames") + }) + } + Err(e) => { + debug!("decoding failed: {e}"); + set_error(e.to_string()); + if dec.decoder.conceals_errors() { + wanted = true; + } else { + waiting = true; + } + request(&queue.stats); + Some(e.to_string()) + } + }; + let Some(reason) = failure else { break }; + dec.failures += 1; + if dec.failures < DECODER_FAILURES || !dec.fall_back(codecs, &reason) { + break; } - Ok(None) => {} - Err(e) => { - debug!("decoding failed: {e}"); - set_error(e.to_string()); + lock(&queue.stats).decoder = Some(dec.backend); + if !keyframe { waiting = true; request(&queue.stats); + break; } + // The keyframe that failed starts the next decoder at once. + waiting = false; } } } @@ -2658,7 +2818,7 @@ impl Viewer { session: SessionId, stream_id: &str, codecs: Arc, - on_frame: impl FnMut(VideoFrame) + Send + 'static, + on_frame: impl FnMut(Arc) + Send + 'static, ) -> Self { let request = { let engine = engine.clone(); @@ -2775,7 +2935,7 @@ impl LocalPreview { pub async fn start( codecs: Arc, mut config: StreamerConfig, - on_frame: impl FnMut(VideoFrame) + Send + 'static, + on_frame: impl FnMut(Arc) + Send + 'static, ) -> Result { // The audio would go nowhere. config.audio = false; @@ -3044,6 +3204,144 @@ mod tests { assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}"); } + /// A VP8 decoder for the pipeline tests: fails (with errors, or giving + /// no picture), or gives a 2x2 picture per frame; conceals losses or not. + #[derive(Clone, Copy)] + struct FakeDecoder { + errors: bool, + pictures: bool, + conceals: bool, + } + + impl voelin_media::VideoDecoder for FakeDecoder { + fn codec(&self) -> Codec { + Codec::Vp8 + } + + fn decode(&mut self, _: &[u8]) -> voelin_media::Result> { + if self.errors { + let message = "made to fail".into(); + return Err(voelin_media::Error::Decoder { codec: Codec::Vp8, message }); + } + Ok(self.pictures.then(|| VideoFrame::black_i420(2, 2))) + } + + fn conceals_errors(&self) -> bool { + self.conceals + } + } + + impl voelin_media::codec::hw::DecoderFactory for FakeDecoder { + fn backend(&self) -> DecoderBackend { + DecoderBackend::Hardware("fake") + } + + fn codec(&self) -> Codec { + Codec::Vp8 + } + + fn api(&self) -> &'static str { + "test" + } + + fn is_hardware(&self) -> bool { + true + } + + fn create(&self) -> voelin_media::Result> { + Ok(Box::new(*self)) + } + } + + /// A decoder that fails, with errors or by giving no picture from + /// several keyframes, is replaced by the next of its codec's ladder + /// (libvpx here) without ending the stream: pictures go on. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn a_failing_decoder_is_replaced_by_the_next() { + for errors in [true, false] { + let fake = FakeDecoder { errors, pictures: false, conceals: false }; + let codecs = Arc::new(Codecs::builtin().with_decoder(Arc::new(fake))); + assert_eq!(codecs.decoders_for(Codec::Vp8)[0], DecoderBackend::Hardware("fake")); + assert_eq!(codecs.decoders_for(Codec::Vp8).last(), Some(&DecoderBackend::Libvpx)); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (320, 240), + ..StreamerConfig::default() + }; + let (tx, rx) = std_mpsc::channel(); + let preview = LocalPreview::start(codecs, config, move |picture| { + let _ = tx.send(picture); + }) + .await + .unwrap(); + for _ in 0..10 { + let picture = rx.recv_timeout(Duration::from_secs(10)).expect("no picture"); + assert_eq!((picture.width, picture.height), (320, 240)); + } + let stats = preview.stats(); + assert_eq!(stats.decoder, Some(DecoderBackend::Libvpx), "errors {errors}: {stats:?}"); + assert!(stats.keyframe_requests > 0, "{stats:?}"); + } + } + + /// After a lost frame a decoder that conceals the loss goes on decoding + /// while a keyframe is asked for, again every half second until one + /// comes; one that does not skips to the keyframe. + #[test] + fn losses_ask_for_keyframes_until_one_comes() { + for conceals in [true, false] { + let fake = FakeDecoder { errors: false, pictures: true, conceals }; + let codecs = Arc::new(Codecs::builtin().with_decoder(Arc::new(fake))); + let (tx, pictures) = std_mpsc::channel(); + let requests = Arc::new(AtomicU32::new(0)); + let pipeline = VideoPipeline::new( + codecs, + move |_| { + let _ = tx.send(()); + }, + { + let requests = requests.clone(); + move || { + requests.fetch_add(1, Ordering::Relaxed); + } + }, + ); + let frame = |keyframe: bool, contiguous: bool| MediaFrame { + kind: MediaKind::Video, + codec: voelin_stream::Codec::Vp8, + time: MediaTime::new(0, Frequency::NINETY_KHZ), + network_time: Instant::now(), + contiguous, + // VP8's frame tag: bit 0 clear on keyframes. + data: Arc::from(if keyframe { &[0x10_u8, 0][..] } else { &[0x11, 0][..] }), + }; + let got = + |n: usize| (0..n).all(|_| pictures.recv_timeout(Duration::from_secs(2)).is_ok()); + pipeline.push(frame(true, true)); + pipeline.push(frame(false, true)); + assert!(got(2), "conceals {conceals}"); + pipeline.push(frame(false, false)); + pipeline.push(frame(false, true)); + if conceals { + assert!(got(2), "decoding goes on"); + } else { + assert!(pictures.recv_timeout(Duration::from_millis(300)).is_err(), "skipped"); + } + std::thread::sleep(Duration::from_millis(1200)); + let asked = requests.load(Ordering::Relaxed); + assert!(asked >= 2, "conceals {conceals}: {asked} requests"); + pipeline.push(frame(true, true)); + assert!(got(1), "the keyframe decodes"); + let asked = requests.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(700)); + assert_eq!(requests.load(Ordering::Relaxed), asked, "no more requests"); + let stats = pipeline.stats(); + assert_eq!(stats.skipped, if conceals { 0 } else { 2 }, "{stats:?}"); + assert_eq!(stats.decoder, Some(DecoderBackend::Hardware("fake"))); + } + } + fn layer(id: LayerId, scale: f32, max_fps: Option, bitrate: u64) -> LayerSpec { LayerSpec { id, scale, max_fps, ..LayerSpec::single(bitrate) } } diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index eb2b7ba..cc00841 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1031,14 +1031,31 @@ pub static STREAM_SRTP_PROFILES: Key> = Key::new( ) .validated(valid_srtp); -/// Use hardware video encoders and decoders where available. +/// Use hardware video encoders where available. pub static STREAM_HARDWARE_ACCELERATION: Key = Key::new( "stream.hardware_acceleration", Kind::Bool, - "Use hardware video encoders and decoders where available.", + "Use hardware video encoders where available.", || true, ); +/// Use hardware video decoders where available. +pub static STREAM_HARDWARE_DECODING: Key = Key::new( + "stream.hardware_decoding", + Kind::Bool, + "Use hardware video decoders where available.", + || true, +); + +/// Video decoder: `auto`, `software`, or the name of a decoder backend. +pub static STREAM_DECODER_BACKEND: Key = Key::new( + "stream.decoder_backend", + Kind::Text { suggestions: &["auto", "software"] }, + "Video decoder: auto, software, or a decoder's name.", + || "auto".into(), +) +.validated(not_empty); + /// Who may watch our stream without being asked. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -1282,6 +1299,8 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> { &STREAM_ENCODER_BACKEND, &STREAM_SRTP_PROFILES, &STREAM_HARDWARE_ACCELERATION, + &STREAM_HARDWARE_DECODING, + &STREAM_DECODER_BACKEND, &STREAM_PERMISSIONS, &CHAT_STORE_HISTORY, &CHAT_HISTORY_PAGE, @@ -1352,6 +1371,8 @@ mod tests { ); assert!(s.get(&STREAM_HARDWARE_ACCELERATION)); assert_eq!(s.get(&STREAM_ENCODER_BACKEND), "auto"); + assert!(s.get(&STREAM_HARDWARE_DECODING)); + assert_eq!(s.get(&STREAM_DECODER_BACKEND), "auto"); assert!(s.get(&CHAT_STORE_HISTORY)); assert_eq!(s.get(&CHAT_HISTORY_PAGE), 100); assert_eq!(s.get(&CHAT_DEDUPE_TOLERANCE_MS), 5000); diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 113f858..056ef6c 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -17,7 +17,10 @@ use anyhow::{Context, Result}; use slint::{ComponentHandle, ModelRc, VecModel}; use tokio::runtime::Runtime; use tracing::warn; -use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings}; +use voelin_core::media::decoder_preference; +use voelin_core::settings::{ + AUDIO, CRASH_REPORTS, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings, +}; use voelin_core::stream::StreamInfo; use voelin_core::{ AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState, @@ -559,7 +562,8 @@ pub fn run(options: RunOptions) -> Result<()> { if settings.global_ptt { ptt.set(Some(settings.ptt_key.clone())); } - let video = Video::new(&dir, settings.openh264); + let mut video = Video::new(&dir, settings.openh264); + video.set_decoder_preference(decoder_preference(&prefs)); let switches = crate::dev::Switches::from_env(); let app = App { ui: ui.as_weak(), @@ -730,6 +734,8 @@ impl App { self.playback = self.prefs.get(&CLIENT_PLAYBACK); } else if appearance_keys().iter().any(|k| k.name() == key) { self.apply_appearance(); + } else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() { + self.video.set_decoder_preference(decoder_preference(&self.prefs)); } } diff --git a/crates/voelin-ui/src/video.rs b/crates/voelin-ui/src/video.rs index 8ff4c5d..a767c2f 100644 --- a/crates/voelin-ui/src/video.rs +++ b/crates/voelin-ui/src/video.rs @@ -13,8 +13,8 @@ use tracing::warn; use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId}; use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert}; use voelin_core::media::{ - self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig, - Viewer, peer_config, preferred_codec, stream_codec, + self, AudioSourceSpec, DecoderPreference, EncoderPreference, Latest, LocalPreview, Streamer, + StreamerConfig, Viewer, peer_config, preferred_codec, stream_codec, }; use voelin_core::stream::{LayerSpec, PeerConfig}; use voelin_core::studio::Studio; @@ -62,6 +62,9 @@ pub(crate) struct Video { /// automatic), from the settings. encoder: EncoderPreference, codec: Option, + /// Which decoders to use (`stream.hardware_decoding`, + /// `stream.decoder_backend`). + decoder: DecoderPreference, /// Sources of the share dialog, by index. sources: Vec, } @@ -75,6 +78,7 @@ impl Video { codecs: Arc::new(Codecs::new()), encoder: EncoderPreference::default(), codec: None, + decoder: DecoderPreference::default(), #[cfg(not(target_os = "android"))] openh264_dir: data_dir.join("openh264"), #[cfg(not(target_os = "android"))] @@ -108,7 +112,19 @@ impl Video { self.codec = codec; } - /// Every encoder backend, what works and why the rest does not. + /// Decode with other decoders (`stream.hardware_decoding`, + /// `stream.decoder_backend`): streams watched from now on. + pub fn set_decoder_preference(&mut self, decoder: DecoderPreference) { + if decoder != self.decoder { + let mut codecs = (*self.codecs).clone(); + codecs.set_decoder_preference(decoder.clone()); + self.codecs = Arc::new(codecs); + self.decoder = decoder; + } + } + + /// Every encoder and decoder backend, what works and why the rest does + /// not. #[allow(dead_code, reason = "for the integrations page")] pub fn encoder_report(&self) -> EncoderReport { self.codecs.report() @@ -140,7 +156,11 @@ impl Video { use openh264::State; if !enabled { self.h264 = State::Off; - self.codecs = Arc::new(Codecs::new().with_preference(self.encoder.clone())); + self.codecs = Arc::new( + Codecs::new() + .with_preference(self.encoder.clone()) + .with_decoder_preference(self.decoder.clone()), + ); return; } if matches!(self.h264, State::Loaded(_) | State::Downloading) { @@ -156,8 +176,12 @@ impl Video { #[cfg(not(target_os = "android"))] fn loaded(&mut self, library: openh264::OpenH264) { self.h264 = openh264::State::Loaded(library.path().to_owned()); - self.codecs = - Arc::new(Codecs::new().with_openh264(library).with_preference(self.encoder.clone())); + self.codecs = Arc::new( + Codecs::new() + .with_openh264(library) + .with_preference(self.encoder.clone()) + .with_decoder_preference(self.decoder.clone()), + ); } /// Download Cisco's OpenH264 (only on the user's request). `done` runs @@ -344,8 +368,8 @@ impl Video { fn deliver( pictures: Arc>, wake: impl Fn() + Send + Sync + 'static, -) -> impl FnMut(VideoFrame) + Send + 'static { - move |frame: VideoFrame| { +) -> impl FnMut(Arc) + Send + 'static { + move |frame: Arc| { let mut buffer = Picture::new(frame.width, frame.height); let stride = frame.width as usize * 4; if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) { diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 6fc1671..c78e925 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -812,7 +812,7 @@ async fn watch( ); let mut tick = tokio::time::interval(Duration::from_millis(100)); let mut first_picture = true; - let mut last_picture: Option = None; + let mut last_picture: Option> = None; let summary = |video: u64, audio: u64, decoder: &VideoPipeline| { let stats = decoder.stats(); println!( @@ -821,7 +821,7 @@ async fn watch( stats.error.map(|e| format!(" (last error: {e})")).unwrap_or_default() ); }; - let save_last = |last: &Option| -> Result<()> { + let save_last = |last: &Option>| -> Result<()> { match (save, last) { (Some(path), Some(picture)) => { save_png(picture, path)?; From 338fb1c117a0bb7eaa94975ee010f1e9bb439b83 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:14:11 +0300 Subject: [PATCH 3/9] Measure H.264 with B-frames at 1440p60, through the decoders and the pipeline Watching the official client's stream (H.264 from AMF at 2560x1440 and 60 fps, with B-frames and rare keyframes) had a very bad frame rate in the app, which decoded it with Cisco's OpenH264. Two ignored measurements reproduce such a stream with the ffmpeg command (x264 with 3 B-frames, h264_vaapi with 2, ten seconds of testsrc2 at 8 Mbit/s, keyframes every ten seconds). ffmpeg_decoders.rs decodes it with every H.264 decoder as fast as it goes. Release build, RX 7900 GRE, FFmpeg 9.0.1, OpenH264 2.6.0: h264_vaapi 398-424 fps, slowest frame 4.0-6.8 ms, every picture h264 276-302 fps, slowest frame 6.6-8.0 ms, every picture openh264 8 of 600 pictures, 592 errors: it does not decode B-frames Both FFmpeg decoders give the same pictures (thumbnails compared), in order. decode_rate.rs plays it in real time into a VideoPipeline whose consumer converts every picture to RGBA as the app does: ladder (h264_vaapi), no loss: 59.9 fps ladder (h264_vaapi), a frame lost a second: 58.9 fps (concealed) OpenH264 alone, either way: 0.8 fps So the frame rate was OpenH264 failing on every B-frame and the pipeline then waiting for keyframes; with FFmpeg's decoders first in the ladder the stream plays at its full rate. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/tests/decode_rate.rs | 125 +++++++++++++++ crates/voelin-media/tests/ffmpeg_decoders.rs | 159 +++++++++++++++++++ 2 files changed, 284 insertions(+) create mode 100644 crates/voelin-core/tests/decode_rate.rs diff --git a/crates/voelin-core/tests/decode_rate.rs b/crates/voelin-core/tests/decode_rate.rs new file mode 100644 index 0000000..fa51bd0 --- /dev/null +++ b/crates/voelin-core/tests/decode_rate.rs @@ -0,0 +1,125 @@ +//! The viewer's pipeline on an H.264 stream with B-frames at 2560x1440 and +//! 60 fps, like the official client sends (AMF with B-frames, keyframes +//! rarely): frames pushed in real time into a `VideoPipeline`, every +//! picture converted to RGBA as the app shows it, with and without a lost +//! frame every second. The stream is the one `voelin-media`'s +//! `h264_with_b_frames_at_1440p60` measurement makes (in the temporary +//! directory); `VOELIN_OPENH264_LIB` adds Cisco's OpenH264 alone, the +//! decoder the app used before FFmpeg's. Run with `--release --ignored`. + +#![cfg(feature = "media-desktop")] + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use voelin_core::media::voelin_media::{Codec, Codecs, convert}; +use voelin_core::media::{DecodeStats, VideoPipeline}; +use voelin_stream::{Frequency, MediaFrame, MediaKind, MediaTime}; + +/// The access units of an Annex B stream with access unit delimiters. +fn access_units(stream: &[u8]) -> Vec<&[u8]> { + let mut starts = Vec::new(); + let mut i = 0; + while i + 3 < stream.len() { + if stream[i..i + 3] == [0, 0, 1] { + if stream[i + 3] & 0x1f == 9 { + starts.push(if i > 0 && stream[i - 1] == 0 { i - 1 } else { i }); + } + i += 3; + } else { + i += 1; + } + } + starts.push(stream.len()); + starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect() +} + +/// `units` at 60 fps into a pipeline of `codecs`, every `loss`-th frame +/// lost; the pictures shown and the pipeline's statistics. +fn play(codecs: Codecs, units: &[&[u8]], loss: Option) -> (u64, DecodeStats) { + let shown = Arc::new(AtomicU64::new(0)); + let rgba = Mutex::new(vec![0u8; 2560 * 1440 * 4]); + let pipeline = VideoPipeline::new( + Arc::new(codecs), + { + let shown = shown.clone(); + move |picture| { + let stride = picture.width as usize * 4; + let mut rgba = rgba.lock().unwrap(); + rgba.resize(stride * picture.height as usize, 0); + convert::to_rgba(&picture, &mut rgba, stride).unwrap(); + shown.fetch_add(1, Ordering::Relaxed); + } + }, + || {}, + ); + let started = Instant::now(); + let mut contiguous = true; + for (n, unit) in units.iter().enumerate() { + let due = started + Duration::from_micros(16_667 * n as u64); + std::thread::sleep(due.saturating_duration_since(Instant::now())); + if loss.is_some_and(|every| n % every == every - 1) { + contiguous = false; + continue; + } + pipeline.push(MediaFrame { + kind: MediaKind::Video, + codec: voelin_stream::Codec::H264, + time: MediaTime::new(1500 * n as u64, Frequency::NINETY_KHZ), + network_time: Instant::now(), + contiguous, + data: Arc::from(*unit), + }); + contiguous = true; + } + std::thread::sleep(Duration::from_millis(200)); + (shown.load(Ordering::Relaxed), pipeline.stats()) +} + +#[test] +#[ignore = "a measurement: needs the stream voelin-media's measurement makes"] +fn h264_with_b_frames_plays_at_full_rate() { + let dir = std::env::temp_dir().join("voelin-h264-bframes"); + let mut played = 0; + for stream in ["h264_vaapi", "x264"] { + let Ok(data) = std::fs::read(dir.join(format!("{stream}-bframes-1440p60.h264"))) else { + eprintln!("{stream}: no stream in {}, skipped", dir.display()); + continue; + }; + let units = access_units(&data); + let mut setups = vec![("ladder", Codecs::new())]; + if let Some(path) = std::env::var_os("VOELIN_OPENH264_LIB") { + let library = + voelin_core::media::voelin_media::codec::h264::OpenH264::load(path).unwrap(); + setups.push(("openh264", Codecs::builtin().with_openh264(library))); + } + for (name, codecs) in setups { + for loss in [None, Some(60)] { + let ladder = codecs.decoders_for(Codec::H264); + let (shown, stats) = play(codecs.clone(), &units, loss); + let seconds = units.len() as f64 / 60.0; + eprintln!( + "{stream} 2560x1440@60 with B-frames, {name} {ladder:?}, {}: {shown} of {} \ + pictures shown ({:.1} fps), decoder {:?}, skipped {}, keyframe requests {}, \ + last error {:?}", + if loss.is_some() { "a frame lost every second" } else { "no loss" }, + units.len(), + shown as f64 / seconds, + stats.decoder, + stats.skipped, + stats.keyframe_requests, + stats.error, + ); + if name == "ladder" { + // Everything but the frames lost and the two the decoder + // still holds at the end. + let lost = loss.map_or(0, |every| units.len() / every); + assert!(shown + 3 + lost as u64 >= units.len() as u64, "{shown}"); + } + } + } + played += 1; + } + assert!(played > 0, "no stream: run voelin-media's h264_with_b_frames_at_1440p60 first"); +} diff --git a/crates/voelin-media/tests/ffmpeg_decoders.rs b/crates/voelin-media/tests/ffmpeg_decoders.rs index 85199e6..33affd4 100644 --- a/crates/voelin-media/tests/ffmpeg_decoders.rs +++ b/crates/voelin-media/tests/ffmpeg_decoders.rs @@ -239,3 +239,162 @@ fn decoders_with_and_without_ffmpeg() { .unwrap(); assert!(child.success(), "without FFmpeg: {child}"); } + +/// The access units of an Annex B H.264 stream that has access unit +/// delimiters (`aud=1` in x264, `-aud 1` in VA-API), as a stream's frames. +fn access_units(stream: &[u8]) -> Vec<&[u8]> { + let mut starts = Vec::new(); + let mut i = 0; + while i + 3 < stream.len() { + if stream[i..i + 3] == [0, 0, 1] { + if stream[i + 3] & 0x1f == 9 { + starts.push(if i > 0 && stream[i - 1] == 0 { i - 1 } else { i }); + } + i += 3; + } else { + i += 1; + } + } + starts.push(stream.len()); + starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect() +} + +/// A 32x18 luma thumbnail (block averages), to compare pictures cheaply. +fn thumbnail(picture: &VideoFrame) -> Vec { + let y = match &picture.data { + voelin_media::FrameData::I420 { y, .. } | voelin_media::FrameData::Nv12 { y, .. } => y, + _ => panic!("not YUV"), + }; + let (w, bw, bh) = + (picture.width as usize, picture.width as usize / 32, picture.height as usize / 18); + let mut out = Vec::with_capacity(32 * 18); + for by in 0..18 { + for bx in 0..32 { + let sum: u64 = (by * bh..(by + 1) * bh) + .map(|row| { + y.row(row, w)[bx * bw..(bx + 1) * bw].iter().map(|&p| u64::from(p)).sum::() + }) + .sum(); + out.push((sum / (bw * bh) as u64) as u8); + } + } + out +} + +/// Make `path` with the `ffmpeg` command from `args` (output options +/// last), unless it is there; whether it is. +fn ffmpeg_command(path: &std::path::Path, args: &[&str]) -> bool { + if path.exists() { + return true; + } + let made = std::process::Command::new("ffmpeg") + .args(["-hide_banner", "-loglevel", "error", "-y"]) + .args(args) + .arg(path) + .status(); + if !made.is_ok_and(|s| s.success()) { + let _ = std::fs::remove_file(path); + return false; + } + true +} + +/// H.264 with B-frames at 2560x1440 and 60 fps, like the official client's +/// stream (AMF with B-frames and rare keyframes): every H.264 decoder of +/// the ladder, and Cisco's OpenH264 with `VOELIN_OPENH264_LIB`, decodes it; +/// how fast, the slowest frame, and whether every picture comes out, in +/// order (against FFmpeg's software decoder). The streams come from the +/// `ffmpeg` command: x264 with 3 B-frames, `h264_vaapi` with 2, ten +/// seconds of `testsrc2` at 8 Mbit/s, keyframes every ten seconds. Run with +/// `--release`. +#[test] +#[ignore = "a measurement: needs the ffmpeg command; run with --release"] +fn h264_with_b_frames_at_1440p60() { + if ffmpeg().is_none() { + return; + } + let dir = std::env::temp_dir().join("voelin-h264-bframes"); + std::fs::create_dir_all(&dir).unwrap(); + let source = "-f lavfi -i testsrc2=size=2560x1440:rate=60 -t 10"; + let rate = "-g 600 -b:v 8M -maxrate 9M -bufsize 9M -f h264"; + let x264 = "-c:v libx264 -preset veryfast -profile:v high -bf 3 -x264-params aud=1"; + let vaapi = "-vf format=nv12,hwupload -c:v h264_vaapi -profile:v high -bf 2 -aud 1"; + let mut streams = Vec::new(); + for (name, args) in [ + ("x264", format!("{source} {x264} -pix_fmt yuv420p {rate}")), + ("h264_vaapi", format!("-vaapi_device /dev/dri/renderD128 {source} {vaapi} {rate}")), + ] { + let path = dir.join(format!("{name}-bframes-1440p60.h264")); + let args: Vec<&str> = args.split(' ').collect(); + if ffmpeg_command(&path, &args) { + streams.push((name, std::fs::read(&path).unwrap())); + } else { + eprintln!("{name}: the ffmpeg command did not make the stream, skipped"); + } + } + let codecs = Codecs::new(); + let openh264 = std::env::var_os("VOELIN_OPENH264_LIB") + .map(|path| voelin_media::codec::h264::OpenH264::load(path).unwrap()); + let mut names: Vec = + codecs.decoders_for(Codec::H264).iter().map(|b| b.to_string()).collect(); + names.extend(openh264.as_ref().map(|_| "openh264".to_owned())); + for (stream, data) in &streams { + let units = access_units(data); + let mut reference: Option>> = None; + for name in &names { + let mut decoder: Box = match (name.as_str(), &openh264) { + ("openh264", Some(library)) => Box::new(library.decoder().unwrap()), + _ => { + let backend = + codecs.decoders_for(Codec::H264).into_iter().find(|b| b.name() == name); + codecs.new_decoder_with(Codec::H264, backend.unwrap()).unwrap() + } + }; + let mut picture = VideoFrame::black_i420(0, 0); + let mut thumbnails = Vec::with_capacity(units.len()); + let (mut errors, mut slowest, mut busy) = (0, Duration::ZERO, Duration::ZERO); + for unit in &units { + let started = Instant::now(); + let result = decoder.decode_into(unit, &mut picture); + let took = started.elapsed(); + (slowest, busy) = (slowest.max(took), busy + took); + match result { + Ok(true) => { + assert_eq!((picture.width, picture.height), (2560, 1440), "{name}"); + thumbnails.push(thumbnail(&picture)); + } + Ok(false) => {} + Err(_) => errors += 1, + } + } + let fps = thumbnails.len() as f64 / busy.as_secs_f64(); + let differing = reference.as_ref().map_or(0, |reference| { + let differs = |(a, b): &(&Vec, &Vec)| { + a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 3) + }; + thumbnails.iter().zip(reference).filter(differs).count() + }); + eprintln!( + "{stream} 2560x1440@60 with B-frames, {name}: {} of {} pictures, {errors} errors, \ + {fps:.0} fps, slowest frame {:.1} ms, {differing} differ from FFmpeg's software decoder", + thumbnails.len(), + units.len(), + slowest.as_secs_f64() * 1000.0, + ); + if name == "h264" { + reference = Some(thumbnails); + } else if name.ends_with("_vaapi") { + assert_eq!(errors, 0, "{name}"); + assert!(thumbnails.len() + 3 >= units.len(), "{name}: pictures missing"); + } + } + } + // What a viewer adds per picture: the NV12 or I420 picture to RGBA. + let mut rgba = vec![0; 2560 * 1440 * 4]; + let i420 = VideoFrame::black_i420(2560, 1440); + let started = Instant::now(); + for _ in 0..30 { + convert::to_rgba(&i420, &mut rgba, 2560 * 4).unwrap(); + } + eprintln!("to RGBA at 2560x1440: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0 / 30.0); +} From 200b715b9e6870f1b0827af8497ec32218c66d1e Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:15:36 +0300 Subject: [PATCH 4/9] voelinctl stream encoders: list the decoders and each codec's ladder The report has the decoders now: print them like the encoders, with their self-test results and rank, and the order a viewer tries each codec's decoders in. --decoder and --no-hardware-decoding rank them as the settings stream.decoder_backend and stream.hardware_decoding would. Co-Authored-By: Claude Opus 5.5 --- tools/voelinctl/src/bench.rs | 44 ++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs index a8e8fb8..a308a88 100644 --- a/tools/voelinctl/src/bench.rs +++ b/tools/voelinctl/src/bench.rs @@ -12,7 +12,9 @@ use clap::{Args, Subcommand}; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::capture::synthetic::Pattern; use voelin_core::media::voelin_media::{Codec, Codecs}; -use voelin_core::media::{EncoderPreference, MediaSink, Streamer, StreamerConfig, preferred_codec}; +use voelin_core::media::{ + DecoderPreference, EncoderPreference, MediaSink, Streamer, StreamerConfig, preferred_codec, +}; use voelin_stream::{EncodedFrame, LayerId, LayerSet, LayerSpec, MediaKind}; use crate::alloc; @@ -29,9 +31,10 @@ enum StreamTool { /// test pattern without a server; print per-stage and per-layer numbers /// and heap allocations per frame. Bench(BenchArgs), - /// List the video encoders: the FFmpeg libraries found, every backend - /// with its self-test result (or why it cannot be used), and the order - /// the streamer would use them in. + /// List the video encoders and decoders: the FFmpeg libraries found, + /// every backend with its self-test result (or why it cannot be used), + /// the order the streamer would use the encoders in, and each codec's + /// decoders in the order a viewer tries them. Encoders(EncodersArgs), } @@ -44,6 +47,12 @@ struct EncodersArgs { /// Rank without hardware encoders (`stream.hardware_acceleration` off). #[arg(long)] no_hardware: bool, + /// Decoder choice to rank by (as the setting `stream.decoder_backend`). + #[arg(long, default_value = "auto")] + decoder: String, + /// Rank without hardware decoders (`stream.hardware_decoding` off). + #[arg(long)] + no_hardware_decoding: bool, /// Cisco's OpenH264 library, to list it as well. #[arg(long)] openh264: Option, @@ -127,7 +136,11 @@ fn codecs_for(encoder: &str, no_hardware: bool, openh264: Option<&PathBuf>) -> R } fn encoders(args: EncodersArgs) -> Result<()> { - let codecs = codecs_for(&args.encoder, args.no_hardware, args.openh264.as_ref())?; + let codecs = codecs_for(&args.encoder, args.no_hardware, args.openh264.as_ref())? + .with_decoder_preference(DecoderPreference { + hardware: !args.no_hardware_decoding, + backend: args.decoder.parse().unwrap_or_default(), + }); let report = codecs.report(); match &report.ffmpeg { Ok(text) => println!("{text}"), @@ -160,6 +173,27 @@ fn encoders(args: EncodersArgs) -> Result<()> { let order: Vec = codecs.encoders().iter().map(|(codec, backend)| format!("{codec} {backend}")).collect(); println!("\nstreamer order: {}", order.join(", ")); + println!(); + println!("{:<18} {:<5} {:<17} {:<8} {:<5} status", "decoder", "codec", "api", "kind", "rank"); + let mut list = report.decoders.clone(); + list.sort_by_key(|d| (d.status.is_err(), d.codec.name(), d.rank.unwrap_or(usize::MAX))); + for d in &list { + println!( + "{:<18} {:<5} {:<17} {:<8} {:<5} {}", + d.name, + d.codec.name(), + d.api, + if d.hardware { "hardware" } else { "software" }, + d.rank.map_or("-".to_owned(), |r| r.to_string()), + d.status.as_ref().err().map_or("ok", String::as_str), + ); + } + println!("\nviewer order (each codec's decoders, best first):"); + for codec in codecs.decoders() { + let ladder: Vec = + codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect(); + println!(" {codec}: {}", ladder.join(" > ")); + } Ok(()) } From 543c8960b2fc7c842ba69798835e65d5ee02aa01 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:19:08 +0300 Subject: [PATCH 5/9] Interop: Chromium's AV1, VP9 and H.264 decode in the engine's pipeline The official client sends AV1 from modern GPUs, and H.264 after it re-aligns; nothing checked that our viewer takes what a libwebrtc sender produces. Headless Chromium now offers its canvas in AV1, VP9 and H.264 in turn to our viewer peer, configured with peer_config like a watch (accepting what this machine decodes), and a VideoPipeline must decode 30 pictures of each at the canvas's size with the first decoder of the codec's ladder, keyframe requests going back as PLIs. Chromium 152 (Arch Linux, VOELIN_CHROMIUM=/usr/bin/chromium) sends all three; here they decode on the GPU (av1_vaapi, vp9_vaapi, h264_vaapi). Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/tests/browser_codecs.rs | 78 +++++++++++++++++++++- tests/interop/README.md | 4 ++ 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/crates/voelin-core/tests/browser_codecs.rs b/crates/voelin-core/tests/browser_codecs.rs index 2cf1840..0162fc2 100644 --- a/crates/voelin-core/tests/browser_codecs.rs +++ b/crates/voelin-core/tests/browser_codecs.rs @@ -2,7 +2,8 @@ //! pattern, encoded by each encoder this machine has as a share encodes the //! screen, sent by our streamer peer offering just that codec, must decode //! at its size in headless Chromium (libwebrtc, the stack the official -//! TeamSpeak 6 client is built on). +//! TeamSpeak 6 client is built on). And the other way: what Chromium sends +//! (AV1, VP9, H.264) our viewer accepts and the engine's pipeline decodes. //! //! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs //! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are @@ -11,6 +12,8 @@ #![cfg(feature = "media-desktop")] +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use serde_json::{Value, json}; @@ -18,8 +21,8 @@ use tokio::time::timeout; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::{Codec, Codecs}; use voelin_core::media::{ - EncodedSource, EncoderPreference, Streamer, StreamerConfig, decoded_everywhere, media_codec, - peer_config, preferred_codec, video_codec, + EncodedSource, EncoderPreference, Streamer, StreamerConfig, VideoPipeline, decoded_everywhere, + media_codec, peer_config, preferred_codec, video_codec, }; use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec}; use voelin_stream::{Peer, PeerEvent}; @@ -185,3 +188,72 @@ async fn share_offer_picks_a_codec_every_client_decodes() { browser.quit().await; decoded(&video).unwrap(); } + +/// Headless Chromium sends its canvas (320x240) in AV1, VP9 and H.264 in +/// turn (what it cannot send is skipped; a system Chromium sends H.264) to +/// our viewer peer, which accepts what this machine decodes +/// (`peer_config`); the engine's pipeline decodes 30 pictures at that size +/// with the first decoder of the codec's ladder (VA-API where it decodes +/// the codec), asking the browser for keyframes as a watch does. +#[tokio::test(flavor = "multi_thread")] +async fn browser_streams_decode_in_the_pipeline() { + if !enabled() { + eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let mut browser = Browser::start().await; + let codecs = Arc::new(Codecs::new()); + let config = peer_config(&codecs, PeerConfig::loopback()); + let mut decoded = Vec::new(); + for codec in [Codec::Av1, Codec::Vp9, Codec::H264] { + let offer = browser.call(json!({ "op": "offer", "codec": codec.name() })).await; + if offer.get("unsupported").is_some() { + eprintln!("{codec}: the browser cannot send it, skipped"); + continue; + } + assert!(config.accept_video_codecs.contains(&video_codec(codec)), "{codec} not accepted"); + let (mut peer, answer) = + Peer::answer(&config, offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": answer })).await; + let keyframe = Arc::new(AtomicBool::new(false)); + let (tx, pictures) = std::sync::mpsc::channel(); + let pipeline = VideoPipeline::new( + codecs.clone(), + move |picture| { + let _ = tx.send((picture.width, picture.height)); + }, + { + let keyframe = keyframe.clone(); + move || keyframe.store(true, Ordering::Relaxed) + }, + ); + let mut sizes = Vec::new(); + let _ = timeout(Duration::from_secs(15), async { + while let Some(event) = peer.next_event().await { + match event { + PeerEvent::Media(frame) => pipeline.push(frame), + PeerEvent::Closed => break, + _ => {} + } + if keyframe.swap(false, Ordering::Relaxed) { + peer.request_keyframe(); + } + sizes.extend(pictures.try_iter()); + if sizes.len() >= 30 { + break; + } + } + }) + .await; + let stats = pipeline.stats(); + peer.close(); + eprintln!("{codec}: {} pictures, {stats:?}", sizes.len()); + assert!(sizes.len() >= 30, "{codec}: {} pictures decoded, {stats:?}", sizes.len()); + assert!(sizes.iter().all(|&s| s == (320, 240)), "{codec}: {sizes:?}"); + assert_eq!(stats.codec, Some(codec)); + assert_eq!(stats.decoder, codecs.decoders_for(codec).first().copied(), "{stats:?}"); + decoded.push(codec); + } + browser.quit().await; + assert!(decoded.contains(&Codec::Av1), "the browser sent no AV1: {decoded:?}"); +} diff --git a/tests/interop/README.md b/tests/interop/README.md index ca36a94..d83af96 100644 --- a/tests/interop/README.md +++ b/tests/interop/README.md @@ -14,6 +14,7 @@ TeamSpeak server is involved. | `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus, over `AES_CM_128_HMAC_SHA1_80`. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe | | `real_encoders_decode_in_browser` (voelin-core) | Every encoder this machine has (`Codecs::encoders()`), as a share uses it: the 1280x720 test pattern through the `Streamer`, VA-API encoders also from DMA-BUFs as the ScreenCast portal hands over the screen; our streamer peer offers that codec alone (H.264 as Constrained Baseline, see below); the browser must decode at least 60 frames at 1280x720 in 3 s. Codecs the browser does not answer (HEVC, H.264 in Playwright's Chromium) are skipped | | `share_offer_picks_a_codec_every_client_decodes` (voelin-core) | The offer a share makes on this machine (`preferred_codec`, `peer_config`): the browser, answering with the first codec of the offer it lists as the official client does, must pick one every TeamSpeak client decodes (`decoded_everywhere`), and decode it | +| `browser_streams_decode_in_the_pipeline` (voelin-core) | The other way: Chromium sends its canvas (320x240) in AV1, VP9 and H.264 in turn (skipping what it cannot send) to our viewer peer, which accepts what this machine decodes (`peer_config`); the engine's `VideoPipeline` must decode 30 pictures at 320x240 with the first decoder of the codec's ladder (`Codecs::decoders_for`), keyframe requests going to the browser as PLIs | | `browser_renegotiates_with_rust` | Chromium streams VP8, then sends a new offer on the same connection with VP9 first (as the official client re-offers when it does not encode the codec we chose); `Peer::renegotiate` answers on the same peer, in the new offer's codec order; VP9 frames must arrive | | `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` | @@ -72,6 +73,9 @@ may do the same; see `docs/protocol-notes/ts6-streaming.md`. 0 and 1): it does not answer an offer of Constrained High alone (`640c1f`, what our streamers offer), yet decodes High profile streams when it negotiated another profile (its decoder is FFmpeg's). +- Chromium 152 (Arch Linux build, `VOELIN_CHROMIUM=/usr/bin/chromium`) sends + AV1, VP9 and H.264; our pipeline decodes all three on the GPU here (AMD, + VA-API: `av1_vaapi`, `vp9_vaapi`, `h264_vaapi`), at the canvas's size. - With str0m's bandwidth estimation and pacer on our streamer peer, Chromium's transport-cc feedback yields estimates within the first second (about 640 kbit/s rising towards the desired bitrate with the 720 kbit/s synthetic From 8612b85518f1630de51f6e54685775d2a5189f1b Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:20:49 +0300 Subject: [PATCH 6/9] Test that FFmpeg's decoders allocate nothing per picture decode_into reuses the caller's frame and the decoder's own download frame, so a running decoder should make no Rust allocation per picture. A counting global allocator (as the mixer's and the studio's tests have) checks it for every decoder that passed its self-test, the VA-API ones included: here av1_vaapi, hevc_vaapi, vp9_vaapi, h264_vaapi, libdav1d, libaom-av1, hevc, vp9, h264 and vp8 make none over 30 pictures at 640x360. FFmpeg's own buffers are its mallocs and its pools. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/tests/decoder_alloc.rs | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 crates/voelin-media/tests/decoder_alloc.rs diff --git a/crates/voelin-media/tests/decoder_alloc.rs b/crates/voelin-media/tests/decoder_alloc.rs new file mode 100644 index 0000000..815a47c --- /dev/null +++ b/crates/voelin-media/tests/decoder_alloc.rs @@ -0,0 +1,108 @@ +//! FFmpeg's decoders allocate nothing per picture once running: every +//! decoder that passed its self-test (hardware ones included: the GPU's +//! pictures are copied through a frame of our own) decodes into the same +//! `VideoFrame` with `decode_into`, counted with a global allocator that +//! counts only on the thread that asks. FFmpeg's own buffers are malloc'd +//! by FFmpeg and pooled by it; they are not Rust allocations. +#![cfg(feature = "ffmpeg")] +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::time::Duration; + +use voelin_media::capture::synthetic::SyntheticScreen; +use voelin_media::ffmpeg::{FfmpegDecoder, decoder}; +use voelin_media::{Codecs, EncoderConfig, VideoDecoder, VideoFrame}; + +thread_local! { + static COUNTING: Cell = const { Cell::new(false) }; + static COUNT: Cell = const { Cell::new(0) }; +} + +fn count() { + // `try_with`: never panics, also while the thread is torn down; const + // thread locals without destructors never allocate. + let _ = COUNTING.try_with(|on| { + if on.get() { + let _ = COUNT.try_with(|n| n.set(n.get() + 1)); + } + }); +} + +struct Counting; + +// SAFETY: every method forwards to `System` with the caller's arguments +// unchanged, so `System`'s guarantees hold; counting touches only +// thread-local cells and never allocates. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged (see above). + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: forwarded unchanged. + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static ALLOCATOR: Counting = Counting; + +/// Allocations `f` makes on this thread. +fn allocations(f: impl FnOnce()) -> u64 { + COUNT.with(|n| n.set(0)); + COUNTING.with(|on| on.set(true)); + f(); + COUNTING.with(|on| on.set(false)); + COUNT.with(Cell::get) +} + +#[test] +fn decoders_allocate_nothing_per_picture() { + assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1); + let codecs = Codecs::new(); + let screen = SyntheticScreen::new(640, 360); + let mut tested = Vec::new(); + for status in decoder::probe().iter().filter(|s| s.available.is_ok()) { + let codec = status.spec.codec; + let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() }; + let Ok(mut encoder) = codecs.new_encoder(codec, config) else { continue }; + let mut stream = Vec::new(); + for n in 0..40u64 { + let frame = screen.frame(n, 30).with_timestamp(Duration::from_millis(33 * n)); + stream.extend(encoder.encode(&frame, n == 0).unwrap().into_iter().map(|f| f.data)); + } + let mut decoder = FfmpegDecoder::new(status.spec).unwrap(); + let mut picture = VideoFrame::black_i420(0, 0); + // The first pictures size the buffers. + for data in &stream[..10] { + decoder.decode_into(data, &mut picture).unwrap(); + } + let mut decoded = 0; + let counted = allocations(|| { + for data in &stream[10..] { + decoded += usize::from(decoder.decode_into(data, &mut picture).unwrap()); + } + }); + eprintln!("{}: {counted} allocations for {decoded} pictures", status.spec.name); + assert!(decoded + 3 >= stream.len() - 10, "{}: {decoded} pictures", status.spec.name); + assert_eq!(counted, 0, "{}", status.spec.name); + tested.push(status.spec.name); + } + eprintln!("tested: {tested:?}"); +} From 44d674cf0d734f1602dde789fc2103be14252231 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:28:50 +0300 Subject: [PATCH 7/9] docs: FFmpeg's decoders, the ladder, what a viewer accepts now media.md describes the decoders (hardware through FFmpeg's hwaccel API, then FFmpeg's software ones, then the built-in ones), hw_device_ctx and how it is found, the self-test clips, the ladder on this machine, the settings, the pipeline's fallback and loss recovery, the measurements of H.264 with B-frames at 1440p60, and what was tested where (VA-API on the RX 7900 GRE, the browser interop; NVDEC, D3D11VA, DXVA2 and VideoToolbox only type-checked or not at all). The protocol notes say what Voelin now accepts from official streamers and why their H.264 decoded so badly before (OpenH264 and B-frames). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++ docs/media.md | 190 ++++++++++++++++++++++++--- docs/protocol-notes/ts6-streaming.md | 27 ++++ 3 files changed, 205 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55af48f..0704a70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,15 @@ The first release is in preparation. another offered codec get their own encoder. Settings: `stream.hardware_acceleration`, `stream.encoder_backend`, `stream.codec`; `voelinctl stream encoders` lists what works. +- Video decoding through the installed FFmpeg as well: hardware first + (VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox), then FFmpeg's software + decoders, then the built-in ones; each decoder is tested at start, and + one that fails while watching is replaced by the next without ending the + stream. Viewers now take AV1, HEVC and H.264 without OpenH264, and + H.264 with B-frames as the official client sends it (OpenH264 showed + under 1 fps of such a stream; 60 fps now). After a lost frame H.264 and + HEVC go on decoding while a keyframe is asked for. Settings: + `stream.hardware_decoding`, `stream.decoder_backend`. - `tsgw`: companion gateway for server admins (presence, channel chat relay, history). - Chat history: messages are kept on the device and, with a gateway, what diff --git a/docs/media.md b/docs/media.md index 299811b..3ada234 100644 --- a/docs/media.md +++ b/docs/media.md @@ -24,11 +24,14 @@ described in [studio.md](studio.md). | `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API; MediaCodec's surface path on Android) | | `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time). On Android `rendered(width, height, timestamp)`: a screen picture the virtual display renders straight into MediaCodec's input surface, only its size and time travel | | `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | -| `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time) | +| `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time); `decode_into(&[u8], &mut VideoFrame) -> bool` reuses the frame's buffers (FFmpeg's decoders: no allocation per picture); `conceals_errors()` (FFmpeg's H.264 and HEVC: frames after a lost one still decode) | | `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | -| `Codecs` | `new()` (probes FFmpeg / MediaCodec once per process), `builtin()` (compiled-in codecs only), `with_openh264(lib)`, `with_preference(EncoderPreference)` / `set_preference`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order under the preference), `encoders_for(&pref)`, `new_decoder(codec)`, `new_encoder(codec, config)`, `new_encoder_preferring(codec, config, &pref)`, `new_encoder_with(codec, backend, config)`, `pick_encoder(&accepted)`, `is_hardware(backend)`, `report()`; cheap to clone | +| `Codecs` | `new()` (probes FFmpeg / MediaCodec once per process), `builtin()` (compiled-in codecs only), `with_openh264(lib)`, `with_preference(EncoderPreference)` / `set_preference`, `decoders()` (viewer order: every codec one decoder here decodes), `decoders_for(codec)` (that codec's decoders, best first: the ladder), `with_decoder_preference(DecoderPreference)` / `set_decoder_preference`, `with_decoder(factory)` (an application's decoder, first), `encoders()` / `encoder_codecs()` (streamer order under the preference), `encoders_for(&pref)`, `new_decoder(codec)` (the first of the ladder that opens), `new_decoder_with(codec, DecoderBackend)`, `new_encoder(codec, config)`, `new_encoder_preferring(codec, config, &pref)`, `new_encoder_with(codec, backend, config)`, `pick_encoder(&accepted)`, `is_hardware(backend)`, `report()`; cheap to clone | | `EncoderPreference { hardware, backend: BackendChoice }` | settings `stream.hardware_acceleration` and `stream.encoder_backend` (`auto`, `software`, or a backend name such as `h264_vaapi`, `libx264`, `libvpx`, `openh264`) | -| `EncoderReport { ffmpeg, zero_copy, encoders: Vec }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference | +| `EncoderReport { ffmpeg, zero_copy, encoders: Vec, decoders: Vec }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference (for a decoder: its place in its codec's ladder) | +| `DecoderBackend` | `Ffmpeg("h264_vaapi")`, `Ffmpeg("libdav1d")`, `Libvpx`, `OpenH264`, `Dav1d`, `Hardware("mediacodec")`; `name()` is the settings spelling | +| `DecoderPreference` | the `EncoderPreference` type for decoders: settings `stream.hardware_decoding` and `stream.decoder_backend` (`auto`, `software`, or a decoder's name such as `h264_vaapi`, `h264`, `libdav1d`, `libvpx`, `openh264`) | +| `ffmpeg::{FfmpegDecoder, DECODERS, decoder::probe}` | FFmpeg's decoders, see [FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime) | | `EncoderBackend` | `Libvpx`, `OpenH264`, `Ffmpeg("h264_vaapi")`, `Hardware("mediacodec")`; `name()` is the settings spelling | | `ffmpeg::{Ffmpeg, probe, FfmpegEncoder, BACKENDS}` | FFmpeg loaded at runtime (feature `ffmpeg`), see [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) | | `ffmpeg::avio::Connection`, `ffmpeg::audio::AacEncoder` | bytes written through libavformat's protocols (`rtmp://`, `rtmps://`) with their write errors and an abort flag; the studio's Opus as AAC through FFmpeg's own codecs. See [RTMP output](#rtmp-output) | @@ -186,18 +189,33 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder never below 3.1, the level offered before); str0m's other H.264 variants are only accepted, never offered, so a viewer cannot answer a profile we do not send. -- `VideoPipeline` decodes on its own thread. It starts at a keyframe, and - after a lost frame (`contiguous == false`, a lagging frame bus, a queue - longer than 30 frames) or a decoder error it skips to the next keyframe, - asking for one at most every 500 ms. Keyframes are recognised from the +- `VideoPipeline` decodes on its own thread, with the first decoder of the + stream codec's ladder that opens (`Codecs::decoders_for`, see + [FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime)). It starts at a + keyframe. After a lost frame (`contiguous == false`, a lagging frame + bus, a queue longer than 30 frames) a decoder that conceals losses + (`conceals_errors`: FFmpeg's H.264 and HEVC) goes on decoding while a + keyframe is asked for; the others skip to the next keyframe, as they do + after a decoder error. A keyframe that is wanted is asked for again every + 500 ms until one decodes, also while no frame arrives. A decoder that + fails three times in a row (an error, or ten frames without a picture, + which also asks for a keyframe; decoders of streams with B-frames hold a + few) is replaced by the next of the ladder without ending the watch: the + keyframe that failed starts the next one at once, otherwise it waits for + the next keyframe, and the switch is logged with its reason. The last + decoder of the ladder stays. Keyframes are recognised from the bitstream (VP8 frame tag, VP9 header, H.264 IDR/SPS NAL units, AV1 - sequence header OBU). `stats()` (`DecodeStats`) tells the codec, the - picture's size, pictures decoded and skipped, the video bytes received, - and the decoded frame rate and received bitrate since the previous call - (at least half a second); the watch screen shows codec, size, rate and - bitrate over the player and in Stream Info, refreshed once a second. - These are read from the pipeline, which runs in the app, not sent as - engine events: the engine never sees the decoded pictures. + sequence header OBU). Pictures go to the callback as `Arc` + from a pool of four: the decoder writes into one nobody holds + (`decode_into`), so a consumer that converts and drops each picture, as + the app does, costs no allocations. `stats()` (`DecodeStats`) tells the + codec, the decoder in use, the picture's size, pictures decoded and + skipped, the video bytes received, and the decoded frame rate and + received bitrate since the previous call (at least half a second); the + watch screen shows codec, size, rate and bitrate over the player and in + Stream Info, refreshed once a second. These are read from the pipeline, + which runs in the app, not sent as engine events: the engine never sees + the decoded pictures. - `Viewer` feeds a `VideoPipeline` from the engine and sends `RequestStreamKeyframe`; `LocalPreview` runs capture → encoder → decoder without a server (the desktop app's `VOELIN_DEMO_STREAM`). @@ -301,7 +319,10 @@ e.g. calls). ## Codecs -Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with +Preference: a viewer accepts AV1 > HEVC > VP9 > H.264 > VP8, each with the +best decoder that works here (hardware, then FFmpeg's software decoders, +then the built-in ones; see [FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime)); +a streamer encodes with hardware (H.264 > AV1 > VP9 > VP8 > HEVC) > VP8 (libvpx) > H.264 (x264 and OpenH264 through FFmpeg, then Cisco's OpenH264) > VP9 (libvpx, expensive in software) > AV1 (SVT-AV1, libaom through FFmpeg). `Codecs` filters both lists @@ -316,13 +337,14 @@ off), the automatic order after it. | libvpx | `vpx` (default) | VP8, VP9 | VP8, VP9 | system libvpx (1.14 tested), dynamically linked; bindings from `libvpx-native-sys` (pre-generated, no bindgen) | | OpenH264 | `openh264` (default) | H.264 Constrained High / Baseline | H.264 | Cisco's prebuilt binary, loaded at runtime | | dav1d | `av1` | – | AV1 | system libdav1d >= 1.3 (1.4.1 tested) | -| FFmpeg | `ffmpeg` (default; off on Android) | H.264, HEVC, AV1, VP9, VP8 in hardware; H.264 (x264, OpenH264), AV1 (SVT-AV1, libaom, rav1e) in software | – | the system's (or `VOELIN_FFMPEG_DIR`'s) libavcodec / libavutil, any major version, loaded at runtime; see below | +| FFmpeg | `ffmpeg` (default; off on Android) | H.264, HEVC, AV1, VP9, VP8 in hardware; H.264 (x264, OpenH264), AV1 (SVT-AV1, libaom, rav1e) in software | AV1, HEVC, VP9, H.264, VP8 in hardware (VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox) and in software (dav1d, libaom, FFmpeg's own) | the system's (or `VOELIN_FFMPEG_DIR`'s) libavcodec / libavutil, any major version, loaded at runtime; see below | | MediaCodec (Android) | – | H.264, VP8, VP9 | VP8, VP9, H.264, AV1 | the device's default codec per type through the NDK (`ndk` crate); an encoder factory named `mediacodec` | HEVC (`Codec::H265`): str0m packetizes and depacketizes H.265, so it can be negotiated; it is offered last and only when a hardware encoder has it, i.e. -used only by a peer that takes none of the other codecs. There is no HEVC -decoder, so viewers never accept it. +used only by a peer that takes none of the other codecs. Viewers accept it +where FFmpeg decodes it (in hardware, or with FFmpeg's own decoder, which +every build has). ### FFmpeg encoders, loaded at runtime @@ -356,7 +378,8 @@ the software encoders above are used as before. {0, 1}, `AV_NOPTS_VALUE` in exactly one layout), `AVCodecContext.hw_frames_ctx` (for VA-API; located from the offsets `av_opt_find` reports for its neighbours `hwaccel_flags` and `err_detect` / `extra_hw_frames` (libavcodec - 61+) or `max_pixels` (up to 60), and NULL in a new context), + 61+) or `max_pixels` (up to 60), and NULL in a new context), and + `hw_device_ctx` beside it (the device of hardware decoders), `AVHWFramesContext` `format`, `sw_format`, `width`, `height`, `initial_pool_size` (with or without `internal`, which libavutil 59 removed; `device_ctx` and both formats checked in a new context), and for @@ -519,6 +542,87 @@ the software encoders above are used as before. (no compression metadata); the portal offers it ahead of LINEAR (see [Capture](#capture)). See [the measurements](#zero-copy-measured). +### FFmpeg decoders, loaded at runtime + +The same runtime-loaded FFmpeg decodes (`ffmpeg/decoder.rs`). Every codec a +viewer may get has a ladder of decoders, tried best first +(`Codecs::decoders_for`), and a viewer accepts every codec one of them +decodes (`Codecs::decoders`, which `peer_config` puts in +`accept_video_codecs`): + +1. hardware, through FFmpeg's hwaccel API (`ffmpeg::DECODERS`; the names are + FFmpeg's names of its hwaccels): `av1_vaapi`, `hevc_vaapi`, `vp9_vaapi`, + `h264_vaapi`, `vp8_vaapi` and, for NVIDIA's driver, which has no VA-API + of its own, `*_nvdec` (Linux); `*_d3d11va`, then `*_dxva2` (Windows; AV1, + HEVC, VP9, H.264); `*_videotoolbox` (macOS; the same four). On Android + MediaCodec instead, which hardware decoding off does not leave out + (Android has no other decoders); +2. FFmpeg's software decoders: `libdav1d`, then `libaom-av1` (AV1; FFmpeg's + own `av1` decoder decodes only in hardware), `hevc`, `vp9`, `h264`, `vp8`; +3. the built-in ones: `libvpx` (VP8, VP9), `openh264` (H.264, once Cisco's + library is loaded), `dav1d` (AV1, feature `av1`). + +The settings choose like the encoders' (`DecoderPreference`): +`stream.hardware_decoding` (on by default) leaves the first group out, and +`stream.decoder_backend` is `auto`, `software`, or a decoder's name, which +then comes first for its codec (even in hardware with hardware decoding +off). The app applies them when they change, to streams watched from then +on (`Video::set_decoder_preference`); a running watch keeps its decoder. + +- Hardware decoding: FFmpeg's own decoder (`av1`, `hevc`, `vp9`, `h264`, + `vp8`) gets the process's device in `AVCodecContext.hw_device_ctx`, a + field without an AVOption, located like `hw_frames_ctx` (right before + `hwaccel_flags` in every layout from libavcodec 58; checked to be NULL in + a new context; 560 in FFmpeg 9's headers, as the test compares). FFmpeg's + default `get_format` then picks the device's surfaces, so no callback is + installed. The devices are shared: VA-API's is the encoders' (the first + render node, or `VOELIN_VAAPI_DEVICE`), the others the type's default. + Pictures are copied out of the GPU with `av_hwframe_transfer_data` into + an NV12 frame of the decoder's own, reused while the size stays, and + from there into the caller's `VideoFrame` (`decode_into` reuses its + buffers): no Rust allocation per picture for any decoder + (`tests/decoder_alloc.rs`). Zero-copy display was not the goal; both + copies are part of the 2.4-2.5 ms per 1440p picture measured in + [Decoders, measured](#decoders-measured). +- Packets are handed over without a reference, so FFmpeg copies them into + its own padded buffer; pictures come out as `yuv420p` (or `yuvj420p`) + and are taken as I420, or as NV12; anything else (10-bit, 4:4:4) is an + error, and the ladder moves on. +- Latency: slice threads only (frame threads would hold a picture per + thread before the first comes out), `threads` up to 8 in software and 1 + in hardware, dav1d's `max_frame_delay` 1 (`framethreads` 1 before FFmpeg + 5.0). Every frame's picture comes out of the call that decoded it, except + what B-frames reorder. +- The self-test (`ffmpeg::decoder::probe()`, once per process, every decoder + on a thread of its own, at the same time as the encoders' probe in + `Codecs::new()`): each decoder decodes a three-frame clip of its codec + (`src/ffmpeg/clips/`, a keyframe and two frames that predict from it, of a + test picture at 320x240 made by our own encoders: `h264_vaapi`, + `hevc_vaapi`, `av1_vaapi` and libvpx; `write_self_test_clips`, ignored, + writes them again). Every frame must give its picture at once, at its + size, above 30 dB against the test picture, and a hardware decoder must + have decoded on the GPU: when the GPU lacks the codec, FFmpeg silently + decodes in software (VP8 on AMD), which the self-test reports as + unusable with FFmpeg's reason, since FFmpeg's software decoder follows + in the ladder anyway. NVDEC is not tried without an NVIDIA GPU (the + encoders' vendor check). Here the probe takes about 50 ms. +- At runtime, when the GPU does not take a stream (a profile or a size it + lacks), FFmpeg decodes it in software through the same decoder + (`FfmpegDecoder::cpu_pictures`), except AV1, which FFmpeg decodes only in + hardware: that is an error, and the pipeline's ladder moves on to dav1d. + +`voelinctl stream encoders` lists the decoders with their self-test +results and each codec's ladder. On the Radeon RX 7900 GRE with FFmpeg +9.0.1: + +| Codec | Ladder | Not used | +|---|---|---| +| AV1 | `av1_vaapi` > `libdav1d` > `libaom-av1` | `av1_nvdec` (no NVIDIA GPU), `dav1d` (built without `av1`) | +| HEVC | `hevc_vaapi` > `hevc` | `hevc_nvdec` | +| VP9 | `vp9_vaapi` > `vp9` > `libvpx` | `vp9_nvdec` | +| H.264 | `h264_vaapi` > `h264` (> `openh264` once loaded) | `h264_nvdec` | +| VP8 | `vp8` > `libvpx` | `vp8_vaapi` (the GPU has no VP8 decoder: "No support for codec vp8 profile"), `vp8_nvdec` | + ### RTMP output The studio's RTMP output ([studio.md](studio.md#outputs-studiooutput)) @@ -889,6 +993,39 @@ self-test: 1920x1080 is sent as 1920x1072, 1366x768 as 1344x768. H.264 has no such problem; its SPS crops whatever the hardware pads (exact at all 12 sizes tried, 320x240 to 3440x1440). +### Decoders, measured + +An H.264 stream with B-frames at 2560x1440 and 60 fps, as the official +client sends it (AMF on an AMD GPU: B-frames, a lookahead, keyframes +rarely), made with the `ffmpeg` command (x264 `veryfast` with 3 B-frames, +`h264_vaapi` with 2; `testsrc2`, 8 Mbit/s, a keyframe every 10 s). Release +build, Radeon RX 7900 GRE, FFmpeg 9.0.1, Cisco's OpenH264 2.6.0. + +Decoding as fast as it goes (`tests/ffmpeg_decoders.rs` +`h264_with_b_frames_at_1440p60`, `--ignored`): pictures out of 600 frames, +pictures per second of decoding (copied into a `VideoFrame`), the slowest +frame. Both FFmpeg decoders give the same pictures, in order. + +| Decoder | x264 stream | `h264_vaapi` stream | +|---|---|---| +| `h264_vaapi` | 598, 424 fps, 6.8 ms | 599, 398 fps, 4.0 ms | +| `h264` (software) | 598, 276 fps, 8.0 ms | 599, 302 fps, 6.6 ms | +| OpenH264 | 8, 592 errors | 8, 592 errors | + +Played in real time into a `VideoPipeline` whose consumer converts every +picture to RGBA as the app does (`voelin-core/tests/decode_rate.rs`, +`--ignored`), both streams alike: + +| Decoders | No loss | A frame lost every second | +|---|---|---| +| the ladder (`h264_vaapi`) | 59.9 fps | 58.9 fps (concealed; a keyframe asked for every 500 ms meanwhile) | +| OpenH264 alone (the app before FFmpeg's decoders) | 0.8 fps | 0.8 fps | + +OpenH264 does not decode B-frames: every B-frame is an error, and the +pipeline then waited for keyframes the encoder sends every few seconds at +most. That was the "very bad frame rate" of an official client's stream in +the app. + ### Wayland screen capture, measured Same machine, a 2560x1440 Wayland desktop through the ScreenCast portal, @@ -994,7 +1131,9 @@ test -p voelin-media` (skipped without `DISPLAY`). FFmpeg needs nothing at build time (feature `ffmpeg` only adds `libloading`); its tests run with the runtime libraries installed (`libavcodec60` on Ubuntu 24.04) and are skipped without them; `VOELIN_OPENH264_LIB` lets them decode x264's output -with Cisco's OpenH264, `--features av1` AV1 with dav1d. +with Cisco's OpenH264, `--features av1` AV1 with dav1d. The decoder tests +(`tests/ffmpeg_decoders.rs`, `tests/decoder_alloc.rs`) need the same and an +encoder per codec they check (each is skipped without one). Windows: libvpx is not found through pkg-config there. Install it (e.g. `vcpkg install libvpx:x64-windows`) and set `VPX_LIB_DIR`, `VPX_INCLUDE_DIR` @@ -1035,6 +1174,15 @@ has not run on Windows yet. | OpenH264 download, SHA-256 check, reuse | `tests/openh264.rs -- --ignored` | tested locally (network) | | H.264 library missing / unknown file | unit + integration tests | tested | | AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; streams of SVT-AV1, rav1e, libaom, `av1_vaapi` and `av1_amf` decoded (rows below) | +| FFmpeg decoders' self-test: every decoder of the build, the clips and the test picture, a GPU decoder that falls back to software reported as unusable | `ffmpeg::decoder::tests`, `tests/ffmpeg_decoders.rs` `probe_reports_every_decoder` | tested on the Radeon RX 7900 GRE: VA-API decodes AV1, HEVC, VP9 and H.264; `vp8_vaapi` reported unusable (the GPU has no VP8 decoder); NVDEC skipped (no NVIDIA GPU) | +| Every encoder of the machine → every decoder of its codec (PSNR > 28 dB, every frame a picture) | `tests/ffmpeg_decoders.rs` `every_encoder_decodes_with_every_decoder` | tested: 20 pairs (`av1_vaapi`, SVT-AV1, libaom → `av1_vaapi`, `libdav1d`, `libaom-av1`; `h264_vaapi`, x264 → `h264_vaapi`, `h264`; `hevc_vaapi` → `hevc_vaapi`, `hevc`; libvpx → `vp9_vaapi`, `vp9`, `vp8`, `libvpx`), 36.4-38.1 dB | +| VA-API decoding on the GPU (every picture from a VA-API surface, none from FFmpeg's software path), 320x240 and 1920x1080 | `tests/ffmpeg_decoders.rs` `vaapi_decodes_on_the_gpu` | tested: `av1_vaapi`, `hevc_vaapi`, `vp9_vaapi`, `h264_vaapi`; skipped where no VA-API decoder works | +| No allocation per picture in any FFmpeg decoder | `tests/decoder_alloc.rs` (counting allocator) | tested: 0 allocations over 30 pictures for each of the ten decoders that work here | +| What a viewer accepts with and without FFmpeg (`VOELIN_FFMPEG=0`) | `tests/ffmpeg_decoders.rs` `decoders_with_and_without_ffmpeg` (the second half in a child process) | tested: AV1, HEVC, VP9, H.264, VP8 with FFmpeg; VP9, VP8 (libvpx) without | +| A failing decoder replaced by the next of the ladder (errors, or no pictures), pictures going on; after a loss a concealing decoder goes on and one that does not skips to the keyframe, keyframes asked for every 500 ms until one comes | `voelin-core` `media::tests::a_failing_decoder_is_replaced_by_the_next`, `losses_ask_for_keyframes_until_one_comes` | tested (a decoder made to fail ahead of libvpx) | +| H.264 with B-frames at 1440p60: every decoder, and the pipeline in real time with and without losses | `tests/ffmpeg_decoders.rs` `h264_with_b_frames_at_1440p60`, `voelin-core/tests/decode_rate.rs` (both `--ignored`, `--release`) | measured, see [Decoders, measured](#decoders-measured) | +| Chromium's AV1, VP9 and H.264 → our viewer → the pipeline, at their size | `voelin-core/tests/browser_codecs.rs` `browser_streams_decode_in_the_pipeline` (`VOELIN_INTEROP=1`, system Chromium 152) | tested: decoded by `av1_vaapi`, `vp9_vaapi`, `h264_vaapi` | +| Hardware decoders NVDEC, D3D11VA, DXVA2, VideoToolbox | – | not tested (no such hardware here); NVDEC is skipped by the vendor check, the Windows table type-checks for `x86_64-pc-windows-gnu`, the macOS one is not compiled here | | X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested | | wlroots capture (wlr-screencopy v3): outputs, pixels, a change arriving as a new frame, queue API | `tests/wlroots_capture.rs` against headless sway 1.9 (`VOELIN_WLROOTS_TEST_DISPLAY`) | tested; the ext-image-copy-capture path is untested (sway 1.9 predates it) | | Converter (strides, unpadded last row, odd sizes, RGBA/I420/NV12), scaler (flat, area average, half), pyramid (sharing, recycling, steady-state pools) | unit tests | tested | @@ -1053,7 +1201,7 @@ has not run on Windows yet. | Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) | | x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame | | Hardware encoders VA-API and AMF (H.264, HEVC, AV1) in the streamer pipeline | `voelinctl stream bench` on a Radeon RX 7900 GRE, 1080p60 / 1440p60 / simulcast | tested: full frame rate, 0.20-0.52 cores against 1.16-2.55 for software, 1.02 allocations per encoded frame, every backend within 2 % of the target bitrate once `av1_vaapi` got a two-second buffer (it overshot by 3.5-8 %; see the tables above) | -| Hardware encoders → our decoders: `h264_vaapi` / `h264_amf` → OpenH264, `av1_vaapi` / `av1_amf` → dav1d (PSNR > 28 dB, decoded size, keyframes at start and on request, timestamps, bitrate change) at 320x240 and 1920x1080 | `tests/ffmpeg.rs` `hardware_encoders_roundtrip` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested on the Radeon RX 7900 GRE: it found the AV1 encoder padding 1080 rows to 1082 (and other sizes to 64x16), now cropped (see above). HEVC is not decoded (no decoder here) | +| Hardware encoders → our decoders: `h264_vaapi` / `h264_amf` → OpenH264, `av1_vaapi` / `av1_amf` → dav1d (PSNR > 28 dB, decoded size, keyframes at start and on request, timestamps, bitrate change) at 320x240 and 1920x1080 | `tests/ffmpeg.rs` `hardware_encoders_roundtrip` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested on the Radeon RX 7900 GRE: it found the AV1 encoder padding 1080 rows to 1082 (and other sizes to 64x16), now cropped (see above). HEVC is decoded by FFmpeg's decoders in `tests/ffmpeg_decoders.rs` | | The alignment an AV1 encoder pads to, from the sequence header it writes | `ffmpeg::encoder::tests::av1_declared_size_and_alignment` (every optional header field), the self-test on the GPU | tested: (64, 16) for `av1_vaapi` and `av1_amf`, (2, 2) for SVT-AV1, rav1e and libaom | | Hardware encoders NVENC, Quick Sync, Media Foundation, VideoToolbox | – | not tested (no such hardware here); NVENC and Quick Sync are skipped by the vendor check and the Windows code type-checks for `x86_64-pc-windows-gnu` | | H.264 SPS against the offered `profile-level-id` (`profile_idc`, `level_idc`) for every usable backend, two sizes, both profiles | `tests/ffmpeg.rs` `sps_carries_the_offered_profile_and_level` | tested: it found `h264_amf` emitting level 4.2 where the offer said 3.1; with the level now set, all backends emit the offered level | diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 5a483c2..f426cd4 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -313,6 +313,33 @@ with a new peer, so the connection broke and nothing was shown. Now against Chromium: `browser_renegotiates_with_rust` (VP8, then a re-offer of VP9 on the same connection; VP9 frames arrive). +### What Voelin accepts from official streamers (2026-10-03) + +The re-offer above came from our answer lacking AV1, and the H.264 the +official client then sent decoded badly: its encoder (AMF on the user's +AMD GPU, 2560x1440 at 60 fps, 6-9 Mbit/s) uses B-frames and a lookahead +(its log prints QP for "IDR / P / B-frames") although the negotiated +profile is Constrained High, and asked for a keyframe only twice in the +session. Voelin decoded H.264 with Cisco's OpenH264 2.6.0, which does not +decode B-frames: in a 1440p60 test stream with B-frames it gave 8 pictures +of 600, every B-frame an error, and the viewer then waited for keyframes. + +A Voelin viewer now decodes with FFmpeg first ([media.md](../media.md#ffmpeg-decoders-loaded-at-runtime)): +hardware (VA-API on Linux, D3D11VA / DXVA2 on Windows, VideoToolbox on +macOS, NVDEC), then FFmpeg's software decoders, then the built-in libvpx, +OpenH264 and dav1d. It accepts AV1, HEVC, VP9, H.264 and VP8 wherever one +of them works (any FFmpeg build has software HEVC, VP9, H.264 and VP8; +AV1 needs dav1d or libaom in it, or a GPU), and answers in the offer's +order, so an official client that offers AV1 first gets AV1 back and no +longer re-aligns. H.264 no longer depends on OpenH264, and B-frames +decode: the same 1440p60 stream plays at 59.9 fps through VA-API, 58.9 +fps with a frame lost every second (FFmpeg's H.264 decoder conceals the +loss while a keyframe is asked for, every half second until one comes), +against 0.8 fps with OpenH264. Headless Chromium 152's AV1, VP9 and H.264 +streams decode in the pipeline at their size (`browser_codecs.rs` +`browser_streams_decode_in_the_pipeline`). Watching the official client +itself with these decoders is still to be confirmed. + ## Open questions - [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above). From 1f7967cc9b731906566ee7ba4eea0a420bc3ed49 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:33:33 +0300 Subject: [PATCH 8/9] Measure AV1 at 1440p60 through every AV1 decoder The official client sends AV1 from GPUs that encode it, so the decoders' measurement covers it too: streams from av1_vaapi (hardware, as the official client's AMF) and SVT-AV1 at 2560x1440 and 60 fps, decoded by every decoder of the AV1 ladder and compared with dav1d's pictures. All 600 pictures from each, the same: av1_vaapi 301-309 fps, libdav1d (8 threads) 412-426 fps, libaom 240-286 fps (release build, RX 7900 GRE, FFmpeg 9.0.1). The H.264 measurement shares the helpers now, and its table in media.md gives the range of two runs on a desktop in use. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-media/tests/ffmpeg_decoders.rs | 144 +++++++++++++++---- docs/media.md | 29 +++- 2 files changed, 136 insertions(+), 37 deletions(-) diff --git a/crates/voelin-media/tests/ffmpeg_decoders.rs b/crates/voelin-media/tests/ffmpeg_decoders.rs index 33affd4..9a7ef1f 100644 --- a/crates/voelin-media/tests/ffmpeg_decoders.rs +++ b/crates/voelin-media/tests/ffmpeg_decoders.rs @@ -299,32 +299,51 @@ fn ffmpeg_command(path: &std::path::Path, args: &[&str]) -> bool { true } -/// H.264 with B-frames at 2560x1440 and 60 fps, like the official client's -/// stream (AMF with B-frames and rare keyframes): every H.264 decoder of -/// the ladder, and Cisco's OpenH264 with `VOELIN_OPENH264_LIB`, decodes it; -/// how fast, the slowest frame, and whether every picture comes out, in -/// order (against FFmpeg's software decoder). The streams come from the -/// `ffmpeg` command: x264 with 3 B-frames, `h264_vaapi` with 2, ten -/// seconds of `testsrc2` at 8 Mbit/s, keyframes every ten seconds. Run with -/// `--release`. -#[test] -#[ignore = "a measurement: needs the ffmpeg command; run with --release"] -fn h264_with_b_frames_at_1440p60() { - if ffmpeg().is_none() { - return; +/// The temporal units of a low-overhead AV1 stream (`-f obu`), each +/// starting with a temporal delimiter OBU. +fn temporal_units(stream: &[u8]) -> Vec<&[u8]> { + let mut starts = Vec::new(); + let mut pos = 0; + while pos < stream.len() { + let header = stream[pos]; + if (header >> 3) & 0xf == 2 { + starts.push(pos); + } + // Every OBU of such a stream has its size (LEB128). + let (mut at, mut size, mut shift) = (pos + 1 + usize::from(header & 4 != 0), 0, 0); + loop { + let byte = stream[at]; + at += 1; + size |= usize::from(byte & 0x7f) << shift; + shift += 7; + if byte & 0x80 == 0 { + break; + } + } + pos = at + size; } + starts.push(stream.len()); + starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect() +} + +/// Streams of ten seconds of `testsrc2` at 2560x1440 and 60 fps, made with +/// the `ffmpeg` command from each encoder's `args` (kept in the temporary +/// directory, made again only when missing). +fn streams_1440p60( + encoders: &[(&'static str, &str)], + format: &str, +) -> Vec<(&'static str, Vec)> { let dir = std::env::temp_dir().join("voelin-h264-bframes"); std::fs::create_dir_all(&dir).unwrap(); let source = "-f lavfi -i testsrc2=size=2560x1440:rate=60 -t 10"; - let rate = "-g 600 -b:v 8M -maxrate 9M -bufsize 9M -f h264"; - let x264 = "-c:v libx264 -preset veryfast -profile:v high -bf 3 -x264-params aud=1"; - let vaapi = "-vf format=nv12,hwupload -c:v h264_vaapi -profile:v high -bf 2 -aud 1"; let mut streams = Vec::new(); - for (name, args) in [ - ("x264", format!("{source} {x264} -pix_fmt yuv420p {rate}")), - ("h264_vaapi", format!("-vaapi_device /dev/dri/renderD128 {source} {vaapi} {rate}")), - ] { - let path = dir.join(format!("{name}-bframes-1440p60.h264")); + for &(name, args) in encoders { + let vaapi = name.ends_with("_vaapi"); + let device = if vaapi { "-vaapi_device /dev/dri/renderD128 " } else { "" }; + let upload = if vaapi { "-vf format=nv12,hwupload " } else { "" }; + let args = format!("{device}{source} {upload}{args} -g 600 -b:v 8M -f {format}"); + let suffix = if format == "h264" { "-bframes" } else { "" }; + let path = dir.join(format!("{name}{suffix}-1440p60.{format}")); let args: Vec<&str> = args.split(' ').collect(); if ffmpeg_command(&path, &args) { streams.push((name, std::fs::read(&path).unwrap())); @@ -332,22 +351,40 @@ fn h264_with_b_frames_at_1440p60() { eprintln!("{name}: the ffmpeg command did not make the stream, skipped"); } } + streams +} + +/// Every decoder of `codec`'s ladder (and OpenH264 with +/// `VOELIN_OPENH264_LIB`, for H.264) on each of `streams` (frames as +/// `split` cuts them), as fast as it goes: pictures, errors, pictures per +/// second of decoding (copied into a `VideoFrame`), the slowest frame, and +/// the pictures that differ from those of `reference`, which comes first +/// in the ladder's software part. Hardware decoders must decode every +/// picture. +fn decode_rates( + codec: Codec, + what: &str, + streams: &[(&str, Vec)], + split: fn(&[u8]) -> Vec<&[u8]>, + reference: &str, +) { let codecs = Codecs::new(); let openh264 = std::env::var_os("VOELIN_OPENH264_LIB") + .filter(|_| codec == Codec::H264) .map(|path| voelin_media::codec::h264::OpenH264::load(path).unwrap()); - let mut names: Vec = - codecs.decoders_for(Codec::H264).iter().map(|b| b.to_string()).collect(); + let mut names: Vec = codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect(); + // The reference first, so that every other decoder is compared with it. + names.sort_by_key(|n| n != reference); names.extend(openh264.as_ref().map(|_| "openh264".to_owned())); - for (stream, data) in &streams { - let units = access_units(data); + for (stream, data) in streams { + let units = split(data); let mut reference: Option>> = None; for name in &names { let mut decoder: Box = match (name.as_str(), &openh264) { ("openh264", Some(library)) => Box::new(library.decoder().unwrap()), _ => { - let backend = - codecs.decoders_for(Codec::H264).into_iter().find(|b| b.name() == name); - codecs.new_decoder_with(Codec::H264, backend.unwrap()).unwrap() + let backend = codecs.decoders_for(codec).into_iter().find(|b| b.name() == name); + codecs.new_decoder_with(codec, backend.unwrap()).unwrap() } }; let mut picture = VideoFrame::black_i420(0, 0); @@ -375,20 +412,48 @@ fn h264_with_b_frames_at_1440p60() { thumbnails.iter().zip(reference).filter(differs).count() }); eprintln!( - "{stream} 2560x1440@60 with B-frames, {name}: {} of {} pictures, {errors} errors, \ - {fps:.0} fps, slowest frame {:.1} ms, {differing} differ from FFmpeg's software decoder", + "{stream} 2560x1440@60{what}, {name}: {} of {} pictures, {errors} errors, {fps:.0} \ + fps, slowest frame {:.1} ms, {differing} differ from the reference decoder", thumbnails.len(), units.len(), slowest.as_secs_f64() * 1000.0, ); - if name == "h264" { + if reference.is_none() { reference = Some(thumbnails); } else if name.ends_with("_vaapi") { assert_eq!(errors, 0, "{name}"); assert!(thumbnails.len() + 3 >= units.len(), "{name}: pictures missing"); + assert_eq!(differing, 0, "{name}"); } } } +} + +/// H.264 with B-frames at 2560x1440 and 60 fps, like the official client's +/// stream (AMF with B-frames and rare keyframes): every H.264 decoder of +/// the ladder, and Cisco's OpenH264 with `VOELIN_OPENH264_LIB`, decodes it; +/// how fast, the slowest frame, and whether every picture comes out, in +/// order (against FFmpeg's software decoder). The streams come from the +/// `ffmpeg` command: x264 with 3 B-frames, `h264_vaapi` with 2, ten +/// seconds of `testsrc2` at 8 Mbit/s, keyframes every ten seconds. Run with +/// `--release`. +#[test] +#[ignore = "a measurement: needs the ffmpeg command; run with --release"] +fn h264_with_b_frames_at_1440p60() { + if ffmpeg().is_none() { + return; + } + let streams = streams_1440p60( + &[ + ( + "x264", + "-c:v libx264 -preset veryfast -profile:v high -bf 3 -x264-params aud=1 -pix_fmt yuv420p -maxrate 9M -bufsize 9M", + ), + ("h264_vaapi", "-c:v h264_vaapi -profile:v high -bf 2 -aud 1 -maxrate 9M"), + ], + "h264", + ); + decode_rates(Codec::H264, " with B-frames", &streams, access_units, "h264"); // What a viewer adds per picture: the NV12 or I420 picture to RGBA. let mut rgba = vec![0; 2560 * 1440 * 4]; let i420 = VideoFrame::black_i420(2560, 1440); @@ -398,3 +463,20 @@ fn h264_with_b_frames_at_1440p60() { } eprintln!("to RGBA at 2560x1440: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0 / 30.0); } + +/// AV1 at 2560x1440 and 60 fps, which the official client sends from GPUs +/// that encode it: every AV1 decoder of the ladder, against dav1d. Streams +/// from `av1_vaapi` (hardware, as the official client's AMF) and SVT-AV1. +/// Run with `--release`. +#[test] +#[ignore = "a measurement: needs the ffmpeg command; run with --release"] +fn av1_at_1440p60() { + if ffmpeg().is_none() { + return; + } + let streams = streams_1440p60( + &[("av1_vaapi", "-c:v av1_vaapi"), ("libsvtav1", "-c:v libsvtav1 -preset 10")], + "obu", + ); + decode_rates(Codec::Av1, "", &streams, temporal_units, "libdav1d"); +} diff --git a/docs/media.md b/docs/media.md index 3ada234..5bfd2f8 100644 --- a/docs/media.md +++ b/docs/media.md @@ -582,7 +582,7 @@ on (`Video::set_decoder_preference`); a running watch keeps its decoder. from there into the caller's `VideoFrame` (`decode_into` reuses its buffers): no Rust allocation per picture for any decoder (`tests/decoder_alloc.rs`). Zero-copy display was not the goal; both - copies are part of the 2.4-2.5 ms per 1440p picture measured in + copies are part of the 2.4-3.3 ms per 1440p picture measured in [Decoders, measured](#decoders-measured). - Packets are handed over without a reference, so FFmpeg copies them into its own padded buffer; pictures come out as `yuv420p` (or `yuvj420p`) @@ -1003,13 +1003,14 @@ build, Radeon RX 7900 GRE, FFmpeg 9.0.1, Cisco's OpenH264 2.6.0. Decoding as fast as it goes (`tests/ffmpeg_decoders.rs` `h264_with_b_frames_at_1440p60`, `--ignored`): pictures out of 600 frames, -pictures per second of decoding (copied into a `VideoFrame`), the slowest -frame. Both FFmpeg decoders give the same pictures, in order. +pictures per second of decoding (copied into a `VideoFrame`; two runs on +a desktop in use), the slowest frame. Both FFmpeg decoders give the same +pictures, in order. | Decoder | x264 stream | `h264_vaapi` stream | |---|---|---| -| `h264_vaapi` | 598, 424 fps, 6.8 ms | 599, 398 fps, 4.0 ms | -| `h264` (software) | 598, 276 fps, 8.0 ms | 599, 302 fps, 6.6 ms | +| `h264_vaapi` | 598, 368-424 fps, 6.8-9.0 ms | 599, 355-398 fps, 4.0-8.8 ms | +| `h264` (software) | 598, 276-283 fps, 4.9-8.0 ms | 599, 268-302 fps, 6.6-8.7 ms | | OpenH264 | 8, 592 errors | 8, 592 errors | Played in real time into a `VideoPipeline` whose consumer converts every @@ -1026,6 +1027,22 @@ pipeline then waited for keyframes the encoder sends every few seconds at most. That was the "very bad frame rate" of an official client's stream in the app. +AV1 at 2560x1440 and 60 fps, which the official client sends from GPUs that +encode it (`av1_at_1440p60`, `--ignored`; streams from `av1_vaapi` and +SVT-AV1 preset 10, 8 Mbit/s): every decoder gave all 600 pictures, the same +as dav1d's. + +| Decoder | `av1_vaapi` stream | SVT-AV1 stream | +|---|---|---| +| `av1_vaapi` | 309 fps, 11.4 ms | 301 fps, 15.4 ms | +| `libdav1d` (8 threads) | 412 fps, 8.6 ms | 426 fps, 31.2 ms | +| `libaom-av1` | 240 fps, 24.7 ms | 286 fps, 49.6 ms | + +dav1d on 8 of the 32 cores outruns the GPU here, whose pictures also have to +be copied out of it; the ladder still takes the GPU first, for the CPU it +leaves free (the rule of the whole project: the best first, the others as +fallbacks). Every decoder has 4-7 times the 60 fps it needs. + ### Wayland screen capture, measured Same machine, a 2560x1440 Wayland desktop through the ScreenCast portal, @@ -1180,7 +1197,7 @@ has not run on Windows yet. | No allocation per picture in any FFmpeg decoder | `tests/decoder_alloc.rs` (counting allocator) | tested: 0 allocations over 30 pictures for each of the ten decoders that work here | | What a viewer accepts with and without FFmpeg (`VOELIN_FFMPEG=0`) | `tests/ffmpeg_decoders.rs` `decoders_with_and_without_ffmpeg` (the second half in a child process) | tested: AV1, HEVC, VP9, H.264, VP8 with FFmpeg; VP9, VP8 (libvpx) without | | A failing decoder replaced by the next of the ladder (errors, or no pictures), pictures going on; after a loss a concealing decoder goes on and one that does not skips to the keyframe, keyframes asked for every 500 ms until one comes | `voelin-core` `media::tests::a_failing_decoder_is_replaced_by_the_next`, `losses_ask_for_keyframes_until_one_comes` | tested (a decoder made to fail ahead of libvpx) | -| H.264 with B-frames at 1440p60: every decoder, and the pipeline in real time with and without losses | `tests/ffmpeg_decoders.rs` `h264_with_b_frames_at_1440p60`, `voelin-core/tests/decode_rate.rs` (both `--ignored`, `--release`) | measured, see [Decoders, measured](#decoders-measured) | +| H.264 with B-frames and AV1 at 1440p60: every decoder, and (H.264) the pipeline in real time with and without losses | `tests/ffmpeg_decoders.rs` `h264_with_b_frames_at_1440p60`, `av1_at_1440p60`, `voelin-core/tests/decode_rate.rs` (all `--ignored`, `--release`) | measured, see [Decoders, measured](#decoders-measured) | | Chromium's AV1, VP9 and H.264 → our viewer → the pipeline, at their size | `voelin-core/tests/browser_codecs.rs` `browser_streams_decode_in_the_pipeline` (`VOELIN_INTEROP=1`, system Chromium 152) | tested: decoded by `av1_vaapi`, `vp9_vaapi`, `h264_vaapi` | | Hardware decoders NVDEC, D3D11VA, DXVA2, VideoToolbox | – | not tested (no such hardware here); NVDEC is skipped by the vendor check, the Windows table type-checks for `x86_64-pc-windows-gnu`, the macOS one is not compiled here | | X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested | From 686787f33cb0c04ef6b23bb63ffa02a5c2fdb035 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 23:34:40 +0300 Subject: [PATCH 9/9] Log once when the last decoder of a ladder keeps failing A stream no decoder here takes would otherwise warn every three failures for as long as it is watched; the first time says it all. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/media.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 6dd17b2..d11dc9a 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -2639,6 +2639,8 @@ struct ActiveDecoder { failures: u32, /// Frames taken since the last picture or failure. without_picture: u32, + /// It failed with no other decoder left (logged once). + last_failed: bool, } impl ActiveDecoder { @@ -2653,7 +2655,15 @@ impl ActiveDecoder { .map_or_else(|| format!("no decoder for {codec}"), |e| e.to_string()) }) })?; - Ok(Self { codec, backend, decoder, rest, failures: 0, without_picture: 0 }) + Ok(Self { + codec, + backend, + decoder, + rest, + failures: 0, + without_picture: 0, + last_failed: false, + }) } /// The next decoder of `rest` that opens; the last error if none did. @@ -2687,7 +2697,9 @@ impl ActiveDecoder { true } Err(_) => { - warn!(%codec, %failed, "the decoder fails ({reason}), and no other is left"); + if !std::mem::replace(&mut self.last_failed, true) { + warn!(%codec, %failed, "the decoder fails ({reason}), and no other is left"); + } false } }