diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index 5f16d35e..771ade05 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -266,9 +266,10 @@ fn main() { // triage needs. if let Some(seq) = parser.sequence_header() { println!( - "SEQ: use_128x128_superblock={} bit_depth={} max_frame={}x{}", + "SEQ: use_128x128_superblock={} bit_depth={} mono_chrome={} max_frame={}x{}", seq.use_128x128_superblock, seq.color_config.bit_depth, + seq.color_config.mono_chrome, seq.max_frame_width, seq.max_frame_height ); @@ -310,6 +311,9 @@ fn main() { let mut shown = 0usize; let mut dims = (0usize, 0usize); let mut buf: Vec = Vec::new(); + // lane-av1mono: a monochrome stream is luma only, so the raw dump is a + // single plane -- exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes. + let mono = parser.sequence_header().is_some_and(|s| s.color_config.mono_chrome); let result = ec_av1::stream::decode_stream_with(&data, |f, _idx, is_shown| { if !is_shown { return Ok(()); @@ -318,8 +322,9 @@ fn main() { if shown == 1 { dims = (f.width, f.height); } + let planes: &[&Vec] = if mono { &[&f.y] } else { &[&f.y, &f.u, &f.v] }; if let Some(w) = f16.as_mut() { - let n = 2 * (f.y.len() + f.u.len() + f.v.len()); + let n = 2 * planes.iter().map(|p| p.len()).sum::(); if null16 { // Timing runs point EC_PROBE_OUT16 at /dev/null; the u16->LE // conversion was ~2% of the main thread for bytes nobody reads. @@ -328,7 +333,7 @@ fn main() { buf.clear(); buf.resize(n, 0); let mut off = 0; - for p in [&f.y, &f.u, &f.v] { + for p in planes { let end = off + 2 * p.len(); for (d, &s) in buf[off..end].chunks_exact_mut(2).zip(p.iter()) { d.copy_from_slice(&s.to_le_bytes()); @@ -341,7 +346,7 @@ fn main() { } if let Some(w) = f8.as_mut() { buf.clear(); - for p in [&f.y, &f.u, &f.v] { + for p in planes { buf.extend(p.iter().map(|&s| s as u8)); } w.write_all(&buf).expect("writing raw planes"); diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 8ba409de..98e1f44d 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -86,6 +86,16 @@ pub(crate) struct FrameCtx { pub(crate) lossless_flag: std::cell::Cell, pub(crate) cdef_bits: std::cell::Cell, pub(crate) bit_depth: std::cell::Cell, + /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec + /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as + /// `av1_num_planes(cm)` and every chroma read site is guarded by + /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`, + /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes + /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma + /// coefficients on any block. Set once per frame from the sequence header + /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread + /// that last saw a 4:2:0 one never inherits the wrong plane count. + pub(crate) mono_chrome: std::cell::Cell, pub(crate) superres: std::cell::Cell<(u32, u32)>, pub(crate) cdef_transmitted: std::cell::Cell, pub(crate) cdef_sb_cols: std::cell::Cell, @@ -175,6 +185,7 @@ impl FrameCtx { lossless_flag: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), + mono_chrome: std::cell::Cell::new(false), superres: std::cell::Cell::new((0, 8)), cdef_transmitted: std::cell::Cell::new(false), cdef_sb_cols: std::cell::Cell::new(0), @@ -269,6 +280,7 @@ impl WithRef for T {} pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx { let out = FrameCtx::new(); out.bit_depth.set(fctx.bit_depth.get()); + out.mono_chrome.set(fctx.mono_chrome.get()); out.interp_filter.set(fctx.interp_filter.get()); out.grain_bit_depth.set(fctx.grain_bit_depth.get()); out.superres.set(fctx.superres.get()); @@ -566,6 +578,19 @@ pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) { fctx.bit_depth.with(|c| c.set(bit_depth)); } +/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a +/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma +/// symbol or chroma coefficient and the output picture is luma only. +pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool { + fctx.mono_chrome.with(std::cell::Cell::get) +} + +/// Sets [`mono`] for the current thread, called once per frame from +/// [`crate::stream`]'s decode loop like [`set_bit_depth`]. +pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) { + fctx.mono_chrome.with(|c| c.set(mono_chrome)); +} + /// This frame's superres state: `(upscaled_width, superres_denom)`, or /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid, @@ -6780,6 +6805,39 @@ fn read_coeffs_rect( Ok((Grid::Own(grid), tx_type)) } +/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the +/// [`read_plane`] family already has. +/// +/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop +/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a +/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves +/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`] +/// enforces that for every strip that reads its chroma through it, but the rect +/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`], +/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`]) +/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes +/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated +/// chroma read desyncs at the FIRST rect leaf of the frame and every later +/// symbol -- and therefore every later pixel -- is decoded from the wrong +/// place, without ever tripping a refusal (the desynced values stay inside +/// every coded alphabet). +fn read_chroma_coeffs_rect( + dec: &mut SymbolDecoder, + coding: &mut TxbTables, + scan: &[u16], + w: usize, + h: usize, + skip_ctx: usize, + sign_ctx: usize, + default_tx_type: TxType, + fctx: &crate::decode::FrameCtx, +) -> Result<(Grid, TxType)> { + if mono(fctx) { + return Ok((Grid::Zero(w * h), TxType::DctDct)); + } + read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type) +} + /// What one coded block leaves behind for the blocks that read it as a /// neighbour: whether it coded anything at all, and the sign of its DC — /// [`crate::tile`]'s own private `Neighbour`. @@ -9047,6 +9105,12 @@ fn read_intra_mode_rect( Option, Option, )> { + // lane-av1mono: libaom guards every chroma symbol read with + // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`), + // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/ + // `palette_uv` even on a chroma-reference strip. Fold the plane count + // into the same `has_chroma` this reader already gates on. + let has_chroma = has_chroma && !mono(fctx); let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if ec_istep { // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line @@ -9805,7 +9869,14 @@ fn decode_rect_split( let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new(); let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh)); let reach = block_reach; - let (u_grid, v_grid) = if m.skip { + let (u_grid, v_grid) = if mono(fctx) { + // lane-av1mono: a monochrome frame codes no chroma coefficients on + // any block (`plane < av1_num_planes == 1`), so the whole chroma + // section -- the skipped-strip pushes, the lossless raster and the + // un-split `read_coeffs_rect` below -- is bypassed. + let zero = Grid::Zero(chroma_w * chroma_h); + (zero.clone(), zero) + } else if m.skip { let zero = Grid::Zero(chroma_w * chroma_h); if let Some((ub, _)) = &m.palette_uv { set_palette_pred(ub.clone(), fctx); @@ -10456,8 +10527,14 @@ fn decode_intra_rect_in_inter( // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the // superblock-level strip reads the no-CFL alphabet -- the same split // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. - let cfl_allowed = cfl_allowed_px(bw, bh, fctx); - let uv_mode = if cfl_allowed { + // + // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol + // (libaom `decodemv.c:933`). + let has_chroma = !mono(fctx); + let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx); + let uv_mode = if !has_chroma { + DC_PRED + } else if cfl_allowed { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) @@ -10518,8 +10595,11 @@ fn decode_intra_rect_in_inter( } // A 2:1 strip of at least 8x8 is always a chroma reference, so // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here. - let use_palette_uv = - uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; + // lane-av1mono: libaom's actual guard is `num_planes > 1 && + // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602). + let use_palette_uv = has_chroma + && uv_mode == DC_PRED + && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; if crate::envflags::env_flag!("EC_PALSYN") { eprintln!("EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0); } @@ -11059,7 +11139,7 @@ fn decode_block_rect( let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); - let (u_levels, u_tx_type) = read_coeffs_rect( + let (u_levels, u_tx_type) = read_chroma_coeffs_rect( dec, &mut u_coding, chroma_scan, @@ -11068,6 +11148,7 @@ fn decode_block_rect( u_skip_ctx, dc_sign_ctx(around[1].2), u_default_tx, + fctx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); @@ -11102,7 +11183,7 @@ fn decode_block_rect( let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); - let (v_levels, v_tx_type) = read_coeffs_rect( + let (v_levels, v_tx_type) = read_chroma_coeffs_rect( dec, &mut v_coding, chroma_scan, @@ -11111,6 +11192,7 @@ fn decode_block_rect( v_skip_ctx, dc_sign_ctx(around[2].2), v_default_tx, + fctx, )?; if crate::envflags::env_flag!("EC_AV1_TRACE") { let (rng, _) = dec.debug_state(); @@ -11441,9 +11523,9 @@ fn decode_leaf_rect( let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); - let (u_l, u_tx_type) = read_coeffs_rect( + let (u_l, u_tx_type) = read_chroma_coeffs_rect( dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, - dc_sign_ctx(around[1].2), u_default_tx, + dc_sign_ctx(around[1].2), u_default_tx, fctx, )?; u_levels = u_l; let u_residual = dequant_and_inverse_typed_wh( @@ -11460,9 +11542,9 @@ fn decode_leaf_rect( let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); - let (v_l, v_tx_type) = read_coeffs_rect( + let (v_l, v_tx_type) = read_chroma_coeffs_rect( dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, - dc_sign_ctx(around[2].2), v_default_tx, + dc_sign_ctx(around[2].2), v_default_tx, fctx, )?; v_levels = v_l; let v_residual = dequant_and_inverse_typed_wh( @@ -11791,7 +11873,7 @@ fn decode_block_rect4( let default_tx = default_intra_tx_type(uv_predict_mode as u8); let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode); - let (levels, tx_type) = read_coeffs_rect( + let (levels, tx_type) = read_chroma_coeffs_rect( dec, &mut coding, chroma_scan, @@ -11800,6 +11882,7 @@ fn decode_block_rect4( skip_ctx, dc_sign_ctx(around[plane].2), default_tx, + fctx, )?; planes.push((levels, tx_type)); } @@ -12441,7 +12524,7 @@ fn decode_rect4_16_strip( let default_tx = default_intra_tx_type(uv_predict_mode as u8); let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); - let (levels, tx_type) = read_coeffs_rect( + let (levels, tx_type) = read_chroma_coeffs_rect( dec, &mut coding, chroma_scan, @@ -12450,6 +12533,7 @@ fn decode_rect4_16_strip( skip_ctx, dc_sign_ctx(around[plane].2), default_tx, + fctx, )?; planes.push((levels, tx_type)); } @@ -12965,7 +13049,7 @@ fn decode_block_rect64( let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); } - let (u_levels, u_tx_type) = read_coeffs_rect( + let (u_levels, u_tx_type) = read_chroma_coeffs_rect( dec, &mut u_coding, chroma_scan, @@ -12974,6 +13058,7 @@ fn decode_block_rect64( u_skip_ctx, dc_sign_ctx(around[1].2), TxType::DctDct, + fctx, )?; if coeff_trace_on() { let (rng, _) = dec.debug_state(); @@ -13029,7 +13114,7 @@ fn decode_block_rect64( let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); } - let (v_levels, v_tx_type) = read_coeffs_rect( + let (v_levels, v_tx_type) = read_chroma_coeffs_rect( dec, &mut v_coding, chroma_scan, @@ -13038,6 +13123,7 @@ fn decode_block_rect64( v_skip_ctx, dc_sign_ctx(around[2].2), TxType::DctDct, + fctx, )?; if coeff_trace_on() { let (rng, _) = dec.debug_state(); @@ -13270,11 +13356,15 @@ fn read_intra_mode( 0 }; istep!("angle_y", angle_delta_y); - // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided - // here so every `decode_block` caller (64x64 and 128x128 roots included) - // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin. - let cfl = cfl && cfl_allowed_px(side, side, fctx); - let uv_mode = if cfl { + // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette + // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref` + // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader + // gates its chroma symbols on. + let has_chroma = !mono(fctx); + let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx); + let uv_mode = if !has_chroma { + DC_PRED + } else if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) @@ -13375,8 +13465,16 @@ fn read_intra_mode( // scope always reconstructs chroma alongside luma (`decode_block` // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref` // is always true here and does not need threading in. + // + // lane-av1mono: libaom's actual guard is `num_planes > 1 && + // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a + // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size` + // symbol even at this chroma-owning square block. let palette_uv_mode_ctx = usize::from(use_palette_y); - if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 { + if has_chroma + && uv_mode == DC_PRED + && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 + { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx); palette_uv_pending = Some((n, u_colors, v_colors)); @@ -14038,6 +14136,14 @@ fn read_plane( // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check. smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) -> Result { + // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's + // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) + // never reaches a chroma plane -- no u/v coefficient symbol is coded and + // no chroma write is recorded. Return the all-zero grid the caller's + // neighbour bookkeeping reads, without consuming a bit. + if plane_idx > 0 && mono(fctx) { + return Ok(Grid::Zero(side * side)); + } let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) } else { @@ -15916,6 +16022,9 @@ fn read_intra_mode_sub8( seg_w_mi: usize, seg_h_mi: usize, fctx: &crate::decode::FrameCtx, ) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option)> { + // lane-av1mono: a monochrome leaf codes no chroma mode (libaom + // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`. + let has_chroma = has_chroma && !mono(fctx); let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if ec_istep { @@ -16131,6 +16240,11 @@ fn decode_leaf_split4( last_uv = chroma; } } + // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no + // chroma to reconstruct and no uv_mode was read. + let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) { + (Grid::Zero(16), Grid::Zero(16)) + } else { let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); @@ -16172,6 +16286,8 @@ fn decode_leaf_split4( )?; (ug, vg) }; + (u_grid, v_grid) + }; // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s // rescaling is wrong for an already-mi-unit position, so this inlines @@ -16518,6 +16634,12 @@ fn decode_leaf_rect8( last_uv = chroma; } } + // lane-av1mono: a monochrome frame codes no chroma at all -- no + // `uv_mode` was read ([`read_intra_mode_sub8`] folds the plane count in), + // so there is no chroma to reconstruct and no chroma coefficient to read. + let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) { + (Grid::Zero(16), Grid::Zero(16)) + } else { let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (gpx / 2, gpy / 2); let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx); @@ -16559,6 +16681,8 @@ fn decode_leaf_rect8( )?; (ug, vg) }; + (u_grid, v_grid) + }; // `update_partition_context` at the 8x8 level writes // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}` @@ -18498,6 +18622,11 @@ fn read_inter_plane_rect( inherited_luma_tx_type: Option, luma_skip_ctx: Option, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, TxType)> { + // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma + // coefficients (`plane < av1_num_planes == 1`). + if plane_idx > 0 && mono(fctx) { + return Ok((Grid::Zero(w * h), TxType::DctDct)); + } let skip_ctx = if plane_idx == 0 { // `get_txb_ctx_general`: 0 only when this unit IS the whole plane // block; a var-tx leaf passes its own neighbour-table context. @@ -24737,6 +24866,11 @@ fn read_inter_plane( // lone-transform-unit 0. luma_skip_ctx: Option, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, TxType)> { + // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma + // coefficients (`plane < av1_num_planes == 1`). + if plane_idx > 0 && mono(fctx) { + return Ok((Grid::Zero(side * side), TxType::DctDct)); + } let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) } else { @@ -29747,11 +29881,16 @@ fn decode_inter_block( // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the // arithmetic coder by the wrong interval, desyncing the tile from this // block on. - let cfl_allowed = cfl_allowed_px(write_w, write_h, fctx); + // lane-av1mono: a monochrome block codes no chroma mode/CFL symbol + // (libaom `decodemv.c:933`). + let has_chroma = !mono(fctx); + let cfl_allowed = has_chroma && cfl_allowed_px(write_w, write_h, fctx); if !cfl_allowed { hit!(NOCFL_UV_MODE_HITS); } - let uv_mode = if cfl_allowed { + let uv_mode = if !has_chroma { + DC_PRED + } else if cfl_allowed { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) @@ -29822,8 +29961,9 @@ fn decode_inter_block( if crate::envflags::env_flag!("EC_PALSYN") { eprintln!("EC_PALSYN_PRE sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} rng={}", palette_y_pending.map_or(0, |(n, _)| n), dec.debug_state().0); } - let use_palette_uv = - uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; + let use_palette_uv = has_chroma + && uv_mode == DC_PRED + && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; if crate::envflags::env_flag!("EC_PALSYN") { eprintln!("EC_PALSYN sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0); } @@ -31177,6 +31317,9 @@ fn decode_intra_sub8_leaf( tx_select: bool, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result { + // lane-av1mono: a monochrome leaf codes no chroma mode (libaom + // `decodemv.c:933`). + let has_chroma = has_chroma && !mono(fctx); let vert = bw < bh; let (w_mi, h_mi) = (bw / MI, bh / MI); let (gr, gc) = group_mi; @@ -31499,6 +31642,26 @@ fn decode_intra_sub8_leaf( h.set(s); }); } + // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map + // needs EVERY writer): a sub-8x8 group published no palette state, so + // once an 8x8 leaf of the same row can BE a palette block, the group + // left the row's band holding that earlier block's size and the next + // intra block read `av1_get_palette_mode_ctx` one too high (measured: + // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers + // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` + // needs `bsize >= BLOCK_8X8`), so the group always clears. + // + // lane-av1mono: this publish is NOT chroma work and must run BEFORE the + // `!has_chroma` return below. libaom's mi grid holds + // `palette_size[0] == 0` in every cell of such a group whatever the + // plane count, and on a monochrome frame EVERY sub-8 leaf passes + // `has_chroma == false`, so a publish placed after the return never ran + // at all: the band kept an earlier palette block's size, the next block + // read `palette_y_mode` off CDF row 1 where libaom reads row 0, decoded + // a palette libaom never coded, and the tile desynced one block later + // (measured: gray testsrc2 320x240, decode-order frame 33, mi(42,50), + // ours ctx 2 where libaom gathers 1). + record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); if !has_chroma { return Ok(mode); } @@ -31517,15 +31680,6 @@ fn decode_intra_sub8_leaf( neighbours.above_uv_mode[c] = uv_predict_mode; neighbours.left_uv_mode[r] = uv_predict_mode; neighbours.record_uv_mode_mi(gr, gc, 2, 2, uv_predict_mode); - // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map - // needs EVERY writer): a sub-8x8 group published no palette state, so - // once an 8x8 leaf of the same row can BE a palette block, the group - // left the row's band holding that earlier block's size and the next - // intra block read `av1_get_palette_mode_ctx` one too high (measured: - // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers - // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` - // needs `bsize >= BLOCK_8X8`), so the group always clears. - record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); let (u_grid, v_grid): (Grid, Grid) = if skip { @@ -33871,7 +34025,12 @@ fn decode_inter_block8( // row (`get_uv_mode`, identity over `V_PRED..=D67_PRED`). Every value // but `DC_PRED` was refused here, which is what blocked the low-cq // CDEF arms and the 10-bit gates. - let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); + let has_chroma = !mono(fctx); + let uv_mode = if !has_chroma { + DC_PRED + } else { + dec.symbol(&mut cdfs.uv_mode_cfl[mode]) + }; if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { eprintln!( "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}", @@ -33885,7 +34044,7 @@ fn decode_inter_block8( hit!(SMOOTH_UV_HITS); hit!(INTRA_IN_INTER8_UV_SMOOTH_HITS); } - let alpha = if uv_mode == UV_CFL_PRED { + let alpha = if has_chroma && uv_mode == UV_CFL_PRED { hit!(INTRA_IN_INTER8_UV_CFL_HITS); Some(read_cfl_alphas(dec, cdfs)) } else { @@ -33942,7 +34101,8 @@ fn decode_inter_block8( } // lane-uv8 r1: `read_palette_mode_info` reads the UV symbol only // when `uv_mode == UV_DC_PRED` (decodemv.c). - let use_palette_uv = uv_mode == DC_PRED + let use_palette_uv = has_chroma + && uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; if crate::envflags::env_flag!("EC_PALSYN") { eprintln!( diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index a50ec7ec..2628d6ab 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1243,6 +1243,9 @@ pub(crate) struct SeqFlags { pub(crate) enable_interintra_compound: bool, pub(crate) use_sb128: bool, pub(crate) bit_depth: u8, + /// lane-av1mono: `color_config.mono_chrome` (spec 5.5.2): + /// `NumPlanes == 1`, no chroma is coded or reconstructed. + pub(crate) mono_chrome: bool, pub(crate) order_hint_bits: u32, pub(crate) mc_identity: bool, } @@ -1259,6 +1262,7 @@ impl SeqFlags { enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound), use_sb128: seq.is_some_and(|s| s.use_128x128_superblock), bit_depth: seq.map_or(8, |s| s.color_config.bit_depth), + mono_chrome: seq.is_some_and(|s| s.color_config.mono_chrome), order_hint_bits: seq.map_or(0, |s| s.order_hint_bits), mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0), } @@ -1633,6 +1637,10 @@ fn decode_frame( // `a_lossless_libaom_inter_frame_decodes_sample_exact`. crate::decode::set_lossless(coded_lossless, fctx); crate::decode::set_bit_depth(bit_depth, fctx); + // lane-av1mono: the sequence header's `mono_chrome`, set per frame like + // the bit depth so a mono frame decoded on a thread that last saw a + // 4:2:0 one never inherits the wrong plane count. + crate::decode::set_mono(seq.mono_chrome, fctx); // spec 7.16: this frame's superres state, for the filter chain -- // `decode.rs` upscales between CDEF and loop restoration and sizes // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an @@ -2016,40 +2024,31 @@ pub(crate) mod tests { ); } - /// lane-av1-decode (pilot resume, 2026-09-19): a real libaom MONOCHROME key - /// frame is currently REFUSED BY NAME, and this gate pins that as today's - /// measured first stop for a real encoder stream. + /// lane-av1mono: the INVERSE of the pilot's + /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the + /// pilot's merge `d71084ae` landed on `main` (after this lane's base + /// `7f4e8301`): the very same recipe now decodes, and its luma is + /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this + /// lane into `main` must therefore resolve that pinning gate by adopting + /// this witness in its place. /// - /// The parked lane's first wall (64x64 superblock-level partition arms) is - /// ALREADY CLOSED on this tree (both user films decode byte-exact; the - /// SB-level HORZ/VERT/AB/1:4 arms are witness-gated), so the re-measurement - /// this gate belongs to had to find where a real stream stops TODAY. A - /// `-pix_fmt gray` encode of the crate's own fixture recipe does. + /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`, + /// so libaom codes NO chroma symbol anywhere in the sequence -- not the + /// mode syntax, not a coefficient. That reaches all three classes this lane + /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma + /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect` + /// DIRECTLY instead of through `read_plane`'s own plane gate, and the + /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before + /// it returns (an uncleared band made the next block read `palette_y_mode` + /// off the wrong CDF row and silently desynced the rest of the tile -- + /// measured at decode-order frame 33 of this very recipe). /// - /// Root cause (localised with `EC_TRACE_MODE_STEP` on the instrumented - /// aomdec oracle vs this decoder, both over the same OBU): on the mono - /// stream ours reads `angle_uv` at `rng=50996`, while aomdec reads NO - /// `uv_mode`/`angle_uv` at all (the guard below); the first divergence at - /// `(0,0)` is aomdec reading `tx_depth ctx=0 cat=1` (`rng=43616`) where - /// ours reads a `uv_mode` (val=13). libaom's - /// `decodemv.c` guards that read with - /// `if (!cm->seq_params->monochrome && xd->is_chroma_ref)`: a monochrome - /// frame codes NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` at all, - /// while this decoder's block layer has no `num_planes`/monochrome notion - /// and reads them for every block. That is the whole desync; the - /// "a Golomb tail longer than this decoder reads" refusal is the SYMPTOM - /// (the reader is left mid-symbol), not the defect -- which is why that - /// string's PROVEN claim ("read_golomb_reads_every_value_a_conformant_stream_can_carry") - /// does not contradict this gate. - /// - /// The twin 4:2:0 encode of the SAME source and recipe decodes, so this is - /// a monochrome defect and not a recipe defect. When monochrome decode - /// lands, flip this gate to a witness (decode BOTH twins pixel-exact - /// against ffmpeg); the refusal string is the tripwire. - #[test] - fn a_real_libaom_monochrome_key_frame_is_refused_by_name() { - const NAME: &str = "a_real_libaom_monochrome_key_frame_is_refused_by_name"; - const REFUSAL: &str = "a Golomb tail longer than this decoder reads"; + /// The 4:2:0 twin of the same source and settings is the control: it proves + /// the recipe is decodable, so a failure here is about the plane count and + /// not about the source or the encoder settings. + #[test] + fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() { + const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact"; if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); return; @@ -2057,9 +2056,23 @@ pub(crate) mod tests { let emit = |pix: &str| -> Vec { let out = Command::new("ffmpeg") .args([ - "-v", "error", "-f", "lavfi", "-i", - "testsrc2=size=320x240:rate=30:duration=2", "-pix_fmt", pix, - "-c:v", "libaom-av1", "-cpu-used", "8", "-b:v", "300k", "-f", "obu", "-", + "-v", + "error", + "-f", + "lavfi", + "-i", + "testsrc2=size=320x240:rate=30:duration=2", + "-pix_fmt", + pix, + "-c:v", + "libaom-av1", + "-cpu-used", + "8", + "-b:v", + "300k", + "-f", + "obu", + "-", ]) .stdin(Stdio::null()) .stdout(Stdio::piped()) @@ -2073,24 +2086,40 @@ pub(crate) mod tests { ); out.stdout }; - // CONTROL: the identical recipe at 4:2:0 decodes -- so the refusal below - // is about monochrome, not about the source or the encoder settings. + // CONTROL: the identical recipe at 4:2:0 still decodes. let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode"); assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames"); - let err = decode_stream(&emit("gray")) - .err() - .map(|e| e.to_string()) - .unwrap_or_else(|| { - panic!("{NAME}: the monochrome stream now decodes -- flip this gate to a witness") - }); - assert!( - err.contains(REFUSAL), - "{NAME}: the monochrome stream stopped without the measured refusal \ - {REFUSAL:?} -- the desync moved; re-measure before trusting this gate. got: {err}" - ); + // THE WITNESS: the monochrome stream decodes and every luma sample + // equals ffmpeg's own decode of the same OBU. + let gray = emit("gray"); + let ours = decode_stream(&gray) + .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}")); + let (width, height) = (320usize, 240usize); + const FRAMES: usize = 60; + assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames"); + let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES); + for (i, plane) in reference.chunks_exact(width * height).enumerate() { + assert_eq!(ours[i].width, width, "{NAME}: frame {i} width"); + assert_eq!(ours[i].height, height, "{NAME}: frame {i} height"); + assert_eq!( + ours[i].y.len(), + width * height, + "{NAME}: frame {i} luma length" + ); + for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() { + assert_eq!( + *want, + u16::from(*got), + "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}", + j / width, + j % width + ); + } + } eprintln!( - "{NAME}: 4:2:0 twin {} frames, monochrome refused by name ({REFUSAL})", - twin.len() + "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg", + twin.len(), + ours.len() ); } @@ -3366,6 +3395,49 @@ pub(crate) mod tests { .collect() } + /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma + /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes + /// (lane-av1mono). Fed down a stdin writer thread for the reason the 4:2:0 + /// helper documents. + fn ffmpeg_decode_gray_sequence( + stream: &[u8], + width: usize, + height: usize, + frames: usize, + ) -> Vec { + let mut child = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("ffmpeg failed to start"); + let mut stdin = child.stdin.take().expect("ffmpeg stdin"); + let payload = stream.to_vec(); + let writer = std::thread::Builder::new() + .name("ec-av1-ffmpeg-gray-in".into()) + .spawn(move || { + let _ = stdin.write_all(&payload); + }) + .expect("spawning the ffmpeg stdin writer"); + let out = child.wait_with_output().expect("ffmpeg failed to run"); + writer.join().expect("ffmpeg stdin writer thread"); + assert!( + out.status.success(), + "ffmpeg refused the monochrome stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + out.stdout.len(), + width * height * frames, + "expected {frames} monochrome frames, ffmpeg said: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + } + /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples /// are 2-byte little-endian, one full 16-bit range regardless of the /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the diff --git a/lanes/av1mono.report.md b/lanes/av1mono.report.md new file mode 100644 index 00000000..8518e2b0 --- /dev/null +++ b/lanes/av1mono.report.md @@ -0,0 +1,593 @@ +# lane-av1-mono — monochrome AV1 decode is luma byte-exact (60f kf, 120f inter, mono.ivf) + +Base: `main` **7f4e8301** (the WIP `av1: WIP monochrome plane model` commit; its +parent is `f0727a87`). Worktree `edith_codecs-av1mono`, branch `lane-av1-mono`, +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1mono` (private). No push. +Status: **COMPLETE** — a monochrome AV1 stream decodes and its luma is byte-exact +against ffmpeg's own decode, on all three witnesses. The luma half of the pilot's +first real-stream wall (§3.1 of `lanes/av1decode.report.md`) is closed. + +## TL;DR + +The previous continuation (Yunus) died mid-flight on a provider outage, leaving a +working tree that *was* the fix but was buried under **24,000+ lines of omp +edit-tool rustfmt churn** (`git diff --stat` read 17300/6908 changed lines). This +session (1) salvaged a **semantic-only 19-hunk diff** out of that churn, (2) +verified it fixes the luma defect, (3) proved the three witnesses, the corpus, the +film windows and the suite. + +- **Salvage:** churn → `decode.rs` 88 lines, `stream.rs` 142 lines (211 insertions, + 19 deletions). Method and proof below. +- **Root cause of the luma mismatch:** a **palette-mode neighbour band** that a + mono sub-8x8 leaf left uncleared. The publish (`record_strip_palette`) sat + *after* the `if !has_chroma { return }` early-out; on a monochrome frame EVERY + sub-8 leaf takes that early-out, so the band kept an earlier palette block's + size, the next block read `palette_y_mode` off CDF row 1 where libaom reads row + 0, and the tile silently desynced one block later. (Symptom had been read as a + reconstruction defect; it is an entropy desync.) +- **Second class closed:** the rect-strip paths call `read_coeffs_rect` on planes + 1/2 **directly** (bypassing `read_plane`'s own mono gate), so a mono frame + consumed a chroma coefficient symbol libaom never coded. New + `read_chroma_coeffs_rect` gates those 8 call sites. + +## Salvage (what the dirty tree contained, what was kept/reverted) + +`git status` at handover: `M crates/ec-av1/src/decode.rs`, `M crates/ec-av1/src/stream.rs`. + +1. **Hunk classifier first** (`rustfmt-semantic-only-diff` recipe): a hunk is + fmt-only iff its removed/added lines are equal after JOINING + stripping + whitespace + folding trailing commas. Result: 677 hunks decode (609 fmt-only), + 426 hunks stream (406 fmt-only) — *but this classifier is incomplete here*: + the local rustfmt **wraps `ok_or_else(|| expr)` closure bodies in `{ ... }`**, + so 40+ pure reflow hunks were flagged "semantic" (a brace pair my normalizer + cannot fold away). Trusting it would have kept thousands of churn lines. +2. **Decisive method instead:** rustfmt the *committed* file and diff it against + the working tree. `rustfmt --edition 2024 <7f4e8301 file>` ≈ the working tree: + decode.rs 43620 vs 43672 lines (52-line residual), stream.rs 38666 vs 38805 + (139-line residual). So the working tree **was** `rustfmt(HEAD) + a small + semantic delta` — the previous agent had not left a half-applied edit. +3. Extract `S = diff(rustfmt(7f4e8301), W)` (19 + 2 hunks), apply `S` to the + committed file, and prove correctness mechanically: **`rustfmt(HEAD + S) == W` + byte-for-byte** on both files. Whitespace-only home for every non-semantic line + is then guaranteed: applying only `S` to `HEAD` cannot carry churn. +4. The `patch` of `S` onto `HEAD` needed fuzz at 5 of the 8 call sites and put + `fctx,`/`let (` at the wrong indent there; fixed by hand (indentation is + HEAD-style; the diff now shows ONLY identifier renames, `fctx` args, the new + fn, the palette move, and the test). +5. **Coherence:** the semantic set is coherent — no orphaned variable, no broken + syntax, one self-contained feature (`read_chroma_coeffs_rect` + the palette + move). Nothing had to be reverted. + +## Root cause + +`decode_intra_sub8_leaf` (`decode.rs`). libaom's MI grid writes +`palette_size[0] == 0` for **every** cell of a sub-8x8 group whatever the plane +count (`av1_allow_palette` needs `bsize >= BLOCK_8X8`, so no sub-8 piece is ever +a palette block). ec-av1 did publish that clear — but only on the **chroma-reference** +path, after `if !has_chroma { return Ok(mode) }`. On a mono frame +`has_chroma == false` for every sub-8 leaf (`NumPlanes == 1`), so the publish +never ran: the row's band kept an earlier palette block's size, the next intra +block read `av1_get_palette_mode_ctx` one too high, decoded a `palette_y_mode` +symbol libaom never coded, and the tile desynced. + +Measured: gray testsrc2 320x240, **decode-order frame 33**, mi(42,50) — ours ctx 2 +where libaom gathers 1. (First *pixel* divergence on the 60-frame stream lands at +frame 0, because the key frame's own early blocks already carry the mismatch.) + +## Fix + +- `crates/ec-av1/src/decode.rs` + - **`record_strip_palette(...)` moved BEFORE the `!has_chroma` return** in + `decode_intra_sub8_leaf` — unconditional, matching libaom's MI grid, with the + extended comment. (This is the luma fix.) + - New **`read_chroma_coeffs_rect`**: a mono early-return of `Grid::Zero` + + `TxType::DctDct` before delegating to `read_coeffs_rect`; applied at the 8 + chroma call sites that read planes 1/2 directly + (`decode_block_rect`, `decode_leaf_rect`, `decode_block_rect4`, + `decode_rect4_16_strip`, `decode_block_rect64`). Closes the + `reader-gate-not-on-every-path` class. +- `crates/ec-av1/src/stream.rs` + - New witness test **`a_real_libaom_monochrome_key_frame_decodes_pixel_exact`** + (the inverted form of the pilot's pinning gate) + `ffmpeg_decode_gray_sequence` + helper. + +## Semantic-only diff vs 7f4e8301 + +```diff +diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs +index 6399854a..75cd8aad 100644 +--- a/crates/ec-av1/src/decode.rs ++++ b/crates/ec-av1/src/decode.rs +@@ -6805,6 +6805,39 @@ fn read_coeffs_rect( + Ok((Grid::Own(grid), tx_type)) + } + ++/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the ++/// [`read_plane`] family already has. ++/// ++/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop ++/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a ++/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves ++/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`] ++/// enforces that for every strip that reads its chroma through it, but the rect ++/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`], ++/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`]) ++/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes ++/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated ++/// chroma read desyncs at the FIRST rect leaf of the frame and every later ++/// symbol -- and therefore every later pixel -- is decoded from the wrong ++/// place, without ever tripping a refusal (the desynced values stay inside ++/// every coded alphabet). ++fn read_chroma_coeffs_rect( ++ dec: &mut SymbolDecoder, ++ coding: &mut TxbTables, ++ scan: &[u16], ++ w: usize, ++ h: usize, ++ skip_ctx: usize, ++ sign_ctx: usize, ++ default_tx_type: TxType, ++ fctx: &crate::decode::FrameCtx, ++) -> Result<(Grid, TxType)> { ++ if mono(fctx) { ++ return Ok((Grid::Zero(w * h), TxType::DctDct)); ++ } ++ read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type) ++} ++ + /// What one coded block leaves behind for the blocks that read it as a + /// neighbour: whether it coded anything at all, and the sign of its DC — + /// [`crate::tile`]'s own private `Neighbour`. +@@ -11106,7 +11139,7 @@ fn decode_block_rect( + let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); + let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); + let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); +- let (u_levels, u_tx_type) = read_coeffs_rect( ++ let (u_levels, u_tx_type) = read_chroma_coeffs_rect( + dec, + &mut u_coding, + chroma_scan, +@@ -11115,6 +11148,7 @@ fn decode_block_rect( + u_skip_ctx, + dc_sign_ctx(around[1].2), + u_default_tx, ++ fctx, + )?; + if crate::envflags::env_flag!("EC_AV1_TRACE") { + let (rng, _) = dec.debug_state(); +@@ -11149,7 +11183,7 @@ fn decode_block_rect( + let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); + let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); + let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); +- let (v_levels, v_tx_type) = read_coeffs_rect( ++ let (v_levels, v_tx_type) = read_chroma_coeffs_rect( + dec, + &mut v_coding, + chroma_scan, +@@ -11158,6 +11192,7 @@ fn decode_block_rect( + v_skip_ctx, + dc_sign_ctx(around[2].2), + v_default_tx, ++ fctx, + )?; + if crate::envflags::env_flag!("EC_AV1_TRACE") { + let (rng, _) = dec.debug_state(); +@@ -11488,9 +11523,9 @@ fn decode_leaf_rect( + let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); + let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); + let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); +- let (u_l, u_tx_type) = read_coeffs_rect( ++ let (u_l, u_tx_type) = read_chroma_coeffs_rect( + dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, +- dc_sign_ctx(around[1].2), u_default_tx, ++ dc_sign_ctx(around[1].2), u_default_tx, fctx, + )?; + u_levels = u_l; + let u_residual = dequant_and_inverse_typed_wh( +@@ -11507,9 +11542,9 @@ fn decode_leaf_rect( + let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); + let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); + let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); +- let (v_l, v_tx_type) = read_coeffs_rect( ++ let (v_l, v_tx_type) = read_chroma_coeffs_rect( + dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, +- dc_sign_ctx(around[2].2), v_default_tx, ++ dc_sign_ctx(around[2].2), v_default_tx, fctx, + )?; + v_levels = v_l; + let v_residual = dequant_and_inverse_typed_wh( +@@ -11838,7 +11873,7 @@ fn decode_block_rect4( + let default_tx = default_intra_tx_type(uv_predict_mode as u8); + let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); + let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode); +- let (levels, tx_type) = read_coeffs_rect( ++ let (levels, tx_type) = read_chroma_coeffs_rect( + dec, + &mut coding, + chroma_scan, +@@ -11847,6 +11882,7 @@ fn decode_block_rect4( + skip_ctx, + dc_sign_ctx(around[plane].2), + default_tx, ++ fctx, + )?; + planes.push((levels, tx_type)); + } +@@ -12488,7 +12524,7 @@ fn decode_rect4_16_strip( + let default_tx = default_intra_tx_type(uv_predict_mode as u8); + let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); + let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); +- let (levels, tx_type) = read_coeffs_rect( ++ let (levels, tx_type) = read_chroma_coeffs_rect( + dec, + &mut coding, + chroma_scan, +@@ -12497,6 +12533,7 @@ fn decode_rect4_16_strip( + skip_ctx, + dc_sign_ctx(around[plane].2), + default_tx, ++ fctx, + )?; + planes.push((levels, tx_type)); + } +@@ -13012,7 +13049,7 @@ fn decode_block_rect64( + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); + } +- let (u_levels, u_tx_type) = read_coeffs_rect( ++ let (u_levels, u_tx_type) = read_chroma_coeffs_rect( + dec, + &mut u_coding, + chroma_scan, +@@ -13021,6 +13058,7 @@ fn decode_block_rect64( + u_skip_ctx, + dc_sign_ctx(around[1].2), + TxType::DctDct, ++ fctx, + )?; + if coeff_trace_on() { + let (rng, _) = dec.debug_state(); +@@ -13076,7 +13114,7 @@ fn decode_block_rect64( + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); + } +- let (v_levels, v_tx_type) = read_coeffs_rect( ++ let (v_levels, v_tx_type) = read_chroma_coeffs_rect( + dec, + &mut v_coding, + chroma_scan, +@@ -13085,6 +13123,7 @@ fn decode_block_rect64( + v_skip_ctx, + dc_sign_ctx(around[2].2), + TxType::DctDct, ++ fctx, + )?; + if coeff_trace_on() { + let (rng, _) = dec.debug_state(); +@@ -31604,6 +31643,26 @@ fn decode_intra_sub8_leaf( + h.set(s); + }); + } ++ // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map ++ // needs EVERY writer): a sub-8x8 group published no palette state, so ++ // once an 8x8 leaf of the same row can BE a palette block, the group ++ // left the row's band holding that earlier block's size and the next ++ // intra block read `av1_get_palette_mode_ctx` one too high (measured: ++ // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers ++ // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` ++ // needs `bsize >= BLOCK_8X8`), so the group always clears. ++ // ++ // lane-av1mono: this publish is NOT chroma work and must run BEFORE the ++ // `!has_chroma` return below. libaom's mi grid holds ++ // `palette_size[0] == 0` in every cell of such a group whatever the ++ // plane count, and on a monochrome frame EVERY sub-8 leaf passes ++ // `has_chroma == false`, so a publish placed after the return never ran ++ // at all: the band kept an earlier palette block's size, the next block ++ // read `palette_y_mode` off CDF row 1 where libaom reads row 0, decoded ++ // a palette libaom never coded, and the tile desynced one block later ++ // (measured: gray testsrc2 320x240, decode-order frame 33, mi(42,50), ++ // ours ctx 2 where libaom gathers 1). ++ record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); + if !has_chroma { + return Ok(mode); + } +@@ -31622,15 +31681,6 @@ fn decode_intra_sub8_leaf( + neighbours.above_uv_mode[c] = uv_predict_mode; + neighbours.left_uv_mode[r] = uv_predict_mode; + neighbours.record_uv_mode_mi(gr, gc, 2, 2, uv_predict_mode); +- // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map +- // needs EVERY writer): a sub-8x8 group published no palette state, so +- // once an 8x8 leaf of the same row can BE a palette block, the group +- // left the row's band holding that earlier block's size and the next +- // intra block read `av1_get_palette_mode_ctx` one too high (measured: +- // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers +- // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette` +- // needs `bsize >= BLOCK_8X8`), so the group always clears. +- record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]); + + let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); + let (u_grid, v_grid): (Grid, Grid) = if skip { +diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs +index a0b1bd43..d361662c 100644 +--- a/crates/ec-av1/src/stream.rs ++++ b/crates/ec-av1/src/stream.rs +@@ -2024,6 +2024,105 @@ pub(crate) mod tests { + ); + } + ++ /// lane-av1mono: the INVERSE of the pilot's ++ /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the ++ /// pilot's merge `d71084ae` landed on `main` (after this lane's base ++ /// `7f4e8301`): the very same recipe now decodes, and its luma is ++ /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this ++ /// lane into `main` must therefore resolve that pinning gate by adopting ++ /// this witness in its place. ++ /// ++ /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`, ++ /// so libaom codes NO chroma symbol anywhere in the sequence -- not the ++ /// mode syntax, not a coefficient. That reaches all three classes this lane ++ /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma ++ /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect` ++ /// DIRECTLY instead of through `read_plane`'s own plane gate, and the ++ /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before ++ /// it returns (an uncleared band made the next block read `palette_y_mode` ++ /// off the wrong CDF row and silently desynced the rest of the tile -- ++ /// measured at decode-order frame 33 of this very recipe). ++ /// ++ /// The 4:2:0 twin of the same source and settings is the control: it proves ++ /// the recipe is decodable, so a failure here is about the plane count and ++ /// not about the source or the encoder settings. ++ #[test] ++ fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() { ++ const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact"; ++ if !have_ffmpeg() { ++ eprintln!("SKIP {NAME}: no ffmpeg"); ++ return; ++ } ++ let emit = |pix: &str| -> Vec { ++ let out = Command::new("ffmpeg") ++ .args([ ++ "-v", ++ "error", ++ "-f", ++ "lavfi", ++ "-i", ++ "testsrc2=size=320x240:rate=30:duration=2", ++ "-pix_fmt", ++ pix, ++ "-c:v", ++ "libaom-av1", ++ "-cpu-used", ++ "8", ++ "-b:v", ++ "300k", ++ "-f", ++ "obu", ++ "-", ++ ]) ++ .stdin(Stdio::null()) ++ .stdout(Stdio::piped()) ++ .stderr(Stdio::piped()) ++ .output() ++ .expect("ffmpeg failed to run"); ++ assert!( ++ out.status.success(), ++ "{NAME}: ffmpeg ({pix}) failed: {}", ++ String::from_utf8_lossy(&out.stderr) ++ ); ++ out.stdout ++ }; ++ // CONTROL: the identical recipe at 4:2:0 still decodes. ++ let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode"); ++ assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames"); ++ // THE WITNESS: the monochrome stream decodes and every luma sample ++ // equals ffmpeg's own decode of the same OBU. ++ let gray = emit("gray"); ++ let ours = decode_stream(&gray) ++ .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}")); ++ let (width, height) = (320usize, 240usize); ++ const FRAMES: usize = 60; ++ assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames"); ++ let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES); ++ for (i, plane) in reference.chunks_exact(width * height).enumerate() { ++ assert_eq!(ours[i].width, width, "{NAME}: frame {i} width"); ++ assert_eq!(ours[i].height, height, "{NAME}: frame {i} height"); ++ assert_eq!( ++ ours[i].y.len(), ++ width * height, ++ "{NAME}: frame {i} luma length" ++ ); ++ for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() { ++ assert_eq!( ++ *want, ++ u16::from(*got), ++ "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}", ++ j / width, ++ j % width ++ ); ++ } ++ } ++ eprintln!( ++ "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg", ++ twin.len(), ++ ours.len() ++ ); ++ } ++ + /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a + /// shape the parser cannot hand [`decode_stream`]. + /// +@@ -3296,6 +3395,49 @@ pub(crate) mod tests { + .collect() + } + ++ /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma ++ /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes ++ /// (lane-av1mono). Fed down a stdin writer thread for the reason the 4:2:0 ++ /// helper documents. ++ fn ffmpeg_decode_gray_sequence( ++ stream: &[u8], ++ width: usize, ++ height: usize, ++ frames: usize, ++ ) -> Vec { ++ let mut child = Command::new("ffmpeg") ++ .args([ ++ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-", ++ ]) ++ .stdin(Stdio::piped()) ++ .stdout(Stdio::piped()) ++ .stderr(Stdio::piped()) ++ .spawn() ++ .expect("ffmpeg failed to start"); ++ let mut stdin = child.stdin.take().expect("ffmpeg stdin"); ++ let payload = stream.to_vec(); ++ let writer = std::thread::Builder::new() ++ .name("ec-av1-ffmpeg-gray-in".into()) ++ .spawn(move || { ++ let _ = stdin.write_all(&payload); ++ }) ++ .expect("spawning the ffmpeg stdin writer"); ++ let out = child.wait_with_output().expect("ffmpeg failed to run"); ++ writer.join().expect("ffmpeg stdin writer thread"); ++ assert!( ++ out.status.success(), ++ "ffmpeg refused the monochrome stream: {}", ++ String::from_utf8_lossy(&out.stderr) ++ ); ++ assert_eq!( ++ out.stdout.len(), ++ width * height * frames, ++ "expected {frames} monochrome frames, ffmpeg said: {}", ++ String::from_utf8_lossy(&out.stderr) ++ ); ++ out.stdout ++ } ++ + /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples + /// are 2-byte little-endian, one full 16-bit range regardless of the + /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the +``` + +## Witnesses (quoted) + +All three run on the final tree; the probe is +`$HOME/.cache/cargo-target-av1mono/release/examples/decode_probe`. + +``` +(a) gray 60f key frame -- ffmpeg testsrc2 320x240 30fps 2s -pix_fmt gray +OK: 60 frames decoded, 320x240 +gray60 EQUAL True + +(b) gray 120f (inter frames) -- same recipe, duration 4 +OK: 120 frames decoded, 320x240 +gray120 EQUAL True + +(c) fixtures/bitstreams/av1-monochrome.ivf (remuxed to OBU) +OK: 60 frames decoded, 320x240 +mono.ivf EQUAL True +``` + +Comparison for (a)/(b)/(c): probe `EC_PROBE_OUT16` writes the 8-bit sample in the +**low byte** of each u16, so the check is `probe[0::2] == ffmpeg -pix_fmt gray -f +rawvideo`. All three are STRONGER than the charter expected: (c) was expected to +stop at the named intrabc-rect refusal, but that refusal was itself a *symptom* of +this desync, so with the desync gone the fixture now decodes **all 60 frames +byte-exact**. (Class, per the pilot §3.3/3.4: a routing refusal reached only +because the desynced read picked wrong block sizes.) + +Scoped test: +``` +$ cargo test -p ec-av1 --lib a_real_libaom_monochrome_key_frame_decodes_pixel_exact -- --nocapture +a_real_libaom_monochrome_key_frame_decodes_pixel_exact: 4:2:0 twin 60 frames, monochrome 60 frames byte-exact vs ffmpeg +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 651 filtered out +``` + +## Regression + +**Corpus (9 `fixtures/bitstreams/av1-*.ivf`), byte-identity vs the LANE BASE +(`7f4e8301`, own probe at `$HOME/.cache/cargo-target-av1base`):** + +``` +av1-1080p-23.976-10bit IDENTICAL(rc=0) da2b8484b94b244a +av1-1080p-23.976-8bit IDENTICAL(rc=0) 407148a9397461fa +av1-1080p-60-10bit IDENTICAL(rc=0) 83087317d215b128 +av1-1080p-60-8bit IDENTICAL(rc=0) 4aff1fdedc0599a8 +av1-2160p-23.976-8bit IDENTICAL(rc=0) ea683b4a9e2b8891 +av1-altref IDENTICAL(rc=0) ea2f84d929b52f5e +av1-monochrome DIFFER base=49d757b50b8d9175 lane=b869441a9cf29d87 <-- the fix +av1-profile1-444 IDENTICAL(rc=0) 6620e894ff971cba +av1-tiles-1280 IDENTICAL(rc=0) 5e59dbc445eb4e17 +``` + +Only the monochrome fixture moves; every non-mono stream is bit-identical to the +base. **`av1-profile1-444` is IDENTICAL to the base and is NOT byte-exact vs +ffmpeg** — that is the pilot §3.2 4:4:4 block-routing defect, pre-existing and +out of this lane's scope (same probe, same output at base and lane). + +**Against ffmpeg** (correct sample packing per bit depth): +`av1-1080p-23.976-10bit`, `av1-1080p-23.976-8bit`, `av1-1080p-60-10bit`, +`av1-1080p-60-8bit`, `av1-2160p-23.976-8bit`, `av1-altref`, `av1-monochrome`, +`av1-tiles-1280` → all MATCH (sha256). `av1-profile1-444` → differs (above). + +**Film windows** (the pilot's 13 real 3840x1608 10-bit windows +`~/.cache/av1dec-recon/p-*.obu`, compared to the pilot's own ffmpeg `.ref` decodes): + +``` +p-reelb2700 MATCH [OK: 104 frames] p-reelb300 MATCH [OK: 136] p-reelb5700 MATCH [OK: 247] +p-hgb1500 MATCH [OK: 242] p-hgb2100 MATCH [OK: 173] p-hgb3300 MATCH [OK: 279] +p-hgb3900 MATCH [OK: 210] p-hgb4500 MATCH [OK: 141] p-hgb5100 MATCH [OK: 71] +p-hgb6300 MATCH [OK: 177] p-hgb6900 MATCH [OK: 108] p-hgb7500 MATCH [OK: 284] +p-hgb900 MATCH [OK: 67] +``` + +All 13 byte-identical. Refusals were not touched (`refusal_inventory` tests are in +the suite below). + +## Merge interaction (for the orchestrator) + +`main` now carries the pilot's **`a_real_libaom_monochrome_key_frame_is_refused_by_name`** +(merged at `d71084ae`, after this lane's base `7f4e8301`). This lane adds the +**inverted witness** `..._decodes_pixel_exact` in the same `stream.rs` test module +and does NOT edit the pinning test (per charter). A merge will **conflict in +`crates/ec-av1/src/stream.rs`**: the resolution is to DROP the pilot's pinning +gate and keep this lane's byte-exact witness (the pinning gate asserts the very +behaviour this lane removes, so it must fail once mono decode lands). The +witness test's own doc comment records this. + +## Gates + +- `cargo check -p ec-av1` (post-salvage) → rc 0. +- `cargo check -p ec-av1 --all-targets` → rc 0, **0 warnings** (second target dir + `$HOME/.cache/cargo-target-av1mono-check`). +- `cargo test -p ec-av1 --lib` to completion → **592 passed, 0 failed, 60 ignored** + (6724 s), on the final tree. + +## Repro + +``` +ffmpeg -v error -f lavfi -i "testsrc2=size=320x240:rate=30:duration=2" \ + -pix_fmt gray -c:v libaom-av1 -cpu-used 8 -b:v 300k -f obu -y /tmp/gray.obu +P=$HOME/.cache/cargo-target-av1mono/release/examples/decode_probe +EC_PROBE_OUT16=$HOME/m.raw16 $P /tmp/gray.obu # OK: 60 frames +ffmpeg -v error -i /tmp/gray.obu -pix_fmt gray -f rawvideo $HOME/ref.gray +python3 -c "d=open('$HOME/m.raw16','rb').read()[0::2]; print(bytes(d)==open('$HOME/ref.gray','rb').read())" # True +``` + +## Suite + +``` +$ cargo test -p ec-av1 --lib +test result: ok. 592 passed; 0 failed; 60 ignored; 0 measured; 0 filtered out; finished in 6724.24s +``` + +Same count as the pilot's completed run on `main` (592/0/60, 6716 s), so no test +regressed, no test was added-but-unrun, and the 60 ignored are the pre-existing +single-process-global cases. `cargo check -p ec-av1 --all-targets` → rc 0, 0 +warnings on the same final bytes. + +## Deferred / not chased + +- `av1-profile1-444.ivf` chroma non-exactness (pilot §3.2 4:4:4 block-routing) — + pre-existing, unchanged by this lane. +- The pilot's 4:4:4-fast / all-intra / warped-cpu0 recipes — untouched.