//! Encoder conformance: what this encoder writes is what this decoder — and, //! in the ffmpeg-driven half of the suite, what ffmpeg — reconstructs. //! //! The load-bearing property is that the encoder's own reconstruction is //! *bit-identical* to a decode of its bitstream. Both sides share the //! prediction, transform and deblocking code, so a mismatch means the syntax //! written does not describe the picture reconstructed, which is the one class //! of encoder bug that quality metrics cannot see. use ec_h264::{Decoder, Encoder, EncoderConfig, NalOutcome, OutputOrder, PictureView, Preset}; /// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. type Planes = (Vec, Vec, Vec); /// A synthetic source with real structure: moving edges, a gradient and a /// noisy patch, so intra, inter and skip all get exercised. struct Clip { w: usize, h: usize, y: Vec, u: Vec, v: Vec, } impl Clip { fn new(w: usize, h: usize) -> Clip { Clip { w, h, y: vec![0; w * h], u: vec![0; w / 2 * h / 2], v: vec![0; w / 2 * h / 2], } } /// Frame `t`: a diagonal gradient, a moving box and a deterministic noise /// field that keeps the residual from vanishing. fn render(&mut self, t: usize) { let (w, h) = (self.w, self.h); for y in 0..h { for x in 0..w { let grad = ((x + y * 2 + t * 3) % 256) as u8; let noise = ((x * 37 + y * 17 + t * 11) % 23) as u8; let box_x = (t * 5) % (w.saturating_sub(40).max(1)); let inside = x >= box_x && x < box_x + 40 && y >= h / 4 && y < h / 4 + 30; self.y[y * w + x] = if inside { 200u8.saturating_sub(noise) } else { grad / 2 + noise }; } } for y in 0..h / 2 { for x in 0..w / 2 { self.u[y * (w / 2) + x] = (100 + ((x + t) % 40)) as u8; self.v[y * (w / 2) + x] = (140 + ((y + t * 2) % 30)) as u8; } } } fn view(&self) -> PictureView<'_> { PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) } } /// Decode a whole stream with this crate's decoder, returning one I420 triple /// per picture. fn decode_all(stream: &[u8]) -> Vec { let mut dec = Decoder::new(); dec.set_output_order(OutputOrder::Decode); let mut out = Vec::new(); for nal in ec_h264_syntax::AnnexBIter::new(stream) { if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { dec.end_picture().expect("end of picture"); dec.push_nal(nal).expect("decoder accepts the NAL"); } while let Some(frame) = dec.next_frame() { out.push(planes_of(&frame)); } } dec.flush().expect("flush"); while let Some(frame) = dec.next_frame() { out.push(planes_of(&frame)); } out } fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { let (w, h) = (frame.width as usize, frame.height as usize); let mut planes = Vec::new(); for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] .into_iter() .enumerate() { let plane = &frame.planes[i]; let mut out = Vec::with_capacity(pw * ph); for row in 0..ph { out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); } planes.push(out); } let v = planes.pop().unwrap(); let u = planes.pop().unwrap(); let y = planes.pop().unwrap(); (y, u, v) } fn psnr(a: &[u8], b: &[u8]) -> f64 { let mse: f64 = a .iter() .zip(b) .map(|(&x, &y)| { let d = f64::from(x) - f64::from(y); d * d }) .sum::() / a.len() as f64; if mse == 0.0 { 99.0 } else { 10.0 * (255.0 * 255.0 / mse).log10() } } /// The encoder's reconstruction and a decode of its bitstream agree sample for /// sample, over a QP sweep, both presets, single and multi threaded. #[test] fn reconstruction_matches_the_decoder() { let mut t8x8_mbs = (0, 0); for (w, h) in [(176, 144), (208, 122), (64, 48)] { let mut clip = Clip::new(w, h); for qp in [12, 24, 33, 44] { for (threads, preset, cabac, t8x8) in [ (1usize, Preset::Fast, true, false), (4, Preset::Balanced, true, false), (1, Preset::Fast, false, false), (3, Preset::Balanced, false, false), (2, Preset::Balanced, true, true), (2, Preset::Balanced, false, true), ] { let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.qp = qp; cfg.gop_size = 5; cfg.threads = threads; cfg.preset = preset; cfg.cabac = cabac; cfg.transform_8x8 = t8x8; let mut enc = Encoder::new(cfg).expect("encoder"); let mut stream = Vec::new(); let mut recons = Vec::new(); for t in 0..8 { clip.render(t); let picture = enc.encode(&clip.view()).expect("encode"); stream.extend_from_slice(&picture.au); recons.push(enc.reconstruction().expect("a reconstruction")); } if t8x8 { let (intra, inter) = enc.transform_8x8_mbs(); t8x8_mbs.0 += intra; t8x8_mbs.1 += inter; } let decoded = decode_all(&stream); assert_eq!( decoded.len(), recons.len(), "{w}x{h} qp {qp}: picture count" ); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { assert_eq!( dec.0, rec.0, "{w}x{h} qp {qp} t{threads}: luma of picture {i}" ); assert_eq!( dec.1, rec.1, "{w}x{h} qp {qp} t{threads}: Cb of picture {i}" ); assert_eq!( dec.2, rec.2, "{w}x{h} qp {qp} t{threads}: Cr of picture {i}" ); } } } } // The flag-on streams above really carried 8x8 macroblocks of both kinds. assert!( t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, "8x8 MBs across the sweep: intra {} inter {}", t8x8_mbs.0, t8x8_mbs.1 ); } /// Quality tracks the quantiser, and a low QP is close to lossless: a stream /// that decodes bit-exactly could still be encoding garbage, and this is what /// says it is not. #[test] fn quality_follows_the_quantiser() { let (w, h) = (176, 144); let mut clip = Clip::new(w, h); let mut last = 0.0; for qp in [40, 30, 20, 10] { let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.qp = qp; cfg.gop_size = 4; cfg.threads = 1; let mut enc = Encoder::new(cfg).expect("encoder"); let mut total = 0.0; for t in 0..6 { clip.render(t); enc.encode(&clip.view()).expect("encode"); let (y, _, _) = enc.reconstruction().unwrap(); total += psnr(&clip.y, &y); } let avg = total / 6.0; assert!( avg > last, "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}" ); if qp == 10 { assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}"); } last = avg; } } /// Constant bitrate lands within a quarter of the target over a short clip, /// and every GOP boundary is an IDR the decoder can start from. #[test] fn rate_control_hits_its_target() { let (w, h) = (352, 288); let mut clip = Clip::new(w, h); let bitrate = 1_500_000u32; let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.bitrate = bitrate; cfg.framerate = 25.0; cfg.gop_size = 25; cfg.threads = 2; let mut enc = Encoder::new(cfg).expect("encoder"); let mut bits = 0u64; let frames = 50; let mut keys = 0; for t in 0..frames { clip.render(t); let p = enc.encode(&clip.view()).expect("encode"); bits += p.au.len() as u64 * 8; keys += u32::from(p.key_frame); } assert_eq!(keys, 2, "one IDR per GOP"); let actual = bits as f64 / (frames as f64 / 25.0); let ratio = actual / f64::from(bitrate); assert!( (0.7..1.35).contains(&ratio), "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})" ); } /// Every picture of a `gop_size` 1 stream is an IDR, which is what an /// intraframe master asks for. #[test] fn all_intra_when_the_gop_is_one() { let (w, h) = (64, 64); let mut clip = Clip::new(w, h); let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.gop_size = 1; cfg.qp = 26; let mut enc = Encoder::new(cfg).expect("encoder"); let mut stream = Vec::new(); for t in 0..4 { clip.render(t); let p = enc.encode(&clip.view()).expect("encode"); assert!(p.key_frame, "picture {t} is not a key frame"); stream.extend_from_slice(&p.au); } assert_eq!(decode_all(&stream).len(), 4); } // --------------------------------------------------------------------------- // ffmpeg-driven half: the third-party oracle. Skipped loudly when ffmpeg is // absent, exactly like the conformance suite's ffmpeg cross-check. // --------------------------------------------------------------------------- /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture. fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option> { // Distinct per call, not per process: several #[test]s in this binary // call this on parallel threads, and a path keyed only on stream length // lets one call's cleanup delete another's still-being-read file. static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id())); std::fs::create_dir_all(&dir).ok()?; let path = dir.join(format!( "s{}-{}.264", stream.len(), SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) )); std::fs::write(&path, stream).ok()?; let mut cmd = ec_testkit::ffmpeg(); cmd.args(["-v", "error"]); cmd.args(extra); cmd.arg("-i").arg(&path); cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]); let out = cmd.output().ok()?; let _ = std::fs::remove_file(&path); if !out.status.success() { eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); return None; } let frame = w * h * 3 / 2; if frame == 0 || out.stdout.len() % frame != 0 { eprintln!( "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", out.stdout.len() ); return None; } Some( out.stdout .chunks(frame) .map(|f| { let (y, rest) = f.split_at(w * h); let (u, v) = rest.split_at(w / 2 * h / 2); (y.to_vec(), u.to_vec(), v.to_vec()) }) .collect(), ) } /// Encode a clip and hand back the stream with the encoder's reconstructions. fn encode_clip( w: usize, h: usize, frames: usize, configure: impl FnOnce(&mut EncoderConfig), ) -> (Vec, Vec, (u64, u64)) { let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.gop_size = 10; cfg.threads = 3; configure(&mut cfg); let mut enc = Encoder::new(cfg).expect("encoder"); let mut clip = Clip::new(w, h); let mut stream = Vec::new(); let mut recons = Vec::new(); for t in 0..frames { clip.render(t); stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); recons.push(enc.reconstruction().expect("reconstruction")); } (stream, recons, enc.transform_8x8_mbs()) } /// ffmpeg's decode of our stream is our reconstruction, sample for sample, /// across a QP sweep and at a size that is not a multiple of a macroblock. #[test] fn ffmpeg_decodes_bit_exactly() { let mut t8x8_mbs = (0, 0); for (w, h) in [(176, 144), (322, 242)] { for qp in [10, 20, 28, 37, 47] { let cavlc = qp % 2 == 0; // both entropy coders across the sweep let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { cfg.qp = qp; cfg.cabac = !cavlc; cfg.transform_8x8 = t8x8; }); t8x8_mbs.0 += intra; t8x8_mbs.1 += inter; let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count"); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}"); assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}"); assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}"); } } } assert!( t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, "8x8 MBs across the sweep: intra {} inter {}", t8x8_mbs.0, t8x8_mbs.1 ); } /// The same stream under constant bitrate, which is the mode edith exports in. #[test] fn ffmpeg_decodes_a_cbr_stream_bit_exactly() { let (w, h) = (352, 288); let (stream, recons, _) = encode_clip(w, h, 12, |cfg| { cfg.bitrate = 2_000_000; cfg.framerate = 25.0; }); let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); assert_eq!(decoded.len(), recons.len()); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { assert_eq!(dec.0, rec.0, "luma of frame {i}"); assert_eq!( (dec.1.clone(), dec.2.clone()), (rec.1.clone(), rec.2.clone()), "chroma of frame {i}" ); } } /// The VA-API hardware decoder on this machine accepts the same stream: a /// bitstream a driver refuses is not a bitstream edith can ship, whatever a /// software decoder says about it. #[test] fn vaapi_decodes_our_stream() { if !std::path::Path::new("/dev/dri/renderD128").exists() { eprintln!("SKIP vaapi_decodes_our_stream: no render node"); return; } let (w, h) = (352, 288); let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { cfg.qp = 26; cfg.transform_8x8 = true; }); assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream"); let Some(decoded) = ffmpeg_decode( &stream, w, h, &[ "-hwaccel", "vaapi", "-hwaccel_device", "/dev/dri/renderD128", ], ) else { eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here"); return; }; assert_eq!(decoded.len(), recons.len(), "VA-API frame count"); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { let p = psnr(&dec.0, &rec.0); assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB"); } } /// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and /// decoded by this crate, are re-encoded and handed back to ffmpeg. /// /// Synthetic clips do not have film grain, hard cuts, or the residual /// statistics an encoder actually meets; a stream that survives a gradient and /// a moving box says nothing about one. Every picture must decode to exactly /// the encoder's own reconstruction, and the run reports the rate it landed on /// against the rate it was asked for. #[test] fn real_library_frames_encode_and_decode_exactly() { use ec_core::registry::Decoder as _; let path = ec_testkit::fixture("open/sintel_trailer-720p.mp4"); let (w, h) = (1280, 720); let (params, mut demux, index) = open_h264_source(path.as_os_str()); let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); let mut sources: Vec = Vec::new(); while sources.len() < 12 { let Ok(packet) = demux.next_packet() else { break; }; if packet.stream != index { continue; } dec.send_packet(&packet).expect("decode"); while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { if sources.len() < 12 { sources.push(planes_of(&f)); } } } assert!( sources.len() >= 6, "only {} pictures decoded from the library file", sources.len() ); let bitrate = 8_000_000u32; let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.bitrate = bitrate; cfg.framerate = 25.0; cfg.gop_size = 25; cfg.threads = 0; let mut enc = Encoder::new(cfg).expect("encoder"); let mut stream = Vec::new(); let mut recons = Vec::new(); let mut bits = 0u64; for (y, u, v) in &sources { let view = PictureView::i420(w as u32, h as u32, y, u, v); let p = enc.encode(&view).expect("encode"); bits += p.au.len() as u64 * 8; stream.extend_from_slice(&p.au); recons.push(enc.reconstruction().expect("reconstruction")); } let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); assert_eq!(decoded.len(), recons.len(), "picture count"); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip"); assert_eq!(dec.1, rec.1, "Cb of picture {i}"); assert_eq!(dec.2, rec.2, "Cr of picture {i}"); } let quality: f64 = sources .iter() .zip(&recons) .map(|((y, ..), (ry, ..))| psnr(y, ry)) .sum::() / sources.len() as f64; let rate = bits as f64 / (sources.len() as f64 / 25.0); eprintln!( "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB", sources.len(), rate / 1000.0, f64::from(bitrate) / 1000.0 ); assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); } /// Opens `path` by probing its bytes — MP4 carries an `ftyp` box at offset 4, /// Matroska starts with EBML magic `1A 45 DF A3` — never by extension. Returns /// the first H.264 video track's codec parameters (whose `extradata` is the /// avcC or CodecPrivate) and a boxed demuxer plus the track's stream index. /// /// A video track that is not H.264 (AV1, HEVC, …) is refused with a message /// naming the codec, never a panic inside the demuxer. fn open_h264_source( path: &std::ffi::OsStr, ) -> ( ec_core::registry::CodecParameters, Box, u32, ) { use std::io::{Read, Seek, SeekFrom}; let file = std::fs::File::open(path).expect("source opens"); let mut reader = std::io::BufReader::new(file); // corner-cut: a 12-byte probe reads only the two magics this gate opens // — 'ftyp' at 4 for MP4, EBML at 0 for Matroska. A third container this // crate grows to support would need its own magic here; upgrade by // extending the if-chain. let mut head = [0u8; 12]; let n = reader.read(&mut head).expect("read container head"); reader.seek(SeekFrom::Start(0)).expect("rewind"); let demux: Box = if ec_matroska::is_matroska(&head[..n]) { Box::new(ec_matroska::MatroskaDemuxer::new(reader).expect("ec-matroska opens the file")) } else if n >= 8 && &head[4..8] == b"ftyp" { Box::new(ec_mp4::Mp4Demuxer::new(reader).expect("ec-mp4 opens the file")) } else { panic!( "{}: not an MP4 or Matroska container", path.to_string_lossy() ) }; let streams = demux.streams(); if let Some((params, index)) = streams .iter() .find(|s| s.params.codec == ec_core::registry::CodecId::H264) .map(|s| (s.params.clone(), s.index)) { return (params, demux, index); } // No H.264 track: name what the video track actually is, so an AV1 or // HEVC file is refused clearly rather than panicking inside a find. if let Some(codec) = streams .iter() .find(|s| matches!(s.params.media, ec_core::registry::MediaParameters::Video(_))) .map(|s| s.params.codec) { panic!( "{}: video track is {:?}, not H.264 — this gate measures H.264 only", path.to_string_lossy(), codec ); } panic!("{}: no video track found", path.to_string_lossy()); } // --------------------------------------------------------------------------- // The encoder's rate-quality distance from x264: the survey's rank-1 gap, // because until this test existed the repo could measure our decoder against // every reference and our encoder against nothing but itself. // --------------------------------------------------------------------------- /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. /// /// The default preset codes every P macroblock as one 16x16 partition, so the /// bit-exactness sweeps above never put a 16x8, an 8x16 or a P_8x8 -- and so /// never a `sub_mb_type` -- in front of another decoder. This does. #[test] fn balanced_partitions_decode_bit_exactly() { let (w, h) = (176, 144); for qp in [16, 26, 36] { let cavlc = qp == 26; // both entropy coders write sub_mb_type let (stream, recons, _) = encode_clip(w, h, 8, |cfg| { cfg.qp = qp; cfg.cabac = !cavlc; cfg.preset = ec_h264::Preset::Balanced; }); let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count"); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}"); assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}"); assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}"); } } } #[test] fn force_keyframe_restarts_the_gop() { let (w, h) = (64, 64); let mut clip = Clip::new(w, h); let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.gop_size = 4; cfg.threads = 1; let mut enc = Encoder::new(cfg).expect("encoder"); let mut stream = Vec::new(); let keys: Vec = (0..8) .map(|t| { clip.render(t); let pic = enc.encode_with(&clip.view(), t == 2).expect("encode"); stream.extend_from_slice(&pic.au); pic.key_frame }) .collect(); assert_eq!(keys, [true, false, true, false, false, false, true, false]); assert_eq!(decode_all(&stream).len(), 8); }