diff --git a/crates/ec-av1/src/decode/block.rs b/crates/ec-av1/src/decode/block.rs index 2c328062..753f0894 100644 --- a/crates/ec-av1/src/decode/block.rs +++ b/crates/ec-av1/src/decode/block.rs @@ -586,146 +586,6 @@ pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// deleted: `PREFILT_PICTURE_IDX` is bumped after this point, not before it, so /// the counter that names these files is the per-var map. // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. -#[allow(clippy::too_many_arguments)] -pub(super) fn dump_stage16( - var: &str, - y: &PlaneBuf<'_>, - u: &PlaneBuf<'_>, - v: &PlaneBuf<'_>, - fw: usize, - fh: usize, - ss_x: usize, - ss_y: usize, -) { - // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by - // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed - // `.f0` name kept only the LAST frame, so a mid-sequence divergence could - // not be read at all. - // - // lane-unwritten-dep: the chroma extent is PER-AXIS subsampling, not - // `div_ceil(2)` on both. The hardcoded pair was a 4:2:0 assumption and it - // was load-bearing: on a 64x64 4:2:2 frame (ss_x = 1, ss_y = 0) it wrote - // 32x32 chroma per plane where the frame carries 32x64, so HALF of each - // chroma plane appeared in NO stage dump at all. A stage bisect that reads - // "identical pre-deblock, differs post-deblock" off these dumps is then - // measuring the dump's blind spot, not the pipeline's: the samples it could - // not see are exactly the region where the 4:2:2 witness's output diverges - // (chroma rows 32..63 -- the old `fh.div_ceil(2)` crop wrote 32 of 64 rows, - // so everything from row 32 up was invisible; 2048 samples). `round_ss` is - // the same rounding the - // decoder's own plane extents use, and it matches the oracle's - // `uv_crop_width` / `uv_crop_height` per axis. - // - // ONE file per frame: `dump_stage_idx` advances on every call, so creating - // the file inside the plane loop would write three files per frame and - // shift every later frame's index. - // - // lane-av1dumploud: this used to be `let _ = f.write_all(&bytes)` per row, so - // a full filesystem left a SHORT file that no reader could tell from a - // complete one. `LoudDump` is given the exact expected length this function - // knows -- `(fw*fh + 2*cw*ch) * 2`, u16 LE -- and checks it against the file - // on disk; a shortfall aborts the decode instead of leaving a plausible - // artefact behind. - if let Ok(path) = crate::envflags::var(var) { - let cw = round_ss(fw, ss_x); - let ch = round_ss(fh, ss_y); - let expected = (fw * fh + 2 * cw * ch) * 2; - let mut d = crate::dumpio::LoudDump::create( - var, - format!("{path}.f{}", dump_stage_idx(var)), - expected, - ); - for (p, w, h) in [(y, fw, fh), (u, cw, ch), (v, cw, ch)] { - for row in 0..h { - let mut bytes = Vec::with_capacity(w * 2); - for &s in &p.data[row * p.width..][..w] { - bytes.extend_from_slice(&s.to_le_bytes()); - } - d.write(&bytes); - } - } - d.finish(); - } -} - -/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a -/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so -/// every frame overwrote the previous one and only the LAST frame survived, -/// which silently defeats any per-frame filter-stage bisection. -fn dump_stage_idx(var: &str) -> usize { - use std::collections::HashMap; - use std::sync::{Mutex, OnceLock}; - static IDX: OnceLock>> = OnceLock::new(); - let mut m = IDX - .get_or_init(|| Mutex::new(HashMap::new())) - .lock() - .unwrap(); - let e = m.entry(var.to_string()).or_insert(0); - let i = *e; - *e += 1; - i -} - -pub(super) fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { - // lane-av1dumploud: loud on a short write (see [`crate::dumpio::LoudDump`]). - // The expected length is the three planes' own data lengths -- the writer - // iterates exactly `p.data`, so this is the same extent, not a re-derivation - // that could disagree with it. - if let Ok(path) = crate::envflags::var(var) { - let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - var, - format!("{path}.f{}", dump_stage_idx(var)), - &[&narrow(y), &narrow(u), &narrow(v)], - ); - } -} - -/// `EC_AV1_PREFILT_WIDE_DUMP=` -> `.f`, the pre-loop-filter -/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for -/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`, -/// `uv_width`/`uv_height`), so the two can be diffed directly. -/// -/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path -/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were -/// measurement traps, and the second one is why the first went unnoticed: -/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide -/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an -/// inter frame had no pre-filter rung to compare against and got attributed to -/// reconstruction when the oracle could not see it. The `static` also restarted -/// per monomorphisation, so every frame after the first overwrote `.f0` -- a -/// per-frame bisection silently compared the LAST decoded frame. The counter -/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on -/// the inter path (skipped when the filter pipeline is active, which has -/// already deblocked by the time the tile tail runs -- same condition -/// `capture_filter_replay` guards itself with). -pub(super) fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { - let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else { - return; - }; - // lane-av1dumploud: loud on a short write. Expected length is - // `sum(true_width * true_height)` over the three planes -- the crop the - // writer itself builds, so the check cannot disagree with the bytes. - let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP"); - let crop = |plane: &PlaneBuf<'_>| -> Vec { - let mut out = Vec::with_capacity(plane.true_width * plane.true_height); - for row in 0..plane.true_height { - out.extend( - plane.data[row * plane.width..][..plane.true_width] - .iter() - .map(|&s| s as u8), - ); - } - out - }; - let (cy, cu, cv) = (crop(y), crop(u), crop(v)); - crate::dumpio::write_planes( - "EC_AV1_PREFILT_WIDE_DUMP", - format!("{path}.f{idx}"), - &[&cy, &cu, &cv], - ); -} - /// Unwritten samples [`census_unwritten`] has counted since the last /// [`take_unwritten_samples`] -- process-global (not thread-local) because the /// gate reads it after the decode, from a different thread than the one that diff --git a/crates/ec-av1/src/decode/coeffs.rs b/crates/ec-av1/src/decode/coeffs.rs index dc3134da..1aaa5056 100644 --- a/crates/ec-av1/src/decode/coeffs.rs +++ b/crates/ec-av1/src/decode/coeffs.rs @@ -2310,29 +2310,6 @@ impl Neighbours { left |= self.left[mi_r + cell][0].level; } let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)]; - if crate::envflags::env_flag!("EC_ECDUMP") { - let ab: Vec = (0..above_mi) - .map(|k| self.above[mi_c + k][0].level.to_string()) - .collect(); - let lf: Vec = (0..left_mi) - .map(|k| self.left[mi_r + k][0].level.to_string()) - .collect(); - // lane-av1mix: the last few msac register states, so the - // byte-position of the `all_zero` read can be matched against - // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a - // second run. - let recent = crate::msac::symtrace::ecdump_recent(4) - .iter() - .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})")) - .collect::>() - .join(" "); - eprintln!( - "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]", - ab.join(","), - lf.join(","), - recent - ); - } if crate::envflags::env_flag!("EC_AV1_TRACE") { eprintln!( "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}", diff --git a/crates/ec-av1/src/decode/frame_tile.rs b/crates/ec-av1/src/decode/frame_tile.rs index 9a091a8f..18b9f4b2 100644 --- a/crates/ec-av1/src/decode/frame_tile.rs +++ b/crates/ec-av1/src/decode/frame_tile.rs @@ -3228,11 +3228,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ); } - // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's - // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against - // that isolate whether a decode-order frame's mismatch already exists - // in reconstruction (this dump) vs is introduced by the loop filter - // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. if crate::envflags::env_flag!("EC_OBMC") || crate::envflags::env_flag!("EC_TRACE_MODE") @@ -3243,36 +3238,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) ); } - dump_stage16( - "EC_AV1_PREFILT_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); census_unwritten(&y, &u, &v); - if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { - // lane-av1dumploud: loud on a short write (see the key-frame twin - // above -- same file, same shape, same three planes). - let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - "EC_AV1_PREFILT_DUMP", - format!("{path}.f{idx}"), - &[&narrow(&y), &narrow(&u), &narrow(&v)], - ); - } else { - PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - // lane-av1444edge: the inter-frame path's mi-aligned pre-loop-filter - // dump, the rung the key-frame path has always had (see - // `dump_prefilter_wide`). Placed beside the padded `EC_AV1_PREFILT_DUMP` - // above, i.e. before the loop filters run, so the two agree on the point - // in the sequence they sample. - dump_prefilter_wide(&y, &u, &v); // lane-av1fwd: the encoder scores ~25 filter candidates against this // same coded tile ([`FilterReplay`]). Capture the reconstruction here, // before either filter has touched it -- but only on the shape whose @@ -3314,20 +3280,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( plane_snapshot(&v, ss_y(fctx) as u32), ) }); - // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own - // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter - // dump above these bisect WHICH filter stage introduced a mismatch. - dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTDEBLOCK_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); apply_cdef( &mut y, &mut u, @@ -3339,17 +3291,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( None, None, ); - dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTCDEF_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): diff --git a/crates/ec-av1/src/decode/inter_block.rs b/crates/ec-av1/src/decode/inter_block.rs index 1f80c5c6..a1884b0b 100644 --- a/crates/ec-av1/src/decode/inter_block.rs +++ b/crates/ec-av1/src/decode/inter_block.rs @@ -2316,11 +2316,6 @@ pub(super) fn decode_inter_block( }; (mv, false) }; - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - " MODE mi=({mi_row},{mi_col}) dbg={dbg_mode} mv={mv:?}" - )); - } if crate::envflags::env_flag!("EC_TRACE_MODE") { for (i, e) in stack.entries.iter().enumerate() { eprintln!( diff --git a/crates/ec-av1/src/decode/key_tile.rs b/crates/ec-av1/src/decode/key_tile.rs index fca1ae84..e9fa6c99 100644 --- a/crates/ec-av1/src/decode/key_tile.rs +++ b/crates/ec-av1/src/decode/key_tile.rs @@ -2750,11 +2750,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } crate::timeline::recon_done(); - // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's - // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against - // that isolate whether a decode-order frame's mismatch already exists - // in reconstruction (this dump) vs is introduced by the loop filter - // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. if crate::envflags::env_flag!("EC_OBMC") || crate::envflags::env_flag!("EC_TRACE_MODE") @@ -2765,33 +2760,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) ); } - dump_stage16( - "EC_AV1_PREFILT_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); census_unwritten(&y, &u, &v); - if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { - // lane-av1dumploud: loud on a short write (three discarded - // `write_all` results before). Expected length = the three planes' own - // data lengths: this dump is the PADDED plane, not a crop, so the - // writer's extent is `p.data` itself. - let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - "EC_AV1_PREFILT_DUMP", - format!("{path}.f{idx}"), - &[&narrow(&y), &narrow(&u), &narrow(&v)], - ); - } else { - PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - dump_prefilter_wide(&y, &u, &v); // lane-av1fwd: the encoder's filter search re-decodes this same key // frame tile per candidate -- capture it once (see [`FilterReplay`]), // on the shape whose tail is the two filter calls and nothing else. @@ -2848,20 +2817,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( plane_snapshot(&v, ss_y(fctx) as u32), ) }); - // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own - // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter - // dump above these bisect WHICH filter stage introduced a mismatch. - dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTDEBLOCK_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); apply_cdef( &mut y, &mut u, @@ -2873,17 +2828,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( None, None, ); - dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTCDEF_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): @@ -3009,24 +2953,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( fctx.last_frame_wide_margin.with(|m| { *m.borrow_mut() = if true_width > fw || true_height > fh { let yc = crop(&y, true_width, true_height); - if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") { - static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - // corner-cut: this diagnostic dump stays 8-bit-narrowed - // regardless of the stream's real bit depth (debug-only, - // never read by a gate); widen if a >8-bit margin dump - // is ever needed. - // - // lane-av1dumploud: loud on a short write. Expected length is - // `true_width * true_height` -- the crop this dump is exactly, - // not a re-derived geometry. - let narrow: Vec = yc.iter().map(|&s| s as u8).collect(); - crate::dumpio::write_planes( - "EC_AV1_MARGIN_DUMP", - format!("{path}.f{idx}"), - &[&narrow], - ); - } Some(Picture { width: true_width, height: true_height, diff --git a/crates/ec-av1/src/dumpio.rs b/crates/ec-av1/src/dumpio.rs deleted file mode 100644 index 61394b1c..00000000 --- a/crates/ec-av1/src/dumpio.rs +++ /dev/null @@ -1,568 +0,0 @@ -//! Loud dump writing: a dump that cannot hold every byte it claims to hold is -//! a failure, not a diagnostic artefact. -//! -//! lane-av1dumploud: every dump site in this crate wrote through -//! `let _ = f.write_all(..)`. A full filesystem, an `RLIMIT_FSIZE`, or any other -//! `ENOSPC`/`EFBIG` therefore left a SHORT file on disk and nothing said so. -//! Measured consequence, twice in one day: a sentinel-vs-plain hash difference -//! that read as decoder nondeterminism reproduced bit-for-bit as a truncated -//! dump (`lanes/unwritten-dep.report.md`: frames 0..4 complete plus 13 320 192 -//! bytes of frame 5, with `EC_AV1_FINAL_DUMP`'s discarded write error), and an -//! empty dump read as instability. That artefact started a whole defect class, -//! and a silently wrong diagnostic is worse than a loud one, so every dump site -//! goes through [`LoudDump`]: the caller states the expected byte count from the -//! geometry it already has, the writer checks that count twice -- once against -//! the bytes it was handed, once against the file's own length on disk -- and -//! any shortfall aborts the decode with the file, the counts, and the OS error. -//! -//! The success path is byte-identical to the old `write_all` loop: same bytes, -//! same order, same file names. -//! -//! The failure path is a panic, not a returned `Result`: the dump sites sit in -//! the middle of `fn decode_*` functions with no error channel for them, and a -//! dump that failed IS a decode failure (the run's measurement is void). This -//! is a debug instrument -- it only runs when its env var is set -- so the -//! panic cannot affect a normal decode. - -use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -/// One dump file, with the byte count it owes accounted for as it goes. -pub struct LoudDump { - /// Human-readable label for the failure line: the env var, or - /// `VAR.suffix` when the file names something the var alone does not. - site: String, - path: PathBuf, - file: Option, - written: usize, - /// `None` only for a stream whose total length is genuinely unknowable at - /// open time (an append-mode text table). Short-write detection still - /// applies -- `write_all` reports a short write as `Err` -- but the failure - /// line then carries no expected count, because inventing one would be a - /// guess. - expected: Option, -} - -impl LoudDump { - /// Open `path` for `site`, expecting exactly `expected` bytes in total. - /// - /// Failing to CREATE is loud too: a requested dump that does not exist is - /// the same silent hole as one that is short (the reader sees no file, or - /// an empty one), and it is the more common of the two (a missing parent - /// directory, a path a sweep reused as a directory). - pub fn create(site: &str, path: impl AsRef, expected: usize) -> Self { - let path = path.as_ref().to_path_buf(); - let file = File::create(&path).unwrap_or_else(|e| { - abort( - site, - &path, - 0, - Some(expected), - &format!("could not create the dump file: {e}"), - ) - }); - Self { - site: site.to_string(), - path, - file: Some(file), - written: 0, - expected: Some(expected), - } - } - - /// Open `path` for `site` in APPEND mode with no knowable total length -- - /// the CDF-table text dump, whose file spans every frame of a run. Write - /// errors are still fatal; the length check is simply absent (see - /// [`LoudDump::expected`]). - pub fn append_unknown(site: &str, path: impl AsRef) -> Self { - let path = path.as_ref().to_path_buf(); - let file = OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .unwrap_or_else(|e| { - abort( - site, - &path, - 0, - None, - &format!("could not open the dump file: {e}"), - ) - }); - Self { - site: site.to_string(), - path, - file: Some(file), - written: 0, - expected: None, - } - } - - /// Hand `chunk` to the file. Overrunning `expected` is a caller bug (the - /// count and the writer disagree) and aborts just as loudly as a short - /// write, because one of the two is certainly lying. - pub fn write(&mut self, chunk: &[u8]) { - if let Some(exp) = self.expected - && self.written + chunk.len() > exp - { - abort( - &self.site, - &self.path, - self.written, - Some(exp), - &format!( - "the writer was handed {} bytes but only {} remained of the {} it declared", - chunk.len(), - exp - self.written, - exp - ), - ); - } - let r = self.file.as_mut().expect("live dump").write_all(chunk); - if let Err(e) = r { - // MEASURED, do not assume: under `RLIMIT_FSIZE` the kernel stores - // everything up to the cap and THEN returns `EFBIG` (measured: - // a 49 152 B frame under caps of 4 KiB / 10 KiB / 30 KiB left - // 4 096 / 10 240 / 30 720 B on disk, with `write_all` confirming - // none of it). So "bytes written" on this line is the file's real - // length, not the count `write_all` got to acknowledge -- the - // acknowledged count rides along in the reason. - let f = self.file.as_ref().expect("live dump"); - let on_disk = f - .metadata() - .map(|m| m.len() as usize) - .unwrap_or(self.written); - abort( - &self.site, - &self.path, - on_disk, - self.expected, - &format!( - "write failed with {} bytes confirmed in hand: {e}", - self.written - ), - ); - } - self.written += chunk.len(); - } - - /// Close the dump: flush, then check the file's own length on disk. - /// - /// The on-disk check is not redundant with the write loop. `write_all` - /// reports what the FILE ACCEPTED, and the reader's question is what the - /// filesystem ended up holding -- a sparse/short final flush, a quota, or a - /// filesystem-level reservation failure all land here rather than in - /// `write`. - pub fn finish(mut self) { - let Some(mut file) = self.file.take() else { - return; - }; - if let Err(e) = file.flush() { - abort( - &self.site, - &self.path, - self.written, - self.expected, - &format!("flush failed after {} bytes: {e}", self.written), - ); - } - let Some(exp) = self.expected else { - return; - }; - let on_disk = match file.metadata() { - Ok(m) => m.len() as usize, - Err(e) => abort( - &self.site, - &self.path, - self.written, - Some(exp), - &format!("could not stat the finished dump: {e}"), - ), - }; - if on_disk != exp { - abort( - &self.site, - &self.path, - on_disk, - Some(exp), - "the file on disk is not the length the writer declared", - ); - } - } -} - -/// The single failure line every short dump now ends on. `site`, the path, the -/// bytes on disk vs the bytes owed, and the reason. -fn abort(site: &str, path: &Path, got: usize, expected: Option, why: &str) -> ! { - panic!("{}", failure_line(site, path, got, expected, why)); -} - -/// The failure line itself, so the fatal and the reporting shapes cannot -/// drift apart. -fn failure_line(site: &str, path: &Path, got: usize, expected: Option, why: &str) -> String { - let owed = match expected { - Some(e) => format!("{e}"), - None => "an unknown number of".to_string(), - }; - format!( - "ec-av1 dump FAILED [{}] {}: wrote {} of {} bytes: {}", - site, - path.display(), - got, - owed, - why - ) -} - -/// Write `bytes` to `path` as a FATAL pin: [`pin`] IS a wrapper -- three -/// [`LoudDump`] calls (`create`/`write`/`finish`), so it inherits the flush and -/// the flush-then-stat ordering for free. -/// -/// lane-av1pinloud: the test-pin sites in `stream.rs` wrote with -/// `let _ = std::fs::write(..)` and then named the path in the panic that -/// followed ("stream pinned at {}"), so an `ENOSPC`/`EFBIG` left a TRUNCATED -/// stream at exactly the path the reader was told to replay -- the same -/// silent-truncation class as the dump path, one hop later. Success path is -/// byte-identical: same bytes, same path, truncate-then-write. -pub fn pin(site: &str, path: impl AsRef, bytes: &[u8]) { - let mut d = LoudDump::create(site, path, bytes.len()); - d.write(bytes); - d.finish(); -} - -/// [`pin`]'s NON-FATAL twin, for a site that must not die on a failed pin -- a -/// gate whose real failure is the assert that comes after the pin attempt, and -/// whose comment says so. -/// -/// This one RE-IMPLEMENTS the check rather than wrapping [`LoudDump`], whose -/// failure channel is `panic!`: it cannot report instead of dying. So it does -/// `fs::write` + `metadata` itself. Only the failure LINE is shared, via -/// [`failure_line`] -- the ordering (flush-then-stat) and the -/// write-error-handling are not shared with [`LoudDump`], and a reader must not -/// assume they are. -/// -/// Non-fatal, but not silent: a shortfall comes back as the very same failure -/// line [`pin`] would have panicked with, expected-vs-on-disk counts included, -/// for the caller to print as a warning. -#[cfg(test)] // only the self-test below calls it; keeps the non-test build free of dead code -pub fn pin_reporting(site: &str, path: impl AsRef, bytes: &[u8]) -> Result<(), String> { - let path = path.as_ref(); - let expected = bytes.len(); - if let Err(e) = std::fs::write(path, bytes) { - let on_disk = std::fs::metadata(path) - .map(|m| m.len() as usize) - .unwrap_or(0); - return Err(failure_line( - site, - path, - on_disk, - Some(expected), - &format!("could not write the pin: {e}"), - )); - } - let on_disk = match std::fs::metadata(path) { - Ok(m) => m.len() as usize, - Err(e) => { - return Err(failure_line( - site, - path, - expected, - Some(expected), - &format!("could not stat the written pin: {e}"), - )); - } - }; - if on_disk != expected { - return Err(failure_line( - site, - path, - on_disk, - Some(expected), - "the pinned file on disk is not the length of the stream", - )); - } - Ok(()) -} - -/// Write `planes` (already narrowed to their dump's sample width) as ONE dump -/// file, failing loudly on any shortfall. `expected` is the sum of the plane -/// lengths -- the same extents the writer iterates, so a plane that is shorter -/// than its geometry claims cannot hide here. -pub fn write_planes(site: &str, path: impl AsRef, planes: &[&[u8]]) { - let expected: usize = planes.iter().map(|p| p.len()).sum(); - let mut d = LoudDump::create(site, path, expected); - for p in planes { - d.write(p); - } - d.finish(); -} - -#[cfg(test)] -mod tests { - use super::*; - use std::process::Command; - - fn scratch(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!("ec-av1-dumpio-{tag}-{}", std::process::id())); - let _ = std::fs::remove_file(&p); - p - } - - fn caught(f: impl FnOnce() + std::panic::UnwindSafe) -> String { - let prev = std::panic::take_hook(); - std::panic::set_hook(Box::new(|_| {})); - let r = std::panic::catch_unwind(f); - std::panic::set_hook(prev); - let e = r.expect_err("the short dump must abort"); - e.downcast_ref::() - .cloned() - .or_else(|| e.downcast_ref::<&str>().map(|s| (*s).to_string())) - .expect("panic payload is a string") - } - - #[test] - fn success_path_is_byte_identical_to_the_old_write_all_loop() { - let p = scratch("ok"); - let planes: [&[u8]; 3] = [b"abc", b"", b"de"]; - write_planes("T", &p, &planes); - assert_eq!(std::fs::read(&p).unwrap(), b"abcde"); - let _ = std::fs::remove_file(&p); - } - - /// `/dev/full` accepts an `open` for write and returns `ENOSPC` from every - /// write -- the hermetic stand-in for the full filesystem that produced the - /// 13 320 192-byte truncated frame in `lanes/unwritten-dep.report.md`. - #[test] - #[cfg(unix)] - fn full_device_short_write_is_loud() { - let msg = caught(|| write_planes("EC_AV1_FINAL_DUMP", "/dev/full", &[b"abc", b"de"])); - assert!( - msg.starts_with("ec-av1 dump FAILED [EC_AV1_FINAL_DUMP] /dev/full: wrote "), - "{msg}" - ); - assert!(msg.contains("No space left on device"), "{msg}"); - // The counts must be there, or the line does not say what was lost. - assert!(msg.contains(" of 5 bytes"), "{msg}"); - } - - #[test] - fn uncreatable_dump_is_loud() { - let p = std::env::temp_dir().join(format!("ec-av1-nodir-{}/x", std::process::id())); - let msg = caught(|| write_planes("T", &p, &[b"abc"])); - assert!(msg.contains("could not create the dump file"), "{msg}"); - } - - /// A writer that under-declares its own expected length is the same silent - /// hole: the reader gets a file the site believes is complete. - #[test] - fn under_declared_expected_length_is_loud() { - let p = scratch("under"); - let msg = caught(|| { - let mut d = LoudDump::create("T", &p, 2); - d.write(b"abcdef"); - d.finish(); - }); - assert!( - msg.contains("was handed 6 bytes but only 2 remained of the 2 it declared"), - "{msg}" - ); - let _ = std::fs::remove_file(&p); - } - - #[test] - fn append_unknown_takes_no_length_claim() { - let p = scratch("append"); - { - let mut a = LoudDump::append_unknown("T", &p); - a.write(b"x"); - a.finish(); - let mut b = LoudDump::append_unknown("T", &p); - b.write(b"y"); - b.finish(); - } - assert_eq!(std::fs::read(&p).unwrap(), b"xy"); - let msg = caught(|| { - let mut a = LoudDump::append_unknown("T", "/dev/full"); - a.write(b"x"); - a.finish(); - }); - assert!(msg.contains("of an unknown number of bytes"), "{msg}"); - let _ = std::fs::remove_file(&p); - } - /// THE reproduction of the incident this module exists for: a real decode, - /// a real `RLIMIT_FSIZE`, a real truncated `EC_AV1_FINAL_DUMP` file left - /// on disk -- and the run stopping with the bytes-vs-bytes line instead of - /// carrying on to a measurement built on the fragment. - /// - /// `/dev/full` (the unit test above) proves the writer's check works but - /// never leaves a partial file behind, because `create` on it succeeds and - /// nothing is ever stored. `RLIMIT_FSIZE` is the shape - /// `lanes/unwritten-dep.report.md` actually measured: frames 0..4 complete - /// plus 13 320 192 bytes of frame 5. `SIGXFSZ` is IGNORED (`trap "" XFSZ`) - /// so the limit surfaces as `write`'s `EFBIG` -- exactly what a full - /// filesystem's `ENOSPC` does -- instead of killing the child outright. - #[test] - #[cfg(unix)] - fn a_real_decode_under_a_file_size_cap_fails_loudly() { - let dir = std::env::temp_dir().join(format!("ec-av1-dumpio-cap-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let prefix = dir.join("ours"); - // 8 blocks of 512 B = 4096 B: far below one 256x128 4:2:0 8-bit frame - // (49 152 B), far above the file header, so the write lands and fails - // PART way rather than at create. - let out = Command::new("bash") - .args([ - "-c", - "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"", - // $0 for `bash -c` is the test binary itself. - std::env::current_exe().unwrap().to_str().unwrap(), - "--exact", - "dumpio::tests::dumpio_child_decode", - "--nocapture", - ]) - .env("EC_AV1_DUMPLOUD_CHILD", "1") - .env("EC_AV1_FINAL_DUMP", &prefix) - // One thread, so the dump panic lands on the main thread and the - // child's exit status is the decode's own. - .env("EC_AV1_THREADS", "1") - .output() - .expect("spawning the capped child"); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success(), - "the decode must FAIL under a file-size cap, not finish with a truncated dump\n{stderr}" - ); - assert!( - stderr.contains("ec-av1 dump FAILED [EC_AV1_FINAL_DUMP]"), - "the failure line must name the dump site\n{stderr}" - ); - assert!( - stderr.contains("File too large"), - "the failure line must carry the OS error\n{stderr}" - ); - // One 256x128 4:2:0 8-bit frame is 256*128*3/2 = 49 152 B, and the - // failure line's "wrote N of 49152" must name the file's REAL length, - // not the count `write_all` managed to acknowledge: a line that - // under-reports is a line that sends the reader back to the dump to - // measure it themselves. - let frag = std::fs::metadata(format!("{}.f0", prefix.display())) - .unwrap() - .len(); - assert!( - frag < 49152, - "the capped child left a {frag}-byte frame where 49152 B was owed" - ); - assert!( - stderr.contains(&format!("wrote {frag} of 49152 bytes")), - "the failure line's written count must be the file's actual length ({frag})\n{stderr}" - ); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Child half of [`a_real_decode_under_a_file_size_cap_fails_loudly`]. It is - /// not a gate: with no `EC_AV1_DUMPLOUD_CHILD` guard it decodes nothing and - /// asserts nothing, so a plain `cargo test` run is unaffected. - #[test] - fn dumpio_child_decode() { - if std::env::var("EC_AV1_DUMPLOUD_CHILD").is_err() { - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/420_mixll_256x128_6f.obu"); - let bytes = std::fs::read(&path).expect("the pinned fixture"); - let _ = crate::stream::decode_stream(&bytes); - } - - #[test] - fn pin_success_path_is_byte_identical() { - let p = scratch("pin-ok"); - pin("TEST_PIN", &p, b"stream bytes"); - assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes"); - let _ = std::fs::remove_file(&p); - } - - #[test] - #[cfg(unix)] - fn pin_to_a_full_device_is_loud() { - let msg = caught(|| pin("TEST_PIN", "/dev/full", b"stream bytes")); - assert!( - msg.starts_with("ec-av1 dump FAILED [TEST_PIN] /dev/full: wrote "), - "{msg}" - ); - assert!(msg.contains("No space left on device"), "{msg}"); - assert!(msg.contains(" of 12 bytes"), "{msg}"); - } - - /// The reporting shape: same failure line, returned instead of panicked, - /// so a gate whose real failure is the assert after the pin keeps that - /// assert -- but the reader still learns the pin is short. - #[test] - #[cfg(unix)] - fn pin_reporting_is_loud_but_not_fatal() { - let line = pin_reporting("TEST_PIN", "/dev/full", b"stream bytes").unwrap_err(); - assert!( - line.contains("ec-av1 dump FAILED [TEST_PIN] /dev/full"), - "{line}" - ); - assert!(line.contains(" of 12 bytes"), "{line}"); - let p = scratch("pin-reporting-ok"); - pin_reporting("TEST_PIN", &p, b"stream bytes").expect("a healthy pin reports nothing"); - assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes"); - let _ = std::fs::remove_file(&p); - } - - /// The pin path's own reproduction: a real `RLIMIT_FSIZE` leaves a real - /// truncated stream at the path the panic names. Without the check the - /// reader replays the fragment and blames the decoder. - #[test] - #[cfg(unix)] - fn a_pin_under_a_file_size_cap_fails_loudly() { - let dir = std::env::temp_dir().join(format!("ec-av1-pin-cap-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let out = Command::new("bash") - .args([ - "-c", - "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"", - std::env::current_exe().unwrap().to_str().unwrap(), - "--exact", - "dumpio::tests::pin_child_under_cap", - "--nocapture", - ]) - .env("EC_AV1_PINLOUD_CHILD", &dir) - .output() - .expect("spawning the capped child"); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(!out.status.success(), "a short pin must fail\n{stderr}"); - assert!(stderr.contains("ec-av1 dump FAILED [TEST_PIN]"), "{stderr}"); - assert!(stderr.contains("File too large"), "{stderr}"); - let frag = std::fs::metadata(dir.join("cap-pinned.obu")).unwrap().len(); - assert!( - frag < 32768, - "the capped child left {frag} bytes where 32768 B was owed" - ); - assert!( - stderr.contains(&format!("wrote {frag} of 32768 bytes")), - "{stderr}" - ); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Child half of [`a_pin_under_a_file_size_cap_fails_loudly`]. Not a gate: - /// with no `EC_AV1_PINLOUD_CHILD` set it writes nothing and asserts nothing. - #[test] - fn pin_child_under_cap() { - let Ok(dir) = std::env::var("EC_AV1_PINLOUD_CHILD") else { - return; - }; - // `ulimit -f 8` is 8 KiB, so 4x that is guaranteed to run PAST the cap - // (a write of exactly the cap size succeeds) and land a fragment. - pin( - "TEST_PIN", - Path::new(&dir).join("cap-pinned.obu"), - &[7u8; 32768], - ); - } -} diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 7098cfa9..ce7d0062 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -28,7 +28,6 @@ pub mod census; mod compound; pub mod decode; pub mod encode; -mod dumpio; pub mod encoder; #[doc(hidden)] pub mod fault; diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 55694552..99653ccc 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -144,9 +144,6 @@ impl SymbolEncoder { /// shorter than a two-symbol alphabet's three entries. pub fn symbol_fixed(&mut self, symbol: usize, cdf: &[u16]) { assert!(cdf.len() >= 3, "a CDF covers at least two symbols"); - if !self.pricing && symtrace::dir().is_some() { - symtrace::push(symbol, cdf.len() - 1, cdf[0]); - } let nsyms = cdf.len() - 1; assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet"); @@ -204,7 +201,6 @@ impl SymbolEncoder { /// payload end on a byte boundary with no terminator. pub fn finish(mut self) -> Vec { assert!(!self.pricing, "a pricer holds no bytes to flush"); - symtrace::flush('w'); // Round the interval's low end up to a value with 14 low zero bits, // then set bit 14: the result is inside the interval (the interval is // at least 2^15 wide before normalisation) and its tail bits are all @@ -317,7 +313,6 @@ pub struct SymbolDecoder<'a> { impl Drop for SymbolDecoder<'_> { fn drop(&mut self) { - symtrace::flush('r'); } } @@ -517,20 +512,12 @@ impl<'a> SymbolDecoder<'a> { /// [`SymbolEncoder::symbol_fixed`]. #[inline] pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { - if symtrace::dir().is_some() { - let s = self.symbol_fixed_raw(cdf); - symtrace::push(s, cdf.len() - 1, cdf[0]); - return s; - } self.symbol_fixed_raw(cdf) } #[inline] fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize { let nsyms = cdf.len() - 1; - if symtrace::ecdump_armed() { - symtrace::ecdump(0, self.value, self.range, self.bit as i64); - } // Two-symbol alphabets are most of the stream (every flag, every bit of // a literal), and their walk has exactly one boundary: computing it // straight skips the loop and its bounds work. @@ -627,9 +614,6 @@ impl<'a> SymbolDecoder<'a> { // the range multiply is a shift. let cur = ((self.range >> 8) << 7) + EC_MIN_PROB; let bit = self.bool_cur(cur); - if symtrace::dir().is_some() { - symtrace::push(bit, 2, EQUIPROBABLE[0]); - } v = (v << 1) | bit as u32; } v @@ -982,168 +966,3 @@ pub(crate) mod tests { } } -/// Symbol-by-symbol writer/reader trace (`EC_AV1_SYMTRACE=`), the -/// instrument a desync between OUR writer and OUR reader is bisected with: -/// every non-pricing [`SymbolEncoder`] and every [`SymbolDecoder`] dumps one -/// line per symbol (`index value nsyms cdf0`) into `/w-.txt` / -/// `/r-.txt`, and the first line where the two differ names the -/// divergent symbol. `EC_AV1_SYMTRACE_AT=` additionally prints a -/// backtrace at that index on both sides, which names the syntax element. -/// Off (the variable unset) this is one relaxed load per symbol. -pub(crate) mod symtrace { - use std::cell::RefCell; - use std::collections::VecDeque; - use std::sync::OnceLock; - - static DIR: OnceLock> = OnceLock::new(); - static AT: OnceLock> = OnceLock::new(); - static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - - thread_local! { - static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) }; - static ECD: RefCell> = const { RefCell::new(VecDeque::new()) }; - // lane-av1dumploud: the file's PATH travels with it, so a short write - // can name the file it truncated instead of reconstructing a name. - static ECD_READER: RefCell> = const { RefCell::new(None) }; - static ECD_IDX: RefCell = const { RefCell::new(0) }; - } - - /// lane-av1mix: `(low, value, rng, bitpos)` state register dump, one line - /// per symbol read, byte-for-byte diffable against libaom's `EC_ECDUMP` - /// (`decodetxb.c`, `r->ec.dif` masked to 16 bits / `r->ec.rng` / - /// `od_ec_dec_tell`). Reader-only, `EC_AV1_ECDUMP=`: each reader - /// writes `/ecdump-.txt`. - pub(crate) fn ecdump(low: u32, value: u32, rng: u32, bitpos: i64) { - if !ecdump_armed() { - return; - } - let dir = std::env::var("EC_AV1_ECDUMP").unwrap_or_else(|_| "/tmp".to_string()); - let idx = ECD_IDX.with(|c| { - let mut g = c.borrow_mut(); - let n = *g; - *g += 1; - n - }); - let _ = idx; - let line = format!("{idx} ({low},{value},{rng},{bitpos})\n"); - ECD_READER.with(|f| { - use std::io::Write; - let mut slot = f.borrow_mut(); - if slot.is_none() { - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let path = format!("{dir}/ecdump-{seq:05}.txt"); - eprintln!("ECDUMP -> {path}"); - *slot = Some((std::fs::File::create(&path).expect("ecdump file"), path)); - } - // lane-av1dumploud: loud on a short write. This file is one line - // per symbol for a whole run, so its total length is unknowable at - // open time -- the failure line says "an unknown number of" rather - // than declaring a length it would have to invent. - let (file, path) = slot.as_mut().expect("just opened"); - if let Err(e) = file.write_all(line.as_bytes()) { - panic!( - "ec-av1 dump FAILED [EC_AV1_ECDUMP] {path}: \ - write failed after a partial line of {} bytes: {e}", - line.len() - ); - } - }); - ECD.with(|q| { - let mut q = q.borrow_mut(); - q.push_back((low, value, rng, bitpos as u32)); - if q.len() > 512 { - q.pop_front(); - } - }); - } - - /// lane-av1mix: the last `n` dumped register states (most recent last). - #[allow(dead_code)] // diagnostic helper for lane sessions - pub(crate) fn ecdump_recent(n: usize) -> Vec<(u32, u32, u32, u32)> { - if std::env::var_os("EC_AV1_ECDUMP").is_none() { - return Vec::new(); - } - ECD.with(|q| { - let q = q.borrow(); - let skip = q.len().saturating_sub(n); - q.iter().skip(skip).copied().collect() - }) - } - - pub(crate) fn dir() -> Option<&'static str> { - DIR.get_or_init(|| { - crate::envflags::var("EC_AV1_SYMTRACE") - .ok() - .filter(|v| !v.is_empty()) - }) - .as_deref() - } - - /// lane-av1mix: `EC_AV1_ECDUMP=` arms the decoder state-register dump. - pub(crate) fn ecdump_armed() -> bool { - static ARMED: std::sync::LazyLock = - std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_ECDUMP").is_some()); - *ARMED - } - - /// `EC_AV1_SYMTRACE_AT=` or `=:` (inclusive). - fn at() -> Option<(usize, usize)> { - *AT.get_or_init(|| { - let v = crate::envflags::var("EC_AV1_SYMTRACE_AT").ok()?; - let (a, b) = v.split_once(':').unwrap_or((v.as_str(), v.as_str())); - Some((a.parse().ok()?, b.parse().ok()?)) - }) - } - - /// A caller's own annotation, interleaved with this coder's symbol lines - /// (`# ...`) so the writer/reader diff shows the state around a desync. - pub(crate) fn note(line: &str) { - if dir().is_none() { - return; - } - BUF.with(|b| { - let (buf, _) = &mut *b.borrow_mut(); - buf.push_str("# "); - buf.push_str(line); - buf.push('\n'); - }); - } - - pub(crate) fn push(value: usize, nsyms: usize, cdf0: u16) { - BUF.with(|b| { - let (buf, n) = &mut *b.borrow_mut(); - if at().is_some_and(|(a, b)| (a..=b).contains(n)) { - eprintln!( - "SYMTRACE at {n}: {}", - std::backtrace::Backtrace::force_capture() - ); - } - buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n")); - *n += 1; - }); - } - - /// Flushes this coder's lines as `/-.txt` and starts the - /// next coder's trace. - pub(crate) fn flush(side: char) { - let Some(dir) = dir() else { return }; - BUF.with(|b| { - let (buf, n) = &mut *b.borrow_mut(); - if !buf.is_empty() { - // lane-av1dumploud: loud on a short write. `std::fs::write` - // returned a `Result` this used to discard, and the check was - // hand-rolled against the buffer length only; lane-av1pinloud - // folded it into the shared writer so this site also gets the - // on-disk length check the dump path already had. - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - crate::dumpio::pin( - "EC_AV1_SYMTRACE", - format!("{dir}/{side}-{seq:05}.txt"), - buf.as_bytes(), - ); - } - buf.clear(); - *n = 0; - }); - } -} diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index f16d1067..004832e8 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -1863,24 +1863,6 @@ pub fn find_mv_stack_with_sign_bias( .checked_sub(1) .is_some_and(|c| grid.skip_at(mi_row, c)); - // lane-sb128b: the writer/reader stack diff instrument (`EC_AV1_MVDBG=1`) - // -- one line per built stack, in build order, so the two sides' logs - // diff to the first block whose candidate list differs. - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - "MVDBG mi=({mi_row},{mi_col}) b=({bw4}x{bh4}) ref={ref_frame} n={} mv={:?}", - candidates.len(), - candidates.iter().map(|e| (e.mv, e.weight)).collect::>(), - )); - let row = mi_row.checked_sub(1).map(|r| { - (mi_col..mi_col + bw4).map(|c| grid.get(r, c).map(|m| (m.ref_frame, m.mv))).collect::>() - }); - let col = mi_col.checked_sub(1).map(|c| { - (mi_row..mi_row + bh4).map(|r| grid.get(r, c).map(|m| (m.ref_frame, m.mv))).collect::>() - }); - crate::msac::symtrace::note(&format!(" above={row:?}")); - crate::msac::symtrace::note(&format!(" left={col:?}")); - } MvStack { entries: candidates, nearest_mv, diff --git a/crates/ec-av1/src/stream/mod.rs b/crates/ec-av1/src/stream/mod.rs index 8b9d9089..8201483d 100644 --- a/crates/ec-av1/src/stream/mod.rs +++ b/crates/ec-av1/src/stream/mod.rs @@ -36,29 +36,7 @@ fn no_grain() -> bool { std::env::var_os("EC_AV1_NO_GRAIN").is_some() } -// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the -// current thread, overriding the environment variable. Every ffmpeg/aomdec -// pixel gate in this repo compares SHOWN frames only (class -// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc -// stream carries were never compared at all; the gate that does compare -// them needs a dump path that cannot race a sibling test's decode on -// another thread, which a process-global env var cannot give. -thread_local! { - static FINAL_DUMP_PREFIX: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; -} - -/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix. -#[allow(dead_code)] -pub(crate) fn set_final_dump_prefix(prefix: Option) { - FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix); -} -fn final_dump_prefix() -> Option { - FINAL_DUMP_PREFIX - .with(|c| c.borrow().clone()) - .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok()) -} /// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search: /// (HORZ_4 strips, VERT_4 strips, strips that read coefficients). @@ -855,7 +833,6 @@ fn collect_one( /// A persistent AV1 stream decoder: feed it temporal units in decode order. pub struct StreamDecoder { threads: usize, - final_dump: Option, parser: Av1Parser, pictures_shown: usize, pictures_decoded: usize, @@ -935,7 +912,6 @@ impl StreamDecoder { let (tx, rx) = std::sync::mpsc::channel::(); Self { threads, - final_dump: final_dump_prefix(), parser: Av1Parser::new(), pictures_shown: 0, pictures_decoded: 0, @@ -995,7 +971,6 @@ impl StreamDecoder { let mut pending_tiles = std::mem::take(&mut self.pending_tiles); let threads = self.threads; let StreamDecoder { - final_dump, parser, ref_slots, motion_field_slots, @@ -1328,7 +1303,6 @@ impl StreamDecoder { pictures_shown += 1; } let tx = tx.clone(); - let dump = final_dump.clone(); crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown); // The job outlives this call, so it owns its tile bytes (a copy of // this frame's compressed tiles) instead of borrowing `data`. @@ -1490,7 +1464,6 @@ impl StreamDecoder { snap, decode_idx, shown_idx, - dump.as_deref(), // lane-twostage publishes a frame's meta at its tile // boundary instead of after its filters, so a consumer // parses over its producer's filter tail. It is ON by @@ -1602,7 +1575,6 @@ impl StreamDecoder { snap, pictures_decoded, pictures_shown, - final_dump.as_deref(), None, )?; let motion_field = motion_field.expect("the inline path passes no stage-1 sink"); @@ -1909,7 +1881,6 @@ fn decode_frame( snap: RefSnapshot<'_>, decode_idx: usize, shown_idx: usize, - final_dump: Option<&str>, // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`. stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>, ) -> Result { @@ -2533,54 +2504,6 @@ fn decode_frame( // *initial* table into the slots it refreshes, not the adapted // end-of-tile one. let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from); - if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") { - // lane-av1dumploud: loud on a short write. This one is APPEND-mode and - // spans every frame of a run, so there is no total length to declare - // (`append_unknown` says so on the failure line rather than guessing - // one); the per-line writes are still checked, so an ENOSPC halfway - // through a table no longer passes as a complete one. - let mut f = crate::dumpio::LoudDump::append_unknown("EC_AV1_DUMP_TABLES", &path); - let mut line = |s: String| f.write(s.as_bytes()); - line(format!("=== frame idx={shown_idx} ===\n")); - line(format!("partition_w64 {:?}\n", stored_cdfs.partition_w64)); - line(format!("partition_w32 {:?}\n", stored_cdfs.partition_w32)); - line(format!("partition_w16 {:?}\n", stored_cdfs.partition_w16)); - line(format!("skip {:?}\n", stored_cdfs.skip)); - line(format!("new_mv {:?}\n", stored_cdfs.new_mv)); - line(format!("zero_mv {:?}\n", stored_cdfs.zero_mv)); - line(format!("ref_mv {:?}\n", stored_cdfs.ref_mv)); - line(format!("mv_joint {:?}\n", stored_cdfs.mv_joint)); - f.finish(); - } - // lane-comppin r3: decode-order (not display-order) dump of every - // frame's own post-deblock buffer -- the pre-existing pixel diff - // (`scratch_isolate_pinned_mismatch`) only ever compares *shown* - // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a - // later shown frame is otherwise invisible; diff this byte-for-byte - // against `EC_AV1_POSTDEBLOCK_DUMP.fN` from the instrumented aomdec build - // (rung 6, `scripts/instrument-aom-oracle.sh`; 1 byte per sample, so it is - // byte-comparable only at 8-bit -- for HBD use rung 12 `EC_AV1_FINAL_DUMP`) - // to isolate whether the defect is in a hidden frame's own - // reconstruction or downstream of it. - if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") { - // lane-hbd r4: debug dump narrows to u8 -- this diagnostic - // predates 10-bit support and is an 8-bit-oracle comparison - // only (aomdec's own dump is 8-bit here too). - // - // lane-av1dumploud: loud on a short write; expected length is the three - // planes' own lengths (narrowing is 1 byte per sample, so the count is - // unchanged). - let narrow = |v: &[u16]| -> Vec { v.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - "EC_AV1_DECODE_ORDER_DUMP", - format!("{path}.f{decode_idx}"), - &[ - &narrow(&picture.y), - &narrow(&picture.u), - &narrow(&picture.v), - ], - ); - } // lane-hidden r1: the frame exactly as it is about to be stored into // the reference slots -- after deblock/CDEF/LR/superres, in DECODE // order, hidden (`show_frame == 0`) alt-ref frames included, and @@ -2621,32 +2544,6 @@ fn decode_frame( // caller receives is censused by `decode::census_unwritten_grained`, at // `apply_grain`'s own return, over its own counters. decode::census_unwritten_final(&picture.y, &picture.u, &picture.v); - if let Some(prefix) = final_dump { - // lane-av1dumploud: this is the site that produced the 13 320 192-byte - // truncated frame in `lanes/unwritten-dep.report.md` -- `let _ = - // f.write_all(&buf)` swallowed the ENOSPC. Expected length is derived - // from the PLANES and the sample width, independently of `buf`, so a - // writer that builds the wrong buffer still gets caught. - let sample_width = if bit_depth == 8 { 1 } else { 2 }; - let expected = (picture.y.len() + picture.u.len() + picture.v.len()) * sample_width; - let mut f = crate::dumpio::LoudDump::create( - "EC_AV1_FINAL_DUMP", - format!("{prefix}.f{decode_idx}"), - expected, - ); - for plane in [&picture.y, &picture.u, &picture.v] { - if bit_depth == 8 { - f.write(&plane.iter().map(|&s| s as u8).collect::>()); - } else { - let mut row = Vec::with_capacity(plane.len() * 2); - for &s in plane { - row.extend_from_slice(&s.to_le_bytes()); - } - f.write(&row); - } - } - f.finish(); - } if let Some(why) = fctx.corrupt.get() { return Err(Error::corrupt(format!("AV1 frame {decode_idx}: {why}"))); } diff --git a/crates/ec-av1/src/tile/blocks.rs b/crates/ec-av1/src/tile/blocks.rs index 1cb20814..faa3b21e 100644 --- a/crates/ec-av1/src/tile/blocks.rs +++ b/crates/ec-av1/src/tile/blocks.rs @@ -2771,12 +2771,6 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( mi_rows as usize, ); let (mv, is_new_mv) = write_inter_mode(&mut enc, cdfs, info, &stack)?; - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}", - info.mode, info.ref_mv_idx, info.mv - )); - } (mv, (0, 0), is_new_mv) }; for dr in 0..SB_MI as usize { @@ -3202,12 +3196,6 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( ); let (mv, is_new_mv) = write_inter_mode(&mut enc, cdfs, info, &stack)?; - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}", - info.mode, info.ref_mv_idx, info.mv - )); - } grid.set( mi_row, mi_col,