From 8b9ea9ca1d5d4ae05b079ae6cdfaeda5b01c3e1a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 19:30:29 +0000 Subject: [PATCH] voelin-media: test FFmpeg encoders end to end, fix what that found The self-test and a roundtrip through our own decoders (OpenH264 for H.264, dav1d for AV1) run for every FFmpeg software encoder present: x264, SVT-AV1, rav1e and libaom all decode above 28 dB PSNR with the keyframes where they were asked for. Fixes: SVT-AV1 takes CBR from rc=2 and rejects a maximum rate equal to the target; rav1e refuses a keyframe interval of 2^30 and holds about 20 frames even in low-latency mode, so it is only used when named; a new session flushes the old one so delayed frames are not lost; the first packet of a session counts as a keyframe; FFmpeg's log lines go to the encoder they are about when backends are tested in parallel. Codecs::builtin() gives the compiled-in codecs alone, for tests that check libvpx or OpenH264 specifically. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/src/codec/hw.rs | 6 + crates/voelin-media/src/codec/mod.rs | 101 +++++++- crates/voelin-media/src/ffmpeg/encoder.rs | 103 ++++++--- crates/voelin-media/src/ffmpeg/layout.rs | 13 +- crates/voelin-media/src/ffmpeg/mod.rs | 27 ++- crates/voelin-media/src/ffmpeg/sys.rs | 3 +- crates/voelin-media/tests/codec_roundtrip.rs | 4 +- crates/voelin-media/tests/ffmpeg.rs | 230 +++++++++++++++++++ crates/voelin-media/tests/openh264.rs | 4 +- 9 files changed, 439 insertions(+), 52 deletions(-) create mode 100644 crates/voelin-media/tests/ffmpeg.rs diff --git a/crates/voelin-media/src/codec/hw.rs b/crates/voelin-media/src/codec/hw.rs index 3d80de0..7cedb6d 100644 --- a/crates/voelin-media/src/codec/hw.rs +++ b/crates/voelin-media/src/codec/hw.rs @@ -25,6 +25,12 @@ pub trait EncoderFactory: Send + Sync { true } + /// Whether the automatic choice may use it (not for encoders with a long + /// delay; those are used only when named in the settings). + fn is_automatic(&self) -> bool { + true + } + /// The backend its encoders report. fn backend(&self) -> EncoderBackend { EncoderBackend::Hardware(self.name()) diff --git a/crates/voelin-media/src/codec/mod.rs b/crates/voelin-media/src/codec/mod.rs index 5c4b634..f020003 100644 --- a/crates/voelin-media/src/codec/mod.rs +++ b/crates/voelin-media/src/codec/mod.rs @@ -389,6 +389,14 @@ struct Candidate { codec: Codec, backend: EncoderBackend, hardware: bool, + /// See [`hw::EncoderFactory::is_automatic`]. + automatic: bool, +} + +impl Candidate { + fn builtin(codec: Codec, backend: EncoderBackend) -> Self { + Self { codec, backend, hardware: false, automatic: true } + } } /// The codecs this build and machine can use, and factories for them. @@ -435,6 +443,17 @@ impl Codecs { } } + /// Only the codecs compiled into this crate (libvpx, OpenH264 once + /// loaded, dav1d): no FFmpeg or MediaCodec, nothing probed. + pub fn builtin() -> Self { + Self { + factories: Vec::new(), + #[cfg(feature = "openh264")] + openh264: None, + preference: EncoderPreference::default(), + } + } + /// Enable H.264 through a loaded OpenH264 library. #[cfg(feature = "openh264")] pub fn with_openh264(mut self, library: h264::OpenH264) -> Self { @@ -505,7 +524,8 @@ impl Codecs { let factories = |codec: Codec, hardware: bool, list: &mut Vec| { for f in self.factories.iter().filter(|f| f.is_hardware() == hardware) { if f.codecs().contains(&codec) { - list.push(Candidate { codec, backend: f.backend(), hardware }); + let automatic = f.is_automatic(); + list.push(Candidate { codec, backend: f.backend(), hardware, automatic }); } } }; @@ -514,16 +534,15 @@ impl Codecs { } #[cfg(feature = "vpx")] if vpx::check(Codec::Vp8, true).is_ok() { - list.push(Candidate { codec: Codec::Vp8, backend: EncoderBackend::Libvpx, hardware: false }); + list.push(Candidate::builtin(Codec::Vp8, EncoderBackend::Libvpx)); } factories(Codec::H264, false, &mut list); if self.has_openh264() { - let backend = EncoderBackend::OpenH264; - list.push(Candidate { codec: Codec::H264, backend, hardware: false }); + list.push(Candidate::builtin(Codec::H264, EncoderBackend::OpenH264)); } #[cfg(feature = "vpx")] if vpx::check(Codec::Vp9, true).is_ok() { - list.push(Candidate { codec: Codec::Vp9, backend: EncoderBackend::Libvpx, hardware: false }); + list.push(Candidate::builtin(Codec::Vp9, EncoderBackend::Libvpx)); } for codec in [Codec::Av1, Codec::H265, Codec::Vp8, Codec::Vp9] { factories(codec, false, &mut list); @@ -539,10 +558,10 @@ impl Codecs { /// Encoders in the order `preference` gives. pub fn encoders_for(&self, preference: &EncoderPreference) -> Vec<(Codec, EncoderBackend)> { let all = self.candidates(); - let automatic = |c: &Candidate| preference.hardware || !c.hardware; + let automatic = |c: &Candidate| c.automatic && (preference.hardware || !c.hardware); let chosen: Vec<&Candidate> = match &preference.backend { BackendChoice::Auto => all.iter().filter(|c| automatic(c)).collect(), - BackendChoice::Software => all.iter().filter(|c| !c.hardware).collect(), + BackendChoice::Software => all.iter().filter(|c| c.automatic && !c.hardware).collect(), BackendChoice::Named(name) => { let named = all.iter().filter(|c| c.backend.name() == name); let rest = all.iter().filter(|c| c.backend.name() != name && automatic(c)); @@ -753,12 +772,13 @@ mod tests { #[test] fn preference_order() { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); // Without OpenH264, H.264 is neither offered nor accepted. assert!(!codecs.decoders().contains(&Codec::H264)); assert!(codecs.new_decoder(Codec::H264).is_err()); let err = codecs.new_encoder(Codec::H264, EncoderConfig::default()).err().unwrap(); assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}"); + assert!(codecs.new_decoder(Codec::H265).is_err()); #[cfg(feature = "vpx")] { assert_eq!(codecs.decoders()[..2], [Codec::Vp9, Codec::Vp8]); @@ -777,6 +797,71 @@ mod tests { assert!(order.windows(2).all(|w| w[0] < w[1])); } + struct Fake(&'static str, Codec, bool); + + impl hw::EncoderFactory for Fake { + fn name(&self) -> &'static str { + self.0 + } + + fn codecs(&self) -> Vec { + vec![self.1] + } + + fn create(&self, codec: Codec, _: &EncoderConfig) -> Result> { + Err(unavailable(codec, "fake")) + } + + fn is_hardware(&self) -> bool { + self.2 + } + + fn backend(&self) -> EncoderBackend { + EncoderBackend::Ffmpeg(self.0) + } + } + + #[test] + fn encoder_preference() { + let mut codecs = Codecs::builtin(); + codecs.factories = vec![ + Box::new(Fake("x264", Codec::H264, false)), + Box::new(Fake("vp8_gpu", Codec::Vp8, true)), + Box::new(Fake("h264_gpu", Codec::H264, true)), + Box::new(Fake("hevc_gpu", Codec::H265, true)), + Box::new(Fake("av1_sw", Codec::Av1, false)), + ]; + let names = |preference: EncoderPreference| -> Vec<&'static str> { + codecs.encoders_for(&preference).iter().map(|(_, b)| b.name()).collect() + }; + let auto = names(EncoderPreference::default()); + // Hardware in codec order (HEVC last), then software. + assert_eq!(auto[..3], ["h264_gpu", "vp8_gpu", "hevc_gpu"]); + let position = |list: &[&str], name| list.iter().position(|n| *n == name).unwrap(); + assert!(position(&auto, "x264") < position(&auto, "av1_sw")); + #[cfg(feature = "vpx")] + assert!(position(&auto, "libvpx") < position(&auto, "x264"), "VP8 before software H.264"); + let no_hardware = names(EncoderPreference { hardware: false, ..Default::default() }); + assert!(!no_hardware.iter().any(|n| n.ends_with("_gpu"))); + let software = + names(EncoderPreference { hardware: true, backend: "software".parse().unwrap() }); + assert_eq!(software, no_hardware); + // A named backend comes first, even hardware with acceleration off. + let named = + names(EncoderPreference { hardware: false, backend: "hevc_gpu".parse().unwrap() }); + assert_eq!(named[0], "hevc_gpu"); + assert!(!named[1..].iter().any(|n| n.ends_with("_gpu"))); + // The codecs follow the preference. + codecs.set_preference(EncoderPreference::default()); + assert_eq!(codecs.encoder_codecs()[..3], [Codec::H264, Codec::Vp8, Codec::H265]); + // The report ranks what the preference uses. + let report = codecs.report(); + let openh264 = report.encoders.iter().find(|e| e.name == "openh264").unwrap(); + assert!(openh264.status.is_err() && openh264.rank.is_none()); + assert_eq!("auto".parse::().unwrap(), BackendChoice::Auto); + assert_eq!(BackendChoice::Named("h264_vaapi".into()).to_string(), "h264_vaapi"); + } + #[test] fn thread_heuristic() { let config = EncoderConfig { threads: 3, ..EncoderConfig::default() }; diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 8dae0c9..a3251fa 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -105,7 +105,8 @@ pub static BACKENDS: &[BackendSpec] = &[ backend!("av1_vaapi", Av1, "VA-API", Hardware, Vaapi, false, INFINITE), backend!("av1_qsv", Av1, "Quick Sync", Hardware, Nv12, true, 65535), backend!("libsvtav1", Av1, "SVT-AV1", Software, Yuv420p, false, INFINITE), - backend!("librav1e", Av1, "rav1e", Software, Yuv420p, false, INFINITE), + // rav1e refuses a keyframe interval of 2^30. + backend!("librav1e", Av1, "rav1e", Software, Yuv420p, false, 1 << 29), backend!("libaom-av1", Av1, "libaom", Software, Yuv420p, false, INFINITE), // VP9 and VP8 (software VP8 / VP9 is libvpx, used directly) backend!("vp9_vaapi", Vp9, "VA-API", Hardware, Vaapi, false, INFINITE), @@ -122,6 +123,13 @@ impl BackendSpec { self.kind == BackendKind::Hardware } + /// Whether the automatic choice may use it: rav1e holds about 20 frames + /// before its first packet even in its low-latency mode (measured with + /// rav1e 0.7), so it is only used when named in the settings. + pub fn is_automatic(&self) -> bool { + self.name != "librav1e" + } + fn is_vaapi(&self) -> bool { self.input == Input::Vaapi } @@ -186,7 +194,8 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< let screen = config.content == ContentHint::Screen; let baseline = config.h264_profile == H264Profile::ConstrainedBaseline; let h264 = spec.codec == Codec::H264; - let generic_profile = if baseline { PROFILE_H264_CONSTRAINED_BASELINE } else { PROFILE_H264_HIGH }; + let generic_profile = + if baseline { PROFILE_H264_CONSTRAINED_BASELINE } else { PROFILE_H264_HIGH }; let mut list = Vec::new(); match spec.family() { "nvenc" => { @@ -213,7 +222,10 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< list.push(opt("look_ahead_depth", &["0"])); list.push(opt("forced_idr", &["1"])); list.push(opt("low_delay_brc", &["1"])); - list.push(opt("scenario", if screen { &["displayremoting"] } else { &["videoconference"] })); + list.push(opt( + "scenario", + if screen { &["displayremoting"] } else { &["videoconference"] }, + )); if h264 { list.push(opt("profile", if baseline { &["baseline"] } else { &["high"] })); } @@ -290,12 +302,18 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec< "libsvtav1" => { let preset = config.speed.unwrap_or(10).to_string(); list.push(Setting { values: vec![preset], ..opt("preset", &[]) }); - list.push(opt("svtav1-params", &["pred-struct=1:lookahead=0:scd=0", "pred-struct=1"])); + list.push(opt( + "svtav1-params", + &["rc=2:pred-struct=1:lookahead=0:scd=0", "rc=2:pred-struct=1"], + )); } "librav1e" => { let speed = config.speed.unwrap_or(10).to_string(); list.push(Setting { values: vec![speed], ..opt("speed", &[]) }); - list.push(opt("rav1e-params", &["low_latency=true"])); + list.push(opt( + "rav1e-params", + &["low_latency=true:rdo_lookahead_frames=1:reservoir_frame_delay=12"], + )); } "libaom-av1" => { let cpu_used = config.speed.unwrap_or(8).to_string(); @@ -356,10 +374,20 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { let c_path = cstr(&path); // SAFETY: out pointer and C strings are valid; no options. let ret = unsafe { - (api.av_hwdevice_ctx_create)(&mut device, kind, c_path.as_ptr(), std::ptr::null_mut(), 0) + (api.av_hwdevice_ctx_create)( + &mut device, + kind, + c_path.as_ptr(), + std::ptr::null_mut(), + 0, + ) }; if ret < 0 { - return Err(format!("VA-API device {path}: {}{}", api.error_text(ret), log_suffix())); + return Err(format!( + "VA-API device {path}: {}{}", + api.error_text(ret), + log_suffix("vaapi") + )); } Ok(Device(device)) }) @@ -369,8 +397,8 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result { } /// FFmpeg's recent messages, appended to an error. -fn log_suffix() -> String { - let log = take_log(); +fn log_suffix(context: &str) -> String { + let log = take_log(context); if log.is_empty() { String::new() } else { format!(" ({})", log.join("; ")) } } @@ -419,6 +447,9 @@ struct Session { hw: Ptr, packet: Ptr, last_pts: Option, + /// No packet came out yet: the first one starts the stream, so it is a + /// keyframe even where the wrapper does not flag it (rav1e). + first_packet: bool, timestamps: Timestamps, nv12: bool, } @@ -488,7 +519,7 @@ impl FfmpegEncoder { "{} {what}: {}{}", self.spec.name, self.ffmpeg.api.error_text(code), - log_suffix() + log_suffix(self.spec.name) ), } } @@ -587,6 +618,7 @@ impl FfmpegEncoder { hw: std::ptr::null_mut(), packet: std::ptr::null_mut(), last_pts: None, + first_packet: true, timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, }; @@ -596,7 +628,9 @@ impl FfmpegEncoder { let (w, h) = (width as c_int, height as c_int); let sw_format = if session.nv12 { pix.nv12 } else { pix.yuv420p }; let format = match self.spec.input { - Input::Vaapi => pix.vaapi.ok_or_else(|| self.unavailable("no VA-API pixel format".into()))?, + Input::Vaapi => { + pix.vaapi.ok_or_else(|| self.unavailable("no VA-API pixel format".into()))? + } _ => sw_format, }; let size = cstr("video_size"); @@ -620,7 +654,9 @@ impl FfmpegEncoder { let gop = self.config.keyframe_interval.map_or(self.spec.infinite_gop, i64::from); let mut list = vec![ generic("b", bitrate), - generic("maxrate", bitrate), + // SVT-AV1 takes CBR from its own `rc=2` and rejects a maximum + // that is not above the target. + generic("maxrate", if self.spec.name == "libsvtav1" { 0 } else { bitrate }), generic("bufsize", bitrate), generic("g", gop), generic("bf", 0), @@ -691,7 +727,8 @@ impl FfmpegEncoder { fn vaapi_pool(&self, width: u32, height: u32) -> Result { let api = &self.ffmpeg.api; let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?; - let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; + let vaapi = + self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?; // SAFETY: `device` is a live device reference. let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) }; if pool.is_null() { @@ -778,11 +815,7 @@ impl FfmpegEncoder { } /// Receive every packet that is ready. - fn drain( - &self, - session: &mut Session, - out: &mut dyn FnMut(EncodedChunk<'_>), - ) -> Result { + fn drain(&self, session: &mut Session, out: &mut dyn FnMut(EncodedChunk<'_>)) -> Result { let api = &self.ffmpeg.api; let mut keyframe = false; loop { @@ -798,11 +831,13 @@ impl FfmpegEncoder { // `size` bytes until av_packet_unref. unsafe { let head = &*session.packet.cast::(); - let key = head.flags & sys::PKT_FLAG_KEY != 0; + let key = head.flags & sys::PKT_FLAG_KEY != 0 || session.first_packet; + session.first_packet = false; keyframe |= key; - let pts_90khz = session.timestamps.take(head.pts).unwrap_or_else(|| { - (head.pts.max(0) as u64) * 90_000 / u64::from(session.fps) - }); + let pts_90khz = session + .timestamps + .take(head.pts) + .unwrap_or_else(|| (head.pts.max(0) as u64) * 90_000 / u64::from(session.fps)); if !head.data.is_null() && head.size > 0 { let data = std::slice::from_raw_parts(head.data, head.size as usize); out(EncodedChunk { data, keyframe: key, pts_90khz }); @@ -855,8 +890,14 @@ impl FfmpegEncoder { } }; if reopen { - // One session at a time (hardware encoders have few). - self.session = None; + // Frames the old session still holds (encoders with a delay) come + // out first; then one session at a time (hardware encoders have + // few). + if let Some(mut old) = self.session.take() + && let Err(e) = self.send(&mut old, std::ptr::null_mut(), out) + { + tracing::debug!(backend = self.spec.name, "flushing the old session: {e}"); + } self.session = Some(self.open(w, h)?); self.reinit = Reinit::No; force = true; @@ -1080,9 +1121,9 @@ pub fn probe() -> &'static [BackendStatus] { spec, available: match test { None => Err("not in this FFmpeg build".into()), - Some(handle) => handle - .join() - .unwrap_or_else(|_| Err("the self-test panicked".into())), + Some(handle) => { + handle.join().unwrap_or_else(|_| Err("the self-test panicked".into())) + } }, }) .collect() @@ -1090,7 +1131,9 @@ pub fn probe() -> &'static [BackendStatus] { for status in &statuses { match &status.available { Ok(()) => tracing::info!(backend = status.spec.name, "FFmpeg encoder available"), - Err(e) => tracing::debug!(backend = status.spec.name, "FFmpeg encoder unusable: {e}"), + Err(e) => { + tracing::debug!(backend = status.spec.name, "FFmpeg encoder unusable: {e}") + } } } statuses @@ -1140,6 +1183,10 @@ impl EncoderFactory for FfmpegFactory { self.spec.is_hardware() } + fn is_automatic(&self) -> bool { + self.spec.is_automatic() + } + fn backend(&self) -> EncoderBackend { EncoderBackend::Ffmpeg(self.spec.name) } diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 9245df0..0df7c63 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -105,8 +105,10 @@ pub fn frame_fields(api: &Api) -> Result { pict_type: offset_of!(FrameWithoutKeyFrame, pict_type), pts: offset_of!(FrameWithoutKeyFrame, pts), }), - _ => Err("unknown AVFrame layout (pict_type / pts not where any known release has them)" - .into()), + _ => { + Err("unknown AVFrame layout (pict_type / pts not where any known release has them)" + .into()) + } } } @@ -208,7 +210,9 @@ fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result { break 'found base + frames_off; } } - return Err("unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into()); + return Err( + "unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into() + ); }; let device = found + size_of::(); // SAFETY: both offsets lie before `hwaccel_flags`, an option of this @@ -377,8 +381,7 @@ pub unsafe fn check_hw_frames_ctx(frame: Ptr, pool: Ptr, refs: FrameRefs) -> boo // SAFETY: guaranteed by the caller; the offset is inside AVFrame. unsafe { let hw: Ptr = read(frame, refs.hw_frames_ctx); - !hw.is_null() - && (*hw.cast::()).data == (*pool.cast::()).data + !hw.is_null() && (*hw.cast::()).data == (*pool.cast::()).data } } diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 5830540..47a9162 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -133,8 +133,7 @@ impl Ffmpeg { static FFMPEG: OnceLock> = OnceLock::new(); FFMPEG .get_or_init(|| { - if std::env::var("VOELIN_FFMPEG").is_ok_and(|v| matches!(v.as_str(), "0" | "off")) - { + if std::env::var("VOELIN_FFMPEG").is_ok_and(|v| matches!(v.as_str(), "0" | "off")) { return Err("disabled by VOELIN_FFMPEG".into()); } let loaded = Self::load(&Search::from_env()); @@ -173,16 +172,32 @@ impl Ffmpeg { } } -type FormatLine = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList, *mut c_char, c_int, *mut c_int) -> c_int; +type FormatLine = unsafe extern "C" fn( + Ptr, + c_int, + *const c_char, + VaList, + *mut c_char, + c_int, + *mut c_int, +) -> c_int; static LOG_FORMAT: OnceLock = OnceLock::new(); /// The last FFmpeg messages (warnings and errors), for error reports. static LOG: Mutex> = Mutex::new(Vec::new()); -/// Take the FFmpeg messages logged since the last call (at most 16). -pub fn take_log() -> Vec { - std::mem::take(&mut *LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) +/// Take the FFmpeg messages logged since the last call (at most 16) that +/// are about `context` (an encoder name such as `h264_vaapi`: FFmpeg +/// prefixes its messages with `[h264_vaapi @ 0x...]`) or about nothing in +/// particular. Messages of other encoders (tested in parallel) stay. +pub fn take_log(context: &str) -> Vec { + let mut log = LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let tag = format!("[{context} @"); + let (mine, others): (Vec, Vec) = + log.drain(..).partition(|line| line.contains(&tag) || !line.contains(" @ 0x")); + *log = others; + mine } unsafe extern "C" fn log_callback(avcl: Ptr, level: c_int, fmt: *const c_char, vl: VaList) { diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index d82b4c6..c95bbb2 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -394,7 +394,8 @@ fn candidates(search: &Search, base: &str) -> Vec { } } if cfg!(windows) - && let Some(dir) = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned)) + && let Some(dir) = + std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned)) { list.extend(files_in(&dir, base)); } diff --git a/crates/voelin-media/tests/codec_roundtrip.rs b/crates/voelin-media/tests/codec_roundtrip.rs index c92561d..07ffb06 100644 --- a/crates/voelin-media/tests/codec_roundtrip.rs +++ b/crates/voelin-media/tests/codec_roundtrip.rs @@ -27,7 +27,7 @@ fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str) /// Encode 30 frames of the pattern, force a keyframe midway, lower the /// bitrate, and check every decoded frame. fn roundtrip(codec: Codec) { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); let screen = SyntheticScreen::new(W, H); let config = EncoderConfig { fps: FPS, bitrate_bps: 1_500_000, ..EncoderConfig::default() }; let mut encoder = codecs.new_encoder(codec, config).unwrap(); @@ -69,7 +69,7 @@ fn vp9_synthetic_roundtrip() { /// Frames from the capture thread go through encode / decode in order. #[tokio::test] async fn capture_thread_to_decoder() { - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); let mut screen = SyntheticScreen::new(W, H); let options = CaptureOptions { fps: 60, cursor: false, queue: 8 }; let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap(); diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs new file mode 100644 index 0000000..8393ecc --- /dev/null +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -0,0 +1,230 @@ +//! Encoders through the system's FFmpeg (loaded at runtime), decoded with +//! this crate's own decoders: H.264 with Cisco's OpenH264 +//! (`VOELIN_OPENH264_LIB`), AV1 with dav1d (`--features av1`). +//! +//! Skipped without FFmpeg. Hardware backends need their GPU and driver; on a +//! machine without them the self-test reports why and they are skipped. +#![cfg(feature = "ffmpeg")] + +use std::time::Duration; + +use voelin_media::capture::synthetic::SyntheticScreen; +use voelin_media::ffmpeg::{BACKENDS, Ffmpeg, FfmpegEncoder, probe}; +use voelin_media::{ + Codec, Codecs, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, convert, +}; + +const W: u32 = 320; +const H: u32 = 240; + +fn ffmpeg() -> Option<&'static Ffmpeg> { + match Ffmpeg::get() { + Ok(f) => Some(f), + Err(e) => { + eprintln!("FFmpeg not available ({e}), skipped"); + None + } + } +} + +fn decoder(codec: Codec) -> Option> { + match codec { + #[cfg(feature = "openh264")] + Codec::H264 => { + let path = std::env::var_os("VOELIN_OPENH264_LIB")?; + let library = voelin_media::codec::h264::OpenH264::load(path).ok()?; + Some(Box::new(library.decoder().unwrap())) + } + #[cfg(feature = "av1")] + Codec::Av1 => Some(Box::new(voelin_media::codec::av1::Dav1dDecoder::new().unwrap())), + _ => None, + } +} + +/// Twelve frames of the moving test pattern, a keyframe forced at 8, a +/// bitrate change at 5: keyframes where asked, timestamps kept, and (with a +/// decoder) every picture decodable at PSNR > 28 dB. +fn roundtrip(name: &'static str) { + let screen = SyntheticScreen::new(W, H); + let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() }; + let mut encoder = FfmpegEncoder::new(name, config).unwrap(); + assert_eq!(encoder.backend(), EncoderBackend::Ffmpeg(name)); + let codec = encoder.codec(); + let mut decoder = decoder(codec); + let mut keyframes = Vec::new(); + let mut sent = Vec::new(); + let mut decoded = 0; + let mut sources = Vec::new(); + // Frames in until the first packet came out (the encoder's delay). + let mut delay = None; + // Until frame 11 came out (encoders with a delay need more input). + for n in 0..60u32 { + if sources.len() > 11 && sent.len() >= 12 { + break; + } + let frame = screen.frame(u64::from(n), 30); + if n == 5 { + encoder.set_bitrate(800_000).unwrap(); + } + let out = encoder.encode(&frame, n == 8).unwrap(); + sources.push(frame); + if delay.is_none() && !out.is_empty() { + delay = Some(n); + } + for f in &out { + sent.push(f.pts_90khz); + // Encoders with a delay hand out older frames: match by time. + let index = sources.iter().position(|s| s.pts_90khz() == f.pts_90khz).unwrap(); + if f.keyframe { + keyframes.push(index); + } + if let Some(decoder) = &mut decoder + && let Some(picture) = decoder.decode(&f.data).unwrap() + { + assert_eq!((picture.width, picture.height), (W, H)); + let psnr = convert::psnr(&sources[index], &picture).unwrap(); + assert!(psnr > 28.0, "{name} frame {index}: PSNR {psnr:.1} dB"); + decoded += 1; + } + } + } + eprintln!( + "{name}: {} packets from {} frames (first after {delay:?}), keyframes at {keyframes:?}, decoded {decoded}", + sent.len(), + sources.len() + ); + assert!(sent.len() >= 8, "{name}: only {} packets", sent.len()); + assert_eq!(keyframes.first(), Some(&0), "{name}"); + assert!(keyframes.contains(&8), "{name}: forced keyframe missing: {keyframes:?}"); + assert!(sent.windows(2).all(|w| w[0] < w[1]), "{name}: timestamps {sent:?}"); + assert_eq!(sent[0], 0); + if decoder.is_some() { + assert!(decoded >= 8, "{name}: decoded {decoded}"); + } +} + +fn available(name: &str) -> bool { + probe().iter().any(|s| s.spec.name == name && s.available.is_ok()) +} + +#[test] +fn probe_reports_every_backend() { + let Some(ffmpeg) = ffmpeg() else { return }; + eprintln!("{:?}", ffmpeg.info()); + let statuses = probe(); + assert_eq!(statuses.len(), BACKENDS.len()); + for status in statuses { + eprintln!("{:>18}: {:?}", status.spec.name, status.available); + if let Err(reason) = &status.available { + assert!(!reason.is_empty()); + } + } + // The report lists them with the built-in ones. + let report = Codecs::new().report(); + assert!(report.ffmpeg.is_ok(), "{report:?}"); + assert!(report.encoders.iter().any(|e| e.name == "libvpx")); + for status in statuses { + let info = report.encoders.iter().find(|e| e.name == status.spec.name).unwrap(); + assert_eq!(info.status, status.available); + let automatic = status.available.is_ok() && status.spec.is_automatic(); + assert_eq!(info.rank.is_some(), automatic, "{}", status.spec.name); + } +} + +#[test] +fn software_encoders_roundtrip() { + if ffmpeg().is_none() { + return; + } + let mut tested = Vec::new(); + for name in ["libx264", "libopenh264", "libsvtav1", "librav1e", "libaom-av1"] { + if available(name) { + roundtrip(name); + tested.push(name); + } else { + eprintln!("{name} skipped: not available"); + } + } + eprintln!("tested: {tested:?}"); +} + +#[test] +fn x264_is_constrained_high_and_changes_size() { + if ffmpeg().is_none() || !available("libx264") { + return; + } + let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() }; + let mut encoder = FfmpegEncoder::new("libx264", config).unwrap(); + let screen = SyntheticScreen::new(W, H); + let first = encoder.encode(&screen.frame(0, 30), false).unwrap(); + // profile_idc 100 (High) without B-frames: what TeamSpeak decodes. + let sps = + first[0].data.windows(5).find(|w| w[..4] == [0, 0, 1, 0x67] || w[..4] == [0, 0, 0, 1]); + assert!(sps.is_some()); + let profile = h264_profile(&first[0].data); + assert_eq!(profile, Some(100), "High profile"); + // A new size: a new session, starting with a keyframe. + let small = SyntheticScreen::new(160, 120); + let out = encoder.encode(&small.frame(1, 30), false); + assert!(out.unwrap().iter().any(|f| f.keyframe)); + // Odd sizes are cropped to even ones instead of failing. + let odd = + voelin_media::VideoFrame::black_i420(201, 151).with_timestamp(Duration::from_millis(66)); + assert!(encoder.encode(&odd, false).unwrap().iter().any(|f| f.keyframe)); + // Baseline on request. + let baseline = EncoderConfig { + h264_profile: voelin_media::H264Profile::ConstrainedBaseline, + ..EncoderConfig::default() + }; + let mut encoder = FfmpegEncoder::new("libx264", baseline).unwrap(); + let out = encoder.encode(&screen.frame(0, 30), false).unwrap(); + assert_eq!(h264_profile(&out[0].data), Some(66)); +} + +/// `profile_idc` of the first SPS in an Annex B stream. +fn h264_profile(data: &[u8]) -> Option { + let mut i = 0; + while i + 4 < data.len() { + if data[i..i + 3] == [0, 0, 1] { + if data[i + 3] & 0x1f == 7 { + return data.get(i + 4).copied(); + } + i += 3; + } else { + i += 1; + } + } + None +} + +#[test] +fn codecs_prefer_ffmpeg_h264_over_nothing() { + if ffmpeg().is_none() || !available("libx264") { + return; + } + let codecs = Codecs::new(); + assert!(codecs.encoder_codecs().contains(&Codec::H264)); + let encoder = codecs.new_encoder(Codec::H264, EncoderConfig::default()).unwrap(); + assert!(matches!(encoder.backend(), EncoderBackend::Ffmpeg(_))); + let named = + voelin_media::EncoderPreference { hardware: false, backend: "libx264".parse().unwrap() }; + let encoder = codecs.new_encoder_preferring(Codec::H264, EncoderConfig::default(), &named); + assert_eq!(encoder.unwrap().backend(), EncoderBackend::Ffmpeg("libx264")); +} + +/// Unknown names and hardware without its device fail with a reason, not +/// a panic. +#[test] +fn unusable_backends_fail_cleanly() { + if ffmpeg().is_none() { + return; + } + assert!(FfmpegEncoder::new("no_such_encoder", EncoderConfig::default()).is_err()); + for status in probe().iter().filter(|s| s.available.is_err()) { + let Ok(mut encoder) = FfmpegEncoder::new(status.spec.name, EncoderConfig::default()) else { + continue; + }; + let frame = voelin_media::VideoFrame::black_i420(W, H); + assert!(encoder.encode(&frame, true).is_err(), "{} passed now", status.spec.name); + } +} diff --git a/crates/voelin-media/tests/openh264.rs b/crates/voelin-media/tests/openh264.rs index d89cc0f..20b4c51 100644 --- a/crates/voelin-media/tests/openh264.rs +++ b/crates/voelin-media/tests/openh264.rs @@ -21,7 +21,7 @@ fn missing_library_is_a_clear_error() { assert!(err.to_string().contains("OpenH264 library not found"), "{err}"); // Without a library, H.264 is neither decodable nor encodable. - let codecs = Codecs::new(); + let codecs = Codecs::builtin(); assert!(!codecs.decoders().contains(&Codec::H264)); assert!(!codecs.encoder_codecs().contains(&Codec::H264)); let err = codecs.new_decoder(Codec::H264).err().unwrap(); @@ -52,7 +52,7 @@ fn sps_profile(data: &[u8]) -> Option { } fn roundtrip(library: OpenH264) { - let codecs = Codecs::new().with_openh264(library.clone()); + let codecs = Codecs::builtin().with_openh264(library.clone()); assert_eq!(codecs.decoders().last(), Some(&Codec::H264)); assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264)));