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 0000000..965cb40 Binary files /dev/null and b/crates/voelin-media/src/ffmpeg/clips/av1.bin differ diff --git a/crates/voelin-media/src/ffmpeg/clips/h264.bin b/crates/voelin-media/src/ffmpeg/clips/h264.bin new file mode 100644 index 0000000..dc59e4b Binary files /dev/null and b/crates/voelin-media/src/ffmpeg/clips/h264.bin differ 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 0000000..d93d6ae Binary files /dev/null and b/crates/voelin-media/src/ffmpeg/clips/hevc.bin differ 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 0000000..27ff8f5 Binary files /dev/null and b/crates/voelin-media/src/ffmpeg/clips/vp8.bin differ 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 0000000..39302de Binary files /dev/null and b/crates/voelin-media/src/ffmpeg/clips/vp9.bin differ 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);