From 8aadafcf755514b3ca243d38238810dcf8fb440c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:36:13 +0300 Subject: [PATCH] U6: ec-h264 tests: delete the zero-alloc and ns/MB perf tests with their tracking allocator and tracking-allocator dev-dependency, and corrupt_streams_never_panic with no_panic.rs --- Cargo.lock | 1 - crates/ec-h264/Cargo.toml | 1 - crates/ec-h264/tests/conformance.rs | 281 ---------------------------- crates/ec-h264/tests/it/main.rs | 4 +- crates/ec-h264/tests/it/no_panic.rs | 85 --------- 5 files changed, 1 insertion(+), 371 deletions(-) delete mode 100644 crates/ec-h264/tests/it/no_panic.rs diff --git a/Cargo.lock b/Cargo.lock index 14b61940..db0e1da8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -551,7 +551,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 46fcb458..5ac1ea07 100644 --- a/crates/ec-h264/Cargo.toml +++ b/crates/ec-h264/Cargo.toml @@ -17,4 +17,3 @@ ec-testkit.workspace = true # 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/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 67a04848..4e819a54 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") } @@ -390,228 +331,6 @@ fn jvt_cavlc_first_idr_bit_exact() { /// 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 diff --git a/crates/ec-h264/tests/it/main.rs b/crates/ec-h264/tests/it/main.rs index 9085f959..919ebddf 100644 --- a/crates/ec-h264/tests/it/main.rs +++ b/crates/ec-h264/tests/it/main.rs @@ -1,8 +1,7 @@ //! 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. +//! `conformance.rs` stays a separate binary. #![forbid(unsafe_code)] @@ -16,5 +15,4 @@ mod high444; mod high444_jvt; mod interlaced; mod mbaff_x264; -mod no_panic; mod refusals; 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" - ); -}