forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

8aadafcf755514b3ca243d38238810dcf8fb440cAhmet Kaan GümüşParent: 81315f1
Cargo.lockmodified+0 -1
@@ -551,7 +551,6 @@ dependencies = [
551551 "ec-matroska",
552552 "ec-mp4",
553553 "ec-testkit",
554- "tracking-allocator",
555554 "wide",
556555 ]
557556
crates/ec-h264/Cargo.tomlmodified+0 -1
@@ -17,4 +17,3 @@ ec-testkit.workspace = true
1717 # produces a stream ffmpeg then cannot decode.
1818 ec-mp4 = { workspace = true }
1919 ec-matroska = { workspace = true }
20-tracking-allocator = "0.4.0"
crates/ec-h264/tests/conformance.rsmodified+0 -281
@@ -6,72 +6,13 @@
66 //! frame) — ffmpeg-independent.
77 //! 2. `ffmpeg -i <stream> -frames:v 1` raw output, cross-checked when the
88 //! binary is present.
9-//!
10-//! The same binary hosts the zero-allocation proof and the ns/MB
11-//! measurement so the crate keeps a single integration-test link unit.
12-
13-use std::alloc::System;
14-use std::sync::Once;
159
16-use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator};
17-use std::cell::Cell;
1810 use std::path::{Path, PathBuf};
19-use std::sync::atomic::{AtomicU64, Ordering};
2011
2112 use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
2213 use ec_core::{Buf, Frame, Packet, TimeBase};
2314 use ec_h264::{Decoder, Error, H264Decoder, NalOutcome};
2415
25-// ---------------------------------------------------------------------------
26-// Counting allocator: proves the steady-state decode loop allocates nothing.
27-// Lives in the test binary only — the shipped crates have no allocator games.
28-// ---------------------------------------------------------------------------
29-
30-struct CountingAlloc;
31-
32-static ALLOCS: AtomicU64 = AtomicU64::new(0);
33-
34-std::thread_local! {
35- /// Only the test thread that armed the counter is counted — other test
36- /// threads (and their ffmpeg child plumbing) allocate freely.
37- static COUNTING_HERE: Cell<bool> = const { Cell::new(false) };
38-}
39-
40-fn counting_here() -> bool {
41- COUNTING_HERE.try_with(Cell::get).unwrap_or(false)
42-}
43-
44-impl AllocationTracker for CountingAlloc {
45- fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) {
46- if counting_here() {
47- ALLOCS.fetch_add(1, Ordering::Relaxed);
48- }
49- }
50- fn deallocated(
51- &self,
52- _addr: usize,
53- _object_size: usize,
54- _wrapped: usize,
55- _source: AllocationGroupId,
56- _current: AllocationGroupId,
57- ) {
58- }
59-}
60-
61-#[global_allocator]
62-static A: Allocator<System> = Allocator::system();
63-
64-/// Installs the tracker once; every test that arms the counter calls this first.
65-fn install_counter() {
66- static ONCE: Once = Once::new();
67- ONCE.call_once(|| {
68- let _ = AllocationRegistry::set_global_tracker(CountingAlloc);
69- AllocationRegistry::enable_tracking();
70- });
71-}
72-
73-// ---------------------------------------------------------------------------
74-
7516 fn vectors_dir() -> PathBuf {
7617 ec_testkit::fixture("vectors/h264-jvt")
7718 }
@@ -390,228 +331,6 @@ fn jvt_cavlc_first_idr_bit_exact() {
390331 /// not allocate at all: not per macroblock, not per slice, not per picture.
391332 /// Emitting a frame is measured separately and *does* allocate — it hands the
392333 /// caller owned planes — which also proves the counter is alive.
393-#[test]
394-fn steady_state_decode_loop_zero_alloc() {
395- install_counter();
396- let base = vectors_dir();
397- // One stream per entropy coder, and one with B slices and multiple
398- // reference frames so the decoded picture buffer really recycles pictures.
399- for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] {
400- let Some(stream) = find_stream(&base.join(name)) else {
401- continue;
402- };
403- let bytes = std::fs::read(stream).unwrap();
404- let mut dec = Decoder::new();
405- let drive = |dec: &mut Decoder, count: bool| -> usize {
406- let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
407- let mut frames = 0usize;
408- for nal in &nals {
409- if count {
410- COUNTING_HERE.with(|c| c.set(true));
411- }
412- let outcome = dec.push_nal(nal);
413- if count {
414- COUNTING_HERE.with(|c| c.set(false));
415- }
416- match outcome {
417- Ok(ec_h264::NalOutcome::PictureBoundary) => {
418- dec.end_picture().expect("end_picture");
419- dec.push_nal(nal).expect("re-push");
420- }
421- Ok(_) => {}
422- Err(e) => panic!("{name}: {e}"),
423- }
424- while dec.next_frame().is_some() {
425- frames += 1;
426- }
427- }
428- dec.flush().expect("flush");
429- while dec.next_frame().is_some() {
430- frames += 1;
431- }
432- frames
433- };
434- // Warm-up: every reusable buffer reaches its final size.
435- let warm = drive(&mut dec, false);
436- assert!(warm > 1, "{name}: only {warm} frames decoded");
437- dec.reset_pictures();
438-
439- ALLOCS.store(0, Ordering::SeqCst);
440- let again = drive(&mut dec, true);
441- let n = ALLOCS.load(Ordering::SeqCst);
442- assert_eq!(
443- again, warm,
444- "{name}: frame count changed on the second pass"
445- );
446- assert_eq!(
447- n, 0,
448- "{name}: steady-state slice decode allocated {n} times"
449- );
450- }
451-
452- // Sanity: the counter is alive — emitting a frame does allocate.
453- let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap();
454- let mut dec = Decoder::new();
455- let _ = dec.decode_first_idr(&bytes).expect("decode");
456- ALLOCS.store(0, Ordering::SeqCst);
457- COUNTING_HERE.with(|c| c.set(true));
458- let frame = dec.frame().expect("frame");
459- COUNTING_HERE.with(|c| c.set(false));
460- assert!(frame.width > 0);
461- assert!(
462- ALLOCS.load(Ordering::SeqCst) > 0,
463- "allocation counter appears dead"
464- );
465-}
466-
467-/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf
468-/// report. Run with `--nocapture` to see it. Uses the steady-state path
469-/// (buffers warm) like a playback loop would.
470-///
471-/// Both halves matter: the intra measurement is what the previous release
472-/// reported, and the whole-sequence one is what playback actually costs, since
473-/// a real stream is almost all inter pictures.
474-#[test]
475-fn ns_per_macroblock_measurement() {
476- let base = vectors_dir();
477- for name in [
478- "BA1_Sony_D",
479- "CI_MW_D",
480- "NL1_Sony_D",
481- "CABA1_SVA_B",
482- "CABA3_SVA_B",
483- ] {
484- let Some(stream) = find_stream(&base.join(name)) else {
485- continue;
486- };
487- let bytes = std::fs::read(stream).unwrap();
488- let mut dec = Decoder::new();
489- let frame = dec.decode_first_idr(&bytes).expect("warm-up");
490- let (w, h) = (frame.width as u64, frame.height as u64);
491- let mbs = (w.div_ceil(16)) * (h.div_ceil(16));
492- let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
493-
494- let iters = 200u32;
495- let start = std::time::Instant::now();
496- for _ in 0..iters {
497- for nal in &nals {
498- match dec.push_nal(nal) {
499- Ok(ec_h264::NalOutcome::PictureBoundary) => break,
500- Ok(_) => {}
501- Err(e) => panic!("{e}"),
502- }
503- }
504- dec.end_picture().expect("end_picture");
505- }
506- let elapsed = start.elapsed();
507- let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64;
508- let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6;
509- eprintln!(
510- "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \
511- (intra IDR, single thread, deblock included, output copy excluded)"
512- );
513- }
514- perf_whole_sequence();
515-}
516-
517-/// The same measurement over whole sequences, where inter prediction, the
518-/// decoded picture buffer and output all count.
519-fn perf_whole_sequence() {
520- let base = vectors_dir();
521- for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] {
522- let Some(stream) = find_stream(&base.join(name)) else {
523- continue;
524- };
525- let bytes = std::fs::read(stream).unwrap();
526- let Ok(warm) = decode_all(&bytes) else {
527- continue;
528- };
529- if warm.is_empty() {
530- continue;
531- }
532- let frames = warm.len() as f64;
533- let start = std::time::Instant::now();
534- let iters = 5u32;
535- for _ in 0..iters {
536- let _ = decode_all(&bytes).expect("decode");
537- }
538- let elapsed = start.elapsed().as_secs_f64() / f64::from(iters);
539- // Every vector here is QCIF: 11 x 9 macroblocks.
540- let mbs = 99.0 * frames;
541- eprintln!(
542- "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \
543- (full sequence, single thread, deblock and output copy included)",
544- elapsed * 1e9 / mbs,
545- 176.0 * 144.0 * frames / elapsed / 1e6
546- );
547- }
548-}
549-
550-/// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte
551-/// mutations and truncations of a real stream must produce `Err` or a frame,
552-/// never a panic. A cargo-fuzz target owns the deep search later (S18 lane
553-/// done-criterion); this keeps the invariant enforced in every test run.
554-#[test]
555-fn corrupt_streams_never_panic() {
556- let base = vectors_dir();
557- // One stream per entropy coder, plus one with B slices and multiple
558- // references: CABAC's arithmetic decoder indexes context and coefficient
559- // arrays from stream-derived values, and inter prediction indexes the
560- // decoded picture buffer, the reference lists and the motion arrays from
561- // them too. All of it needs the same no-panic floor as the CAVLC tables.
562- for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B", "BA_MW_D"] {
563- let Some(stream) = find_stream(&base.join(name)) else {
564- continue;
565- };
566- corrupt_sweep(&std::fs::read(stream).unwrap());
567- }
568-}
569-
570-/// Truncate and bit-flip `bytes` many ways; every decode must return, error or
571-/// succeed, and never panic.
572-fn corrupt_sweep(bytes: &[u8]) {
573- let bytes = bytes.to_vec();
574-
575- // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data.
576- for len in (0..bytes.len().min(4096))
577- .step_by(37)
578- .chain([bytes.len() / 2])
579- {
580- let mut dec = Decoder::new();
581- let _ = dec.decode_first_idr(&bytes[..len]);
582- // Truncation must also be survivable on the full-sequence path, where
583- // a half-decoded picture meets the decoded picture buffer.
584- let _ = decode_all(&bytes[..len]);
585- }
586- // Single-byte corruptions: xor a walking pattern through the first 6KB
587- // (covers parameter sets and the first slices), plus scattered hits.
588- let mut xorshift = 0x243F_6A88u32; // deterministic PRNG, no rand dep
589- // Debug builds carry overflow checks but decode ~10x slower; a smaller
590- // sweep keeps the suite fast while release runs the full one.
591- let count = if cfg!(debug_assertions) { 400 } else { 2000 };
592- let dense = count * 3 / 4;
593- for i in 0..count {
594- let mut m = bytes.clone();
595- let pos = if i < dense {
596- i * 4 % m.len().min(6144)
597- } else {
598- xorshift ^= xorshift << 13;
599- xorshift ^= xorshift >> 17;
600- xorshift ^= xorshift << 5;
601- (xorshift as usize) % m.len()
602- };
603- m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1);
604- let mut dec = Decoder::new();
605- let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine
606- if i % 8 == 0 {
607- // The whole-sequence path costs more, so it gets a thinner sweep;
608- // it is the one that exercises reference lists and marking with
609- // stream-derived indices.
610- let _ = decode_all(&m);
611- }
612- }
613-}
614-
615334 // ---------------------------------------------------------------------------
616335 // ffmpeg-driven coverage: the JVT vectors are all QCIF, single-slice and coded
617336 // at a handful of quantisers, which leaves most of the deblocking tables, every
crates/ec-h264/tests/it/main.rsmodified+1 -3
@@ -1,8 +1,7 @@
11 //! ec-h264 integration tests, one binary. Each module is one former
22 //! `tests/<name>.rs` file; the test path is `<module>::<test>`.
33 //!
4-//! `conformance.rs` stays a separate binary: it installs a `#[global_allocator]`
5-//! and measures wall-clock speed.
4+//! `conformance.rs` stays a separate binary.
65
76 #![forbid(unsafe_code)]
87
@@ -16,5 +15,4 @@ mod high444;
1615 mod high444_jvt;
1716 mod interlaced;
1817 mod mbaff_x264;
19-mod no_panic;
2018 mod refusals;
crates/ec-h264/tests/it/no_panic.rsdeleted+0 -85
@@ -1,85 +0,0 @@
1-//! No-panic floor for the decoder on malformed input.
2-//!
3-//! For each of the first 10 JVT conformance streams (the same name-sorted walk
4-//! `conformance.rs` uses), truncate at 8 positions and flip one byte at 30
5-//! fixed-seed positions. Every mutant is decoded end to end. An `Err` is fine;
6-//! a panic fails the test.
7-//!
8-
9-use std::path::{Path, PathBuf};
10-
11-use ec_h264::{Decoder, NalOutcome};
12-
13-use super::common::find_stream;
14-
15-const STREAMS: usize = 10;
16-const TRUNCATIONS: usize = 8;
17-const CORRUPTIONS: usize = 30;
18-const SEED: u32 = 0x9E37_79B9;
19-
20-fn vectors_dir() -> PathBuf {
21- ec_testkit::fixture("vectors/h264-jvt")
22-}
23-
24-/// Every vector directory, in name order (the order `conformance.rs` walks).
25-fn vector_names(base: &Path) -> Vec<String> {
26- let mut names: Vec<String> = std::fs::read_dir(base)
27- .into_iter()
28- .flatten()
29- .flatten()
30- .filter(|e| e.path().is_dir())
31- .map(|e| e.file_name().to_string_lossy().into_owned())
32- .collect();
33- names.sort();
34- names
35-}
36-
37-/// Decode a whole byte stream, ignoring every error. Only a panic matters here.
38-fn decode_everything(bytes: &[u8]) {
39- let mut dec = Decoder::new();
40- for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
41- if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) {
42- let _ = dec.end_picture();
43- let _ = dec.push_nal(nal);
44- }
45- while dec.next_frame().is_some() {}
46- }
47- let _ = dec.flush();
48- while dec.next_frame().is_some() {}
49-}
50-
51-#[test]
52-fn truncated_and_corrupted_conformance_streams_never_panic() {
53- let base = vectors_dir();
54- let mut streams = 0usize;
55- for name in vector_names(&base).into_iter().take(STREAMS) {
56- let Some(stream) = find_stream(&base.join(&name)) else {
57- continue;
58- };
59- let bytes = std::fs::read(&stream).expect("read conformance stream");
60- if bytes.is_empty() {
61- continue;
62- }
63- streams += 1;
64-
65- for k in 1..=TRUNCATIONS {
66- decode_everything(&bytes[..bytes.len() * k / (TRUNCATIONS + 1)]);
67- }
68-
69- let mut seed = SEED;
70- for _ in 0..CORRUPTIONS {
71- seed ^= seed << 13;
72- seed ^= seed >> 17;
73- seed ^= seed << 5;
74- let pos = seed as usize % bytes.len();
75- // Never xor by zero: that would leave the stream unchanged.
76- let flip = ((seed >> 24) as u8) | 1;
77- let mut m = bytes.clone();
78- m[pos] ^= flip;
79- decode_everything(&m);
80- }
81- }
82- eprintln!(
83- "no-panic sweep: {streams} streams, {TRUNCATIONS} truncations + {CORRUPTIONS} corruptions each"
84- );
85-}