diff --git a/crates/ec-vp9/examples/decode_ivf.rs b/crates/ec-vp9/examples/decode_ivf.rs index 79b27381..4d46e64d 100644 --- a/crates/ec-vp9/examples/decode_ivf.rs +++ b/crates/ec-vp9/examples/decode_ivf.rs @@ -1,8 +1,7 @@ //! Decode an IVF VP9 file and report throughput and an output digest. //! //! Usage: `decode_ivf [threads]`. `threads` sets the tile-column -//! worker count (default: `EC_VP9_THREADS`, else the available parallelism -//! capped at 6). The digest is FNV-1a over every output sample, so runs at +//! worker count (default: the available parallelism capped at 6). The digest is FNV-1a over every output sample, so runs at //! different thread counts can be compared. use ec_vp9::decode::Decoder; @@ -70,11 +69,6 @@ fn main() -> Result<(), Box> { } } let secs = start.elapsed().as_secs_f64(); - if ec_vp9::prof::enabled() { - for (name, t) in ec_vp9::prof::NAMES.iter().zip(ec_vp9::prof::totals()) { - println!("prof {name} {t:.3}s"); - } - } println!( "frames={} shown={} digest={digest:016x} secs={secs:.3} fps={:.2} decode_secs={decode_secs:.3} decode_fps={:.2}", frames.len(), diff --git a/crates/ec-vp9/src/bool.rs b/crates/ec-vp9/src/bool.rs index bc53da6f..b5c199dd 100644 --- a/crates/ec-vp9/src/bool.rs +++ b/crates/ec-vp9/src/bool.rs @@ -96,8 +96,7 @@ impl<'a> BoolDecoder<'a> { } /// Decode one bool whose zero-probability is `prob`/256 (spec 8.3.2 - /// `read_bool`; libvpx `vpx_read`). Under `EC_VP9_TRACE`, prints the - /// decoder state after the read — `B `. + /// `read_bool`; libvpx `vpx_read`). pub fn read_bool(&mut self, prob: u8) -> bool { let prob = u32::from(prob); let split = 1 + (((self.range - 1) * prob) >> 8); @@ -119,9 +118,6 @@ impl<'a> BoolDecoder<'a> { self.value |= self.next_byte(); } } - if crate::trace_enabled() { - eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit)); - } bit } diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 292358a5..b4ed9f58 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -177,7 +177,7 @@ pub struct Decoder { /// /// Boxed for the same reason as `frame_ctxs` below: a `FrameContext` is /// 2039 bytes, and leaving this one inline put 73% of the whole `Decoder` - /// back on the stack. `Stack`: crate::stack_budget. + /// back on the stack. ctx: Box, refs: [Option; 8], /// Frame scratch, live only inside `decode_keyframe`. @@ -190,7 +190,7 @@ pub struct Decoder { /// Boxed because a `FrameContext` is 2039 bytes and four of them inline /// are 8156 of the 10944 a `Decoder` costs a caller that takes one BY /// VALUE from `Decoder::new`. Indexing and whole-array assignment read - /// through the box. `Stack`: crate::stack_budget. + /// through the box. frame_ctxs: Box<[FrameContext; 4]>, /// The previous frame's per-8x8 MV field and segment map /// (`prev_frame->mvs` / `last_frame_seg_map`). @@ -212,12 +212,11 @@ pub struct Decoder { /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its /// averaging variant needs. mc_temp: Vec, - /// Tile-column workers per frame. Set by `EC_VP9_THREADS` when that is a - /// positive integer (clamped to 1..=64); otherwise `default_threads()`. + /// Tile-column workers per frame: `default_threads()` unless `set_threads`. threads: usize, } -/// Default tile-column worker count when `EC_VP9_THREADS` is unset or invalid: +/// Default tile-column worker count: /// the host's available parallelism, capped at 6 (the measured knee for 1080p /// tile streams; see `lanes/vp9speed.report.md`). Falls back to 1 if the /// parallelism cannot be determined. @@ -291,11 +290,7 @@ impl Decoder { syntax_blocks: 0, mc_scratch: Vec::new(), mc_temp: vec![0; 64 * 135 + 64 * 64], - threads: std::env::var("EC_VP9_THREADS") - .ok() - .and_then(|v| v.parse::().ok()) - .filter(|&n| n > 0) - .map_or_else(default_threads, |n| n.clamp(1, 64)), + threads: default_threads(), } } @@ -331,9 +326,6 @@ impl Decoder { // path and `decode_syntax` label the same frame the same way. let index = self.decode_index; self.decode_index += 1; - if crate::trace_enabled() { - eprintln!("B FRAME x FRAME x"); - } if hdr.frame_type == FrameType::Key { return self.decode_key_frame(&hdr, frame); } @@ -365,16 +357,6 @@ impl Decoder { }; // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the // uncompressed-header size / header_size_in_bytes split for diagnosis. - let hdr = { - let mut h = hdr; - if let Ok(v) = std::env::var("EC_VP9_FORCE_UH") { - h.uncompressed_header_size = v.parse().unwrap_or(h.uncompressed_header_size); - } - if let Ok(v) = std::env::var("EC_VP9_FORCE_HSZ") { - h.header_size_in_bytes = v.parse().unwrap_or(h.header_size_in_bytes); - } - h - }; let ch = read_compressed_header( compressed_header_slice(frame, &hdr)?, &mut self.ctx, @@ -548,24 +530,12 @@ impl Decoder { } let hdr_start = hdr.uncompressed_header_size as usize; - if crate::trace_enabled() { - eprintln!("CHSTART frame={index}"); - } let ch = read_compressed_header( compressed_header_slice(frame, hdr)?, &mut self.ctx, hdr, )?; - if crate::interdump_enabled() { - let mut line = format!("PPFLAT frame={index}"); - for row in self.ctx.partition.iter() { - for v in row.iter() { - line.push_str(&format!(" {v}")); - } - } - eprintln!("{line}"); - } // INTRA_FRAME's sign bias is 0 by definition; the coded three land at // LAST/GOLDEN/ALTREF. @@ -629,9 +599,7 @@ impl Decoder { // the walk's signature carries them. let mut grids = new_grids(mi_cols, mi_rows); let mut counts = crate::adapt::Counts::default(); - let t_walk = crate::prof::start(); self.walk_frame(&job, &mut grids, &mut counts)?; - crate::prof::stop(crate::prof::Phase::Walk, t_walk); // Backward adaptation (libvpx vp9_decode_frame): counts from this frame // adapt the stored context the frame started from. Skipped for @@ -674,20 +642,6 @@ impl Decoder { if hdr.refresh_frame_context { self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone(); } - if crate::interdump_enabled() { - eprintln!( - "CHSUM frame={index} tx_mode={} ref_mode={} allow_hp={} interp={} tile_rows={} tile_cols={} pp12={:?} pp0={:?} pp13={:?}", - ch.tx_mode, - ch.reference_mode, - hdr.allow_high_precision_mv, - hdr.interpolation_filter as u8, - hdr.tile_info.rows_log2, - hdr.tile_info.cols_log2, - self.ctx.partition[12], - self.ctx.partition[0], - self.ctx.partition[13] - ); - } if !pixels { return Ok(None); @@ -696,8 +650,7 @@ impl Decoder { // Loop filter post-pass: same extents as the keyframe path, but the // per-cell level comes from the block's own reference and mode class // (`get_filter_level`, vp9_loopfilter.c:249). - if hdr.loop_filter.level > 0 && !crate::knobs::skip_lf() { - let t_lf = crate::prof::start(); + if hdr.loop_filter.level > 0 { let p = self.planes.as_mut().expect("frame scratch"); let (vw, vh) = (mi_cols * 8, mi_rows * 8); grids.filter_frame( @@ -715,7 +668,6 @@ impl Decoder { hdr.loop_filter.sharpness, hdr.bit_depth, ); - crate::prof::stop(crate::prof::Phase::LoopFilter, t_lf); } let pic = self.take_picture(hdr); @@ -812,25 +764,6 @@ impl Decoder { }; } } - if crate::interdump_enabled() { - eprintln!( - "MODE {} {} {} {} {} {} {} {} {} tpos=0 ref0={} ref1={} mvrow={} mvcol={} if={}", - w.frame_index, - row, - col, - sb_type, - info.tx_size, - info.mode, - info.uv_mode, - u8::from(info.skip), - info.segment, - info.ref_frame[0], - info.ref_frame[1], - info.mv[0].0, - info.mv[0].1, - info.interp_filter - ); - } } w.prev_seg = prev_seg; w.prev_mvs = prev_mvs; @@ -1034,7 +967,6 @@ impl Decoder { // Prediction: `dec_build_inter_predictors_sb`, every reference, every // plane, before any token is read. { - let t_mc = crate::prof::start(); let planes = self.planes.as_mut().expect("frame scratch"); let refs = &self.refs; let scratch = &mut self.mc_scratch; @@ -1057,7 +989,6 @@ impl Decoder { sb_type, )?; } - crate::prof::stop(crate::prof::Phase::Mc, t_mc); } if info.skip { @@ -1080,7 +1011,6 @@ impl Decoder { (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize; for brow in (0..max_blocks_high).step_by(step) { for bcol in (0..max_blocks_wide).step_by(step) { - let t_tok = crate::prof::start(); let coef = decode_inter_tx_tokens( r, ectx, @@ -1099,7 +1029,6 @@ impl Decoder { mb_to_right, mb_to_bottom, counts, ); - crate::prof::stop(crate::prof::Phase::Tokens, t_tok); eobtotal += coef.eob; if coef.eob == 0 { continue; @@ -1114,7 +1043,6 @@ impl Decoder { let y0 = ((row * 8) >> ss_y) + brow * 4; let dst_off = y0 * stride + x0; let (data, _) = planes.plane(plane); - let t_idct = crate::prof::start(); inverse_transform_add( tx_size, DCT_DCT, @@ -1125,7 +1053,6 @@ impl Decoder { hdr.quantization.lossless(), bd, ); - crate::prof::stop(crate::prof::Phase::Idct, t_idct); } } } @@ -1159,10 +1086,8 @@ impl Decoder { let aw = width.div_ceil(64) * 64; let ah = height.div_ceil(64) * 64; self.planes = Some(self.frame_planes(aw, ah, hdr.bit_depth, ss_x, ss_y)); - let tail_start = crate::knobs::force_tail() - .unwrap_or_else(|| { - hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize - }); + let tail_start = + hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize; let tail: Vec = frame[tail_start..].to_vec(); self.decode_keyframe_inner(hdr, tx_mode, &tail) } @@ -1210,8 +1135,7 @@ impl Decoder { // Loop filter post-pass (level 0 disables it for the frame). // The extents are the MI-aligned VISIBLE plane (libvpx's masks clear // everything past `mi_cols`/`mi_rows`), not the padded buffer size. - if hdr.loop_filter.level > 0 && !crate::knobs::skip_lf() { - let t_lf = crate::prof::start(); + if hdr.loop_filter.level > 0 { let p = self.planes.as_mut().expect("frame scratch"); let (vw, vh) = (mi_cols * 8, mi_rows * 8); grids.filter_frame( @@ -1229,7 +1153,6 @@ impl Decoder { hdr.loop_filter.sharpness, hdr.bit_depth, ); - crate::prof::stop(crate::prof::Phase::LoopFilter, t_lf); } // `vp9_swap_current_and_last_seg_map` runs only when segmentation is @@ -1536,18 +1459,6 @@ impl Decoder { } for dy in 0..y_mis { for dx in 0..x_mis { - if crate::mvdbg2_enabled() && row + dy == 7 && col + dx >= 30 && col + dx <= 40 - { - eprintln!( - "GWR cell=({} {}) idx={} from=({row} {col}) dy={dy} dx={dx} sb={sb_type} bw={bw} bh={bh} x_mis={x_mis} y_mis={y_mis} mv={:?} ref0={} mi_cols={}", - row + dy, - col + dx, - (row + dy) * mi.mi_cols + col + dx, - info.mv, - info.ref_frame[0], - mi.mi_cols - ); - } mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone()); } } @@ -1756,31 +1667,6 @@ impl Decoder { let nblocks = 1usize << tx_size; let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0)) + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0)); - if crate::trace_enabled() { - eprintln!( - "CTX p={} prob={:?} ax={} ay={} a={} l={} ctx={}", - plane, - self.ctx.coef[tx_size][ptype][0][0][ctx_in], - ax, - ay, - ectx[plane].above[ax], - ectx[plane].left[ay], - ctx_in - ); - } - if crate::trace_enabled() { - eprintln!( - "TXB p={} x={} y={} tx={} a={} l={} deq={},{}", - plane, - x0, - y0, - tx_size, - ectx[plane].above[ax], - ectx[plane].left[ay], - dequant[0], - dequant[1] - ); - } let coef = decode_coefs( r, ptype, @@ -1813,39 +1699,11 @@ impl Decoder { 0 }; write_tx_context(ectx, plane, tx_size, ax, ay, coef.eob > 0, shift_a, shift_l); - if crate::tokdbg_enabled() { - eprintln!( - "TDW row={mi_row} col={mi_col} plane={plane} brow={tx_row} bcol={tx_col} tx={tx_size} eob={} sa={} sl={} aw={:?} lw={:?} intra=1", - coef.eob, - shift_a, - shift_l, - &ectx[plane].above[ax..ax + nblocks], - &ectx[plane].left[ay..ay + nblocks], - ); - } // 4. Residual add. if coef.eob > 0 { let dst_off = y0 * stride + x0; let (data, _) = planes.plane(plane); - let probe = crate::trace_enabled() - && plane == 0 - && std::env::var("EC_VP9_PROBE_TU") - .ok() - .and_then(|s| { - let mut it = s.split(','); - Some((it.next()?.parse::().ok()?, it.next()?.parse().ok()?)) - }) - .is_some_and(|(px, py)| x0 == px && y0 == py); - let t: Option>> = if probe { - Some( - (0..4usize) - .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec()) - .collect(), - ) - } else { - None - }; inverse_transform_add( tx_size, tx_type, @@ -1856,15 +1714,6 @@ impl Decoder { lossless, bd, ); - if let Some(before) = t { - let after: Vec> = (0..4usize) - .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec()) - .collect(); - eprintln!("RC x0={x0} y0={y0} tx={tx_size} mode={mode}"); - for rr in 0..4 { - eprintln!(" pred{rr}={:?} after{rr}={:?}", before[rr], after[rr]); - } - } } Ok(()) } @@ -1966,26 +1815,6 @@ fn reset_skip_context( ectx[plane].left[(offy + i) % lrows] = 0; } } - if crate::tokdbg_enabled() { - // Mirror the oracle's `SKIPCTX` print: the CLEARED window, indexed from - // the reset offset (libvpx's `left_context` is already offset to the - // block), not the whole rolling buffer from base index 0. - let mut line = format!("TDK row={row} col={col} n4w={n4w:?} n4h={n4h:?}"); - for plane in 0..3usize { - let (sx, sy) = if plane == 0 { (0, 0) } else { (ss_x, ss_y) }; - let offx = (col << 1) >> sx; - let offy = (row << 1) >> sy; - let lrows = 32usize >> sy; - let a: Vec = (0..n4w[plane]) - .map(|i| ectx[plane].above[offx + i]) - .collect(); - let l: Vec = (0..n4h[plane].min(lrows)) - .map(|i| ectx[plane].left[(offy + i) % lrows]) - .collect(); - line.push_str(&format!(" p{plane} a={a:?} l={l:?}")); - } - eprintln!("{line}"); - } } /// The entropy-context write-back of one transform block @@ -2085,15 +1914,6 @@ fn decode_inter_tx_tokens( let nblocks = 1usize << tx_size; let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0)) + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0)); - if crate::tokdbg_enabled() { - eprintln!( - "TDB row={row} col={col} plane={plane} brow={brow} bcol={bcol} tx={tx_size} sbt={sb_type} ptype={ptype} inter={} mode={} tt={tx_type} ax={ax} ay={ay} cin={ctx_in} a={:?} l={:?}", - u8::from(info.is_inter), - info.mode, - &ectx[plane].above[ax..ax + nblocks], - &ectx[plane].left[ay..ay + nblocks], - ); - } let coef = decode_coefs( r, ptype, @@ -2124,16 +1944,6 @@ fn decode_inter_tx_tokens( 0 }; write_tx_context(ectx, plane, tx_size, ax, ay, coef.eob > 0, shift_a, shift_l); - if crate::tokdbg_enabled() { - eprintln!( - "TDW row={row} col={col} plane={plane} brow={brow} bcol={bcol} tx={tx_size} eob={} sa={} sl={} aw={:?} lw={:?}", - coef.eob, - shift_a, - shift_l, - &ectx[plane].above[ax..ax + nblocks], - &ectx[plane].left[ay..ay + nblocks], - ); - } coef } @@ -2459,11 +2269,9 @@ impl Decoder { .zip(worker_planes) .map(|(cols, planes)| { scope.spawn(move || -> Result<(Decoder, LfGrids, crate::adapt::Counts)> { - let t_fork = crate::prof::start(); let mut wk = parent.fork(hdr, planes); let mut g = new_grids(mi_cols, mi_rows); let mut c = crate::adapt::Counts::default(); - crate::prof::stop(crate::prof::Phase::Threads, t_fork); wk.walk_columns(job, cols, &mut g, &mut c)?; Ok((wk, g, c)) }) @@ -2478,7 +2286,6 @@ impl Decoder { for res in results { parts.push(res?); } - let t_merge = crate::prof::start(); for (w, (mut wk, g, c)) in parts.into_iter().enumerate() { counts.add(&c); for &tc in &owned[w] { @@ -2506,7 +2313,6 @@ impl Decoder { self.recycle_planes(p); } } - crate::prof::stop(crate::prof::Phase::Threads, t_merge); Ok(()) } @@ -2546,9 +2352,6 @@ impl Decoder { let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI; let row_hi = (((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2) * SB_MI).min(mi_rows); let data = job.tiles[tr * tile_cols + tc]; - if crate::trace_enabled() { - eprintln!("TILE {} bytes tr={tr} tc={tc}", data.len()); - } let mut r = crate::bool::BoolDecoder::new(data)?; for sb_row in (row_lo..row_hi).step_by(SB_MI) { // Left entropy/partition contexts are zeroed at the start diff --git a/crates/ec-vp9/src/header.rs b/crates/ec-vp9/src/header.rs index 533009a5..0ad1e27a 100644 --- a/crates/ec-vp9/src/header.rs +++ b/crates/ec-vp9/src/header.rs @@ -276,15 +276,6 @@ pub(crate) fn read_compressed_header( ctx: &mut FrameContext, hdr: &FrameHeader, ) -> crate::Result { - if crate::interdump_enabled() && !hdr.frame_is_intra { - let mut line = String::from("PPFLAT_PRE"); - for row in ctx.partition.iter() { - for v in row.iter() { - line.push_str(&format!(" {v}")); - } - } - eprintln!("{line}"); - } let lossless = hdr.quantization.lossless(); let mut r = BoolDecoder::new(data)?; let tx_mode = if lossless { @@ -292,9 +283,6 @@ pub(crate) fn read_compressed_header( } else { read_tx_mode(&mut r) }; - if crate::trace_enabled() { - eprintln!("SECT txmode"); - } if tx_mode == TX_MODE_SELECT { for row in 0..2 { for j in 0..1 { @@ -312,32 +300,17 @@ pub(crate) fn read_compressed_header( } } } - if crate::trace_enabled() { - eprintln!("SECT txprobs"); - } read_coef_probs(&mut r, ctx, tx_mode); - if crate::trace_enabled() { - eprintln!("SECT coef"); - } for p in &mut ctx.skip { diff_update_prob(&mut r, p); } let mut reference_mode = SINGLE_REFERENCE; - if crate::trace_enabled() { - eprintln!("SECT skip"); - } if !hdr.frame_is_intra { - if crate::trace_enabled() { - eprintln!("SECT intermode"); - } for i in 0..7 { for j in 0..3 { diff_update_prob(&mut r, &mut ctx.inter_mode[i][j]); } } - if crate::trace_enabled() { - eprintln!("SECT switchable"); - } if hdr.interpolation_filter as u8 == crate::inter::SWITCHABLE { for j in 0..4 { for i in 0..2 { @@ -345,17 +318,11 @@ pub(crate) fn read_compressed_header( } } } - if crate::trace_enabled() { - eprintln!("SECT intrainter"); - } for p in &mut ctx.intra_inter { diff_update_prob(&mut r, p); } // read_frame_reference_mode: `vp9_compound_reference_allowed` gates // the two bits (bias[GOLDEN]/bias[ALTREF] vs bias[LAST]). - if crate::trace_enabled() { - eprintln!("SECT refmode"); - } let allowed = hdr.ref_frame_sign_bias[1] != hdr.ref_frame_sign_bias[0] || hdr.ref_frame_sign_bias[2] != hdr.ref_frame_sign_bias[0]; reference_mode = if allowed { @@ -372,9 +339,6 @@ pub(crate) fn read_compressed_header( SINGLE_REFERENCE }; // read_frame_reference_mode_probs. - if crate::trace_enabled() { - eprintln!("SECT refprobs"); - } if reference_mode == REFERENCE_MODE_SELECT { for p in &mut ctx.comp_inter { diff_update_prob(&mut r, p); @@ -392,31 +356,18 @@ pub(crate) fn read_compressed_header( diff_update_prob(&mut r, p); } } - if crate::trace_enabled() { - eprintln!("SECT ymode"); - } for j in 0..4 { for i in 0..9 { diff_update_prob(&mut r, &mut ctx.y_mode[j][i]); } } - if crate::trace_enabled() { - eprintln!("SECT partition"); - } for j in 0..16 { for i in 0..3 { - let before = ctx.partition[j][i]; diff_update_prob(&mut r, &mut ctx.partition[j][i]); - if crate::interdump_enabled() { - eprintln!("PUPD {} {} {} {}", j, i, before, ctx.partition[j][i]); - } } } // read_mv_probs (vp9_decodeframe.c:76): joints, then per component // sign/classes/class0/bits, then the fractional parts, then hp. - if crate::trace_enabled() { - eprintln!("SECT mv"); - } update_mv_probs(&mut r, &mut ctx.nmv_joints); for comp in 0..2 { update_mv_probs(&mut r, &mut ctx.nmv_sign[comp..comp + 1]); @@ -434,48 +385,9 @@ pub(crate) fn read_compressed_header( for comp in 0..2 { update_mv_probs(&mut r, &mut ctx.nmv_class0_hp[comp..comp + 1]); update_mv_probs(&mut r, &mut ctx.nmv_hp[comp..comp + 1]); - if crate::mvdump_enabled() { - eprintln!( - "MVPROB j0={} j1={} j2={}", - ctx.nmv_joints[0], ctx.nmv_joints[1], ctx.nmv_joints[2] - ); - for comp in 0..2 { - eprintln!( - "MVPROB c{} sign={} class0={} class0hp={} hp={}", - comp, - ctx.nmv_sign[comp], - ctx.nmv_class0[comp][0], - ctx.nmv_class0_hp[comp], - ctx.nmv_hp[comp] - ); - eprint!("MVPROB c{} cls", comp); - for v in ctx.nmv_classes[comp].iter() { eprint!(" {}", v); } - eprintln!(); - eprint!("MVPROB c{} bits", comp); - for v in ctx.nmv_bits[comp].iter() { eprint!(" {}", v); } - eprintln!(); - eprint!("MVPROB c{} c0fp", comp); - for row in ctx.nmv_class0_fp[comp].iter() { for v in row.iter() { eprint!(" {}", v); } } - eprintln!(); - eprint!("MVPROB c{} fp", comp); - for v in ctx.nmv_fp[comp].iter() { eprint!(" {}", v); } - eprintln!(); - } - } } } } - if std::env::var_os("EC_VP9_DBG").is_some() { - eprintln!("DBG tx_mode={} consumed={}", tx_mode, r.byte_offset()); - eprintln!( - "DBG skip_probs={:?} p8x8={:?} p16={:?}", - ctx.skip, ctx.tx_p8x8, ctx.tx_p16x16 - ); - eprintln!( - "DBG coef[0][0][0][0][0..3]={:?} coef[0][0][1][1][0..3]={:?}", - ctx.coef[0][0][0][0], ctx.coef[0][0][1][1] - ); - } ensure(r.overreads() == 0, "compressed header desync")?; Ok(CompressedHeader { tx_mode, diff --git a/crates/ec-vp9/src/inter.rs b/crates/ec-vp9/src/inter.rs index 060746e4..2896e2ae 100644 --- a/crates/ec-vp9/src/inter.rs +++ b/crates/ec-vp9/src/inter.rs @@ -583,7 +583,6 @@ fn find_mv_refs( ) -> (usize, [(i32, i32); MAX_MV_REF_CANDIDATES]) { let search = &MV_REF_BLOCKS[bsize]; let early_break = mode != NEARMV; - let mvref_dbg = crate::mvdbg_enabled() && mode == NEWMV; let mut list = [(0, 0); MAX_MV_REF_CANDIDATES]; let mut count = 0usize; let mut different_ref_found = false; @@ -646,30 +645,6 @@ fn find_mv_refs( } } - if crate::mvdbg2_enabled() - && ((row == 8 && col == 104) || (row == 32 && col == 64) || (row == 8 && col == 32)) - { - for (i, p) in search.iter().enumerate() { - let ins = is_inside(c, row, col, *p); - let c2 = st.at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize); - let qr = (row as i32 + p.0) as usize; - let qc = (col as i32 + p.1) as usize; - match c2 { - Some(cd) => eprintln!( - "MVC r={row} c={col} i={i} p={p:?} q=({qr} {qc}) idx={} inside={ins} ref0={} ref1={} mv0={:?} mv1={:?} inter={}", - qr * c.mi_cols + qc, - cd.ref_frame[0], cd.ref_frame[1], cd.mv[0], cd.mv[1], cd.is_inter - ), - None => eprintln!("MVC r={row} c={col} i={i} p={p:?} q=({qr} {qc}) inside={ins} none"), - } - } - } - if mvref_dbg { - eprintln!( - "MVREF r={row} c={col} bsize={bsize} mode={mode} n={count} l0={:?} l1={:?}", - list[0], list[1] - ); - } if !done && different_ref_found { for p in search.iter() { if !is_inside(c, row, col, *p) { @@ -828,49 +803,27 @@ fn append_sub8x8_mvs_for_idx( /// `read_mv_component` (`vp9_decodemv.c:246`). fn read_mv_component(r: &mut BoolDecoder, fc: &FrameContext, comp: usize, use_hp: bool) -> i32 { - let dbg = crate::interdump_enabled(); - if dbg { - eprintln!("MVF c{comp} sign"); - } let sign = r.read_bool(fc.nmv_sign[comp]); - if dbg { - eprintln!("MVF c{comp} cls"); - } let mv_class = r.read_tree(&MV_CLASS_TREE, &fc.nmv_classes[comp]) as i32; let class0 = mv_class == 0; let mut d = 0i32; let mut mag; - if dbg { - eprintln!("MVF c{comp} class={mv_class}"); - } if class0 { - if dbg { - eprintln!("MVF c{comp} class0bit"); - } d = r.read_bool(fc.nmv_class0[comp][0]) as i32; mag = 0; } else { let n = mv_class + CLASS0_BITS - 1; for i in 0..n { - if dbg { - eprintln!("MVF c{comp} bits[{i}]"); - } d |= (r.read_bool(fc.nmv_bits[comp][i as usize]) as i32) << i; } mag = CLASS0_SIZE << (mv_class + 2); } - if dbg { - eprintln!("MVF c{comp} fp"); - } let fr = if class0 { r.read_tree(&MV_FP_TREE, &fc.nmv_class0_fp[comp][d as usize]) } else { r.read_tree(&MV_FP_TREE, &fc.nmv_fp[comp]) } as i32; let hp = if use_hp { - if dbg { - eprintln!("MVF c{comp} hp"); - } r.read_bool(if class0 { fc.nmv_class0_hp[comp] } else { @@ -897,9 +850,6 @@ fn read_mv( ) -> ((i32, i32), (i32, i32)) { let joint = r.read_tree(&MV_JOINT_TREE, &fc.nmv_joints); let use_hp = allow_hp && use_mv_hp(pred); - if crate::interdump_enabled() { - eprintln!("MVJ joint={joint} use_hp={use_hp} pred={pred:?}"); - } // mv_joint_vertical = joint & 2, mv_joint_horizontal = joint & 1. let mut diff = (0i32, 0i32); if joint & 2 != 0 { @@ -1256,17 +1206,8 @@ fn read_inter_block_mode_info( info.interp_filter = if c.frame_interp == SWITCHABLE { let ictx = switchable_interp_ctx(nb); - if crate::interdump_enabled() { - eprintln!( - "SWI ctx={} p0={} p1={}", - ictx, fc.switchable_interp[ictx][0], fc.switchable_interp[ictx][1] - ); - } let t = r.read_tree(&SWITCHABLE_INTERP_TREE, &fc.switchable_interp[ictx]); counts.switchable_interp[ictx][t as usize] += 1; - if crate::interdump_enabled() { - eprintln!("SWItype {t}"); - } t } else { c.frame_interp diff --git a/crates/ec-vp9/src/intra.rs b/crates/ec-vp9/src/intra.rs index bf8bcab1..db58c772 100644 --- a/crates/ec-vp9/src/intra.rs +++ b/crates/ec-vp9/src/intra.rs @@ -190,22 +190,6 @@ pub(crate) fn build_intra_predictors( // The C's `const_above_row = above_ref` shortcut for bs==4 && // right&&left stages the same bytes, so above_data is equivalent. - if crate::trace_enabled() - && std::env::var("EC_VP9_PROBE_TU") - .ok() - .and_then(|s| { - let mut it = s.split(','); - Some((it.next()?.parse::().ok()?, it.next()?.parse().ok()?)) - }) - .is_some_and(|(px, py)| x0 == px && y0 == py) - { - eprintln!( - "STAGE x0={x0} y0={y0} mode={mode} bs={bs} above={:?} cor={} left={:?}", - &above_data[A..A + 8], - above_data[A - 1], - &left_col[..8] - ); - } let dst = &mut data[y0 * stride + x0..]; dispatch( mode, @@ -218,19 +202,6 @@ pub(crate) fn build_intra_predictors( left_available, bd, ); - if crate::trace_enabled() - && std::env::var("EC_VP9_PROBE_TU") - .ok() - .and_then(|s| { - let mut it = s.split(','); - Some((it.next()?.parse::().ok()?, it.next()?.parse().ok()?)) - }) - .is_some_and(|(px, py)| x0 == px && y0 == py) - { - for rr in 0..bs { - eprintln!("PRED r={rr} {:?}", &dst[rr * stride..rr * stride + bs]); - } - } } fn dispatch( diff --git a/crates/ec-vp9/src/knobs.rs b/crates/ec-vp9/src/knobs.rs deleted file mode 100644 index 01daf1a3..00000000 --- a/crates/ec-vp9/src/knobs.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Debug switches the VP9 decoder reads from the environment, with a -//! per-thread override that tests set instead of editing the process -//! environment (which is `unsafe` in Rust 2024). -//! -//! The decoder reads these on the thread that calls `decode`: tile workers -//! and the loop-filter threads never read them. An override set on a test's -//! own thread therefore covers exactly that test's decodes. With no override -//! set, each reader answers from the environment exactly as it always has. - -use std::cell::Cell; -use std::thread::LocalKey; - -thread_local! { - static SKIP_LF: Cell> = const { Cell::new(None) }; - static FORCE_TAIL: Cell> = const { Cell::new(None) }; -} - -/// Restores the value a knob had before the guard was created, when dropped. -#[doc(hidden)] -#[must_use = "the override ends as soon as this guard is dropped"] -pub struct Override { - restore: Option>, -} - -impl Drop for Override { - fn drop(&mut self) { - if let Some(restore) = self.restore.take() { - restore(); - } - } -} - -fn force(slot: &'static LocalKey>, value: T) -> Override { - let prev = slot.with(|c| c.replace(value)); - Override { - restore: Some(Box::new(move || slot.with(|c| c.set(prev)))), - } -} - -/// `EC_VP9_SKIP_LF`: when set, the loop-filter post-pass is skipped. -pub(crate) fn skip_lf() -> bool { - SKIP_LF - .with(Cell::get) - .unwrap_or_else(|| std::env::var_os("EC_VP9_SKIP_LF").is_some()) -} - -/// `EC_VP9_FORCE_TAIL`: overrides the keyframe tail start offset, if set and -/// parseable. -pub(crate) fn force_tail() -> Option { - FORCE_TAIL.with(Cell::get).or_else(|| { - std::env::var("EC_VP9_FORCE_TAIL") - .ok() - .and_then(|s| s.parse().ok()) - }) -} - -/// Forces `EC_VP9_SKIP_LF` on (`Some(true)`), off (`Some(false)`) or back to -/// the environment (`None`) on this thread, until the guard drops. -#[doc(hidden)] -pub fn set_skip_lf(on: Option) -> Override { - force(&SKIP_LF, on) -} - -/// Forces `EC_VP9_FORCE_TAIL` to `tail` on this thread, until the guard drops. -/// `None` returns the knob to the environment. -#[doc(hidden)] -pub fn set_force_tail(tail: Option) -> Override { - force(&FORCE_TAIL, tail) -} diff --git a/crates/ec-vp9/src/lib.rs b/crates/ec-vp9/src/lib.rs index 56fad8f9..4949b329 100644 --- a/crates/ec-vp9/src/lib.rs +++ b/crates/ec-vp9/src/lib.rs @@ -42,13 +42,9 @@ pub mod decode; pub mod header; pub(crate) mod inter; pub mod intra; -#[doc(hidden)] -pub mod knobs; pub mod loopfilter; pub(crate) mod mc; pub mod modes; -pub mod prof; -mod stack_budget; pub mod stream; pub mod tables; pub mod tokens; @@ -75,54 +71,3 @@ pub(crate) fn round_pow2(v: i32, n: i32) -> i32 { (v + (1 << (n - 1))) >> n } -/// Whether `EC_VP9_TRACE` decision tracing is enabled, resolved once per -/// process. An `var_os` per bool read would lock std's ENV lock on every -/// coefficient; the hot path is a single relaxed atomic load. -pub(crate) fn trace_enabled() -> bool { - use std::sync::atomic::{AtomicU8, Ordering}; - static STATE: AtomicU8 = AtomicU8::new(0); - match STATE.load(Ordering::Relaxed) { - 0 => { - let on = std::env::var_os("EC_VP9_TRACE").is_some(); - STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); - on - } - 1 => false, - _ => true, - } -} - -/// Cached `getenv` probe: `EC_VP9_*` gates are consulted per block, per MV -/// component and per switchable-interp read, and `std::env::var_os` locks std's -/// ENV lock, so each gate resolves once per process and the hot path is a -/// single relaxed atomic load (see `trace_enabled`). -macro_rules! cached_gate { - ($fn_name:ident, $env:literal) => { - pub(crate) fn $fn_name() -> bool { - use std::sync::atomic::{AtomicU8, Ordering}; - static STATE: AtomicU8 = AtomicU8::new(0); - match STATE.load(Ordering::Relaxed) { - 0 => { - let on = std::env::var_os($env).is_some(); - STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); - on - } - 1 => false, - _ => true, - } - } - }; -} - -// Per-block dump gate for the inter-syntax lane (scratch harnesses); -// a candidate-list dump (`mode == NEWMV` only); -// a search-position cell + grid-store dump; and a post-compressed-header -// MV probability table dump. (Plain comments: a doc comment on a macro -// invocation is an "unused doc comment" warning.) -cached_gate!(interdump_enabled, "EC_VP9_INTERDUMP"); -cached_gate!(mvdbg_enabled, "EC_VP9_MVDGB"); -cached_gate!(mvdbg2_enabled, "EC_VP9_MVDGB2"); -cached_gate!(mvdump_enabled, "EC_VP9_MVDUMP"); -// [scratch] per-transform-block token state (the inter pixel lane). -cached_gate!(tokdbg_enabled, "EC_VP9_TOKDGB"); -cached_gate!(lfmasksy_enabled, "EC_VP9_LFMASKSY"); diff --git a/crates/ec-vp9/src/loopfilter.rs b/crates/ec-vp9/src/loopfilter.rs index ba33ece5..8f2af9b7 100644 --- a/crates/ec-vp9/src/loopfilter.rs +++ b/crates/ec-vp9/src/loopfilter.rs @@ -20,26 +20,6 @@ use crate::tables::*; -/// `LFTRACE` gate, optionally limited to one frame by `EC_VP9_LF_FRAME` -/// (the n-th `filter_frame` call of the process — the decode order's frame -/// index). The oracle's own LF trace is gated the same way, which is what lets -/// the two edge lists be diffed per frame. -fn lftrace_on() -> bool { - use std::sync::atomic::{AtomicUsize, Ordering}; - if std::env::var_os("LFTRACE").is_none() { - return false; - } - static CALLS: AtomicUsize = AtomicUsize::new(0); - let n = CALLS.fetch_add(1, Ordering::Relaxed); - match std::env::var("EC_VP9_LF_FRAME") - .ok() - .and_then(|v| v.parse::().ok()) - { - Some(f) => f == n, - None => true, - } -} - /// `vp9_loopfilter.c` UV mask tables (BLOCK_SIZES indexed 4X4..64X64). const UV_LEFT_PRED: [u16; 13] = [ 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0011, 0x0001, 0x0011, 0x1111, 0x0011, @@ -582,22 +562,6 @@ impl LfGrids { } // [scratch] EC_VP9_LFMASKSY: per-superblock luma masks after // `vp9_adjust_mask`, in the oracle's `LFMASKSY` field order. - if crate::lfmasksy_enabled() { - eprintln!( - "LFY {} {} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - sbr, - sbc, - left[TX_4X4], - left[TX_8X8], - left[TX_16X16], - left[TX_32X32], - above[TX_4X4], - above[TX_8X8], - above[TX_16X16], - above[TX_32X32], - int4 - ); - } (left, above, int4) } @@ -632,9 +596,7 @@ impl LfGrids { h: usize, sharpness: u8, bd: u8, - trace: bool, ) { - let lftrace = trace && lftrace_on(); // Luma masks, ported from vp9_setup_mask/build_masks and // vp9_adjust_mask (bit i = MI row i>>3, MI col i&7; each bit // covers an 8x8 cell). Edges are emitted from the masks. @@ -676,20 +638,9 @@ impl LfGrids { t = 8; } lpf_edge(data, yy * stride + xx, stride, 1, t, bl, li, th, 8, bd); - if lftrace { - let kind = match t { - 16 => "V16", - 8 => "V8", - _ => "V4", - }; - eprintln!("{kind} {} {}", xx, yy); - } } if int4 & bit != 0 && xx + 8 <= w && yy + 8 <= h { lpf_edge(data, yy * stride + xx + 4, stride, 1, 4, bl, li, th, 8, bd); - if lftrace { - eprintln!("V4I {} {}", xx + 4, yy); - } } } } @@ -725,14 +676,6 @@ impl LfGrids { t = 8; } lpf_edge(data, yy * stride + xx, stride, 0, t, bl, li, th, 8, bd); - if lftrace { - let kind = match t { - 16 => "H16", - 8 => "H8", - _ => "H4", - }; - eprintln!("{kind} {} {}", xx, yy); - } } } // Internal 4x4 luma edge at yy + 4. libvpx's luma @@ -754,9 +697,6 @@ impl LfGrids { 8, bd, ); - if lftrace { - eprintln!("H4I {} {}", xx, yy + 4); - } } } } @@ -1277,8 +1217,8 @@ impl LfGrids { // output is identical to the serial order. let chroma = |data_u: &mut [Sample], data_v: &mut [Sample]| { if ss_x == 0 && ss_y == 0 { - self.filter_ss00_plane(data_u, uv_stride, uv_w, uv_h, sharpness, bd, false); - self.filter_ss00_plane(data_v, uv_stride, uv_w, uv_h, sharpness, bd, false); + self.filter_ss00_plane(data_u, uv_stride, uv_w, uv_h, sharpness, bd); + self.filter_ss00_plane(data_v, uv_stride, uv_w, uv_h, sharpness, bd); } else if ss_x == 1 && ss_y == 1 { self.filter_ss11_plane(data_u, uv_stride, uv_h, sharpness, bd); self.filter_ss11_plane(data_v, uv_stride, uv_h, sharpness, bd); @@ -1289,7 +1229,7 @@ impl LfGrids { }; std::thread::scope(|scope| { scope.spawn(|| chroma(u, v)); - self.filter_ss00_plane(y, stride, y_w, y_h, sharpness, bd, true); + self.filter_ss00_plane(y, stride, y_w, y_h, sharpness, bd); }); } } diff --git a/crates/ec-vp9/src/modes.rs b/crates/ec-vp9/src/modes.rs index afe18879..357f11b2 100644 --- a/crates/ec-vp9/src/modes.rs +++ b/crates/ec-vp9/src/modes.rs @@ -278,11 +278,5 @@ pub(crate) fn read_intra_frame_mode_info( // uv mode: `vp9_kf_uv_mode_prob` indexed by y mode, decoded with the // SAME intra_mode_tree (decodemv.c:232 calls read_intra_mode). mi.uv_mode = r.read_tree(&INTRA_MODE_TREE, &kf_uv_probs(mi.mode)); - if crate::trace_enabled() { - eprintln!( - "MODE row={} col={} bsize={} skip={} tx={} y={} uv={}", - row, col, sb_type, mi.skip as u8, mi.tx_size, mi.mode, mi.uv_mode - ); - } Ok(mi) } diff --git a/crates/ec-vp9/src/prof.rs b/crates/ec-vp9/src/prof.rs deleted file mode 100644 index c3ec9271..00000000 --- a/crates/ec-vp9/src/prof.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! Phase timers for the decoder, enabled by `EC_VP9_PROFILE=1`. -//! -//! Each phase accumulates CPU nanoseconds across all threads (atomic adds), so with -//! tile threads the sums can exceed wall time. Off by default: `start` is then one -//! relaxed atomic load and no clock read. - -use std::sync::atomic::{AtomicU64, AtomicU8, Ordering}; -use std::time::Instant; - -/// Phases, indexes into [`TOTALS`]. -#[derive(Clone, Copy)] -pub(crate) enum Phase { - /// Whole tile walk (parse plus reconstruction). - Walk = 0, - /// Inter prediction (motion compensation) for all planes of a block. - Mc = 1, - /// Coefficient token decoding. - Tokens = 2, - /// Inverse transform and add. - Idct = 3, - /// Loop filter over the whole frame. - LoopFilter = 4, - /// Tile-thread overhead: worker state setup and copying columns back. - Threads = 5, -} - -/// Names for [`report`], in [`Phase`] order. -pub const NAMES: [&str; 6] = ["walk", "mc", "tokens", "idct", "loopfilter", "threads"]; - -static TOTALS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; - -/// Whether `EC_VP9_PROFILE` turned the timers on (read once per process). -pub fn enabled() -> bool { - static STATE: AtomicU8 = AtomicU8::new(0); - match STATE.load(Ordering::Relaxed) { - 0 => { - let on = std::env::var_os("EC_VP9_PROFILE").is_some_and(|v| v != "0"); - STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); - on - } - s => s == 2, - } -} - -/// Start a timer; `None` when profiling is off. -pub(crate) fn start() -> Option { - if enabled() { - Some(Instant::now()) - } else { - None - } -} - -/// Add the time since `t` to `phase`. -pub(crate) fn stop(phase: Phase, t: Option) { - if let Some(t) = t { - TOTALS[phase as usize].fetch_add(t.elapsed().as_nanos() as u64, Ordering::Relaxed); - } -} - -/// Accumulated seconds per phase, in [`NAMES`] order. -pub fn totals() -> [f64; 6] { - std::array::from_fn(|i| TOTALS[i].load(Ordering::Relaxed) as f64 * 1e-9) -} diff --git a/crates/ec-vp9/src/stack_budget.rs b/crates/ec-vp9/src/stack_budget.rs deleted file mode 100755 index 56b45524..00000000 --- a/crates/ec-vp9/src/stack_budget.rs +++ /dev/null @@ -1,748 +0,0 @@ -#![cfg(test)] -//! A measured bound on the crate's BY-VALUE types, and a gate that bites. -//! -//! # The class -//! -//! A large struct returned BY VALUE from a public constructor is a stack -//! cost, not a heap cost, and the cost is paid by the CALLER. The -//! constructors nest, and in an unoptimized build each level materialises -//! its whole `Result` return slot before the inner call returns. So one -//! value's `size_of` is the MULTIPLIER, and the chain length is the other -//! factor. -//! -//! That is not hypothetical. `Decoder` was **10,944** bytes by value -- -//! five INLINE `FrameContext` slots (2,039 bytes each: the `frame_ctxs` -//! array of four, plus the `ctx` in force) -- and 10,944 is **1.34x** this -//! crate's 8 KiB by-value budget. Boxing both fields -//! (`frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box`) took -//! it to **768**, and [`the_frame_contexts_stay_behind_a_box`] is the pin -//! that keeps it there. -//! -//! # Why this module exists -//! -//! One boxed field is one measurement. This module is the sweep: -//! -//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a -//! public `fn` can return by value, with a measured `size_of` recorded -//! as of this commit. [`the_measured_inventory_is_accurate`] fails if a -//! type's size moves, so the table cannot rot into stale small numbers. -//! 2. [`STACK_BUDGET`] is the bound, and -//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for -//! every public row, so a regression reds naming the type. -//! 3. [`the_frame_contexts_stay_behind_a_box`] pins the boxed field, with -//! a negative control so the pin cannot be matching a comment. -//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the -//! capability arm: it really constructs `Decoder` on a deliberately -//! tight thread and asserts real post-construction state, pinning the -//! measured live stack of the by-value return path. At 256 KiB it does -//! NOT red the unboxing mutation -- a 10,944-byte struct is not that -//! expensive; the budget assert and the box pin are what red, BY NAME. -//! The arm's own docs carry the measured threshold table. -//! 5. [`every_by_value_public_return_is_in_the_inventory`] re-derives the -//! set of by-value public returns from the crate source. -//! [`the_inventory_scan_is_not_vacuous`] is its control. -//! -//! # The bound, and why this number -//! -//! [`STACK_BUDGET`] = 8192 bytes (8 KiB) -- the SAME number as ec-av1's, -//! deliberately, so one bound covers the by-value class across the codec -//! crates rather than each crate calibrating its own. -//! -//! **The quantity being bounded.** Not `size_of` in the abstract, but -//! *what a caller can be made to owe*: the size of one by-value return, -//! multiplied by how many public levels hold a copy at once. Three inputs: -//! 1. **The smallest stack a caller can hand this crate is 2 MiB.** That -//! is libtest's default test thread and what `std::thread::Builder` -//! hands a caller who does not ask for a size. A library consumer gets -//! no `.cargo/config.toml` -- and this repo's sets -//! `RUST_MIN_STACK = 67108864`, which HIDES the problem from this -//! workspace's own runs. The bound is therefore derived against the -//! 2 MiB an unconfigured caller really has. -//! 2. **The deepest PUBLIC by-value chain is 3** -//! ([`DEEPEST_PUBLIC_CHAIN`]): `stream::decode_stream` (stream.rs:74) -//! -> `stream::decode_stream_with` (stream.rs:88) -> -//! `Decoder::decode` (decode.rs:238), after which the remaining frames -//! (`decode_one`, `decode_keyframe`, `decode_inter`) are private. The -//! test asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- the -//! by-value return slots may claim at most an EIGHTH of a caller's -//! stack, leaving the rest for the decode walk, which is the thing that -//! actually needs it. -//! 3. **The budget applies only to types a `pub fn` returns.** The -//! crate-private 2,039-byte `FrameContext` is measured and listed but -//! NOT bounded, because no caller can reach it by value -- every field -//! holding one is a `Box`, pinned by -//! [`the_frame_contexts_stay_behind_a_box`]. Bounding it would -//! calibrate the number to something unreachable. -//! -//! **Where the number sits.** At 8 KiB with the worst public return at -//! 768 bytes ([`Decoder`]), the worst a caller owes on return slots -//! alone is `3 x 768 = 2,304` bytes -- 0.11% of a 2 MiB thread, and the -//! budget itself is 10.7x the largest live by-value type. Both directions -//! have room, which is the point: a bound the largest type sits just -//! under is a bound the next lane will quietly raise. -//! -//! **What it catches.** The pre-fix `Decoder` (10,944 B) is **1.34x over** -//! -- the SMALLEST over-budget case of the three crates this sweep has -//! measured (ec-av1's pre-fix `Av1Encoder` was 17.1x over, ec-ac3's -//! pre-fix `Ac3Decoder` 2.43x). It still reds, and by a factor rather than -//! a hair, which is all a bound has to do. -//! -//! # This crate's inventory is SMALL, and that is a measurement -//! -//! ec-av1's floor for bound-checked public rows is 10. **ec-vp9 genuinely -//! has 3** ([`Decoder`], [`Picture`], [`BoolDecoder`]) and the floor is -//! lowered to 3 rather than padded with types this crate does not have. -//! The reason is structural, not accidental: every other module here -//! (`inter`, `mc`, `modes`, `tokens`, `transform`, `loopfilter`, `intra`, -//! `header`, `tables`) exposes ZERO `pub fn` -- its API is -//! `pub(crate)`, reached through `Decoder`. There are 13 `pub fn` lines -//! in the whole crate, 11 of which return a primitive, a `Self`, or -//! `()`. -//! -//! The sweep is still worth having at that size, and the reason is -//! direction of travel: the scan found exactly ONE by-value public return -//! name (`Picture`, from `Decoder::decode`), because `Decoder::new` -//! returns `Self` and `BoolDecoder::new` returns `Result`, both of -//! which the matcher exempts. A tiny inventory is a floor to grow into, -//! and [`every_by_value_public_return_is_in_the_inventory`] is what makes -//! a new 40 KB by-value return impossible to add unnoticed -- which is the -//! only direction that can actually bite here. -//! -//! # What it does not claim -//! -//! `size_of` is layout, not stack depth. The residual is why -//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs -//! for real instead of trusting the arithmetic. And note -//! [`the_frame_contexts_stay_behind_a_box`] pins ONE field: `Decoder::ctx` -//! (decode.rs:129) is still an INLINE `FrameContext`, and at 2,039 bytes -//! it is 72.8% of the 2,800 a caller pays today. Boxing that too is the -//! obvious next move in this class; this module only records the -//! measurement. - -use crate::bool::BoolDecoder; -use crate::decode::{Decoder, Picture}; - -/// The per-type ceiling for a type a CALLER can be made to hold by value, in -/// bytes. See the module docs for the derivation; it is two-sided, and both -/// sides are measured. -pub(crate) const STACK_BUDGET: usize = 8192; - -/// The deepest PUBLIC by-value chain in this crate, counted from the source: -/// `stream::decode_stream` (stream.rs:74) -> `stream::decode_stream_with` -/// (stream.rs:88) -> `Decoder::decode` (decode.rs:238) is three public -/// levels, after which `decode_one` / `decode_keyframe` / `decode_inter` -/// are private. The budget is checked against three. -/// -/// The by-value return slots IN that chain are all small -/// (`Result>`, `Result<()>`, `Result>`); the -/// 2,800-byte `Decoder` is a by-value LOCAL in `decode_stream_with` that -/// stays live across the inner `decode` calls. Multiplying the chain by the -/// crate's worst public return is the conservative direction, and is what -/// [`every_by_value_type_fits_the_stack_budget`] asserts. -#[cfg(test)] -const DEEPEST_PUBLIC_CHAIN: usize = 3; - -/// Every type in this crate a public `fn` can return BY VALUE, with the -/// `size_of` measured at the commit that wrote this table. `None` means "not -/// yet measured", which [`the_measured_inventory_is_accurate`] rejects. -/// -/// The third column names the return path, so a reader can see why a type is -/// here rather than a coincidence of the type system. -pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ - // -- knobs.rs --------------------------------------------------------- - ( - "Override", - Some(16), - true, - "knobs::set_skip_lf / set_force_tail -> test-only guard that puts an \ - EC_VP9 debug switch back on drop. A boxed restore closure, so one \ - type covers every knob.", - ), - // -- decode.rs -------------------------------------------------------- - ( - "Decoder", - Some(800), - true, - "Decoder::new -> Self (and `Default::default`), the crate's whole \ - public surface. Was 10944 with five inline FrameContext slots \ - (10,195 of it), 1.34x over budget; frame_ctxs and ctx are both \ - Boxes now. Boxing frame_ctxs ALONE left 2800 -- under budget, but \ - with ctx still inline that was 72.8% of it", - ), - ( - "Picture", - Some(96), - true, - "Decoder::decode -> Result>. Its fields ARE pub \ - (y/u/v are Vec), but it is thin -- three Vecs are three \ - heap pointers, so the 96 bytes are a stack cost of three words, \ - not of frame data", - ), - // -- bool.rs ---------------------------------------------------------- - ( - "BoolDecoder", - Some(40), - true, - "bool::BoolDecoder::new(data) -> Result; the sole public \ - by-value return in the crate besides Picture, and the only type a \ - caller can hold by value outside the decode surface", - ), - // -- crate-private: never a public return, and the one that was - // -- inline is behind a Box now. The budget does not apply; the pin - // -- that does is `the_frame_contexts_stay_behind_a_box`. - ( - "FrameContext", - Some(2039), - false, - "header::FrameContext is pub(crate) and the payload of BOTH \ - `frame_ctxs: Box<[FrameContext; 4]>` and `ctx: Box`; \ - five inline were 10195 of the pre-fix 10944. No FrameContext is \ - stored inline in Decoder any more", - ), -]; - -/// The live `size_of` for every inventoried type, keyed BY NAME. -/// -/// Keyed rather than positional on purpose: a row inserted into -/// [`BY_VALUE_TYPES`] without a matching insert here would zip cleanly and -/// assert the wrong type's size against the wrong recorded one. A name key -/// makes that mistake loud instead. -#[cfg(test)] -fn measured_by_name() -> Vec<(&'static str, usize)> { - vec![ - ("Decoder", std::mem::size_of::()), - ("Picture", std::mem::size_of::()), - ("Override", std::mem::size_of::()), - ("BoolDecoder", std::mem::size_of::>()), - ( - "FrameContext", - std::mem::size_of::(), - ), - ] -} - -/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] -/// constructs on. -/// -/// 256 KiB: an eighth of what an unconfigured caller hands this crate, and -/// far above what a 2,800-byte by-value `Decoder` needs in a debug build -/// (the threshold is swept with `EC_VP9_TIGHT_STACK_BYTES`). -const TIGHT_STACK: usize = 256 * 1024; - -#[cfg(test)] -mod tests { - use super::{ - BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, - }; - use crate::bool::BoolDecoder; - use crate::decode::Decoder; - - /// Return types that are not a by-value copy of anything the caller has - /// to own: a pointer, a slice, a `Vec` (three words, and the heap is - /// not the stack), or a primitive. `Self` is a by-value copy of the - /// impl's type, which the inventory rows already cover, so it is exempt - /// from the scan and not from the table. - const THIN: &[&str] = &[ - "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", - "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", - "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", - ]; - - /// The type name a `pub fn` line returns BY VALUE, or `None` when the - /// line returns a pointer, a `Vec`, a primitive, or nothing. - /// - /// One function, shared by the sweep and its control, so the control - /// cannot pass while the sweep's copy of the logic rotted. - fn by_value_return_name(line: &str) -> Option { - let trimmed = line.trim_start(); - if !trimmed.starts_with("pub fn ") { - return None; - } - let arrow = line.find("->")?; - let rest = &line[arrow + 2..]; - let end = rest.find('{').unwrap_or(rest.len()); - let ret = rest[..end].trim(); - if ret.is_empty() { - return None; - } - // Unwrap the `Result<..>` / `Option<..>` layers. ec-av1 unwraps one; - // this crate needs the loop, because its ONE by-value public return - // is spelled `Result>` (decode.rs:238) and a - // single unwrap reads that as the name "Option" -- an uninventoried - // non-type that would have made the sweep permanently red for a - // reason that has nothing to do with the class. - let mut inner = ret; - loop { - let stripped = inner - .strip_prefix("Result<") - .or_else(|| inner.strip_prefix("Option<")); - match stripped { - Some(t) => { - let head = t.split('>').next().unwrap_or(t); - if head.is_empty() { - return None; - } - inner = head; - } - None => break, - } - } - // Drop the error type and any lifetime or generic argument: - // `Result`, `BoolDecoder<'a>` and `Picture` are all - // the bare name for this purpose. Splitting on the comma is - // load-bearing: the first version of this matcher cut only at `>` - // and so read `Result` as the name - // "Decoder, Error". - let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); - if name.is_empty() || THIN.contains(&name) { - return None; - } - // A generic parameter, not a concrete type. - if !name.chars().next().is_some_and(char::is_uppercase) { - return None; - } - Some(name.to_string()) - } - - /// The source files the by-value scan reads. Every module `lib.rs` - /// declares, plus this one; a new module added to `lib.rs` needs - /// adding here, and [`every_by_value_module_is_scanned`] is what keeps - /// that honest. - /// - /// The label is the path relative to `src/`, so a directory module is - /// `tables/mod.rs` rather than `tables.rs`. - const FILES: &[(&str, &str)] = &[ - ("adapt.rs", include_str!("adapt.rs")), - ("bool.rs", include_str!("bool.rs")), - ("decode.rs", include_str!("decode.rs")), - ("header.rs", include_str!("header.rs")), - ("inter.rs", include_str!("inter.rs")), - ("intra.rs", include_str!("intra.rs")), - ("loopfilter.rs", include_str!("loopfilter.rs")), - ("knobs.rs", include_str!("knobs.rs")), - ("mc.rs", include_str!("mc.rs")), - ("modes.rs", include_str!("modes.rs")), - ("prof.rs", include_str!("prof.rs")), - ("stream.rs", include_str!("stream.rs")), - ("tables/mod.rs", include_str!("tables/mod.rs")), - ("tokens.rs", include_str!("tokens.rs")), - ("transform.rs", include_str!("transform.rs")), - ("stack_budget.rs", include_str!("stack_budget.rs")), - ]; - - /// Every module `lib.rs` declares, so the scan's file list cannot - /// silently fall behind a new module. A new `mod foo;` with a - /// by-value `pub fn` that the scan never reads is exactly the hole - /// this class would come back through, so the list is derived, not - /// curated. - #[test] - fn every_by_value_module_is_scanned() { - let lib = include_str!("lib.rs"); - let mut declared: Vec<&str> = Vec::new(); - for line in lib.lines() { - let t = line.trim(); - let rest = t - .strip_prefix("pub mod ") - // This crate's `inter` and `mc` are `pub(crate) mod`, a - // spelling ec-av1 has no instance of. They are declared - // modules and are scanned, so they must be derived here - // too -- otherwise the check below is blind to exactly - // the two files a future by-value return would most - // likely land in. - .or_else(|| t.strip_prefix("pub(crate) mod ")) - .or_else(|| t.strip_prefix("mod ")) - .unwrap_or(""); - if rest.is_empty() { - continue; - } - let name = rest.split([';', ' ']).next().unwrap_or(""); - if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - declared.push(name); - } - } - // 12 modules (incl. the `pub(crate)` ones -- `inter`, `mc`) plus - // this one. The floor is a REACH floor: below it the parse is - // broken, not the crate small. - assert!( - declared.len() >= 13, - "only {} module declarations parsed out of lib.rs, so the derived \ - file list is broken rather than small", - declared.len() - ); - let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); - let mut missing: Vec = declared - .iter() - .filter(|d| { - let flat = format!("{d}.rs"); - let dir = format!("{d}/mod.rs"); - !scanned.iter().any(|s| *s == flat || *s == dir) - }) - .map(|d| (*d).to_string()) - .collect(); - missing.sort(); - assert!( - missing.is_empty(), - "lib.rs declares modules the by-value scan never reads: {:?}. Add \ - them to FILES, or the sweep cannot see a new by-value return that \ - lands in one of them.", - missing - ); - } - - /// The inventory, printed as a sorted table, and checked against the - /// types' real sizes. - /// - /// The print is the instrument: one command - /// (`cargo test -p ec-vp9 --lib -- stack_budget -- --nocapture`) - /// reproduces the whole table, biggest first, so "what is the largest - /// by-value type in this crate" has an answer that is a measurement - /// rather than a grep. - /// - /// The check reds on ANY change with both numbers. That is deliberate: a - /// by-value type that grew raises the question of whether it should - /// have been boxed instead, and auto-accepting the new number would - /// answer that question by default. - #[test] - fn the_measured_inventory_is_accurate() { - let live = measured_by_name(); - assert_eq!( - BY_VALUE_TYPES.len(), - live.len(), - "the inventory names {} types but {} are measured; every row needs \ - a measured size or the sweep is a list of hopes", - BY_VALUE_TYPES.len(), - live.len() - ); - let mut rows: Vec<(&str, usize)> = live.clone(); - rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); - eprintln!( - "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", - rows.len(), - STACK_BUDGET / 1024 - ); - eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET"); - for (name, size) in &rows { - eprintln!( - "{size:>8} {:>6.1}% {name}", - *size as f64 * 100.0 / STACK_BUDGET as f64 - ); - } - for (name, recorded, _public, _path) in BY_VALUE_TYPES { - let recorded = recorded.expect("every inventory row carries a measured size"); - let actual = live - .iter() - .find(|(n, _)| n == name) - .map(|(_, size)| *size) - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); - assert_eq!( - recorded, actual, - "{name} is {actual} bytes, the inventory records {recorded}; \ - update the table deliberately -- a by-value type that changed \ - is a stack cost every caller of its constructor now pays" - ); - } - } - - /// The bound, asserted BY NAME. A regression in any inventoried type - /// reds here naming the type, not "some type is too big". - #[test] - fn every_by_value_type_fits_the_stack_budget() { - let live = measured_by_name(); - let mut checked = 0usize; - for (name, _, public, path) in BY_VALUE_TYPES { - if !public { - continue; - } - checked += 1; - let size = live - .iter() - .find(|(n, _)| n == name) - .map(|(_, size)| *size) - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); - assert!( - size <= STACK_BUDGET, - "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ - stack budget ({:.2}x). It is returned by value from {path}, so \ - every caller pays it on its own stack. Box the large field \ - (frame_ctxs: Box<[FrameContext; 4]> did exactly this for \ - Decoder, 10944 -> 2800) or hand back a reference.", - size as f64 / STACK_BUDGET as f64 - ); - } - // ec-av1's floor is 10. THIS CRATE HAS 4, and that is a measurement, - // not a gap to pad: every module but `bool`, `decode`, `knobs` and - // `stream` exposes zero `pub fn` (its API is `pub(crate)`, reached - // through `Decoder`). Inventing rows to reach ec-av1's number would - // make the gate theatre -- it would count types no caller can reach. - // `knobs::Override` is the fourth: the test-only guard the knob - // setters return. - assert!( - checked == 4, - "{checked} public rows were bound-checked, and this crate has \ - exactly 4 types a caller can hold by value (Decoder, Picture, \ - BoolDecoder, knobs::Override). If a fifth appeared, measure it, \ - add it to BY_VALUE_TYPES, and raise this floor with it; if a row was \ - removed, the count is wrong here and in the inventory." - ); - // The other half of the derivation, asserted so it cannot rot: the - // worst a caller can owe is DEEPEST_CHAIN x the worst public return. - let worst = live - .iter() - .filter(|(n, _)| { - BY_VALUE_TYPES - .iter() - .any(|(row, _, public, _)| row == n && *public) - }) - .map(|(_, size)| *size) - .max() - .expect("at least one public row"); - assert!( - DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, - "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ - public by-value return ({worst} B) is {} B, over an eighth of the \ - 2 MiB stack an unconfigured caller hands this crate; \ - re-derive STACK_BUDGET", - DEEPEST_PUBLIC_CHAIN * worst - ); - } - - /// The four stored frame contexts stay BEHIND A BOX. - /// - /// The budget does not apply to `header::FrameContext` (2,039 B) because - /// no `pub fn` returns it, so bounding it would calibrate the number to - /// something no caller can reach. What keeps four of them off a - /// caller's stack is that the array is a `Box`, and THIS is the pin. - /// - /// It earned its place twice. `Decoder` was 10,944 B, of which 8,156 was - /// `frame_ctxs: [FrameContext; 4]` sitting inline -- 1.34x over budget. - /// Boxing the array alone left 2,800, of which `ctx` was 2,039 (72.8%): - /// under the budget, but with a single field carrying nearly all of it. - #[test] - fn the_frame_contexts_stay_behind_a_box() { - const PINS: &[(&str, &str)] = &[ - // The field declarations (decode.rs:134, decode.rs:139). - ("frame_ctxs: Box<[FrameContext; 4]>", "the frame_ctxs field"), - ("ctx: Box", "the ctx field"), - // Their construction in `Decoder::new` (decode.rs:216, 221). - ( - "Box::new([d.clone(), d.clone(), d.clone(), d])", - "Decoder::new", - ), - ("ctx: Box::new(FrameContext::new(true))", "Decoder::new"), - ]; - const SRC: &str = include_str!("decode.rs"); - for (spelling, where_) in PINS { - assert!( - SRC.contains(spelling), - "decode.rs::{where_} is no longer declared `{spelling}`. An \ - inline `FrameContext` there puts 2039 bytes back into every \ - caller's stack -- five of them were 10195 bytes, which is how \ - `Decoder` was 10944 bytes and 1.34x over the by-value budget \ - before the boxes.", - ); - } - // And the negative control: the unboxed spelling must NOT still be - // present, or the scan above would be matching a comment. - assert!( - !SRC.contains("frame_ctxs: [FrameContext; 4],") && !SRC.contains("ctx: FrameContext,"), - "decode.rs still spells a FrameContext field inline, so the box \ - pin above is matching a spelling that is not the live declaration" - ); - } - - /// CAPABILITY: really construct the heavy type on a tight stack, so a - /// regression ABORTS THE PROCESS instead of costing invisible margin. - /// - /// `Decoder::new` is the crate's one large by-value return path, and it - /// is also the one whose boxing moved the threshold. - /// - /// **What this arm does and does not catch, measured.** Swept in an - /// unoptimized build, one process per point: - /// - /// | stack | pre-fix (unboxed, 10,944 B) | boxed (2,800 B) | - /// |---|---|---| - /// | 16384 | overflow | overflow | - /// | 24576 | overflow | overflow | - /// | 32768 | overflow | **ok** | - /// | 40960 | **ok** | ok | - /// | 262144 (the gate) | **ok** | ok | - /// - /// So the boxing moved the threshold from 40,960 to 32,768 -- real, and - /// HONESTLY SMALL: a 10,944-byte struct does not need a small stack to - /// overflow. **The unboxing mutation does NOT red this arm at 256 KiB.** - /// It reds [`every_by_value_type_fits_the_stack_budget`] (named, with - /// the 1.34x factor) and [`the_frame_contexts_stay_behind_a_box`] - /// instead. This arm is the capability floor -- it pins the real live - /// stack of the crate's by-value return path, which the arithmetic in - /// the other two tests does not model -- and it is deliberately set - /// well clear of the measured 32,768 B so an unoptimised-build - /// regression in stack need shows up here as a margin loss rather than - /// as a mysterious abort. Reproduce either column with - /// `EC_VP9_TIGHT_STACK_BYTES`. - /// - /// The env read is a raw `std::env::var`, not the crate's `cached_gate!` - /// macro: `cached_gate!` answers PRESENCE and caches a bool, and this - /// override needs a VALUE, read once per test run and never on a decode - /// path. Using the hot-path convention for a cold, value-shaped read - /// would be the wrong tool. - #[test] - fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { - let stack: usize = std::env::var("EC_VP9_TIGHT_STACK_BYTES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(TIGHT_STACK); - let handle = std::thread::Builder::new() - .stack_size(stack) - .spawn(|| { - // The by-value return path: a whole `Decoder` built and - // returned from `new` on a 256 KiB stack. - let decoder = Decoder::new(); - // Real post-construction state, not just "did not crash": a - // fresh decoder has parsed no inter frame and produced no - // blocks, and the four boxed frame contexts are addressable - // and distinct from the live `ctx`. - let blocks = decoder.last_frame_blocks(); - let bools = BoolDecoder::new(&[]).expect("BoolDecoder::new on an empty partition"); - let overreads = bools.overreads(); - (blocks, overreads, std::mem::size_of::()) - }) - .expect("spawn tight-stack thread"); - let (blocks, overreads, size) = handle.join().unwrap_or_else(|_| { - panic!( - "Decoder::new overflowed a {stack}-byte stack; that is what the \ - pre-fix 10944-byte by-value layout costs a caller" - ) - }); - assert_eq!( - blocks, 0, - "a freshly constructed Decoder reports {blocks} last-frame blocks" - ); - assert_eq!( - overreads, 0, - "an empty BoolDecoder partition reports {overreads} overreads" - ); - eprintln!("TIGHTSTACK {stack} bytes: Decoder={size} B, constructed and returned"); - } - - /// The sweep's teeth against a NEW by-value return: re-derive the set - /// from the crate source and require every name to be inventoried. - /// - /// Without this the inventory is a list of what someone remembered to - /// measure, and a lane that adds `pub fn make() -> HugeThing` where - /// `HugeThing` is 200 KB of inline tables passes every other test here. - #[test] - fn every_by_value_public_return_is_in_the_inventory() { - let mut found: Vec<(String, String)> = Vec::new(); - let mut pub_fn_lines = 0usize; - for (file, src) in FILES { - for (n, line) in src.lines().enumerate() { - if line.trim_start().starts_with("pub fn ") { - pub_fn_lines += 1; - } - if let Some(name) = by_value_return_name(line) { - found.push((name, format!("{file}:{}", n + 1))); - } - } - } - found.sort(); - found.dedup(); - // A REACH floor, not a size floor: ec-av1 asserts > 5 names because - // it has 20 KB of encoders. This crate has 13 `pub fn` lines in - // total, 11 of which return a primitive / `Self` / `()`, so the - // one by-value public return it really has is `Picture`. Asserting - // a bigger number would be asserting a fact about ec-av1. - assert!( - pub_fn_lines >= 10, - "the scan saw only {pub_fn_lines} `pub fn` lines across {} files, \ - too few to be a real sweep -- the matcher, not the crate, is \ - broken", - FILES.len() - ); - assert!( - !found.is_empty(), - "the by-value return scan found NO name across {} files and {} \ - `pub fn` lines; `Decoder::decode -> Result>` \ - (decode.rs:238) must be in there, so the matcher is broken", - FILES.len(), - pub_fn_lines - ); - - let mut missing = Vec::new(); - for (name, site) in &found { - if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { - missing.push(format!("{name} ({site})")); - } - } - assert!( - missing.is_empty(), - "these types are returned BY VALUE from a public fn and are not in \ - the inventory: {}. Either they are thin enough not to be a stack \ - cost -- say so by adding a row with its measured size -- or they \ - are the next instance of the class this module exists for.", - missing.join(", ") - ); - eprintln!( - "BYVALUE-SCAN {} `pub fn` lines, {} by-value public return name(s): {:?}", - pub_fn_lines, - found.len(), - found - ); - } - - /// The control for the scan above, on synthetic text rather than by - /// trusting the live tree to happen to contain a case. - /// - /// If the matcher silently stopped recognising a shape, the sweep would - /// pass everything and this would still be asserting nothing. So: every - /// by-value spelling this crate uses must yield its type name, and every - /// pointer/Vec/primitive/`Self` spelling must yield nothing. - #[test] - fn the_inventory_scan_is_not_vacuous() { - for synthetic in [ - "pub fn zz_a() -> ZzNotInventoried { todo!() }", - "pub fn zz_b() -> Result { todo!() }", - "pub fn zz_c() -> Result { todo!() }", - "pub fn zz_d() -> Option { todo!() }", - "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", - // The DOUBLE-wrapped shape this crate actually uses, at - // decode.rs:238. A single-layer unwrap reads it as "Option", - // which is not a type and would red the sweep forever. - "pub fn zz_f() -> Result> { todo!() }", - ] { - let name = by_value_return_name(synthetic) - .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); - assert_eq!( - name, "ZzNotInventoried", - "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ - cannot see a new by-value return and its green is vacuous" - ); - assert!( - !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), - "the synthetic control name is in the inventory, so the control \ - proves nothing" - ); - } - for thin in [ - "pub fn zz_t() -> Box { todo!() }", - "pub fn zz_u() -> Result, Error> { todo!() }", - "pub fn zz_v() -> Option<&Path> { todo!() }", - "pub fn zz_w() -> usize { todo!() }", - "pub fn zz_x() -> Self { todo!() }", - "pub fn zz_y() -> Result, Error> { todo!() }", - "pub fn zz_z() { todo!() }", - "fn zz_private() -> ZzNotInventoried { todo!() }", - // The two live spellings this crate exempts on purpose: - // `Vec` is three words and its heap is not the caller's stack. - "pub fn zz_g() -> Result> { todo!() }", - "pub fn zz_h() -> Result { todo!() }", - ] { - assert_eq!( - by_value_return_name(thin), - None, - "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ - above already cover, or not a `pub fn` -- the matcher must not \ - read it as an uninventoried by-value return" - ); - } - } -} diff --git a/crates/ec-vp9/src/tokens.rs b/crates/ec-vp9/src/tokens.rs index caa0146f..79031c9e 100644 --- a/crates/ec-vp9/src/tokens.rs +++ b/crates/ec-vp9/src/tokens.rs @@ -97,12 +97,6 @@ pub(crate) fn decode_coefs( let mut prob: &[u8; 3] = &probs4d[plane_type][usize::from(is_inter)][band][ctx]; while c < max_eob { - if crate::trace_enabled() { - eprintln!( - "TOK c={c} band={band} ctx={ctx} p0={},{},{}", - prob[0], prob[1], prob[2] - ); - } // libvpx `++eob_branch_count[band][ctx]` before the EOB decision. let cell = usize::from(is_inter); counts.eob_branch[tx_size][plane_type][cell][band][ctx] += 1; @@ -179,12 +173,6 @@ pub(crate) fn decode_coefs( dqv = dequant[1] as i32; } coef.eob = c; - if crate::trace_enabled() { - eprintln!( - "EOB p={} x={} y={} tx={} eob={} c0={}", - plane, pos.0, pos.1, tx_size, c, coef.coeffs[0] - ); - } coef } diff --git a/crates/ec-vp9/src/transform.rs b/crates/ec-vp9/src/transform.rs index 4718ee9b..e9aba580 100644 --- a/crates/ec-vp9/src/transform.rs +++ b/crates/ec-vp9/src/transform.rs @@ -762,18 +762,3 @@ pub(crate) fn inverse_transform_add( } } } - -#[cfg(test)] -mod scratch_probe { - use super::*; - #[test] - fn probe_dc38() { - for (name, tt) in [("dct_dct", DCT_DCT), ("dct_adst", DCT_ADST)] { - let mut c = [0i32; 64]; - c[0] = 38; - let mut d = vec![129u16; 64]; - inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false, 8); - println!("{name}: {:?}", &d[..8]); - } - } -} diff --git a/crates/ec-vp9/tests/it/dump_probe.rs b/crates/ec-vp9/tests/it/dump_probe.rs deleted file mode 100644 index 7c7bd665..00000000 --- a/crates/ec-vp9/tests/it/dump_probe.rs +++ /dev/null @@ -1,30 +0,0 @@ -use crate::ivf; -use ec_vp9::decode::Decoder; -#[test] -fn diff_stats() { - let bytes = std::fs::read(ec_testkit::fixture("vp9/key-320.ivf")).unwrap(); - let (_, _, _, frames) = ivf::parse_ivf(&bytes); - let mut d = Decoder::new(); - let pic = d.decode(&frames[0].data).unwrap().unwrap(); - let refout = ec_testkit::ffmpeg() - .args(["-v","error","-i",ec_testkit::fixture("vp9/key-320.ivf").to_str().unwrap(), - "-frames:v","1","-f","rawvideo","-pix_fmt","yuv420p","-"]) - .output().unwrap().stdout; - let w = 320usize; - let mut sb_match = [[0usize; 5]; 4]; - let mut sb_total = [[0usize; 5]; 4]; - let mut first: Option<(usize, usize)> = None; - for y in 0..240 { - for x in 0..320 { - let a = pic.y[y * pic.stride + x] as u8; - let b = refout[y * w + x]; - let (sy, sx) = (y / 64, x / 64); - sb_total[sy][sx] += 1; - if a == b { sb_match[sy][sx] += 1; } else if first.is_none() { first = Some((x, y)); } - } - } - println!("first diff at {:?}", first); - for (i, row) in sb_match.iter().enumerate() { - println!("sb row {i}: {:?}", row.iter().zip(sb_total[i].iter()).map(|(m, t)| format!("{}/{}", m, t)).collect::>()); - } -} diff --git a/crates/ec-vp9/tests/it/scratch_bool.rs b/crates/ec-vp9/tests/it/scratch_bool.rs deleted file mode 100644 index b1176967..00000000 --- a/crates/ec-vp9/tests/it/scratch_bool.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::ivf; -use ec_vp9::bool::BoolDecoder; - -#[test] -fn probe_first_bools() { - let bytes = std::fs::read(ec_testkit::fixture("vp9/lossless-64.ivf")).unwrap(); - let (_, _, _, frames) = ivf::parse_ivf(&bytes); - let frame = &frames[0].data; - println!("slice bytes: {:02x?}", &frame[18..26]); - let mut r = BoolDecoder::new(&frame[18..18 + 113]).unwrap(); - let bits: Vec = (0..8).map(|_| u8::from(r.read_bool(128))).collect(); - println!("first 8 bools(128): {bits:?}"); -} diff --git a/crates/ec-vp9/tests/it/scratch_err.rs b/crates/ec-vp9/tests/it/scratch_err.rs deleted file mode 100644 index 6aca5f15..00000000 --- a/crates/ec-vp9/tests/it/scratch_err.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::ivf; -use ec_vp9::decode::Decoder; -#[test] -fn show_err() { - let bytes = std::fs::read(ec_testkit::fixture("bitstreams/vp9-superframe-altref.ivf")).unwrap(); - let (_, _, _, frames) = ivf::parse_ivf(&bytes); - let mut d = Decoder::new(); - println!("f0 bytes: {:02x?}", &frames[0].data[16..24]); - match d.decode(&frames[0].data) { - Ok(_) => println!("OK"), - Err(e) => println!("ERR: {e}"), - } -} diff --git a/crates/ec-vp9/tests/it/scratch_hdr.rs b/crates/ec-vp9/tests/it/scratch_hdr.rs deleted file mode 100644 index dc39f941..00000000 --- a/crates/ec-vp9/tests/it/scratch_hdr.rs +++ /dev/null @@ -1,22 +0,0 @@ -use ec_vp9_syntax::Vp9Parser; -#[test] -fn hdr_probe() { - for name in ["lossless-64.ivf", "key-320.ivf"] { - let bytes = std::fs::read(ec_testkit::fixture(&format!("vp9/{name}"))).unwrap(); - let fsize = u32::from_le_bytes(bytes[32..36].try_into().unwrap()) as usize; - let frame = &bytes[44..44 + fsize]; - let mut pp = Vp9Parser::new(); - match pp.parse_frame(frame) { - Ok(h) => println!( - "{name}: w={} h={} uhs={} hsib={} lf_level={} sharp={} delta={} base_q={} ydc={} uvdc={} uvac={} seg={} tile={:?} txmode_hdr_bytes={}", - h.width, h.height, h.uncompressed_header_size, h.header_size_in_bytes, - h.loop_filter.level, h.loop_filter.sharpness, h.loop_filter.delta_enabled, - h.quantization.base_q_idx, h.quantization.delta_q_y_dc, - h.quantization.delta_q_uv_dc, h.quantization.delta_q_uv_ac, - h.segmentation.enabled, h.tile_info, - h.header_size_in_bytes - ), - Err(e) => println!("{name}: ERR {e}"), - } - } -} diff --git a/crates/ec-vp9/tests/it/scratch_hdr2.rs b/crates/ec-vp9/tests/it/scratch_hdr2.rs deleted file mode 100644 index a0283f4e..00000000 --- a/crates/ec-vp9/tests/it/scratch_hdr2.rs +++ /dev/null @@ -1,11 +0,0 @@ -use crate::ivf; -use ec_vp9_syntax::Vp9Parser; -#[test] -fn dump_hdr() { - let bytes = std::fs::read(ec_testkit::fixture("vp9/lossless-64.ivf")).unwrap(); - let (_, _, _, frames) = ivf::parse_ivf(&bytes); - let mut p = Vp9Parser::new(); - let h = p.parse_frame(&frames[0].data).unwrap(); - println!("q={:#?} lf={:#?} seg={:#?}", h.quantization, h.loop_filter, h.segmentation); - println!("uh={} hsz={} tile={:#?} w={} h={}", h.uncompressed_header_size, h.header_size_in_bytes, h.tile_info, h.width, h.height); -} diff --git a/crates/ec-vp9/tests/it/scratch_hdr3.rs b/crates/ec-vp9/tests/it/scratch_hdr3.rs deleted file mode 100644 index fc7296cd..00000000 --- a/crates/ec-vp9/tests/it/scratch_hdr3.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::ivf; -use ec_vp9_syntax::Vp9Parser; -#[test] -fn dump_hdr() { - let bytes = std::fs::read(ec_testkit::fixture("bitstreams/vp9-superframe-altref.ivf")).unwrap(); - let (_, _, _, frames) = ivf::parse_ivf(&bytes); - let subs = ec_vp9_syntax::superframe::split(&frames[0].data).unwrap(); - println!("subframes: {}", subs.len()); - let mut p = Vp9Parser::new(); - let h = p.parse_frame(subs[0]).unwrap(); - println!("q={:#?} lf={:#?} seg={:#?}", h.quantization, h.loop_filter, h.segmentation); - println!("uh={} hsz={} tile={:#?} w={} h={}", h.uncompressed_header_size, h.header_size_in_bytes, h.tile_info, h.width, h.height); -} diff --git a/crates/ec-vp9/tests/it/scratch_lfdump.rs b/crates/ec-vp9/tests/it/scratch_lfdump.rs deleted file mode 100644 index cfe9f208..00000000 --- a/crates/ec-vp9/tests/it/scratch_lfdump.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! [scratch] Loop-filter diff map: decode key-320 frame 0 with and without -//! the loop filter (EC_VP9_SKIP_LF=1), print where we disagree with ffmpeg. - -use crate::ivf; - -use ec_vp9::decode::Decoder; - -fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) - .output() - .expect("ffmpeg runs"); - assert!(out.status.success()); - out.stdout -} - -#[test] -fn dump_lf_diff_map() { - let path = - ec_testkit::fixture("vp9/key-320.ivf"); - let bytes = std::fs::read(&path).unwrap(); - let (_f, _w, _h, frames) = ivf::parse_ivf(&bytes); - let reference = ffmpeg_raw_yuv(&path); - - let (w, h) = (320usize, 240usize); - let ysz = w * h; - - // Pre-LF run. - let skip_lf = ec_vp9::knobs::set_skip_lf(Some(true)); - let mut dec = Decoder::new(); - let fi: usize = std::env::var("FRAME") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); - for fr in &frames[..fi] { - dec.decode(&fr.data).expect("decode"); - } - let pic_pre = dec.decode(&frames[fi].data).expect("decode").expect("shown"); - std::fs::write(std::env::temp_dir().join("y_pre_ours.raw"), pic_pre.y[..ysz].iter().map(|&v| v as u8).collect::>()).unwrap(); - std::fs::write(std::env::temp_dir().join("u_pre_ours.raw"), pic_pre.u.iter().map(|&v| v as u8).collect::>()).unwrap(); - std::fs::write(std::env::temp_dir().join("v_pre_ours.raw"), pic_pre.v.iter().map(|&v| v as u8).collect::>()).unwrap(); - drop(skip_lf); - - // Post-LF run (fresh decoder). - let mut dec = Decoder::new(); - for fr in &frames[..fi] { - dec.decode(&fr.data).expect("decode"); - } - let pic_post = dec.decode(&frames[fi].data).expect("decode").expect("shown"); - std::fs::write(std::env::temp_dir().join("y_post_ours.raw"), pic_post.y[..ysz].iter().map(|&v| v as u8).collect::>()).unwrap(); - std::fs::write(std::env::temp_dir().join("u_post_ours.raw"), pic_post.u.iter().map(|&v| v as u8).collect::>()).unwrap(); - std::fs::write(std::env::temp_dir().join("v_post_ours.raw"), pic_post.v.iter().map(|&v| v as u8).collect::>()).unwrap(); - - let fsz = ysz + 2 * (w / 2) * (h / 2); - let ff = &reference[fi * fsz..fi * fsz + ysz]; - let pre = &pic_pre.y[..ysz]; - let post = &pic_post.y[..ysz]; - - let pre_diffs: Vec = (0..ysz).filter(|&i| pre[i] as u8 != ff[i]).collect(); - let post_diffs: Vec = (0..ysz).filter(|&i| post[i] as u8 != ff[i]).collect(); - let lf_changed_ours: Vec = (0..ysz).filter(|&i| pre[i] != post[i]).collect(); - println!("pre-LF diffs vs ffmpeg : {}", pre_diffs.len()); - println!("post-LF diffs vs ffmpeg: {}", post_diffs.len()); - println!("pixels our LF changed : {}", lf_changed_ours.len()); - for &i in post_diffs.iter().take(30) { - println!( - " POST diff ({:3},{:3}) ours {:3} ff {:3} (pre-ours {:3})", - i % w, - i / w, - post[i], - ff[i], - pre[i] - ); - } - for &i in pre_diffs.iter().take(10) { - println!( - " PRE diff ({:3},{:3}) ours {:3} ff {:3}", - i % w, - i / w, - pre[i], - ff[i] - ); - } - - // ASCII map of the top-left 48x32: mark post-LF diffs (#), pre-LF diffs - // (?), pixels only our LF touched (o). - println!("map rows 0..32, cols 0..48 (#=post diff, ?=pre-only, o=our-LF-changed)"); - for y in 0..32 { - let mut line = String::new(); - for x in 0..48 { - let i = y * w + x; - if post_diffs.binary_search(&i).is_ok() { - line.push('#'); - } else if pre_diffs.binary_search(&i).is_ok() { - line.push('?'); - } else if lf_changed_ours.binary_search(&i).is_ok() { - line.push('o'); - } else { - line.push('.'); - } - } - println!("{line}"); - } - // Column/row histograms of post-LF diffs (first 24 of each). - let mut cols = vec![0usize; w]; - let mut rows = vec![0usize; h]; - for &i in &post_diffs { - cols[i % w] += 1; - rows[i / w] += 1; - } - println!( - "diff columns>0: {:?}", - (0..w).filter(|&c| cols[c] > 0).take(24).collect::>() - ); - println!( - "diff rows>0 : {:?}", - (0..h).filter(|&r| rows[r] > 0).take(24).collect::>() - ); - let uv = (w / 2) * (h / 2); - let ff_u = &reference[fi * fsz + ysz..fi * fsz + ysz + uv]; - let ff_v = &reference[fi * fsz + ysz + uv..fi * fsz + ysz + 2 * uv]; - let uw = w / 2; - let u_d: Vec<_> = (0..uv).filter(|&i| pic_post.u[i] as u8 != ff_u[i]).collect(); - let v_d: Vec<_> = (0..uv).filter(|&i| pic_post.v[i] as u8 != ff_v[i]).collect(); - let u_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.u[i] as u8 != ff_u[i]).collect(); - let v_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.v[i] as u8 != ff_v[i]).collect(); - println!("U pre diffs: {} post: {}", u_pre.len(), u_d.len()); - for &i in &u_d { - println!( - " U ({}, {}) pre {} post {} ff {}", - i % uw, - i / uw, - pic_pre.u[i], - pic_post.u[i], - ff_u[i] - ); - } - println!("V pre diffs: {} post: {}", v_pre.len(), v_d.len()); - for &i in &v_d { - println!( - " V ({}, {}) pre {} post {} ff {}", - i % uw, - i / uw, - pic_pre.v[i], - pic_post.v[i], - ff_v[i] - ); - } -} diff --git a/crates/ec-vp9/tests/it/scratch_lossless.rs b/crates/ec-vp9/tests/it/scratch_lossless.rs deleted file mode 100644 index 45c1f52a..00000000 --- a/crates/ec-vp9/tests/it/scratch_lossless.rs +++ /dev/null @@ -1,17 +0,0 @@ -use crate::ivf; -use ec_vp9::decode::Decoder; -#[test] -fn lossless_matches() { - let path = ec_testkit::fixture("vp9/lossless-64.ivf"); - let bytes = std::fs::read(&path).unwrap(); - let (_, w, h, frames) = ivf::parse_ivf(&bytes); - let refout = ec_testkit::ffmpeg() - .args(["-v","error","-i", path.to_str().unwrap(), "-frames:v","1","-f","rawvideo","-pix_fmt","yuv420p","-"]) - .output().unwrap().stdout; - let mut d = Decoder::new(); - let pic = d.decode(&frames[0].data).unwrap().unwrap(); - let ylen = w as usize * h as usize; - let mism: Vec = (0..ylen).filter(|&i| pic.y[i] as u8 != refout[i]).collect(); - println!("w={w} h={h} mismatches={} first={:?} ours={:?} ref={:?}", - mism.len(), mism.first(), mism.first().map(|&i| pic.y[i]), mism.first().map(|&i| refout[i])); -} diff --git a/crates/ec-vp9/tests/it/scratch_pixdump.rs b/crates/ec-vp9/tests/it/scratch_pixdump.rs deleted file mode 100644 index 3c09ee87..00000000 --- a/crates/ec-vp9/tests/it/scratch_pixdump.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Scratch: dump every shown frame's planes for the pixel comparator. -//! -//! `INTER_IVF= EC_VP9_PIXDUMP= cargo test -p ec-vp9 --test scratch_pixdump` -//! -//! Layout matches the oracle: per shown frame, Y (w*h), U and V each -//! (((w+1)/2)*((h+1)/2)) (chroma ceils, so odd extents keep the last column/ -//! row), rows packed to the visible width. - -use ec_vp9::decode::Decoder; - -#[test] -#[ignore = "manual dump: set INTER_IVF and EC_VP9_PIXDUMP"] -fn pixdump() { - let ivf = std::env::var("INTER_IVF").expect("set INTER_IVF"); - let out = std::env::var("EC_VP9_PIXDUMP").expect("set EC_VP9_PIXDUMP"); - let bytes = std::fs::read(&ivf).expect("read ivf"); - let (_, w, h, frames) = parse_ivf(&bytes); - let mut decoder = Decoder::new(); - let mut dump = Vec::new(); - let mut shown = 0usize; - for (i, f) in frames.iter().enumerate() { - match decoder.decode(&f.data) { - Ok(Some(pic)) => { - for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) { - if pic.bit_depth == 8 { - dump.push(v as u8); - } else { - dump.extend_from_slice(&v.to_le_bytes()); - } - } - eprintln!( - "PIXFRAME input={i} shown={shown} {w}x{h} {}x{}", - pic.width, pic.height - ); - shown += 1; - } - Ok(None) => eprintln!("PIXFRAME input={i} hidden"), - Err(e) => { - eprintln!("PIXERR input={i}: {e}"); - break; - } - } - } - std::fs::write(&out, &dump).expect("write dump"); - eprintln!("wrote {} bytes ({shown} shown frames)", dump.len()); -} - -fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { - assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); - let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; - let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); - let width = u16::from_le_bytes([bytes[12], bytes[13]]); - let height = u16::from_le_bytes([bytes[14], bytes[15]]); - let mut pos = hdr_len; - let mut frames = Vec::new(); - while pos + 12 <= bytes.len() { - let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) - as usize; - let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap()); - pos += 12; - if pos + sz > bytes.len() { - break; - } - frames.push(IvfFrame { - pts, - data: bytes[pos..pos + sz].to_vec(), - }); - pos += sz; - } - (fourcc, width, height, frames) -} - -struct IvfFrame { - #[allow(dead_code)] - pts: u64, - data: Vec, -} diff --git a/crates/ec-vp9/tests/it/scratch_pixdump10.rs b/crates/ec-vp9/tests/it/scratch_pixdump10.rs deleted file mode 100644 index 150840fd..00000000 --- a/crates/ec-vp9/tests/it/scratch_pixdump10.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Scratch: dump every shown frame's planes as little-endian u16 for the -//! high-bit-depth pixel comparator. -//! -//! `INTER_IVF= EC_VP9_PIXDUMP= cargo test -p ec-vp9 --test scratch_pixdump10` -//! -//! Layout matches drv_pix10: per shown frame, Y (w*h), U and V each -//! (((w+1)/2)*((h+1)/2)) (chroma ceils), rows packed to the visible width, -//! each sample written as two little-endian bytes. - -use ec_vp9::decode::Decoder; - -#[test] -#[ignore = "manual dump: set INTER_IVF and EC_VP9_PIXDUMP"] -fn pixdump10() { - let ivf = std::env::var("INTER_IVF").expect("set INTER_IVF"); - let out = std::env::var("EC_VP9_PIXDUMP").expect("set EC_VP9_PIXDUMP"); - let bytes = std::fs::read(&ivf).expect("read ivf"); - let (_, w, h, frames) = parse_ivf(&bytes); - let mut decoder = Decoder::new(); - let mut dump = Vec::new(); - let mut shown = 0usize; - for (i, f) in frames.iter().enumerate() { - match decoder.decode(f) { - Ok(Some(pic)) => { - for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) { - dump.extend_from_slice(&v.to_le_bytes()); - } - eprintln!( - "PIXFRAME input={i} shown={shown} {w}x{h} {}x{} bd={}", - pic.width, pic.height, pic.bit_depth - ); - shown += 1; - } - Ok(None) => eprintln!("PIXFRAME input={i} hidden"), - Err(e) => { - eprintln!("PIXERR input={i}: {e}"); - break; - } - } - } - std::fs::write(&out, &dump).expect("write dump"); - eprintln!("wrote {} bytes ({shown} shown frames)", dump.len()); -} - -fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec>) { - assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); - let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; - let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); - let width = u16::from_le_bytes([bytes[12], bytes[13]]); - let height = u16::from_le_bytes([bytes[14], bytes[15]]); - let mut pos = hdr_len; - let mut frames = Vec::new(); - while pos + 12 <= bytes.len() { - let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) - as usize; - let data = bytes[pos + 12..pos + 12 + sz].to_vec(); - frames.push(data); - pos += 12 + sz; - } - (fourcc, width, height, frames) -} diff --git a/crates/ec-vp9/tests/it/scratch_realsweep.rs b/crates/ec-vp9/tests/it/scratch_realsweep.rs deleted file mode 100644 index 6cc30679..00000000 --- a/crates/ec-vp9/tests/it/scratch_realsweep.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! [scratch] Real-content keyframe sweep. -//! -//! The library carries no VP9 content of its own (its one webm, in -//! `~/Downloads`, is VP8), so the keyframe path only ever sees real imagery -//! through a transcode: encode `SWEEP_SRC` as all-intra VP9 with ffmpeg -//! (`-g 1`, so every frame is a keyframe), decode every frame with `ec-vp9`, -//! and diff Y/U/V against ffmpeg's own decode of the same file. -//! -//! ```text -//! SWEEP_SRC=