diff --git a/Cargo.lock b/Cargo.lock index 1cde365d..dafe65a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -548,7 +548,6 @@ dependencies = [ "ec-matroska", "ec-mp4", "ec-testkit", - "tracking-allocator", "wide", ] diff --git a/crates/ec-h264/Cargo.toml b/crates/ec-h264/Cargo.toml index 62f5ba9c..5ac1ea07 100644 --- a/crates/ec-h264/Cargo.toml +++ b/crates/ec-h264/Cargo.toml @@ -6,12 +6,6 @@ edition.workspace = true license.workspace = true authors.workspace = true -[features] -# Internal-only RD experiment switches, compiled only by the measurement harness. -rd-ablation = [] -# Per-stage timing counters in the macroblock coder (measurement builds only). -enc-profile = [] - [dependencies] ec-core = { workspace = true } ec-h264-syntax = { workspace = true } @@ -19,10 +13,7 @@ wide = { workspace = true } [dev-dependencies] ec-testkit.workspace = true -# The conformance harness walks Annex B itself to drive push_nal. -ec-h264-syntax = { workspace = true } # ... and demuxes an MP4 directly where ffmpeg's own Annex B extraction of it # produces a stream ffmpeg then cannot decode. ec-mp4 = { workspace = true } ec-matroska = { workspace = true } -tracking-allocator = "0.4.0" diff --git a/crates/ec-h264/examples/bench_encode.rs b/crates/ec-h264/examples/bench_encode.rs deleted file mode 100644 index e1ec1b26..00000000 --- a/crates/ec-h264/examples/bench_encode.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Throwaway profiling harness for lane-h264perf: repeats the bench's own -//! 640x360x30-frame encode loop N times so a perf sample has enough hits to -//! be useful. Not wired into any product surface; delete before merge if -//! still present. -use ec_h264::{Encoder, EncoderConfig, PictureView}; -use std::time::Instant; - -fn main() { - let path = std::env::args().nth(1).expect("path to raw yuv420p"); - let reps: u32 = std::env::args() - .nth(2) - .and_then(|s| s.parse().ok()) - .unwrap_or(20); - let (w, h) = (640u32, 360u32); - let data = std::fs::read(&path).expect("read raw yuv"); - let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; - let n = data.len() / frame_len; - let start = Instant::now(); - for _ in 0..reps { - let mut cfg = EncoderConfig::new(w, h); - cfg.threads = 1; - let mut enc = Encoder::new(cfg).expect("h264 encoder"); - for frame in data.chunks_exact(frame_len).take(n) { - let (y, rest) = frame.split_at((w * h) as usize); - let (u, v) = rest.split_at(rest.len() / 2); - let view = PictureView::i420(w, h, y, u, v); - enc.encode(&view).expect("h264 encode"); - } - } - let wall = start.elapsed(); - eprintln!( - "{reps} reps x {n} frames in {:.3}s ({:.2} ms/rep)", - wall.as_secs_f64(), - wall.as_secs_f64() * 1000.0 / f64::from(reps) - ); -} diff --git a/crates/ec-h264/examples/h264_clip_encode.rs b/crates/ec-h264/examples/h264_clip_encode.rs deleted file mode 100644 index 8b5ebbb3..00000000 --- a/crates/ec-h264/examples/h264_clip_encode.rs +++ /dev/null @@ -1,107 +0,0 @@ -//! Encode a raw I420 clip and write the bitstream and the encoder's own -//! reconstruction, for the ffmpeg recon-match and rate-control checks in -//! `scripts/h264-lane-check.sh`. Not a product surface. -//! -//! Usage: h264_clip_encode -//! -//! `-` reads raw I420 from stdin, so a 60 s 1080p clip never has to exist on -//! disk. Writes `.h264` (Annex B), and `.recon.yuv` -//! (every reconstructed picture, display order, I420 at the coded size) unless -//! the prefix is `none`. Prints frames, bytes and the wall time spent inside -//! `encode` on stdout. -use ec_h264::{Encoder, EncoderConfig, PictureView}; -use std::io::Write; -use std::time::Instant; - -fn main() { - let args: Vec = std::env::args().collect(); - if args.len() != 9 { - eprintln!( - "usage: h264_clip_encode " - ); - std::process::exit(2); - } - let parse = |i: usize| -> f64 { args[i].parse().expect("numeric argument") }; - let (w, h) = (parse(2) as u32, parse(3) as u32); - let fps = parse(4) as f32; - let bitrate = parse(5) as u32; - let qp = parse(6) as i32; - let threads = parse(7) as usize; - let prefix = &args[8]; - - let (wu, hu) = (w as usize, h as usize); - let cw = wu.div_ceil(2); - let ch = hu.div_ceil(2); - let frame_len = wu * hu + 2 * cw * ch; - let mut input: Box = if args[1] == "-" { - Box::new(std::io::stdin().lock()) - } else { - Box::new(std::fs::File::open(&args[1]).expect("open raw i420 input")) - }; - - let mut cfg = EncoderConfig::new(w, h); - cfg.framerate = fps; - cfg.bitrate = bitrate; - cfg.qp = qp; - cfg.threads = threads; - // H264_CAVLC=1 codes CAVLC instead of the default CABAC (identity checks). - cfg.cabac = std::env::var_os("H264_CAVLC").is_none(); - cfg.gop_size = (fps.round() as u32).max(1) * 2; - let mut enc = Encoder::new(cfg).expect("h264 encoder"); - - let mut stream_out = (prefix != "none") - .then(|| std::fs::File::create(format!("{prefix}.h264")).expect("create bitstream")); - let mut recon_out = (prefix != "none") - .then(|| std::fs::File::create(format!("{prefix}.recon.yuv")).expect("create recon")); - // H264_TRACE=1 prints one line per picture: its QP and size. - let trace = std::env::var_os("H264_TRACE").is_some(); - let mut frame = vec![0u8; frame_len]; - let mut frames = 0usize; - let mut bytes = 0usize; - let mut spent = std::time::Duration::ZERO; - while input.read_exact(&mut frame).is_ok() { - let (y, rest) = frame.split_at(wu * hu); - let (u, v) = rest.split_at(cw * ch); - let view = PictureView::i420(w, h, y, u, v); - let t0 = Instant::now(); - let pic = enc.encode(&view).expect("h264 encode"); - spent += t0.elapsed(); - if trace { - println!( - "trace {frames} key {} qp {} bytes {}", - u8::from(pic.key_frame), - pic.qp, - pic.au.len() - ); - } - frames += 1; - bytes += pic.au.len(); - if let Some(out) = stream_out.as_mut() { - out.write_all(&pic.au).expect("write bitstream"); - } - if let Some(out) = recon_out.as_mut() { - let (ry, ru, rv) = enc.reconstruction().expect("a reconstruction"); - out.write_all(&ry) - .and_then(|_| out.write_all(&ru)) - .and_then(|_| out.write_all(&rv)) - .expect("write reconstruction"); - } - } - println!( - "frames {frames} bytes {bytes} encode_secs {:.3} fps {:.2}", - spent.as_secs_f64(), - frames as f64 / spent.as_secs_f64() - ); - let t = enc.timings(); - println!( - "stages pad {:.3} bands_wall {:.3} bands_busy {:.3} bands_slowest {:.3} stitch {:.3} deblock {:.3} output {:.3}", - t.pad, t.bands_wall, t.bands_busy, t.bands_slowest, t.stitch, t.deblock, t.output - ); - #[cfg(feature = "enc-profile")] - { - let snap = ec_h264::mb_stages::snapshot(); - for (name, ns) in ec_h264::mb_stages::NAMES.iter().zip(snap) { - println!("mb_stage {name} {:.3}", ns as f64 / 1e9); - } - } -} diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index f6d5e5be..f520c2f6 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -107,49 +107,6 @@ pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35]; -/// Where a slice's bits went, in 1/256ths of a bit, by syntax class. The -/// arithmetic decoder spends fractional bits per element, so the sub-bit -/// resolution is the point: a class is charged the movement of -/// `bit_position * 256 + log2(codIRange)` across its own reads. Both our -/// streams and any other encoder's are parsed by this decoder, which is what -/// makes the two accounts comparable. -#[derive(Clone, Copy, Default, Debug)] -pub struct BitAccount { - pub skip: u64, - pub mb_type: u64, - pub mv: u64, - pub ref_idx: u64, - pub cbp_qp: u64, - pub intra_mode: u64, - pub residual_luma: u64, - pub residual_chroma: u64, -} - -impl BitAccount { - /// Every class summed, in 1/256ths of a bit. - pub fn total(&self) -> u64 { - self.skip - + self.mb_type - + self.mv - + self.ref_idx - + self.cbp_qp - + self.intra_mode - + self.residual_luma - + self.residual_chroma - } - - pub(crate) fn add(&mut self, other: &BitAccount) { - self.skip += other.skip; - self.mb_type += other.mb_type; - self.mv += other.mv; - self.ref_idx += other.ref_idx; - self.cbp_qp += other.cbp_qp; - self.intra_mode += other.intra_mode; - self.residual_luma += other.residual_luma; - self.residual_chroma += other.residual_chroma; - } -} - pub(crate) struct Cabac<'a> { r: BitCursor<'a>, /// codIRange (9.3.3.2). @@ -166,8 +123,6 @@ pub(crate) struct Cabac<'a> { /// The macroblock being parsed is intra coded, which flips the /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9). cur_intra: bool, - /// Bits spent so far, by syntax class. - account: BitAccount, } impl<'a> Cabac<'a> { @@ -195,7 +150,6 @@ impl<'a> Cabac<'a> { ctx: MbCtx::default(), cbp_luma_bins: 0, cur_intra: true, - account: BitAccount::default(), }; c.state = init_contexts_full(slice_qp, init_column.min(3)); c.init_engine()?; @@ -293,128 +247,6 @@ impl<'a> Cabac<'a> { /// Declare whether the macroblock being parsed is intra coded /// (9.3.3.1.1.9 reads it for every coded_block_flag). - /// The decoder's position in 1/256ths of a bit: the bits already read plus - /// what the arithmetic engine's interval says it is holding. - fn mark(&self) -> u64 { - self.r.bit_position() * 256 + u64::from(self.range.leading_zeros()) - } - - pub(crate) fn account(&self) -> BitAccount { - self.account - } - - pub(crate) fn mb_type_i(&mut self) -> Result { - let m = self.mark(); - let out = self.mb_type_i_inner(); - self.account.mb_type += self.mark() - m; - out - } - - pub(crate) fn mb_type_p(&mut self) -> Result { - let m = self.mark(); - let out = self.mb_type_p_inner(); - self.account.mb_type += self.mark() - m; - out - } - - pub(crate) fn mb_type_b(&mut self) -> Result { - let m = self.mark(); - let out = self.mb_type_b_inner(); - self.account.mb_type += self.mark() - m; - out - } - - pub(crate) fn sub_mb_type_p(&mut self) -> u32 { - let m = self.mark(); - let out = self.sub_mb_type_p_inner(); - self.account.mb_type += self.mark() - m; - out - } - - pub(crate) fn sub_mb_type_b(&mut self) -> u32 { - let m = self.mark(); - let out = self.sub_mb_type_b_inner(); - self.account.mb_type += self.mark() - m; - out - } - - pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { - let m = self.mark(); - let out = self.mb_skip_flag_inner(b_slice, inc); - self.account.skip += self.mark() - m; - out - } - - pub(crate) fn ref_idx(&mut self, inc: usize) -> Result { - let m = self.mark(); - let out = self.ref_idx_inner(inc); - self.account.ref_idx += self.mark() - m; - out - } - - pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { - let m = self.mark(); - let out = self.mvd_inner(comp, inc); - self.account.mv += self.mark() - m; - out - } - - pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { - let m = self.mark(); - let out = self.transform_size_8x8_flag_inner(); - self.account.cbp_qp += self.mark() - m; - out - } - - pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> { - let m = self.mark(); - let out = self.coded_block_pattern_inner(has_chroma); - self.account.cbp_qp += self.mark() - m; - out - } - - pub(crate) fn mb_qp_delta(&mut self) -> Result { - let m = self.mark(); - let out = self.mb_qp_delta_inner(); - self.account.cbp_qp += self.mark() - m; - out - } - - pub(crate) fn intra4x4_pred_mode(&mut self) -> Result> { - let m = self.mark(); - let out = self.intra4x4_pred_mode_inner(); - self.account.intra_mode += self.mark() - m; - out - } - - pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result { - let m = self.mark(); - let out = self.intra_chroma_pred_mode_inner(); - self.account.intra_mode += self.mark() - m; - out - } - - pub(crate) fn residual_block( - &mut self, - coeff: &mut [i32; 16], - cat: BlockCat, - comp: u8, - na: Option, - nb: Option, - ) -> Result { - let m = self.mark(); - let out = self.residual_block_inner(coeff, cat, comp, na, nb); - let spent = self.mark() - m; - match cat { - BlockCat::ChromaDc(_) | BlockCat::ChromaDc422(_) | BlockCat::ChromaAc => { - self.account.residual_chroma += spent - } - _ if comp != 0 => self.account.residual_chroma += spent, - _ => self.account.residual_luma += spent, - } - out - } - pub(crate) fn set_intra(&mut self, intra: bool) { self.cur_intra = intra; } @@ -432,7 +264,7 @@ impl<'a> Cabac<'a> { } /// mb_type of an I slice (Table 9-36). - fn mb_type_i_inner(&mut self) -> Result { + pub(crate) fn mb_type_i(&mut self) -> Result { let mut ctx = I_MB_TYPE_CTX; ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE); self.mb_type_intra(&ctx) @@ -461,14 +293,14 @@ impl<'a> Cabac<'a> { } /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB. - fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool { + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P }; self.decision(off + inc) } /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice /// mb_type for an intra macroblock. - fn mb_type_p_inner(&mut self) -> Result { + pub(crate) fn mb_type_p(&mut self) -> Result { if self.decision(OFF_MB_TYPE_P) { return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?); } @@ -485,7 +317,7 @@ impl<'a> Cabac<'a> { /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice /// mb_type for an intra macroblock. - fn mb_type_b_inner(&mut self) -> Result { + pub(crate) fn mb_type_b(&mut self) -> Result { if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) { return Ok(0); // B_Direct_16x16 } @@ -523,7 +355,7 @@ impl<'a> Cabac<'a> { } /// sub_mb_type of a P macroblock (Table 9-38). - fn sub_mb_type_p_inner(&mut self) -> u32 { + pub(crate) fn sub_mb_type_p(&mut self) -> u32 { if self.decision(OFF_SUB_TYPE_P) { return 0; } @@ -538,7 +370,7 @@ impl<'a> Cabac<'a> { } /// sub_mb_type of a B macroblock (Table 9-38). - fn sub_mb_type_b_inner(&mut self) -> u32 { + pub(crate) fn sub_mb_type_b(&mut self) -> u32 { if !self.decision(OFF_SUB_TYPE_B) { return 0; // B_Direct_8x8 } @@ -559,7 +391,7 @@ impl<'a> Cabac<'a> { /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the /// first bin (Table 9-39 row 54). - fn ref_idx_inner(&mut self, inc: usize) -> Result { + pub(crate) fn ref_idx(&mut self, inc: usize) -> Result { if !self.decision(OFF_REF_IDX + inc) { return Ok(0); } @@ -578,7 +410,7 @@ impl<'a> Cabac<'a> { /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7. - fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result { + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { let off = OFF_MVD[comp]; if !self.decision(off + inc) { return Ok(0); @@ -603,7 +435,7 @@ impl<'a> Cabac<'a> { /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is /// available and carried the flag itself. - fn transform_size_8x8_flag_inner(&mut self) -> Result { + pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { let cond = |n: Option| match n { None => 0, Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0), @@ -614,7 +446,7 @@ impl<'a> Cabac<'a> { /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7 /// with binIdx 0 the least significant bit. - fn intra4x4_pred_mode_inner(&mut self) -> Result> { + pub(crate) fn intra4x4_pred_mode(&mut self) -> Result> { if self.decision(OFF_PREV_I4) { return Ok(None); } @@ -626,7 +458,7 @@ impl<'a> Cabac<'a> { } /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8. - fn intra_chroma_pred_mode_inner(&mut self) -> Result { + pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result { let cond = |n: Option| match n { None => 0, Some(i) => usize::from( @@ -649,7 +481,7 @@ impl<'a> Cabac<'a> { /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma /// suffix, both with the neighbour contexts of 9.3.3.1.1.4. - fn coded_block_pattern_inner(&mut self, has_chroma: bool) -> Result<(u8, u8)> { + pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> { let (a_lower, a_blk) = match self.ctx.mbaff_a { None => (self.ctx.a, [1u8, 3]), Some(m) => (m.lower, m.blk), @@ -717,7 +549,7 @@ impl<'a> Cabac<'a> { } /// mb_qp_delta: unary bin string of the Table 9-3 mapped value. - fn mb_qp_delta_inner(&mut self) -> Result { + pub(crate) fn mb_qp_delta(&mut self) -> Result { let mut k = 0i32; while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) { k += 1; @@ -729,7 +561,7 @@ impl<'a> Cabac<'a> { } /// residual_block_cabac (7.3.5.3.3) for one block, in scan order. - fn residual_block_inner( + pub(crate) fn residual_block( &mut self, coeff: &mut [i32; 16], cat: BlockCat, @@ -827,22 +659,6 @@ impl<'a> Cabac<'a> { coeff: &mut [i32; 64], comp: u8, cbf: Option<(Option, Option)>, - ) -> Result { - let m = self.mark(); - let out = self.residual_block_8x8_inner(coeff, comp, cbf); - if comp == 0 { - self.account.residual_luma += self.mark() - m; - } else { - self.account.residual_chroma += self.mark() - m; - } - out - } - - fn residual_block_8x8_inner( - &mut self, - coeff: &mut [i32; 64], - comp: u8, - cbf: Option<(Option, Option)>, ) -> Result { *coeff = [0; 64]; if let Some((na, nb)) = cbf { @@ -989,18 +805,6 @@ impl<'a> Cabac<'a> { Ok(bytes) } - /// The raw engine, for the encoder's round-trip test. - #[cfg(test)] - pub(crate) fn decision_for_test(&mut self, ctx_idx: usize) -> bool { - self.decision(ctx_idx) - } - - /// The raw bypass engine, for the encoder's round-trip test. - #[cfg(test)] - pub(crate) fn bypass_for_test(&mut self) -> bool { - self.bypass() - } - /// end_of_slice_flag (ctxIdx 276, DecodeTerminate). pub(crate) fn more_macroblocks(&mut self) -> Result { debug_assert_eq!(CTX_TERMINATE, 276); diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index e2af71a9..be578999 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -29,7 +29,6 @@ use ec_h264_syntax::{ SliceType, Sps, WeightEntry, unescape_rbsp, }; -use crate::cabac::BitAccount; use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line}; use crate::dpb::{ BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE, @@ -141,9 +140,6 @@ pub(crate) struct Core { last_decoded: i32, output_order: OutputOrder, out: VecDeque, - /// Bits parsed so far, by syntax class (CABAC slices only). - account: BitAccount, - shapes: MbShapes, /// Presentation timestamp to attach to the next picture started. pending_pts: Option, /// `PicOrderCnt` of the random-access point most recently established by @@ -278,25 +274,6 @@ impl Decoder { }) } - /// Where the bits of every CABAC slice parsed so far went, by syntax - /// class, in 1/256ths of a bit. - pub fn bit_account(&self) -> BitAccount { - if self.hbd { - self.c16.bit_account() - } else { - self.c8.bit_account() - } - } - - /// How many macroblocks of each shape this decoder has read. - pub fn mb_shapes(&self) -> MbShapes { - if self.hbd { - self.c16.mb_shapes() - } else { - self.c8.mb_shapes() - } - } - /// Decode the first IDR picture of an Annex B stream and return it. pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result { let mut got_slice = false; @@ -612,8 +589,6 @@ impl Core { last_decoded: -1, output_order: OutputOrder::default(), out: VecDeque::new(), - account: BitAccount::default(), - shapes: MbShapes::default(), pending_pts: None, recovery_poc: None, cur_ref_padded: false, @@ -645,20 +620,6 @@ impl Core { Some((sps.width, sps.height)) } - /// Where the bits of every CABAC slice parsed so far went, by syntax - /// class, in 1/256ths of a bit. Any conforming stream can be measured - /// this way, so an encoder's spending can be compared with another's - /// through one account. - pub(crate) fn bit_account(&self) -> BitAccount { - self.account - } - - /// How many macroblocks of each shape this decoder has read, which is what - /// a stream's partitioning looks like from the outside. - pub(crate) fn mb_shapes(&self) -> MbShapes { - self.shapes - } - /// Feed one NAL unit (header byte first, no start code). pub(crate) fn push_nal(&mut self, nal: &[u8]) -> Result { let Some((&header_byte, payload)) = nal.split_first() else { @@ -1030,7 +991,6 @@ impl Core { }; let mut ctx = SliceCtx { - shapes: MbShapes::default(), slice_id, slice_type: sh.slice_type, qp: sh.slice_qp, @@ -1071,10 +1031,6 @@ impl Core { first_mb as usize * 2, pps.entropy_coding_mode, )?; - self.shapes.add(&ctx.shapes); - if let Entropy::Cabac(c) = &r { - self.account.add(&c.account()); - } return Ok(NalOutcome::SliceDecoded); } let groups = if pps.num_slice_groups > 1 { @@ -1154,10 +1110,6 @@ impl Core { more = r.more_macroblocks()?; mb_addr = step(mb_addr); } - self.shapes.add(&ctx.shapes); - if let Entropy::Cabac(c) = &r { - self.account.add(&c.account()); - } Ok(NalOutcome::SliceDecoded) } @@ -1606,40 +1558,6 @@ fn check_supported( Ok(()) } -/// Mutable per-slice decode state. -/// How many macroblocks of each shape a stream codes: the partitioning the -/// encoder chose, counted from the outside. -/// -/// P macroblocks only; a B macroblock's own shapes are not split out. -#[derive(Debug, Default, Clone, Copy)] -pub struct MbShapes { - pub skip: u64, - pub p16x16: u64, - pub p16x8: u64, - pub p8x16: u64, - /// P_8x8 and P_8x8ref0, whatever the sub_mb_types inside are. - pub p8x8: u64, - pub bidir: u64, - pub intra: u64, -} - -impl MbShapes { - /// Add another count into this one. - pub fn add_public(&mut self, o: &MbShapes) { - self.add(o); - } - - pub(crate) fn add(&mut self, o: &MbShapes) { - self.skip += o.skip; - self.p16x16 += o.p16x16; - self.p16x8 += o.p16x8; - self.p8x16 += o.p8x16; - self.p8x8 += o.p8x8; - self.bidir += o.bidir; - self.intra += o.intra; - } -} - /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value. #[derive(Clone, Copy)] struct Geo { @@ -1663,6 +1581,7 @@ impl Geo { } } +/// Mutable per-slice decode state. pub(crate) struct SliceCtx { slice_id: u16, slice_type: SliceType, @@ -1699,8 +1618,6 @@ pub(crate) struct SliceCtx { /// Where the macroblock being decoded sits when the picture is an MBAFF /// frame (`pos.active`); inert otherwise. pos: MbPos, - /// How many macroblocks of each shape this slice decoded. - shapes: MbShapes, } impl SliceCtx { @@ -2241,22 +2158,6 @@ fn decode_macroblock( r.mb_type_i()? }; - if skipped { - ctx.shapes.skip += 1; - } else if ctx.slice_type == SliceType::P { - match mb_type { - 0 => ctx.shapes.p16x16 += 1, - 1 => ctx.shapes.p16x8 += 1, - 2 => ctx.shapes.p8x16 += 1, - 3 | 4 => ctx.shapes.p8x8 += 1, - _ => ctx.shapes.intra += 1, - } - } else if ctx.is_b() { - ctx.shapes.bidir += 1; - } else { - ctx.shapes.intra += 1; - } - // Split the P/B numbering into an inter shape or an intra mb_type. let (shape, intra_type) = if skipped { let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] }; @@ -5006,7 +4907,6 @@ mod tests { }), poc: 4, fpoc: [4, 4], - shapes: MbShapes::default(), }; let mut pic = ramp_picture(|_, _| 0); diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index 7406ec7a..7a9996fd 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -730,44 +730,6 @@ mod tests { use super::*; use crate::cabac::Cabac; - /// The engine round-trips: a pseudo-random bin string written against a - /// spread of contexts, with bypass and terminate bins mixed in, decodes - /// back identically. This is the property every syntax element rests on. - #[test] - fn engine_round_trips() { - let mut state = 0x2545_F491u32; - let mut rand = move |m: u32| { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state % m - }; - let mut plan: Vec<(usize, bool, u8)> = Vec::new(); // (ctx, bin, kind) - for _ in 0..4000 { - let kind = if rand(10) == 0 { 1 } else { 0 }; - plan.push((rand(NUM_CTX as u32) as usize, rand(2) == 1, kind)); - } - let mut enc = CabacEnc::new(BitWriter::new(), 26, 0); - for &(ctx, bin, kind) in &plan { - match kind { - 0 => enc.decision(ctx, bin), - _ => enc.bypass(bin), - } - enc.not_end_of_slice(); - } - let bytes = enc.finish().into_bytes(); - - let mut dec = Cabac::new(&bytes, 0, 26, 0).expect("decoder starts"); - for (i, &(ctx, bin, kind)) in plan.iter().enumerate() { - let got = match kind { - 0 => dec.decision_for_test(ctx), - _ => dec.bypass_for_test(), - }; - assert_eq!(got, bin, "bin {i}"); - assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end"); - } - } - /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat /// 5 blocks over a spread of densities and magnitudes all decode back /// through the decoder's own syntax readers. diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 68e01846..e72c47c9 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -41,7 +41,7 @@ use super::quant::{ forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc, }; -use super::timing::mb_timed; + use super::{ entropy::{EncEntropy, sub_block_4x4}, lambda_ssd, @@ -128,24 +128,12 @@ pub(crate) struct MbEnc<'a> { /// Lagrangian multiplier; it is in the squared-error domain when 8x8 /// transform decisions are enabled. pub lambda: f64, - /// Whether `lambda` is the standard squared-error multiplier. - pub lambda_standard: bool, - /// Extra rate saving an 8x8 trial must buy before it may replace 4x4. - pub t8x8_margin_bits: f64, pub preset: Preset, /// Fast-preset speed knobs (see [`FastKnobs`]). pub fast: FastKnobs, /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must /// be written for every eligible macroblock (7.3.5). pub transform_8x8: bool, - /// Whether intra macroblocks may select 8x8. The PPS can remain enabled - /// while an ablation measures the classes independently. - pub transform_8x8_intra: bool, - /// Whether inter macroblocks may select 8x8. - pub transform_8x8_inter: bool, - /// Whether the ablation restricts 8x8 eligibility to even macroblock - /// rows; odd rows then code exactly as they would with 8x8 disabled. - pub transform_8x8_roweven: bool, pub ls: LevelScale4x4, pub ls8: LevelScale8x8, /// Neighbourhood of the macroblock being written (CABAC). @@ -160,18 +148,6 @@ pub(crate) struct MbEnc<'a> { pub qp_delta_inc: u8, } -impl MbEnc<'_> { - /// Intra 8x8 eligibility of macroblock row `mb_y`. - fn t8x8_intra(&self, mb_y: usize) -> bool { - self.transform_8x8_intra && (mb_y.is_multiple_of(2) || !self.transform_8x8_roweven) - } - - /// Inter 8x8 eligibility of macroblock row `mb_y`. - fn t8x8_inter(&self, mb_y: usize) -> bool { - self.transform_8x8_inter && (mb_y.is_multiple_of(2) || !self.transform_8x8_roweven) - } -} - /// Quantised levels of one macroblock, scan order per block. #[derive(Clone)] struct Levels { @@ -399,7 +375,7 @@ fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { /// The multiplier `motion_rate` applies, for loops that price many vectors. #[inline] fn motion_lambda(e: &MbEnc<'_>) -> f64 { - if e.lambda_standard { + if e.transform_8x8 { e.lambda.sqrt() } else { e.lambda @@ -565,7 +541,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy let mut inter: Option> = None; if e.slice_type == SliceType::P { - inter = Some(mb_timed!(0, choose_inter(pic, e, mb_x, mb_y))); + inter = Some(choose_inter(pic, e, mb_x, mb_y)); } // Intra against inter is decided on real coded cost: both branches are @@ -597,21 +573,21 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy let gate = e.preset == Preset::Fast && e.fast.intra_gate > 0.0; let intra_cost = match inter.as_ref() { Some(c) if gate && e.fast.lazy_i16 => { - let dc = mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2])); + let dc = intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2]); if f64::from(c[0].satd) <= e.fast.intra_gate * f64::from(dc.satd) { dc } else { - mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3])) + intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3]) } } - _ => mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3])), + _ => intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3]), }; let Some(choices) = inter else { - mb_timed!(3, encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost)); + encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost); return; }; - let lambda = if e.lambda_standard { + let lambda = if e.transform_8x8 { e.lambda } else { lambda_ssd(e.qp) @@ -622,10 +598,10 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy if gated { // Inter only and one candidate at Fast: nothing is compared, so the // macroblock is coded straight into the picture and the writer. - mb_timed!(2, encode_inter_mb(pic, e, w, mb_addr, nbr, choices[0])); + encode_inter_mb(pic, e, w, mb_addr, nbr, choices[0]); return; } - let before = mb_timed!(4, save_mb_state(pic, e, mb_addr)); + let before = save_mb_state(pic, e, mb_addr); // The shape and the skip flag are ranked the same way intra and inter are: // by coding each candidate and measuring it. The SATD total that ordered // them inside the search is a prediction-domain estimate that never sees @@ -638,26 +614,23 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy }; let mut best_inter: Option<(f64, MbState, EncEntropy)> = None; for &choice in &choices[..rd_cands.max(1)] { - mb_timed!(4, load_mb_state(pic, e, mb_addr, &before)); - let mut w_c = mb_timed!(5, w.probe_copy()); + load_mb_state(pic, e, mb_addr, &before); + let mut w_c = w.probe_copy(); let start = w_c.bit_len(); - mb_timed!(2, encode_inter_mb(pic, e, &mut w_c, mb_addr, nbr, choice)); + encode_inter_mb(pic, e, &mut w_c, mb_addr, nbr, choice); let bits = (w_c.bit_len() - start) as f64; let rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * bits; if best_inter.as_ref().is_none_or(|b| rd < b.0) { - best_inter = Some((rd, mb_timed!(4, save_mb_state(pic, e, mb_addr)), w_c)); + best_inter = Some((rd, save_mb_state(pic, e, mb_addr), w_c)); } } let (inter_rd, after_inter, w_inter) = best_inter.expect("at least one inter candidate"); - mb_timed!(4, load_mb_state(pic, e, mb_addr, &before)); + load_mb_state(pic, e, mb_addr, &before); - let mut w_intra = mb_timed!(5, w.probe_copy()); + let mut w_intra = w.probe_copy(); let intra_bits = { let start = w_intra.bit_len(); - mb_timed!( - 3, - encode_intra_mb(pic, e, &mut w_intra, mb_addr, nbr, intra_cost) - ); + encode_intra_mb(pic, e, &mut w_intra, mb_addr, nbr, intra_cost); (w_intra.bit_len() - start) as f64 }; let intra_rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * intra_bits; @@ -665,7 +638,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy if intra_rd < inter_rd { w.adopt(w_intra); } else { - mb_timed!(4, load_mb_state(pic, e, mb_addr, &after_inter)); + load_mb_state(pic, e, mb_addr, &after_inter); w.adopt(w_inter); } } @@ -1097,18 +1070,15 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec, mb_x: usize, mb_y: usize) -> Vec= 4 { - let mut improved = true; - while improved { - improved = false; - passes += 1; - if fast && passes > FAST_ME_PASSES { - break; + while step >= 4 { + let mut improved = true; + while improved { + improved = false; + passes += 1; + if fast && passes > FAST_ME_PASSES { + break; + } + for (dx, dy) in ME_PATTERN { + let (dx, dy) = (dx * step, dy * step); + let cand = [best.0[0] + dx, best.0[1] + dy]; + if (cand[0] - mvp[0]).abs() > range * 4 + || (cand[1] - mvp[1]).abs() > range * 4 + { + continue; } - for (dx, dy) in ME_PATTERN { - let (dx, dy) = (dx * step, dy * step); - let cand = [best.0[0] + dx, best.0[1] + dy]; - if (cand[0] - mvp[0]).abs() > range * 4 - || (cand[1] - mvp[1]).abs() > range * 4 - { - continue; - } - let c = cost_of(cand, false); - if c < best.1 { - best = (cand, c); - improved = true; - } + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + improved = true; } } - step /= 2; } - ); + step /= 2; + } // Sub-sample refinement runs on SATD, not SAD: interpolation // smooths, and a sum of absolute differences reads the smoothing // as a better match where a transform-domain cost does not. Worth @@ -1157,79 +1124,77 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec &[], - 1 => &[2], - _ => &[2, 1], - } - }; - if fast && e.fast.me_sub == 1 { - // The four half-sample neighbours on the axes, then only the - // diagonal the two winning axes point at. - let base = best; - let mut axis = [(base.0, base.1); 2]; - for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]] - .into_iter() - .enumerate() - { - for (dx, dy) in dirs { - let cand = [base.0[0] + dx, base.0[1] + dy]; - let c = cost_of(cand, sub_satd); - if c < axis[k].1 { - axis[k] = (cand, c); - } - } - } - let both = axis[0].1 < base.1 && axis[1].1 < base.1; - if both { - let cand = [axis[0].0[0], axis[1].0[1]]; + best.1 = cost_of(best.0, sub_satd); + // Balanced iterates both sub-sample steps to convergence. Fast + // looks at each ring of eight once. + let rings: &[i16] = if !fast { + &[2, 1] + } else { + match e.fast.me_sub { + 0 => &[], + 1 => &[2], + _ => &[2, 1], + } + }; + if fast && e.fast.me_sub == 1 { + // The four half-sample neighbours on the axes, then only the + // diagonal the two winning axes point at. + let base = best; + let mut axis = [(base.0, base.1); 2]; + for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]] + .into_iter() + .enumerate() + { + for (dx, dy) in dirs { + let cand = [base.0[0] + dx, base.0[1] + dy]; let c = cost_of(cand, sub_satd); - if c < best.1 { - best = (cand, c); + if c < axis[k].1 { + axis[k] = (cand, c); } } - for a in axis { - if a.1 < best.1 { - best = a; - } + } + let both = axis[0].1 < base.1 && axis[1].1 < base.1; + if both { + let cand = [axis[0].0[0], axis[1].0[1]]; + let c = cost_of(cand, sub_satd); + if c < best.1 { + best = (cand, c); } } - let rings: &[i16] = if fast && e.fast.me_sub == 1 { - &[] - } else { - rings - }; - for &step in rings { - let mut improved = true; - while improved { - improved = false; - for (dx, dy) in [ - (step, 0), - (-step, 0), - (0, step), - (0, -step), - (step, step), - (-step, -step), - (step, -step), - (-step, step), - ] { - let cand = [best.0[0] + dx, best.0[1] + dy]; - let c = cost_of(cand, sub_satd); - if c < best.1 { - best = (cand, c); - improved = !fast; - } + for a in axis { + if a.1 < best.1 { + best = a; + } + } + } + let rings: &[i16] = if fast && e.fast.me_sub == 1 { + &[] + } else { + rings + }; + for &step in rings { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [ + (step, 0), + (-step, 0), + (0, step), + (0, -step), + (step, step), + (-step, -step), + (step, -step), + (-step, step), + ] { + let cand = [best.0[0] + dx, best.0[1] + dy]; + let c = cost_of(cand, sub_satd); + if c < best.1 { + best = (cand, c); + improved = !fast; } } } - }); + } } ( best.0, @@ -1487,7 +1452,7 @@ fn code_luma_4x4( &source, &resid, &lv.luma[blk], - zero_block_lambda(e, qp, e.t8x8_inter(mb_y)), + zero_block_lambda(e, qp, e.transform_8x8), ) { lv.luma[blk] = [0; 16]; @@ -1535,7 +1500,7 @@ fn code_luma_4x4( let lambda = if w.is_cabac() { GROUP_LAMBDA * lambda_ssd(qp) } else { - zero_block_lambda(e, qp, e.t8x8_inter(mb_y)) + zero_block_lambda(e, qp, e.transform_8x8) }; for g in 0..4 { if rate[g] == 0.0 { @@ -1957,15 +1922,7 @@ fn code_chroma( &source, &resid, &ac[comp][blk], - zero_block_lambda( - e, - qp_c, - if intra { - e.t8x8_intra(mb_y) - } else { - e.t8x8_inter(mb_y) - }, - ), + zero_block_lambda(e, qp_c, e.transform_8x8), ) { ac[comp][blk] = [0; 16]; nz = 0; @@ -2189,7 +2146,7 @@ fn code_intra_4x4( // full rate term this search loses 0.065 dB instead of gaining, // and it loses more the more candidates it sees. let lambda = ZERO_BLOCK_LAMBDA - * if e.lambda_standard { + * if e.transform_8x8 { e.lambda } else { lambda_ssd(qp) @@ -2322,14 +2279,7 @@ fn code_block_8x8( dequant_8x8(&mut raster, &e.ls8, qp); let mut resid = [0i32; 64]; inverse_transform_8x8(&raster, &mut resid); - if !rdoq - && !intra - && !worth_coding( - &d, - &resid, - out, - zero_block_lambda(e, qp, e.transform_8x8_inter), - ) + if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8)) { *out = [0; 64]; return 0; @@ -2807,16 +2757,13 @@ fn encode_intra_mb( let mut pred_modes8 = [2u8; 4]; let mut use_i4 = false; let mut chroma_lv = Levels::default(); - let chroma_mode = mb_timed!( - 10, - choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv) - ); + let chroma_mode = choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv); let mut use_i8 = false; if cost.allow_i4 { let mut lv4 = chroma_lv.clone(); - let (m4, p4) = mb_timed!(6, code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4)); - let cost4 = if e.t8x8_intra(mb_y) { + let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); + let cost4 = if e.transform_8x8 { let bits = intra_mb_bits( pic, e, @@ -2847,8 +2794,8 @@ fn encode_intra_mb( let mut recon8 = [0u8; 256]; let skip8 = e.preset == Preset::Fast && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P)); - let cost8 = if e.t8x8_intra(mb_y) && !skip8 { - let (m8, p8) = mb_timed!(7, code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8)); + let cost8 = if e.transform_8x8 && !skip8 { + let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8); modes8 = m8; pred_modes8 = p8; save_luma(pic, mb_x, mb_y, &mut recon8); @@ -2870,11 +2817,8 @@ fn encode_intra_mb( }; let mut lv16 = chroma_lv; - mb_timed!( - 11, - code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16) - ); - let cost16 = if e.t8x8_intra(mb_y) { + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); + let cost16 = if e.transform_8x8 { let bits = intra_mb_bits( pic, e, @@ -2893,9 +2837,7 @@ fn encode_intra_mb( + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 }; - if cost8 + e.lambda * e.t8x8_margin_bits <= cost4 - && cost8 + e.lambda * e.t8x8_margin_bits <= cost16 - { + if cost8 <= cost4 && cost8 <= cost16 { use_i4 = true; use_i8 = true; restore_luma(pic, mb_x, mb_y, &recon8); @@ -2921,10 +2863,7 @@ fn encode_intra_mb( } } else { lv = chroma_lv; - mb_timed!( - 11, - code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv) - ); + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); } // ---- syntax ---- @@ -3372,9 +3311,9 @@ fn encode_inter_mb( } else { 0 }; - if e.t8x8_inter(mb_y) && tx_mode == 1 { + if e.transform_8x8 && tx_mode == 1 { code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv); - } else if e.t8x8_inter(mb_y) && tx_mode != 2 { + } else if e.transform_8x8 && tx_mode != 2 { // Both transform sizes on the same prediction; the cheaper // rate-distortion cost is coded. let mut pred = [0u8; 256]; @@ -3397,7 +3336,7 @@ fn encode_inter_mb( code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8); let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; - if cost8 + e.lambda * e.t8x8_margin_bits < cost4 { + if cost8 < cost4 { lv = lv8; } else { lv = lv4; @@ -3412,7 +3351,7 @@ fn encode_inter_mb( None => false, Some(_) if empty => true, Some(ssd_skip) => { - let coded = if e.t8x8_inter(mb_y) { + let coded = if e.transform_8x8 { let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv); ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 } else { diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index b00478fd..4c9e7a83 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -27,7 +27,6 @@ mod mb; mod pool; mod quant; mod rc; -pub(crate) mod timing; mod vlc; use ec_core::BitWriter; @@ -37,8 +36,6 @@ use ec_h264_syntax::{SliceType, Sps}; use crate::decoder::deblock_picture; use crate::dpb::{Picture, SliceParams as DeblockParams}; -#[cfg(feature = "rd-ablation")] -use crate::entropy::FLAG_SKIP; use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; use crate::transform::{LevelScale4x4, LevelScale8x8}; @@ -48,8 +45,6 @@ use mb::{MbEnc, Source, encode_mb}; use pool::BandPool; use rc::RateControl; use std::sync::Arc; -use std::time::Instant; -pub use timing::EncodeTimings; pub use mb::Preset; @@ -87,16 +82,6 @@ pub struct EncoderConfig { /// Turning it off restricts the stream to the Baseline/Main-profile 4x4 /// path, which costs 0.7 dB BD-PSNR on film and 0.2 dB on screen capture. pub transform_8x8: bool, - #[cfg(feature = "rd-ablation")] - rd_lambda_standard: bool, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_intra: bool, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_inter: bool, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_roweven: bool, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_margin_bits: f64, } impl EncoderConfig { @@ -114,16 +99,6 @@ impl EncoderConfig { threads: 0, qp: 26, transform_8x8: true, - #[cfg(feature = "rd-ablation")] - rd_lambda_standard: false, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_intra: false, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_inter: false, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_roweven: false, - #[cfg(feature = "rd-ablation")] - rd_transform_8x8_margin_bits: 0.0, } } } @@ -169,7 +144,6 @@ pub struct Encoder { have_reference: bool, /// Macroblocks coded with transform_size_8x8_flag set: (intra, inter). t8x8_mbs: (u64, u64), - timings: timing::EncodeTimings, } /// A picture handed to the encoder: three planes, no padding assumptions. @@ -204,10 +178,6 @@ impl<'a> PictureView<'a> { impl Encoder { /// Build an encoder for `cfg`, refusing what it cannot code. pub fn new(cfg: EncoderConfig) -> Result { - #[cfg(feature = "rd-ablation")] - let mut cfg = cfg; - #[cfg(feature = "rd-ablation")] - apply_rd_ablation(&mut cfg); if cfg.width < 16 || cfg.height < 16 { return Err(Error::unsupported( "picture smaller than one macroblock", @@ -288,7 +258,6 @@ impl Encoder { next_id: 0, have_reference: false, t8x8_mbs: (0, 0), - timings: timing::EncodeTimings::default(), cfg, }) } @@ -304,11 +273,6 @@ impl Encoder { &self.cfg } - /// Where the encode time went so far; see [`EncodeTimings`]. - pub fn timings(&self) -> EncodeTimings { - self.timings - } - /// The reconstruction of the last coded picture, cropped, as I420 planes. /// This is what a conformant decoder produces for that picture — the tests /// compare it against this crate's decoder and against the oracle. @@ -351,9 +315,7 @@ impl Encoder { if frame.width != self.cfg.width || frame.height != self.cfg.height { return Err(Error::corrupt("frame size differs from the encoder's")); } - let t_pad = Instant::now(); self.pad_source(frame)?; - self.timings.pad += t_pad.elapsed().as_secs_f64(); if self.frames == 0 { self.cqo = chroma_qp_offset_for_source(&self.src, self.cfg.width, self.cfg.height); let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo); @@ -399,9 +361,6 @@ impl Encoder { mb_w, }); - let mut busiest = 0.0f64; - let mut busy = 0.0f64; - let t_bands = Instant::now(); let mut answers = Vec::with_capacity(bands.len()); if self.threads == 1 { // One band: coded on this thread, with no workers. @@ -434,8 +393,6 @@ impl Encoder { } let mut outputs: Vec> = Vec::with_capacity(bands.len()); for (band, answer) in answers.into_iter().enumerate() { - busiest = busiest.max(answer.secs); - busy += answer.secs; outputs.push(answer.rbsp); self.workers[band] = answer.pic; } @@ -447,10 +404,6 @@ impl Encoder { if let Some(reference) = shared.reference { self.reference = reference; } - self.timings.bands_wall += t_bands.elapsed().as_secs_f64(); - self.timings.bands_busy += busy; - self.timings.bands_slowest += busiest; - let t_stitch = Instant::now(); // Stitch the bands into worker 0's picture, then filter the whole // picture the way a decoder does. @@ -469,7 +422,6 @@ impl Encoder { for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { merge_band(master, worker, *band); } - self.timings.stitch += t_stitch.elapsed().as_secs_f64(); for &f in &master.mb_flags { if f & FLAG_TRANS8X8 != 0 { if f & FLAG_INTER != 0 { @@ -479,19 +431,7 @@ impl Encoder { } } } - // H5 measurement hook: the chosen candidate's trial SSD is the - // pre-deblock SSD of the macroblock in this picture (round 4 verified - // trial bits and SSD against the final picture), so capturing the - // per-macroblock SSD right before and right after the filter is the - // exact pre/post comparison with no hooks inside the RD trials. - #[cfg(feature = "rd-ablation")] - let rd_pre = rd_trace_capture(master, &self.src); - let t_deblock = Instant::now(); deblock_picture(master); - self.timings.deblock += t_deblock.elapsed().as_secs_f64(); - #[cfg(feature = "rd-ablation")] - rd_trace_write(master, &self.src, self.frames, rd_pre); - let t_output = Instant::now(); master.extend_borders(); master.complete = true; std::mem::swap(master, &mut self.reference); @@ -513,8 +453,6 @@ impl Encoder { } let bits = au.len() as u64 * 8; - self.timings.output += t_output.elapsed().as_secs_f64(); - self.timings.pictures += 1; self.rc.update(idr, qp, bits); self.frames += 1; self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM); @@ -682,7 +620,6 @@ struct BandMsg { struct BandOut { pic: Picture, rbsp: Vec, - secs: f64, } /// Code one band on a worker picture. @@ -693,7 +630,6 @@ fn run_band(msg: BandMsg) -> BandOut { band, picture_id, } = msg; - let t_band = Instant::now(); let (row0, row1) = shared.bands[band]; let mb_w = shared.mb_w; pic.start(&shared.sps); @@ -719,11 +655,7 @@ fn run_band(msg: BandMsg) -> BandOut { cqo: shared.cqo, }, ); - BandOut { - pic, - rbsp, - secs: t_band.elapsed().as_secs_f64(), - } + BandOut { pic, rbsp } } struct BandJob<'a> { @@ -776,15 +708,10 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { slice_id: job.slice_id, qp: job.qp, target_qp: job.qp, - lambda: lambda_for(job.qp, rd_lambda_standard(job.cfg)), - t8x8_margin_bits: rd_transform_8x8_margin_bits(job.cfg), + lambda: lambda_for(job.qp, job.cfg.transform_8x8), preset: job.cfg.preset, fast: fast_knobs(), - lambda_standard: rd_lambda_standard(job.cfg), transform_8x8: job.cfg.transform_8x8, - transform_8x8_intra: rd_transform_8x8_intra(job.cfg), - transform_8x8_inter: rd_transform_8x8_inter(job.cfg), - transform_8x8_roweven: rd_transform_8x8_roweven(job.cfg), ls: LevelScale4x4::new(&[16; 16]), ls8: LevelScale8x8::new(&[16; 64]), mb_ctx: crate::entropy::MbCtx::default(), @@ -801,7 +728,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { let expected = job.band_target * n as f64 / rows as f64; let delta = job.rc.row_delta(spent, expected); e.target_qp = (job.qp + delta).clamp(10, 51); - e.lambda = lambda_for(e.target_qp, rd_lambda_standard(job.cfg)); + e.lambda = lambda_for(e.target_qp, job.cfg.transform_8x8); } for mb_x in 0..mb_w { let addr = mb_y * mb_w + mb_x; @@ -878,167 +805,6 @@ fn lambda_for(qp: i32, standard: bool) -> f64 { } } -#[cfg(feature = "rd-ablation")] -fn apply_rd_ablation(cfg: &mut EncoderConfig) { - if let Ok(lambda) = std::env::var("EC_H264_RD_LAMBDA") { - cfg.rd_lambda_standard = match lambda.as_str() { - "ladder" => false, - "standard" => true, - _ => panic!("EC_H264_RD_LAMBDA must be ladder or standard"), - }; - } - if let Ok(transform) = std::env::var("EC_H264_RD_T8X8") { - let (intra, inter, roweven) = match transform.as_str() { - "off" => (false, false, false), - "on" => (true, true, false), - "roweven" => (true, true, true), - "intra" => (true, false, false), - "inter" => (false, true, false), - _ => panic!("EC_H264_RD_T8X8 must be off, on, roweven, intra, or inter"), - }; - cfg.rd_transform_8x8_intra = intra; - cfg.rd_transform_8x8_inter = inter; - cfg.rd_transform_8x8_roweven = roweven; - cfg.transform_8x8 = intra || inter; - } else if cfg.transform_8x8 { - cfg.rd_transform_8x8_intra = true; - cfg.rd_transform_8x8_inter = true; - } - if let Ok(margin) = std::env::var("EC_H264_RD_T8X8_MARGIN_BITS") { - cfg.rd_transform_8x8_margin_bits = margin - .parse() - .expect("EC_H264_RD_T8X8_MARGIN_BITS must be a number"); - } -} - -/// Luma and chroma SSD of every macroblock against the source, before the -/// deblocking filter — the distortion the RD decision actually paid. -#[cfg(feature = "rd-ablation")] -fn rd_trace_capture(pic: &Picture, src: &Source) -> Option> { - if std::env::var_os("EC_H264_RD_TRACE").is_none() { - return None; - } - let mut out = Vec::with_capacity(pic.mb_w * pic.mb_h); - for mb_y in 0..pic.mb_h { - for mb_x in 0..pic.mb_w { - out.push(rd_trace_ssd(pic, src, mb_x, mb_y)); - } - } - Some(out) -} - -/// One line per macroblock: `frame addr intra trans8 skip qp pre_luma -/// pre_chroma post_luma post_chroma`, appended to `$EC_H264_RD_TRACE`. -#[cfg(feature = "rd-ablation")] -fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option>) { - use std::io::Write; - let Some(pre) = pre else { return }; - let mut out = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture")) - .expect("open EC_H264_RD_TRACE"); - for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() { - let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w); - let f = pic.mb_flags[addr]; - // A discarded write result here is a SILENTLY SHORT trace: the reader - // of `$EC_H264_RD_TRACE` attributes decisions from it and cannot tell a - // short line count from a real one. No length check is possible (append - // mode has no knowable total), so this is the ec-av1 `append_unknown` - // shape: the write error is fatal instead. - writeln!( - out, - "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}", - u8::from(f & FLAG_INTER == 0), - u8::from(f & FLAG_TRANS8X8 != 0), - u8::from(f & FLAG_SKIP != 0), - pic.mb_qp[addr] - ) - .expect("write EC_H264_RD_TRACE"); - } -} - -/// Luma and chroma SSD of one macroblock against the source planes. -#[cfg(feature = "rd-ablation")] -fn rd_trace_ssd(pic: &Picture, src: &Source, mb_x: usize, mb_y: usize) -> (i64, i64) { - let mut luma = 0i64; - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - for row in 0..16 { - let s = (mb_y * 16 + row) * src.stride + mb_x * 16; - for x in 0..16 { - let d = i64::from(src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); - luma += d * d; - } - } - let mut chroma = 0i64; - for (plane, source) in [(&pic.cb, &src.u), (&pic.cr, &src.v)] { - let stride = plane.stride; - let origin = plane.at(mb_x * 8, mb_y * 8); - for row in 0..8 { - let s = (mb_y * 8 + row) * src.c_stride + mb_x * 8; - for x in 0..8 { - let d = i64::from(source[s + x]) - i64::from(plane.data[origin + row * stride + x]); - chroma += d * d; - } - } - } - (luma, chroma) -} - -#[cfg(feature = "rd-ablation")] -fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { - cfg.rd_lambda_standard -} - -#[cfg(not(feature = "rd-ablation"))] -fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { - cfg.transform_8x8 -} - -#[cfg(feature = "rd-ablation")] -fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { - cfg.rd_transform_8x8_intra -} - -#[cfg(not(feature = "rd-ablation"))] -fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { - cfg.transform_8x8 -} - -#[cfg(feature = "rd-ablation")] -fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { - cfg.rd_transform_8x8_inter -} - -#[cfg(not(feature = "rd-ablation"))] -fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { - cfg.transform_8x8 -} - -#[cfg(feature = "rd-ablation")] -fn rd_transform_8x8_roweven(cfg: &EncoderConfig) -> bool { - cfg.rd_transform_8x8_roweven -} - -#[cfg(not(feature = "rd-ablation"))] -fn rd_transform_8x8_roweven(_: &EncoderConfig) -> bool { - false -} - -#[cfg(not(feature = "rd-ablation"))] -const TRANSFORM_8X8_MARGIN_BITS: f64 = 0.0; - -#[cfg(feature = "rd-ablation")] -fn rd_transform_8x8_margin_bits(cfg: &EncoderConfig) -> f64 { - cfg.rd_transform_8x8_margin_bits -} - -#[cfg(not(feature = "rd-ablation"))] -fn rd_transform_8x8_margin_bits(_: &EncoderConfig) -> f64 { - TRANSFORM_8X8_MARGIN_BITS -} - /// Split `mb_h` macroblock rows into at most `n` contiguous bands. fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { let n = n.clamp(1, mb_h); @@ -1198,12 +964,9 @@ mod tests { fn production_lambda_tracks_transform_mode() { let mut cfg = EncoderConfig::new(640, 480); cfg.transform_8x8 = false; - assert_eq!( - lambda_for(26, rd_lambda_standard(&cfg)), - lambda_for(26, false) - ); + assert_eq!(lambda_for(26, cfg.transform_8x8), lambda_for(26, false)); cfg.transform_8x8 = true; - assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26)); + assert_eq!(lambda_for(26, cfg.transform_8x8), lambda_ssd(26)); } /// Flat chroma over textured luma picks the negative chroma QP offset, and diff --git a/crates/ec-h264/src/enc/timing.rs b/crates/ec-h264/src/enc/timing.rs deleted file mode 100644 index ea0a0602..00000000 --- a/crates/ec-h264/src/enc/timing.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Stage timers for one encoder, read through [`Encoder::timings`]. They cost a -//! clock read per stage per picture, which is noise next to a picture's coding. -//! -//! [`Encoder::timings`]: super::Encoder::timings - -/// Wall-clock seconds spent in each stage of `encode`, summed over every -/// picture the encoder has coded. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct EncodeTimings { - /// Pictures counted. - pub pictures: u64, - /// Copying and padding the source planes. - pub pad: f64, - /// The parallel band coding, wall clock. - pub bands_wall: f64, - /// Sum of every band's own coding time (the work the threads share). - pub bands_busy: f64, - /// Sum over pictures of the slowest band (the critical path). - pub bands_slowest: f64, - /// Stitching the bands into one picture. - pub stitch: f64, - /// The in-loop deblocking filter, which runs on one thread. - pub deblock: f64, - /// Border extension, the reference swap and assembling the access unit. - pub output: f64, -} - -/// Per-stage nanosecond counters for the macroblock coder, behind the -/// `enc-profile` feature so a normal build pays nothing. Shared atomics: the -/// bands add to them concurrently, which is fine for a profile. -#[cfg(feature = "enc-profile")] -pub mod mb_stages { - use std::sync::atomic::{AtomicU64, Ordering}; - - /// Stage names, in index order. - pub const NAMES: [&str; 16] = [ - "choose_inter", - "intra_pre_cost", - "inter_rd_candidates", - "intra_rd_total", - "state_save_load", - "entropy_clone", - "intra4x4_rd", - "intra8x8_rd", - "intra_bits_and_ssd", - "(unused)", - "chroma_mode_rd", - "intra16_rd", - "me_seeds", - "me_int", - "me_sub", - "me_chroma_skip", - ]; - pub(crate) static NANOS: [AtomicU64; 16] = [const { AtomicU64::new(0) }; 16]; - - /// Nanoseconds spent in each stage so far, in [`NAMES`] order. - pub fn snapshot() -> [u64; 16] { - std::array::from_fn(|i| NANOS[i].load(Ordering::Relaxed)) - } -} - -/// Time `$body` into stage `$idx` of [`mb_stages`] when profiling, else just run it. -#[cfg(feature = "enc-profile")] -macro_rules! mb_timed { - ($idx:expr, $body:expr) => {{ - let t = std::time::Instant::now(); - let r = $body; - $crate::enc::timing::mb_stages::NANOS[$idx].fetch_add( - t.elapsed().as_nanos() as u64, - std::sync::atomic::Ordering::Relaxed, - ); - r - }}; -} -#[cfg(not(feature = "enc-profile"))] -macro_rules! mb_timed { - ($idx:expr, $body:expr) => { - $body - }; -} -pub(crate) use mb_timed; diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index 67c8430f..5d5ae4cb 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -46,8 +46,8 @@ mod deblock_mbaff; mod decoder; mod dpb; mod enc; -mod fmo; mod entropy; +mod fmo; mod inter; mod inter16; mod mbaff; @@ -57,10 +57,7 @@ mod sample; mod tables; mod transform; -pub use cabac::BitAccount; pub use codec::H264Decoder; -pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder}; +pub use decoder::{Decoder, NalOutcome, OutputOrder}; pub use ec_core::error::{Error, Result}; -#[cfg(feature = "enc-profile")] -pub use enc::timing::mb_stages; -pub use enc::{EncodeTimings, EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; +pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; diff --git a/crates/ec-h264/src/tables.rs b/crates/ec-h264/src/tables.rs index 78471ba8..55a9296d 100644 --- a/crates/ec-h264/src/tables.rs +++ b/crates/ec-h264/src/tables.rs @@ -625,9 +625,6 @@ pub const TC0: [[u8; 52]; 3] = [ ], ]; -/// 4x4 zig-zag scan: scan position -> raster index (Table 8-13, frame scan). -pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; - /// 4x4 field scan: scan position -> raster index (Table 8-13, field scan). pub const FIELD_4X4: [u8; 16] = [0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15]; @@ -640,7 +637,7 @@ pub const FIELD_8X8: [u8; 64] = [ /// 8x8 zig-zag scan: scan position -> raster index (Table 8-14, frame scan). /// Shared with the scaling-list parser, which reads the same scan. -pub use ec_h264_syntax::sps::ZIGZAG_8X8; +pub use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; /// luma4x4BlkIdx -> (x, y) position in 4-sample units within the macroblock /// (spec 6.4.3 inverse 4x4 luma block scan). diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 67a04848..6faefc73 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -6,72 +6,13 @@ //! frame) — ffmpeg-independent. //! 2. `ffmpeg -i -frames:v 1` raw output, cross-checked when the //! binary is present. -//! -//! The same binary hosts the zero-allocation proof and the ns/MB -//! measurement so the crate keeps a single integration-test link unit. - -use std::alloc::System; -use std::sync::Once; -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; -use std::cell::Cell; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; use ec_core::{Buf, Frame, Packet, TimeBase}; use ec_h264::{Decoder, Error, H264Decoder, NalOutcome}; -// --------------------------------------------------------------------------- -// Counting allocator: proves the steady-state decode loop allocates nothing. -// Lives in the test binary only — the shipped crates have no allocator games. -// --------------------------------------------------------------------------- - -struct CountingAlloc; - -static ALLOCS: AtomicU64 = AtomicU64::new(0); - -std::thread_local! { - /// Only the test thread that armed the counter is counted — other test - /// threads (and their ffmpeg child plumbing) allocate freely. - static COUNTING_HERE: Cell = const { Cell::new(false) }; -} - -fn counting_here() -> bool { - COUNTING_HERE.try_with(Cell::get).unwrap_or(false) -} - -impl AllocationTracker for CountingAlloc { - fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) { - if counting_here() { - ALLOCS.fetch_add(1, Ordering::Relaxed); - } - } - fn deallocated( - &self, - _addr: usize, - _object_size: usize, - _wrapped: usize, - _source: AllocationGroupId, - _current: AllocationGroupId, - ) { - } -} - -#[global_allocator] -static A: Allocator = Allocator::system(); - -/// Installs the tracker once; every test that arms the counter calls this first. -fn install_counter() { - static ONCE: Once = Once::new(); - ONCE.call_once(|| { - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); - AllocationRegistry::enable_tracking(); - }); -} - -// --------------------------------------------------------------------------- - fn vectors_dir() -> PathBuf { ec_testkit::fixture("vectors/h264-jvt") } @@ -383,235 +324,6 @@ fn jvt_cavlc_first_idr_bit_exact() { ); } -/// Steady-state slice decoding performs zero heap allocations. -/// -/// After a warm-up pass the picture pool, every per-picture array and the -/// parameter-set store are all sized, so decoding the same stream again must -/// not allocate at all: not per macroblock, not per slice, not per picture. -/// Emitting a frame is measured separately and *does* allocate — it hands the -/// caller owned planes — which also proves the counter is alive. -#[test] -fn steady_state_decode_loop_zero_alloc() { - install_counter(); - let base = vectors_dir(); - // One stream per entropy coder, and one with B slices and multiple - // reference frames so the decoded picture buffer really recycles pictures. - for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] { - let Some(stream) = find_stream(&base.join(name)) else { - continue; - }; - let bytes = std::fs::read(stream).unwrap(); - let mut dec = Decoder::new(); - let drive = |dec: &mut Decoder, count: bool| -> usize { - let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); - let mut frames = 0usize; - for nal in &nals { - if count { - COUNTING_HERE.with(|c| c.set(true)); - } - let outcome = dec.push_nal(nal); - if count { - COUNTING_HERE.with(|c| c.set(false)); - } - match outcome { - Ok(ec_h264::NalOutcome::PictureBoundary) => { - dec.end_picture().expect("end_picture"); - dec.push_nal(nal).expect("re-push"); - } - Ok(_) => {} - Err(e) => panic!("{name}: {e}"), - } - while dec.next_frame().is_some() { - frames += 1; - } - } - dec.flush().expect("flush"); - while dec.next_frame().is_some() { - frames += 1; - } - frames - }; - // Warm-up: every reusable buffer reaches its final size. - let warm = drive(&mut dec, false); - assert!(warm > 1, "{name}: only {warm} frames decoded"); - dec.reset_pictures(); - - ALLOCS.store(0, Ordering::SeqCst); - let again = drive(&mut dec, true); - let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!( - again, warm, - "{name}: frame count changed on the second pass" - ); - assert_eq!( - n, 0, - "{name}: steady-state slice decode allocated {n} times" - ); - } - - // Sanity: the counter is alive — emitting a frame does allocate. - let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap(); - let mut dec = Decoder::new(); - let _ = dec.decode_first_idr(&bytes).expect("decode"); - ALLOCS.store(0, Ordering::SeqCst); - COUNTING_HERE.with(|c| c.set(true)); - let frame = dec.frame().expect("frame"); - COUNTING_HERE.with(|c| c.set(false)); - assert!(frame.width > 0); - assert!( - ALLOCS.load(Ordering::SeqCst) > 0, - "allocation counter appears dead" - ); -} - -/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf -/// report. Run with `--nocapture` to see it. Uses the steady-state path -/// (buffers warm) like a playback loop would. -/// -/// Both halves matter: the intra measurement is what the previous release -/// reported, and the whole-sequence one is what playback actually costs, since -/// a real stream is almost all inter pictures. -#[test] -fn ns_per_macroblock_measurement() { - let base = vectors_dir(); - for name in [ - "BA1_Sony_D", - "CI_MW_D", - "NL1_Sony_D", - "CABA1_SVA_B", - "CABA3_SVA_B", - ] { - let Some(stream) = find_stream(&base.join(name)) else { - continue; - }; - let bytes = std::fs::read(stream).unwrap(); - let mut dec = Decoder::new(); - let frame = dec.decode_first_idr(&bytes).expect("warm-up"); - let (w, h) = (frame.width as u64, frame.height as u64); - let mbs = (w.div_ceil(16)) * (h.div_ceil(16)); - let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); - - let iters = 200u32; - let start = std::time::Instant::now(); - for _ in 0..iters { - for nal in &nals { - match dec.push_nal(nal) { - Ok(ec_h264::NalOutcome::PictureBoundary) => break, - Ok(_) => {} - Err(e) => panic!("{e}"), - } - } - dec.end_picture().expect("end_picture"); - } - let elapsed = start.elapsed(); - let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64; - let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6; - eprintln!( - "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \ - (intra IDR, single thread, deblock included, output copy excluded)" - ); - } - perf_whole_sequence(); -} - -/// The same measurement over whole sequences, where inter prediction, the -/// decoded picture buffer and output all count. -fn perf_whole_sequence() { - let base = vectors_dir(); - for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] { - let Some(stream) = find_stream(&base.join(name)) else { - continue; - }; - let bytes = std::fs::read(stream).unwrap(); - let Ok(warm) = decode_all(&bytes) else { - continue; - }; - if warm.is_empty() { - continue; - } - let frames = warm.len() as f64; - let start = std::time::Instant::now(); - let iters = 5u32; - for _ in 0..iters { - let _ = decode_all(&bytes).expect("decode"); - } - let elapsed = start.elapsed().as_secs_f64() / f64::from(iters); - // Every vector here is QCIF: 11 x 9 macroblocks. - let mbs = 99.0 * frames; - eprintln!( - "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \ - (full sequence, single thread, deblock and output copy included)", - elapsed * 1e9 / mbs, - 176.0 * 144.0 * frames / elapsed / 1e6 - ); - } -} - -/// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte -/// mutations and truncations of a real stream must produce `Err` or a frame, -/// never a panic. A cargo-fuzz target owns the deep search later (S18 lane -/// done-criterion); this keeps the invariant enforced in every test run. -#[test] -fn corrupt_streams_never_panic() { - let base = vectors_dir(); - // One stream per entropy coder, plus one with B slices and multiple - // references: CABAC's arithmetic decoder indexes context and coefficient - // arrays from stream-derived values, and inter prediction indexes the - // decoded picture buffer, the reference lists and the motion arrays from - // them too. All of it needs the same no-panic floor as the CAVLC tables. - for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B", "BA_MW_D"] { - let Some(stream) = find_stream(&base.join(name)) else { - continue; - }; - corrupt_sweep(&std::fs::read(stream).unwrap()); - } -} - -/// Truncate and bit-flip `bytes` many ways; every decode must return, error or -/// succeed, and never panic. -fn corrupt_sweep(bytes: &[u8]) { - let bytes = bytes.to_vec(); - - // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data. - for len in (0..bytes.len().min(4096)) - .step_by(37) - .chain([bytes.len() / 2]) - { - let mut dec = Decoder::new(); - let _ = dec.decode_first_idr(&bytes[..len]); - // Truncation must also be survivable on the full-sequence path, where - // a half-decoded picture meets the decoded picture buffer. - let _ = decode_all(&bytes[..len]); - } - // Single-byte corruptions: xor a walking pattern through the first 6KB - // (covers parameter sets and the first slices), plus scattered hits. - let mut xorshift = 0x243F_6A88u32; // deterministic PRNG, no rand dep - // Debug builds carry overflow checks but decode ~10x slower; a smaller - // sweep keeps the suite fast while release runs the full one. - let count = if cfg!(debug_assertions) { 400 } else { 2000 }; - let dense = count * 3 / 4; - for i in 0..count { - let mut m = bytes.clone(); - let pos = if i < dense { - i * 4 % m.len().min(6144) - } else { - xorshift ^= xorshift << 13; - xorshift ^= xorshift >> 17; - xorshift ^= xorshift << 5; - (xorshift as usize) % m.len() - }; - m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1); - let mut dec = Decoder::new(); - let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine - if i % 8 == 0 { - // The whole-sequence path costs more, so it gets a thinner sweep; - // it is the one that exercises reference lists and marking with - // stream-derived indices. - let _ = decode_all(&m); - } - } -} - // --------------------------------------------------------------------------- // ffmpeg-driven coverage: the JVT vectors are all QCIF, single-slice and coded // at a handful of quantisers, which leaves most of the deblocking tables, every @@ -1401,29 +1113,26 @@ fn switching_slices_are_refused_by_name() { } } - /// Extract the video elementary stream of a real file as Annex B. fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool { - run( - &[ - "-v", - "error", - "-y", - "-i", - &src.to_string_lossy(), - "-map", - "0:v:0", - "-c", - "copy", - "-bsf:v", - "h264_mp4toannexb", - "-frames:v", - &frames.to_string(), - "-f", - "h264", - &dst.to_string_lossy(), - ], - ) + run(&[ + "-v", + "error", + "-y", + "-i", + &src.to_string_lossy(), + "-map", + "0:v:0", + "-c", + "copy", + "-bsf:v", + "h264_mp4toannexb", + "-frames:v", + &frames.to_string(), + "-f", + "h264", + &dst.to_string_lossy(), + ]) } #[test] diff --git a/crates/ec-h264/tests/it/common.rs b/crates/ec-h264/tests/it/common.rs index bc2de8ce..071533d6 100644 --- a/crates/ec-h264/tests/it/common.rs +++ b/crates/ec-h264/tests/it/common.rs @@ -1,28 +1,62 @@ -//! Helpers shared by the merged integration-test modules: byte layouts, the -//! ffmpeg pipes and stream utilities that were identical in each file. - use std::path::{Path, PathBuf}; use ec_core::frame::{PixelFormat, VideoFrame}; +use ec_h264::{Decoder, NalOutcome}; -/// One decoded frame as planar bytes (16-bit little endian samples for High 10). -pub(super) fn frame_bytes(frame: &VideoFrame) -> Vec { - let bytes_per_sample = match frame.format { - PixelFormat::I422 => 1, - PixelFormat::I210 => 2, +pub(super) fn layout(f: PixelFormat) -> (usize, usize, usize) { + match f { + PixelFormat::I444 => (1, 1, 1), + PixelFormat::I410 => (2, 1, 1), + PixelFormat::I422 => (1, 2, 1), + PixelFormat::I210 => (2, 2, 1), + PixelFormat::I420 => (1, 2, 2), + PixelFormat::I010 => (2, 2, 2), other => panic!("unexpected output format {other:?}"), - }; + } +} + +pub(super) fn frame_bytes(frame: &VideoFrame) -> Vec { + let (bps, dx, dy) = layout(frame.format); let (w, h) = (frame.width as usize, frame.height as usize); - let dims = [(w, h), (w.div_ceil(2), h), (w.div_ceil(2), h)]; + let (cw, ch) = (w.div_ceil(dx), h.div_ceil(dy)); let mut out = Vec::new(); - for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { + for (plane, (pw, ph)) in frame.planes.iter().zip([(w, h), (cw, ch), (cw, ch)]) { for y in 0..ph { - out.extend_from_slice(plane.row(y, pw * bytes_per_sample).expect("plane row")); + out.extend_from_slice(plane.row(y, pw * bps).expect("plane row")); } } out } +pub(super) fn decode_all(bytes: &[u8]) -> Result>, ec_h264::Error> { + let mut dec = Decoder::new(); + let mut frames = Vec::new(); + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { + if dec.push_nal(nal)? == NalOutcome::PictureBoundary { + dec.end_picture()?; + dec.push_nal(nal)?; + } + while let Some(f) = dec.next_frame() { + frames.push(frame_bytes(&f)); + } + } + dec.flush()?; + while let Some(f) = dec.next_frame() { + frames.push(frame_bytes(&f)); + } + Ok(frames) +} + +pub(super) fn scratch(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "ec-h264-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + pub(super) fn ffmpeg_frames(stream: &Path, pix_fmt: &str, frame_len: usize) -> Option> { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) @@ -63,19 +97,6 @@ pub(super) fn find_stream(dir: &Path) -> Option { fallback } -/// (bytes per sample, chroma width divisor, chroma height divisor) -pub(super) fn layout(f: PixelFormat) -> (usize, usize, usize) { - match f { - PixelFormat::I444 => (1, 1, 1), - PixelFormat::I410 => (2, 1, 1), - PixelFormat::I422 => (1, 2, 1), - PixelFormat::I210 => (2, 2, 1), - PixelFormat::I420 => (1, 2, 2), - PixelFormat::I010 => (2, 2, 2), - other => panic!("unexpected output format {other:?}"), - } -} - pub(super) fn ffmpeg_pix_frames(stream: &Path, pix_fmt: &str) -> Option> { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-f", "h264", "-i"]) diff --git a/crates/ec-h264/tests/it/encode.rs b/crates/ec-h264/tests/it/encode.rs index 36cffd42..c46d9a31 100644 --- a/crates/ec-h264/tests/it/encode.rs +++ b/crates/ec-h264/tests/it/encode.rs @@ -58,48 +58,6 @@ impl Clip { } } - /// Frame `t` without the per-sample noise field: smooth gradients, a - /// band of sinusoidal texture and a box translating by whole and - /// sub-sample amounts. `render`'s noise is incompressible, which makes a - /// rate-quality comparison read mostly as how willing each encoder is to - /// throw residual away; this one is content where prediction matters, the - /// half a rate-quality comparison is about. - fn render_smooth(&mut self, t: usize) { - let (w, h) = (self.w, self.h); - let ft = t as f64; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f64, y as f64); - // A slow diagonal ramp that drifts by 1.5 samples a frame, so - // motion is not always on the sample grid. - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; - // A textured band, the part a search has to actually find. - let texture = if y > h / 3 && y < 2 * h / 3 { - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) - } else { - 0.0 - }; - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; - let v = if inside { - 196.0 - texture * 0.5 - } else { - 40.0 + (ramp % 90.0).abs() + texture - }; - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; - } - } - for y in 0..h / 2 { - for x in 0..w / 2 { - let (fx, fy) = (x as f64, y as f64); - self.u[y * (w / 2) + x] = - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; - self.v[y * (w / 2) + x] = - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; - } - } - } - fn view(&self) -> PictureView<'_> { PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) } @@ -147,35 +105,6 @@ fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { (y, u, v) } -/// Mean squared error between two equal-length planes. -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { - a.iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum::() - / a.len() as f64 -} - -/// PSNR over all three planes, pooled by sample count the way x264 reports it: -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number -/// rewards an encoder for throwing chroma away — a chroma decision measured -/// against it will always say "code less" — so any decision that can move -/// chroma bits is read here instead. -fn psnr_yuv(a: &(Vec, Vec, Vec), b: &(Vec, Vec, Vec)) -> f64 { - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); - let sse = - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; - let mse = sse / (n_y + 2.0 * n_c); - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - fn psnr(a: &[u8], b: &[u8]) -> f64 { let mse: f64 = a .iter() @@ -193,82 +122,6 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { } } -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { - let mut a = [[0.0; 5]; 4]; - for i in 0..4 { - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; - } - for col in 0..4 { - let mut pivot = col; - for row in col + 1..4 { - if a[row][col].abs() > a[pivot][col].abs() { - pivot = row; - } - } - a.swap(col, pivot); - let div = a[col][col]; - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); - for v in a[col][col..].iter_mut() { - *v /= div; - } - for row in 0..4 { - if row == col { - continue; - } - let f = a[row][col]; - let pivot_row = a[col]; - for (dst, src) in a[row][col..].iter_mut().zip(&pivot_row[col..]) { - *dst -= f * src; - } - } - } - [a[0][4], a[1][4], a[2][4], a[3][4]] -} - -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 -} - -/// A sample window with nothing in it (a film's black head, a fade) codes to -/// almost no bits and decodes back to the source exactly, so every point on -/// both curves sits at the PSNR cap and the BD number is a flat +0.000 that -/// reads like a measurement. Refuse such a window by name. -fn refuse_flat_window(psnrs: impl IntoIterator, skip_var: &str) { - const FLAT_WINDOW_DB: f64 = 90.0; - let ps: Vec = psnrs.into_iter().collect(); - assert!( - ps.iter().any(|&p| p < FLAT_WINDOW_DB), - "the sample window is flat — every point reaches the PSNR cap ({ps:?}); \ - this is a black head or a fade, not content: pass {skip_var} to sample \ - past it" - ); -} - -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); - let ys_candidate = std::array::from_fn(|i| candidate[i].1); - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); - let ys_anchor = std::array::from_fn(|i| anchor[i].1); - let lo = xs_candidate - .iter() - .copied() - .fold(f64::INFINITY, f64::min) - .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); - let hi = xs_candidate - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max) - .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); - assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); - let c_candidate = cubic_fit(xs_candidate, ys_candidate); - let c_anchor = cubic_fit(xs_anchor, ys_anchor); - (cubic_integral(c_candidate, hi) - - cubic_integral(c_candidate, lo) - - cubic_integral(c_anchor, hi) - + cubic_integral(c_anchor, lo)) - / (hi - lo) -} - /// 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] @@ -427,167 +280,6 @@ fn all_intra_when_the_gop_is_one() { // absent, exactly like the conformance suite's ffmpeg cross-check. // --------------------------------------------------------------------------- -/// Write `bytes` to `path` and PROVE the file on disk is exactly that long. -/// -/// lane-h26xpinloud: every write below used `std::fs::write(..).ok()?` and then -/// handed `path` to ffmpeg, which closes only the ERROR path. An Ok-but-short -/// write -- a filesystem that reports success and stores fewer bytes (ENOSPC on -/// a full mount, EFBIG under a size cap, a quota, a failed final flush) -- left -/// ffmpeg decoding a truncated stream, and the failure surfaced as a -/// plausible-looking wrong pixel or a shifted PSNR number, not as a write -/// failure. MEASURED: 1234 bytes written through a path that LOOKS like a -/// stream file in a scratch directory but whose filesystem accepts every byte -/// and stores none returns `Ok`, and the file on disk is 0 bytes. So the length -/// is checked here once, from the same `bytes.len()` the writer used, and any -/// shortfall carries the path, both counts, and the OS error -- or, for the -/// write that reported success and left a short file, the plain statement that -/// there was no OS error, which is exactly the case that used to print nothing. -/// -/// Returns the failure LINE rather than a bare bool, so the bail callers and any -/// panic caller all end on one format that cannot drift apart. The success path -/// is byte-identical to the old `fs::write`: same bytes, same path, truncate -/// then write. -fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { - let expected = bytes.len(); - if let Err(e) = std::fs::write(path, bytes) { - // The count here is the file's REAL length, not what the writer had - // confirmed in hand: under a size cap the kernel stores everything up - // to the cap and only THEN returns the error, and `fs::write` confirms - // none of it. - let on_disk = std::fs::metadata(path) - .map(|m| m.len() as usize) - .unwrap_or(0); - return Err(short_line( - site, - path, - on_disk, - expected, - &format!("the write failed: {e}"), - )); - } - match std::fs::metadata(path) { - Ok(m) if m.len() as usize == expected => Ok(()), - Ok(m) => Err(short_line( - site, - path, - m.len() as usize, - expected, - "the write reported success and the file on disk is still not that long (no OS error)", - )), - Err(e) => Err(short_line( - site, - path, - 0, - expected, - &format!("the written file could not be stat'ed: {e}"), - )), - } -} - -/// The one failure line every short pin ends on: site, path, the bytes the file -/// holds vs the bytes owed, and the reason. -fn short_line( - site: &str, - path: &std::path::Path, - on_disk: usize, - expected: usize, - why: &str, -) -> String { - format!( - "ec-h264 encode pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}", - site, - path.display() - ) -} - -/// A pin whose shortfall is reported and then BAILED on, for a caller that -/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None` -/// from here never reads as a plain "ffmpeg said no". -fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> { - pin_loud(site, path, bytes) - .map_err(|why| eprintln!("{why}")) - .ok() -} - -#[cfg(unix)] -#[test] -fn pin_loud_reds_on_an_ok_but_short_write() { - // The shape the four sites left open: a write that reports success and - // leaves a file of a different length. A symlink to /dev/null accepts every - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- - // a stream path, silently empty. - let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("ok-but-short.264"); - let _ = std::fs::remove_file(&path); - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); - assert!(why.contains(&path.display().to_string()), "{why}"); - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); - std::fs::remove_file(&path).ok(); - - // The control: the same call on a real file succeeds and leaves every byte. - let good = dir.join("whole.264"); - let bytes = vec![7u8; 1234]; - pin_loud("control", &good, &bytes).expect("a whole write is not short"); - assert_eq!(std::fs::read(&good).expect("read back"), bytes); - std::fs::remove_file(&good).ok(); - std::fs::remove_dir_all(&dir).ok(); -} - -#[cfg(unix)] -#[test] -fn pin_loud_reports_what_landed_under_a_size_cap() { - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores - // everything up to the cap and only then returns EFBIG. The line must carry - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count - // the writer confirmed, which is zero. - use std::process::Command; - let Ok(exe) = std::env::current_exe() else { - return; - }; - // SIGXFSZ's default action would kill the child before it can print; - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. - let script = format!( - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", - exe.display() - ); - let out = Command::new("sh") - .args(["-c", &script]) - .env("EC_PINLOUD_CHILD", "1") - .output() - .expect("run the capped child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - assert!(!out.status.success(), "the capped write must fail: {text}"); - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); - assert!( - text.contains("EFBIG") || text.contains("File too large"), - "{text}" - ); -} - -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. -#[test] -fn pin_loud_cap_child() { - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { - return; - } - let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-cap-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("capped.264"); - let why = - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); - std::fs::remove_file(&path).ok(); - std::fs::remove_dir_all(&dir).ok(); - panic!("{why}"); -} - /// 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 @@ -601,7 +293,7 @@ fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option> 7; - let stem = (2..5).contains(&cx); - let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; - let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; - let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); - clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; - } - } - clip.u.fill(128); - clip.v.fill(128); - }; - let run = |t8x8: bool, qp: i32, cabac: bool| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = 10; - cfg.transform_8x8 = t8x8; - cfg.cabac = cabac; - let mut enc = Encoder::new(cfg).expect("encoder"); - let mut clip = Clip::new(w, h); - let (mut bits, mut sum_psnr) = (0usize, 0.0); - let mut share = 0.0; - for t in 0..10 { - render(t, &mut clip); - bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; - let rec = enc.reconstruction().expect("reconstruction"); - sum_psnr += psnr(&clip.y, &rec.0); - } - if t8x8 { - let (i, p) = enc.transform_8x8_mbs(); - eprintln!("8x8 MBs: intra {i} inter {p}"); - share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); - } - (bits as f64, sum_psnr / 10.0, share) - }; - let qps = [22, 26, 30, 34]; - let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); - let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); - refuse_flat_window(off.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); - let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let bd = bd_psnr_delta(&on_curve, &off_curve); - let share = on.iter().map(|&(_, _, share)| share).sum::() / on.len() as f64; - // What the flag buys, not what the encoder is worth: both arms move when - // the paths under them change. It was re-pinned from 0.255 when the 4x4 - // luma path gained its coded_block_pattern group test, which is in the - // flag-off arm and improved it -- the same change moves the absolute - // synthetic comparison against x264 from -4.060 to -3.969 dB, and the - // flag-on arm barely at all, because a transform_8x8 macroblock does not - // go through that path. - const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230; - eprintln!( - "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", - share * 100.0 - ); - assert!(share > 0.0, "no 8x8 macroblocks were coded"); - assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); - assert!( - bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, - "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" - ); -} - /// 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] @@ -968,516 +576,12 @@ fn open_h264_source( panic!("{}: no video track found", path.to_string_lossy()); } -/// The first `want` pictures a second apart from one of the user's media -/// files: demuxed by [`open_h264_source`] (MP4 or Matroska), decoded by this -/// crate, every Nth frame with N the source frame rate. Returns the -/// luma/chroma size and the pictures. -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec) { - use ec_core::registry::Decoder as _; - - let (params, mut demux, index) = open_h264_source(path); - let video = match ¶ms.media { - ec_core::registry::MediaParameters::Video(v) => v, - _ => panic!("the H.264 track carries no video parameters"), - }; - let (w, h) = (video.width as usize, video.height as usize); - // Consecutive pictures by default. This used to take one picture a second, - // which measured an encoder on content it never sees: at a second apart - // nothing is predictable from the previous picture, so P slices went 93% - // intra on film and the inter path was never really under test. - // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a - // second) for the deliberately-uncorrelated case. - let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() { - Ok("fps") => video - .frame_rate - .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)), - Ok(n) => n.parse().unwrap_or(1usize).max(1), - Err(_) => 1, - }; - let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); - // Pictures to pass over before sampling: the head of a film is titles and - // fades, which are not what a codec is measured on. - let skip: usize = std::env::var("EC_H264_CLIP_SKIP") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); - let mut sources: Vec = Vec::new(); - let mut seen = 0usize; - while sources.len() < want { - 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 seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) { - sources.push(planes_of(&f)); - } - seen += 1; - } - } - assert!( - sources.len() >= 10, - "only {} pictures decoded from {}", - sources.len(), - path.to_string_lossy() - ); - eprintln!( - "{}: {}x{}, {} pictures, every {stride}th of {seen}", - path.to_string_lossy(), - w, - h, - sources.len() - ); - (w, h, sources) -} - -/// BD-PSNR of the `transform_8x8` flag (on by default) against flag-off on one real -/// clip from the library, full size, over a QP sweep: the number the synthetic -/// gate above cannot give, because the synthetic clip is content the flag wins -/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; -/// asserts nothing, so a regressing clip fails a gate, not the test run. -/// -/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ -/// real_clip_t8x8_bd_psnr -- --ignored --nocapture -#[test] -#[ignore = "slow measurement on the open 480p trailer"] -fn real_clip_t8x8_bd_psnr() { - let path = ec_testkit::fixture("open/sintel_trailer-480p.mp4"); - let (w, h, sources) = clip_sources(path.as_os_str(), 30); - - let run = |t8x8: bool, qp: i32| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = 10; - cfg.cabac = true; - cfg.transform_8x8 = t8x8; - cfg.framerate = 1.0; // the kept pictures are a second apart - cfg.threads = 0; - let mut enc = Encoder::new(cfg).expect("encoder"); - let (mut bits, mut sum_psnr) = (0usize, 0.0); - for (y, u, v) in &sources { - let view = PictureView::i420(w as u32, h as u32, y, u, v); - bits += enc.encode(&view).expect("encode").au.len() * 8; - let rec = enc.reconstruction().expect("reconstruction"); - sum_psnr += psnr(y, &rec.0); - } - let (i8x8, p8x8) = enc.transform_8x8_mbs(); - let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64; - (bits as f64, sum_psnr / sources.len() as f64, share) - }; - let qps = [22, 26, 30, 34]; - let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect(); - let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect(); - for (i, &qp) in qps.iter().enumerate() { - let (ob, op, _) = off[i]; - let (nb, np, share) = on[i]; - eprintln!( - "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%", - share * 100.0 - ); - } - let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let bd = bd_psnr_delta(&on_curve, &off_curve); - let share = on.iter().map(|&(_, _, s)| s).sum::() / on.len() as f64; - eprintln!( - "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", - share * 100.0 - ); -} - // --------------------------------------------------------------------------- // 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. // --------------------------------------------------------------------------- -/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measures -/// -4.523 dB against x264 there (352x288, 24 pictures of -/// `Clip::render_smooth`, both encoders at their own default effort: our -/// `Preset::Fast`, x264's `-preset medium`). The floor is that number with -/// room for platform noise, so the distance can shrink but not grow -/// unnoticed; it is not a claim that -4.5 dB is fine. On a 3840x1608 clip -/// from the library the same measurement reads -0.728 dB and on a 2560x1440 -/// screen capture -0.500, so this synthetic number is the pessimistic end of -/// the range and not the typical one. -/// -/// It moved -4.449 -> -4.523 when the intra-versus-inter decision started -/// coding both branches for real. That change is worth 0.315 dB on the film -/// clip and 0.564 on the screen capture, and takes fewer bits at every QP -/// while doing it. This clip prefers a heavier rate term in that decision -/// (see the sweep in `enc/mb.rs`), which the two real clips do not. -/// -/// It moved -4.523 -> -4.073 when inter luma levels started being chosen -/// against the CABAC coder's own price for them (0.100 dB on the film clip, -/// 0.029 on the screen capture). -const BD_PSNR_VS_X264_FLOOR: f64 = -4.15; - -fn have_x264() -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-hide_banner", "-encoders"]) - .output() - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264")) -} - -/// Encode raw I420 pictures with x264 at constant QP, matched to what our -/// encoder actually does: Main profile (CABAC, no 8x8 transform), one -/// reference, no B pictures, the same GOP, and adaptive quantisation and psy -/// off so both encoders spend bits by the same rule. Returns the Annex B -/// stream. -fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option> { - // Distinct per call, not per process: two #[test]s in this binary call - // this on parallel threads with overlapping qp values, and a path keyed - // only on qp lets one call's cleanup delete another's still-in-use file. - static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id())); - std::fs::create_dir_all(&dir).ok()?; - let raw = dir.join(format!("in-q{qp}-{seq}.yuv")); - let out = dir.join(format!("out-q{qp}-{seq}.264")); - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); - for (y, u, v) in sources { - buf.extend_from_slice(y); - buf.extend_from_slice(u); - buf.extend_from_slice(v); - } - pin_or_bail("x264_encode_qp", &raw, &buf)?; - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y"]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) - .arg("-i") - .arg(&raw) - // EC_H264_X264_PRESET selects the reference preset; the DONE.md target is - // measured against `veryfast`, the default stays `medium` for the older gates. - .args([ - "-c:v", - "libx264", - "-preset", - &std::env::var("EC_H264_X264_PRESET").unwrap_or_else(|_| "medium".into()), - ]) - .args(["-profile:v", "main", "-qp", &qp.to_string()]) - .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"]) - // ipratio/pbratio 1.0 matter: x264's constant-QP mode otherwise codes - // I pictures at a lower QP than the one asked for, which reads as a - // rate-quality win that is really a different quantiser. - // EC_H264_X264_PARAMS appends to this list, which is how a single - // reference feature gets attributed: running the sweep again with - // `trellis=0` says how much of x264's lead is its rate-distortion - // quantisation rather than its prediction. - .args([ - "-x264-params", - &format!( - "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", - match std::env::var("EC_H264_X264_PARAMS") { - // The value may or may not carry its own leading colon; - // both spell the same thing. Passing it through would not: - // ffmpeg drops the token after an empty one, so "::subme=1" - // silently encodes at the preset's subme and the sweep - // reads as "the feature does nothing". - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => - format!(":{}", extra.trim().trim_matches(':')), - _ => String::new(), - } - ), - ]) - .args(["-f", "h264"]) - .arg(&out) - .output() - .ok()?; - let _ = std::fs::remove_file(&raw); - if !status.status.success() { - eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr)); - return None; - } - let stream = std::fs::read(&out).ok()?; - let _ = std::fs::remove_file(&out); - Some(stream) -} - -/// BD-PSNR of our encoder against x264 at matched features over QP -/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot -/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure -/// the same thing on real content. -/// -/// Both curves are (bits, luma PSNR against the same source pictures), and -/// both are measured on ffmpeg's decode of the stream rather than on an -/// encoder's own reconstruction, so the two halves are read the same way. -/// -/// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison -/// all-intra, which splits the gap between the intra path and the P pictures. -/// -/// `EC_H264_PRESET_BALANCED` runs our half of the comparison at -/// `Preset::Balanced` instead of the default `Preset::Fast`, which separates -/// what search effort buys from what the coder itself costs. -/// -/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film -/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing -/// between the sampled pictures; both default to consecutive pictures from the -/// start of the file. The measurements quoted through this crate that predate -/// those two knobs were taken one picture a second, where nothing is -/// predictable from the previous picture -- they are not comparable with the -/// numbers taken since. -/// -/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture -/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ -/// bd_psnr_vs_x264 -- --nocapture -#[test] -fn bd_psnr_vs_x264() { - assert!(have_x264(), "the pinned ffmpeg has no libx264"); - let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { - Some(path) => clip_sources(&path, 24), - None => { - let (w, h, frames) = (352, 288, 24); - let mut clip = Clip::new(w, h); - let mut sources = Vec::with_capacity(frames); - for t in 0..frames { - clip.render_smooth(t); - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); - } - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); - (w, h, sources) - } - }; - - let gop: u32 = std::env::var("EC_H264_GOP") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(10); - let ours = |qp: i32| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = gop; - if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { - cfg.preset = ec_h264::Preset::Balanced; - } - cfg.cabac = true; - cfg.framerate = 1.0; - cfg.threads = 0; - let mut enc = Encoder::new(cfg).expect("encoder"); - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); - for (y, u, v) in &sources { - let view = PictureView::i420(w as u32, h as u32, y, u, v); - stream.extend_from_slice(&enc.encode(&view).expect("encode").au); - sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0); - } - // Measured the same way x264 is: on what a decoder shows, not on the - // encoder's own reconstruction. The two are printed together because a - // gap between them is a bug in one of the halves, not a rate-quality - // result. - let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - let (sum_u, sum_v) = ( - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::(), - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::(), - ); - eprintln!( - " ours qp {qp}: u {:.2} dB v {:.2} dB", - sum_u / sources.len() as f64, - sum_v / sources.len() as f64 - ); - let (decoded_psnr, recon_psnr) = - (sum / sources.len() as f64, sum_recon / sources.len() as f64); - assert!( - (decoded_psnr - recon_psnr).abs() < 0.05, - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ - stream decodes to {decoded_psnr:.2} dB" - ); - ( - (stream.len() * 8) as f64, - decoded_psnr, - sum_yuv / sources.len() as f64, - ) - }; - let x264 = |qp: i32| { - let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); - let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream"); - assert_eq!( - decoded.len(), - sources.len(), - "x264 returned {} pictures for {} sources", - decoded.len(), - sources.len() - ); - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - let n = sources.len() as f64; - eprintln!( - " x264 qp {qp}: u {:.2} dB v {:.2} dB", - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::() - / n, - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::() - / n - ); - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) - }; - - let qps = [22, 26, 30, 34]; - let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); - let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); - for (i, &qp) in qps.iter().enumerate() { - let (ob, op, oy) = mine[i]; - let (xb, xp, xy) = theirs[i]; - eprintln!( - "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \ - ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", - (ob / xb - 1.0) * 100.0, - op - xp, - oy - xy - ); - } - refuse_flat_window(theirs.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { - v.iter() - .map(|&(b, p, y)| (b, if luma { p } else { y })) - .collect() - }; - let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); - let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); - eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); - eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB"); - - // The floor is calibrated on the synthetic clip; a clip of the user's is a - // measurement, not a gate, because its content is not pinned. - if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 { - assert!( - bd > BD_PSNR_VS_X264_FLOOR, - "BD-PSNR against x264 fell to {bd:+.3} dB, past the \ - {BD_PSNR_VS_X264_FLOOR:+.3} dB floor" - ); - } -} - -/// Where our bits go against where x264's go, class by class, on the same -/// sources at the same QP. Both streams are parsed by this crate's decoder, so -/// the two accounts are the same measurement; the BD-PSNR gate says how much -/// we overspend, this says on what. -/// -/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture -/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ -/// bit_account_vs_x264 -- --nocapture -#[test] -fn bit_account_vs_x264() { - assert!(have_x264(), "the pinned ffmpeg has no libx264"); - let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { - Some(path) => clip_sources(&path, 12), - None => { - let (w, h, frames) = (352, 288, 12); - let mut clip = Clip::new(w, h); - let mut sources = Vec::with_capacity(frames); - for t in 0..frames { - clip.render_smooth(t); - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); - } - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); - (w, h, sources) - } - }; - let gop: u32 = 10; - let account = |stream: &[u8]| { - let mut dec = Decoder::new(); - dec.set_output_order(OutputOrder::Decode); - 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 dec.next_frame().is_some() {} - } - dec.flush().expect("flush"); - while dec.next_frame().is_some() {} - (dec.bit_account(), dec.mb_shapes()) - }; - for qp in [26, 34] { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = gop; - cfg.cabac = true; - cfg.framerate = 1.0; - cfg.threads = 0; - if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { - cfg.preset = ec_h264::Preset::Balanced; - } - let mut enc = Encoder::new(cfg).expect("encoder"); - let mut ours = Vec::new(); - for (y, u, v) in &sources { - let view = PictureView::i420(w as u32, h as u32, y, u, v); - ours.extend_from_slice(&enc.encode(&view).expect("encode").au); - } - let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); - let ((a, sa), (b, sb)) = (account(&ours), account(&theirs)); - eprintln!( - "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes", - sources.len(), - ours.len(), - theirs.len() - ); - let row = |name: &str, ours: u64, theirs: u64| { - let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0); - let delta = if t > 0.0 { - format!("{:+.1}%", (o - t) / t * 100.0) - } else { - "--".to_string() - }; - eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}"); - }; - row("skip", a.skip, b.skip); - row("mb_type", a.mb_type, b.mb_type); - row("mv", a.mv, b.mv); - row("ref_idx", a.ref_idx, b.ref_idx); - row("cbp+qp", a.cbp_qp, b.cbp_qp); - row("intra modes", a.intra_mode, b.intra_mode); - row("residual luma", a.residual_luma, b.residual_luma); - row("residual chroma", a.residual_chroma, b.residual_chroma); - row("total accounted", a.total(), b.total()); - let mix = |n: &str, s: &ec_h264::MbShapes| { - eprintln!( - " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", - s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra - ); - }; - mix("shapes ours", &sa); - mix("shapes x264", &sb); - } -} - /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. /// /// The default preset codes every P macroblock as one 16x16 partition, so the @@ -1486,7 +590,6 @@ fn bit_account_vs_x264() { #[test] fn balanced_partitions_decode_bit_exactly() { let (w, h) = (176, 144); - let mut shapes = ec_h264::MbShapes::default(); 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| { @@ -1501,27 +604,7 @@ fn balanced_partitions_decode_bit_exactly() { assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}"); assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}"); } - let mut dec = Decoder::new(); - dec.set_output_order(OutputOrder::Decode); - 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 dec.next_frame().is_some() {} - } - dec.flush().expect("flush"); - while dec.next_frame().is_some() {} - shapes.add_public(&dec.mb_shapes()); } - eprintln!( - "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", - shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra - ); - assert!( - shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0, - "the sweep has to code every shape, or it proves nothing about them" - ); } #[test] diff --git a/crates/ec-h264/tests/it/high10.rs b/crates/ec-h264/tests/it/high10.rs index 57823585..1050fbdc 100644 --- a/crates/ec-h264/tests/it/high10.rs +++ b/crates/ec-h264/tests/it/high10.rs @@ -8,57 +8,7 @@ use std::path::{Path, PathBuf}; -use ec_core::frame::{PixelFormat, VideoFrame}; -use ec_h264::{Decoder, NalOutcome}; - -/// One decoded frame as I010 bytes (little-endian 16-bit samples, planes -/// back to back), checking the format and plane geometry on the way. -fn frame_bytes(frame: &VideoFrame) -> Vec { - assert_eq!(frame.format, PixelFormat::I010, "High 10 comes out as I010"); - let (w, h) = (frame.width as usize, frame.height as usize); - let dims = [ - (w, h), - (w.div_ceil(2), h.div_ceil(2)), - (w.div_ceil(2), h.div_ceil(2)), - ]; - let mut out = Vec::new(); - for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { - for y in 0..ph { - out.extend_from_slice(plane.row(y, pw * 2).expect("plane row")); - } - } - out -} - -fn decode_all(bytes: &[u8]) -> Result>, ec_h264::Error> { - let mut dec = Decoder::new(); - let mut frames = Vec::new(); - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { - if dec.push_nal(nal)? == NalOutcome::PictureBoundary { - dec.end_picture()?; - dec.push_nal(nal)?; - } - while let Some(f) = dec.next_frame() { - frames.push(frame_bytes(&f)); - } - } - dec.flush()?; - while let Some(f) = dec.next_frame() { - frames.push(frame_bytes(&f)); - } - Ok(frames) -} - -fn ffmpeg_frames(stream: &Path, frame_len: usize) -> Option> { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(stream) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-"]) - .output() - .ok()?; - (out.status.success() && !out.stdout.is_empty() && out.stdout.len() % frame_len == 0) - .then_some(out.stdout) -} +use super::common::{decode_all, ffmpeg_frames, frame_bytes, scratch}; // ---- MD5 (RFC 1321), so the committed fixtures need no ffmpeg ---------------- @@ -142,16 +92,6 @@ fn committed_streams_match_ffmpeg_md5() { // ---- the libx264 sweep -------------------------------------------------------- -fn scratch() -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "ec-h264-high10-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&dir).unwrap(); - dir -} - struct Case { tag: &'static str, /// lavfi source and size. @@ -203,13 +143,14 @@ fn encode(dir: &Path, c: &Case) -> Option { } fn check(c: &Case) -> Result { - let dir = scratch(); + let dir = scratch("high10"); let stream = encode(&dir, c).unwrap_or_else(|| panic!("{}: ffmpeg/libx264 10-bit cannot encode", c.tag)); let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; let ours = decode_all(&bytes).map_err(|e| format!("{}: {e}", c.tag))?; let first = ours.first().ok_or("no frames decoded")?; - let theirs = ffmpeg_frames(&stream, first.len()).ok_or("ffmpeg cannot decode")?; + let theirs = + ffmpeg_frames(&stream, "yuv420p10le", first.len()).ok_or("ffmpeg cannot decode")?; let _ = std::fs::remove_file(&stream); if theirs.len() != first.len() * ours.len() { return Err(format!( @@ -242,7 +183,7 @@ fn sweep(cases: &[Case]) { Err(e) => failed.push(e), } } - let _ = std::fs::remove_dir_all(scratch()); + let _ = std::fs::remove_dir_all(scratch("high10")); assert!( failed.is_empty(), "High 10 mismatches:\n{}", diff --git a/crates/ec-h264/tests/it/high422.rs b/crates/ec-h264/tests/it/high422.rs index 037b55ed..640eeef5 100644 --- a/crates/ec-h264/tests/it/high422.rs +++ b/crates/ec-h264/tests/it/high422.rs @@ -6,38 +6,7 @@ use std::path::{Path, PathBuf}; -use ec_h264::{Decoder, NalOutcome}; - -use super::common::{escape, ffmpeg_frames, frame_bytes}; - -fn decode_all(bytes: &[u8]) -> Result>, ec_h264::Error> { - let mut dec = Decoder::new(); - let mut frames = Vec::new(); - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { - if dec.push_nal(nal)? == NalOutcome::PictureBoundary { - dec.end_picture()?; - dec.push_nal(nal)?; - } - while let Some(f) = dec.next_frame() { - frames.push(frame_bytes(&f)); - } - } - dec.flush()?; - while let Some(f) = dec.next_frame() { - frames.push(frame_bytes(&f)); - } - Ok(frames) -} - -fn scratch() -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "ec-h264-hi422-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&dir).unwrap(); - dir -} +use super::common::{decode_all, escape, ffmpeg_frames, scratch}; struct Case { tag: &'static str, @@ -92,7 +61,7 @@ fn encode(dir: &Path, c: &Case) -> Option { } fn check(c: &Case) -> Result { - let dir = scratch(); + let dir = scratch("hi422"); let stream = encode(&dir, c) .unwrap_or_else(|| panic!("{}: ffmpeg/libx264 cannot encode this case", c.tag)); let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; @@ -132,7 +101,7 @@ fn sweep(cases: &[Case]) { Err(e) => failed.push(e), } } - let _ = std::fs::remove_dir_all(scratch()); + let _ = std::fs::remove_dir_all(scratch("hi422")); assert!( failed.is_empty(), "4:2:2 mismatches:\n{}", @@ -332,21 +301,17 @@ const SMALL: &[Case] = &[ ]; /// Every case at 8 bits, progressive. -#[test] -fn x264_hi422_progressive_8bit() { - sweep(SMALL); +fn progressive_8bit_cases() -> Vec { + SMALL.iter().map(|c| Case { ..*c }).collect() } /// The same at 10 bits. -#[test] -fn x264_hi422_progressive_10bit() { - let cases: Vec = SMALL.iter().map(|c| ten(Case { ..*c })).collect(); - sweep(&cases); +fn progressive_10bit_cases() -> Vec { + SMALL.iter().map(|c| ten(Case { ..*c })).collect() } /// MBAFF at 8 and 10 bits. -#[test] -fn x264_hi422_mbaff() { +fn mbaff_cases() -> Vec { let mut cases: Vec = Vec::new(); for (i, c) in SMALL.iter().enumerate() { // Every other case keeps the sweep quick; the rest run progressive. @@ -360,13 +325,12 @@ fn x264_hi422_mbaff() { format!("mbaff-{}{}", c.tag, if c.ten_bit { "-10" } else { "" }).into_boxed_str(), ); } - sweep(&cases); + cases } /// 1920x1080 intra and long-GOP, progressive and MBAFF (slow). -#[test] -fn x264_hi422_hd() { - sweep(&[ +fn hd_cases() -> Vec { + vec![ case("hd-i-cabac", "testsrc2", "1920x1080", 2, "keyint=1"), case( "hd-b-cabac", @@ -403,7 +367,7 @@ fn x264_hi422_hd() { 2, "keyint=1:cabac=0", ))), - ]); + ] } // ---- I_PCM in 4:2:2 (x264 never writes one) ---------------------------- @@ -530,3 +494,12 @@ fn hi422_pcm_macroblocks_round_trip() { assert_eq!(bytes, &expected, "{bd}-bit I_PCM 4:2:2"); } } + +#[test] +fn x264_hi422_family() { + let mut cases = progressive_8bit_cases(); + cases.extend(progressive_10bit_cases()); + cases.extend(mbaff_cases()); + cases.extend(hd_cases()); + sweep(&cases); +} diff --git a/crates/ec-h264/tests/it/high444.rs b/crates/ec-h264/tests/it/high444.rs index b37900f9..83342653 100644 --- a/crates/ec-h264/tests/it/high444.rs +++ b/crates/ec-h264/tests/it/high444.rs @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; use ec_core::frame::{PixelFormat, VideoFrame}; use ec_h264::{Decoder, NalOutcome}; -use super::common::{ffmpeg_pix_frames, layout}; +use super::common::{ffmpeg_pix_frames, layout, scratch}; /// One decoded frame as planar bytes (16-bit little endian above 8 bits). fn frame_bytes(frame: &VideoFrame) -> (Vec, PixelFormat) { @@ -50,16 +50,6 @@ fn decode_all(bytes: &[u8]) -> Result, PixelFormat)>, ec_h264::Erro Ok(frames) } -fn scratch() -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "ec-h264-hi444-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&dir).unwrap(); - dir -} - #[derive(Clone, Copy)] struct Case { tag: &'static str, @@ -114,7 +104,7 @@ fn encode(dir: &Path, c: &Case) -> Option { } fn check(c: &Case) -> Result { - let dir = scratch(); + let dir = scratch("hi444"); let stream = encode(&dir, c) .unwrap_or_else(|| panic!("{}: ffmpeg/libx264 cannot encode this case", c.tag)); let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; @@ -186,7 +176,7 @@ fn sweep(label: &str, cases: &[Case]) { Err(e) => failed.push(e), } } - let _ = std::fs::remove_dir_all(scratch()); + let _ = std::fs::remove_dir_all(scratch("hi444")); assert!( failed.is_empty(), "{label} mismatches:\n{}", @@ -431,16 +421,14 @@ fn all(pix: &'static str, prefix: &str, mbaff: bool, step: usize) -> Vec { .collect() } -#[test] -fn x264_hi444_8bit() { - sweep("4:4:4 8-bit", &all("yuv444p", "", false, 1)); +fn hi444_8bit_cases() -> Vec { + all("yuv444p", "", false, 1) } -#[test] -fn x264_hi444_mbaff() { +fn hi444_mbaff_cases() -> Vec { let mut cases = all("yuv444p", "mbaff-", true, 2); cases.extend(all("yuv444p10le", "mbaff-", true, 4)); - sweep("4:4:4 MBAFF", &cases); + cases } // ---- lossless (qpprime_y_zero_transform_bypass) ---- @@ -539,19 +527,16 @@ fn lossless(pix: &'static str) -> Vec { LOSSLESS.iter().map(|c| with(c, pix, "", false)).collect() } -#[test] -fn x264_lossless_444_8bit() { - sweep("lossless 4:4:4", &lossless("yuv444p")); +fn lossless_444_8bit_cases() -> Vec { + lossless("yuv444p") } -#[test] -fn x264_lossless_444_10bit() { - sweep("lossless 4:4:4 10-bit", &lossless("yuv444p10le")); +fn lossless_444_10bit_cases() -> Vec { + lossless("yuv444p10le") } /// Profile 244 lossless also carries 4:2:0 and 4:2:2. -#[test] -fn x264_lossless_420_422() { +fn lossless_420_422_cases() -> Vec { let mut cases: Vec = Vec::new(); for (i, c) in LOSSLESS.iter().enumerate() { if i % 2 == 0 { @@ -563,34 +548,30 @@ fn x264_lossless_420_422() { cases.push(with(c, "yuv422p10le", "", false)); } } - sweep("lossless 4:2:0 / 4:2:2", &cases); + cases } -#[test] -fn x264_lossless_mbaff() { +fn lossless_mbaff_cases() -> Vec { let cases: Vec = LOSSLESS .iter() .enumerate() .filter(|(i, _)| i % 4 == 0) .map(|(_, c)| with(c, "yuv444p", "mbaff-", true)) .collect(); - sweep("lossless MBAFF", &cases); + cases } // ---- monochrome ---- -#[test] -fn x264_monochrome_8bit() { - sweep("gray", &all("gray", "", false, 1)); +fn monochrome_8bit_cases() -> Vec { + all("gray", "", false, 1) } -#[test] -fn x264_monochrome_10bit() { - sweep("gray10le", &all("gray10le", "", false, 2)); +fn monochrome_10bit_cases() -> Vec { + all("gray10le", "", false, 2) } -#[test] -fn x264_monochrome_mbaff_and_lossless() { +fn monochrome_mbaff_and_lossless_cases() -> Vec { let mut cases = all("gray", "mbaff-", true, 6); cases.extend( LOSSLESS @@ -599,12 +580,11 @@ fn x264_monochrome_mbaff_and_lossless() { .filter(|(i, _)| i % 3 == 0) .map(|(_, c)| with(c, "gray", "", false)), ); - sweep("gray MBAFF / lossless", &cases); + cases } /// 1280x720 (slow). -#[test] -fn x264_hi444_hd() { +fn hi444_hd_cases() -> Vec { let base = [ case("hd-i-cabac", "testsrc2", "1280x720", 2, "keyint=1"), case( @@ -630,5 +610,21 @@ fn x264_hi444_hd() { } cases.push(with(&base[0], "gray", "", false)); cases.push(with(&base[0], "yuv444p", "mbaff-", true)); - sweep("4:4:4 HD", &cases); + cases +} + +#[test] +fn x264_hi444_family() { + let mut cases = Vec::new(); + cases.extend(hi444_8bit_cases()); + cases.extend(hi444_mbaff_cases()); + cases.extend(lossless_444_8bit_cases()); + cases.extend(lossless_444_10bit_cases()); + cases.extend(lossless_420_422_cases()); + cases.extend(lossless_mbaff_cases()); + cases.extend(monochrome_8bit_cases()); + cases.extend(monochrome_10bit_cases()); + cases.extend(monochrome_mbaff_and_lossless_cases()); + cases.extend(hi444_hd_cases()); + sweep("x264 4:4:4, lossless and monochrome", &cases); } diff --git a/crates/ec-h264/tests/it/main.rs b/crates/ec-h264/tests/it/main.rs index 9085f959..c427882b 100644 --- a/crates/ec-h264/tests/it/main.rs +++ b/crates/ec-h264/tests/it/main.rs @@ -1,8 +1,5 @@ //! ec-h264 integration tests, one binary. Each module is one former //! `tests/.rs` file; the test path is `::`. -//! -//! `conformance.rs` stays a separate binary: it installs a `#[global_allocator]` -//! and measures wall-clock speed. #![forbid(unsafe_code)] @@ -16,5 +13,4 @@ mod high444; mod high444_jvt; mod interlaced; mod mbaff_x264; -mod no_panic; mod refusals; diff --git a/crates/ec-h264/tests/it/mbaff_x264.rs b/crates/ec-h264/tests/it/mbaff_x264.rs index 9084d4fd..773c0e95 100644 --- a/crates/ec-h264/tests/it/mbaff_x264.rs +++ b/crates/ec-h264/tests/it/mbaff_x264.rs @@ -6,61 +6,7 @@ use std::path::{Path, PathBuf}; -use ec_core::frame::{PixelFormat, VideoFrame}; -use ec_h264::{Decoder, NalOutcome}; - -use super::common::ffmpeg_frames; - -/// One decoded frame as planar bytes (16-bit little endian samples for High 10). -fn frame_bytes(frame: &VideoFrame) -> Vec { - let bytes_per_sample = match frame.format { - PixelFormat::I420 => 1, - PixelFormat::I010 => 2, - other => panic!("unexpected output format {other:?}"), - }; - let (w, h) = (frame.width as usize, frame.height as usize); - let dims = [ - (w, h), - (w.div_ceil(2), h.div_ceil(2)), - (w.div_ceil(2), h.div_ceil(2)), - ]; - let mut out = Vec::new(); - for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { - for y in 0..ph { - out.extend_from_slice(plane.row(y, pw * bytes_per_sample).expect("plane row")); - } - } - out -} - -fn decode_all(bytes: &[u8]) -> Result>, ec_h264::Error> { - let mut dec = Decoder::new(); - let mut frames = Vec::new(); - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { - if dec.push_nal(nal)? == NalOutcome::PictureBoundary { - dec.end_picture()?; - dec.push_nal(nal)?; - } - while let Some(f) = dec.next_frame() { - frames.push(frame_bytes(&f)); - } - } - dec.flush()?; - while let Some(f) = dec.next_frame() { - frames.push(frame_bytes(&f)); - } - Ok(frames) -} - -fn scratch() -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "ec-h264-mbaff-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&dir).unwrap(); - dir -} +use super::common::{decode_all, ffmpeg_frames, scratch}; struct Case { tag: &'static str, @@ -105,7 +51,7 @@ fn encode(dir: &Path, c: &Case) -> Option { } fn check(c: &Case) -> Result { - let dir = scratch(); + let dir = scratch("mbaff"); let stream = encode(&dir, c) .unwrap_or_else(|| panic!("{}: ffmpeg/libx264 cannot encode this case", c.tag)); let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; @@ -145,7 +91,7 @@ fn sweep(cases: &[Case]) { Err(e) => failed.push(e), } } - let _ = std::fs::remove_dir_all(scratch()); + let _ = std::fs::remove_dir_all(scratch("mbaff")); assert!( failed.is_empty(), "MBAFF mismatches:\n{}", @@ -171,9 +117,8 @@ const fn case( } /// Small pictures: every coding tool once, quick enough for every run. -#[test] -fn x264_mbaff_small() { - sweep(&[ +fn mbaff_small_cases() -> Vec { + vec![ case("i-cabac-tff", "testsrc2", "192x128", 3, "tff=1:keyint=1"), case("i-cabac-bff", "testsrc2", "192x128", 3, "bff=1:keyint=1"), case( @@ -296,12 +241,11 @@ fn x264_mbaff_small() { 8, "tff=1:bframes=3:subme=9:trellis=2:me=umh", ), - ]); + ] } /// High 10 MBAFF. -#[test] -fn x264_mbaff_high10() { +fn mbaff_high10_cases() -> Vec { let t = |tag, params| Case { tag, src: "testsrc2", @@ -310,19 +254,18 @@ fn x264_mbaff_high10() { ten_bit: true, params, }; - sweep(&[ + vec![ t("h10-i-cabac", "tff=1:keyint=1"), t("h10-i-cavlc", "cabac=0:bff=1:keyint=1"), t("h10-b-cabac", "tff=1:bframes=3"), t("h10-b-cavlc", "cabac=0:bff=1:bframes=3"), t("h10-weightp", "tff=1:bframes=2:weightp=2:weightb=1"), - ]); + ] } /// 720x576 (the broadcast interlaced size). -#[test] -fn x264_mbaff_sd() { - sweep(&[ +fn mbaff_sd_cases() -> Vec { + vec![ case("sd-cabac-tff", "testsrc2", "720x576", 6, "tff=1:bframes=3"), case( "sd-cabac-bff", @@ -352,13 +295,12 @@ fn x264_mbaff_sd() { 6, "tff=1:bframes=2:weightp=2:weightb=1", ), - ]); + ] } /// 1920x1080. -#[test] -fn x264_mbaff_hd() { - sweep(&[ +fn mbaff_hd_cases() -> Vec { + vec![ case( "hd-cabac-tff", "testsrc2", @@ -401,5 +343,15 @@ fn x264_mbaff_hd() { 5, "bff=1:bframes=2:weightp=2:weightb=1", ), - ]); + ] +} + +#[test] +fn x264_mbaff() { + let mut cases = Vec::new(); + cases.extend(mbaff_small_cases()); + cases.extend(mbaff_high10_cases()); + cases.extend(mbaff_sd_cases()); + cases.extend(mbaff_hd_cases()); + sweep(&cases); } diff --git a/crates/ec-h264/tests/it/no_panic.rs b/crates/ec-h264/tests/it/no_panic.rs deleted file mode 100644 index e2a3f77e..00000000 --- a/crates/ec-h264/tests/it/no_panic.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! No-panic floor for the decoder on malformed input. -//! -//! For each of the first 10 JVT conformance streams (the same name-sorted walk -//! `conformance.rs` uses), truncate at 8 positions and flip one byte at 30 -//! fixed-seed positions. Every mutant is decoded end to end. An `Err` is fine; -//! a panic fails the test. -//! - -use std::path::{Path, PathBuf}; - -use ec_h264::{Decoder, NalOutcome}; - -use super::common::find_stream; - -const STREAMS: usize = 10; -const TRUNCATIONS: usize = 8; -const CORRUPTIONS: usize = 30; -const SEED: u32 = 0x9E37_79B9; - -fn vectors_dir() -> PathBuf { - ec_testkit::fixture("vectors/h264-jvt") -} - -/// Every vector directory, in name order (the order `conformance.rs` walks). -fn vector_names(base: &Path) -> Vec { - let mut names: Vec = std::fs::read_dir(base) - .into_iter() - .flatten() - .flatten() - .filter(|e| e.path().is_dir()) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .collect(); - names.sort(); - names -} - -/// Decode a whole byte stream, ignoring every error. Only a panic matters here. -fn decode_everything(bytes: &[u8]) { - let mut dec = Decoder::new(); - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { - if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) { - let _ = dec.end_picture(); - let _ = dec.push_nal(nal); - } - while dec.next_frame().is_some() {} - } - let _ = dec.flush(); - while dec.next_frame().is_some() {} -} - -#[test] -fn truncated_and_corrupted_conformance_streams_never_panic() { - let base = vectors_dir(); - let mut streams = 0usize; - for name in vector_names(&base).into_iter().take(STREAMS) { - let Some(stream) = find_stream(&base.join(&name)) else { - continue; - }; - let bytes = std::fs::read(&stream).expect("read conformance stream"); - if bytes.is_empty() { - continue; - } - streams += 1; - - for k in 1..=TRUNCATIONS { - decode_everything(&bytes[..bytes.len() * k / (TRUNCATIONS + 1)]); - } - - let mut seed = SEED; - for _ in 0..CORRUPTIONS { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - let pos = seed as usize % bytes.len(); - // Never xor by zero: that would leave the stream unchanged. - let flip = ((seed >> 24) as u8) | 1; - let mut m = bytes.clone(); - m[pos] ^= flip; - decode_everything(&m); - } - } - eprintln!( - "no-panic sweep: {streams} streams, {TRUNCATIONS} truncations + {CORRUPTIONS} corruptions each" - ); -}