forge
Explore
Log in

Don't you dare go Hollow

ec-av1: monochrome decode is luma byte-exact (merge lane-av1-mono)

Browse files at this commit

65734b06e1736dceb73049af2ab18aa019e3bfbbAhmet Kaan GümüşParent: 153a67d672ceb9
Merges lane-av1-mono (66a39803) into main. The lane decodes a monochrome
AV1 stream (color_config.mono_chrome, NumPlanes == 1) with luma byte-exact
against ffmpeg's own decode on three witnesses: a 60-frame gray key frame,
a 120-frame gray inter sequence, and the av1-monochrome.ivf fixture.

Conflict: crates/ec-av1/src/stream.rs (3 hunks). The pilot's pinning gate
a_real_libaom_monochrome_key_frame_is_refused_by_name asserts the very
refusal this lane removes, so it was DROPPED and the lane's inverted
witness a_real_libaom_monochrome_key_frame_decodes_pixel_exact kept in its
place, per the reviewer's merge-side guidance. decode.rs and
decode_probe.rs auto-merged to the lane's bytes.

Merged-tree gates: cargo test -p ec-av1 --lib -> 592 passed, 0 failed,
60 ignored (8124 s); cargo check -p ec-av1 --all-targets -> 0 warnings;
probe spot-checks (3 mono witnesses + one 10-bit film window) all byte-exact.
crates/ec-av1/examples/decode_probe.rsmodified+9 -4
@@ -266,9 +266,10 @@ fn main() {
266266 // triage needs.
267267 if let Some(seq) = parser.sequence_header() {
268268 println!(
269- "SEQ: use_128x128_superblock={} bit_depth={} max_frame={}x{}",
269+ "SEQ: use_128x128_superblock={} bit_depth={} mono_chrome={} max_frame={}x{}",
270270 seq.use_128x128_superblock,
271271 seq.color_config.bit_depth,
272+ seq.color_config.mono_chrome,
272273 seq.max_frame_width,
273274 seq.max_frame_height
274275 );
@@ -310,6 +311,9 @@ fn main() {
310311 let mut shown = 0usize;
311312 let mut dims = (0usize, 0usize);
312313 let mut buf: Vec<u8> = Vec::new();
314+ // lane-av1mono: a monochrome stream is luma only, so the raw dump is a
315+ // single plane -- exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes.
316+ let mono = parser.sequence_header().is_some_and(|s| s.color_config.mono_chrome);
313317 let result = ec_av1::stream::decode_stream_with(&data, |f, _idx, is_shown| {
314318 if !is_shown {
315319 return Ok(());
@@ -318,8 +322,9 @@ fn main() {
318322 if shown == 1 {
319323 dims = (f.width, f.height);
320324 }
325+ let planes: &[&Vec<u16>] = if mono { &[&f.y] } else { &[&f.y, &f.u, &f.v] };
321326 if let Some(w) = f16.as_mut() {
322- let n = 2 * (f.y.len() + f.u.len() + f.v.len());
327+ let n = 2 * planes.iter().map(|p| p.len()).sum::<usize>();
323328 if null16 {
324329 // Timing runs point EC_PROBE_OUT16 at /dev/null; the u16->LE
325330 // conversion was ~2% of the main thread for bytes nobody reads.
@@ -328,7 +333,7 @@ fn main() {
328333 buf.clear();
329334 buf.resize(n, 0);
330335 let mut off = 0;
331- for p in [&f.y, &f.u, &f.v] {
336+ for p in planes {
332337 let end = off + 2 * p.len();
333338 for (d, &s) in buf[off..end].chunks_exact_mut(2).zip(p.iter()) {
334339 d.copy_from_slice(&s.to_le_bytes());
@@ -341,7 +346,7 @@ fn main() {
341346 }
342347 if let Some(w) = f8.as_mut() {
343348 buf.clear();
344- for p in [&f.y, &f.u, &f.v] {
349+ for p in planes {
345350 buf.extend(p.iter().map(|&s| s as u8));
346351 }
347352 w.write_all(&buf).expect("writing raw planes");
crates/ec-av1/src/decode.rsmodified+197 -37
@@ -86,6 +86,16 @@ pub(crate) struct FrameCtx {
8686 pub(crate) lossless_flag: std::cell::Cell<bool>,
8787 pub(crate) cdef_bits: std::cell::Cell<u8>,
8888 pub(crate) bit_depth: std::cell::Cell<u8>,
89+ /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec
90+ /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as
91+ /// `av1_num_planes(cm)` and every chroma read site is guarded by
92+ /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`,
93+ /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes
94+ /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma
95+ /// coefficients on any block. Set once per frame from the sequence header
96+ /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread
97+ /// that last saw a 4:2:0 one never inherits the wrong plane count.
98+ pub(crate) mono_chrome: std::cell::Cell<bool>,
8999 pub(crate) superres: std::cell::Cell<(u32, u32)>,
90100 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
91101 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
@@ -175,6 +185,7 @@ impl FrameCtx {
175185 lossless_flag: std::cell::Cell::new(false),
176186 cdef_bits: std::cell::Cell::new(0),
177187 bit_depth: std::cell::Cell::new(8),
188+ mono_chrome: std::cell::Cell::new(false),
178189 superres: std::cell::Cell::new((0, 8)),
179190 cdef_transmitted: std::cell::Cell::new(false),
180191 cdef_sb_cols: std::cell::Cell::new(0),
@@ -269,6 +280,7 @@ impl<T: ?Sized> WithRef for T {}
269280 pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
270281 let out = FrameCtx::new();
271282 out.bit_depth.set(fctx.bit_depth.get());
283+ out.mono_chrome.set(fctx.mono_chrome.get());
272284 out.interp_filter.set(fctx.interp_filter.get());
273285 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
274286 out.superres.set(fctx.superres.get());
@@ -566,6 +578,19 @@ pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
566578 fctx.bit_depth.with(|c| c.set(bit_depth));
567579 }
568580
581+/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a
582+/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma
583+/// symbol or chroma coefficient and the output picture is luma only.
584+pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool {
585+ fctx.mono_chrome.with(std::cell::Cell::get)
586+}
587+
588+/// Sets [`mono`] for the current thread, called once per frame from
589+/// [`crate::stream`]'s decode loop like [`set_bit_depth`].
590+pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) {
591+ fctx.mono_chrome.with(|c| c.set(mono_chrome));
592+}
593+
569594 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
570595 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
571596 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
@@ -6780,6 +6805,39 @@ fn read_coeffs_rect(
67806805 Ok((Grid::Own(grid), tx_type))
67816806 }
67826807
6808+/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
6809+/// [`read_plane`] family already has.
6810+///
6811+/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
6812+/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
6813+/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
6814+/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
6815+/// enforces that for every strip that reads its chroma through it, but the rect
6816+/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
6817+/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
6818+/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
6819+/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
6820+/// chroma read desyncs at the FIRST rect leaf of the frame and every later
6821+/// symbol -- and therefore every later pixel -- is decoded from the wrong
6822+/// place, without ever tripping a refusal (the desynced values stay inside
6823+/// every coded alphabet).
6824+fn read_chroma_coeffs_rect(
6825+ dec: &mut SymbolDecoder,
6826+ coding: &mut TxbTables,
6827+ scan: &[u16],
6828+ w: usize,
6829+ h: usize,
6830+ skip_ctx: usize,
6831+ sign_ctx: usize,
6832+ default_tx_type: TxType,
6833+ fctx: &crate::decode::FrameCtx,
6834+) -> Result<(Grid, TxType)> {
6835+ if mono(fctx) {
6836+ return Ok((Grid::Zero(w * h), TxType::DctDct));
6837+ }
6838+ read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
6839+}
6840+
67836841 /// What one coded block leaves behind for the blocks that read it as a
67846842 /// neighbour: whether it coded anything at all, and the sign of its DC —
67856843 /// [`crate::tile`]'s own private `Neighbour`.
@@ -9047,6 +9105,12 @@ fn read_intra_mode_rect(
90479105 Option<PaletteY>,
90489106 Option<PaletteUv>,
90499107 )> {
9108+ // lane-av1mono: libaom guards every chroma symbol read with
9109+ // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
9110+ // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
9111+ // `palette_uv` even on a chroma-reference strip. Fold the plane count
9112+ // into the same `has_chroma` this reader already gates on.
9113+ let has_chroma = has_chroma && !mono(fctx);
90509114 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
90519115 if ec_istep {
90529116 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
@@ -9805,7 +9869,14 @@ fn decode_rect_split(
98059869 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new();
98069870 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
98079871 let reach = block_reach;
9808- let (u_grid, v_grid) = if m.skip {
9872+ let (u_grid, v_grid) = if mono(fctx) {
9873+ // lane-av1mono: a monochrome frame codes no chroma coefficients on
9874+ // any block (`plane < av1_num_planes == 1`), so the whole chroma
9875+ // section -- the skipped-strip pushes, the lossless raster and the
9876+ // un-split `read_coeffs_rect` below -- is bypassed.
9877+ let zero = Grid::Zero(chroma_w * chroma_h);
9878+ (zero.clone(), zero)
9879+ } else if m.skip {
98099880 let zero = Grid::Zero(chroma_w * chroma_h);
98109881 if let Some((ub, _)) = &m.palette_uv {
98119882 set_palette_pred(ub.clone(), fctx);
@@ -10456,8 +10527,14 @@ fn decode_intra_rect_in_inter(
1045610527 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
1045710528 // superblock-level strip reads the no-CFL alphabet -- the same split
1045810529 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10459- let cfl_allowed = cfl_allowed_px(bw, bh, fctx);
10460- let uv_mode = if cfl_allowed {
10530+ //
10531+ // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
10532+ // (libaom `decodemv.c:933`).
10533+ let has_chroma = !mono(fctx);
10534+ let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
10535+ let uv_mode = if !has_chroma {
10536+ DC_PRED
10537+ } else if cfl_allowed {
1046110538 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1046210539 } else {
1046310540 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
@@ -10518,8 +10595,11 @@ fn decode_intra_rect_in_inter(
1051810595 }
1051910596 // A 2:1 strip of at least 8x8 is always a chroma reference, so
1052010597 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10521- let use_palette_uv =
10522- uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10598+ // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
10599+ // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
10600+ let use_palette_uv = has_chroma
10601+ && uv_mode == DC_PRED
10602+ && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
1052310603 if crate::envflags::env_flag!("EC_PALSYN") {
1052410604 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);
1052510605 }
@@ -11059,7 +11139,7 @@ fn decode_block_rect(
1105911139 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
1106011140 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
1106111141 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
11062- let (u_levels, u_tx_type) = read_coeffs_rect(
11142+ let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
1106311143 dec,
1106411144 &mut u_coding,
1106511145 chroma_scan,
@@ -11068,6 +11148,7 @@ fn decode_block_rect(
1106811148 u_skip_ctx,
1106911149 dc_sign_ctx(around[1].2),
1107011150 u_default_tx,
11151+ fctx,
1107111152 )?;
1107211153 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1107311154 let (rng, _) = dec.debug_state();
@@ -11102,7 +11183,7 @@ fn decode_block_rect(
1110211183 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
1110311184 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
1110411185 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
11105- let (v_levels, v_tx_type) = read_coeffs_rect(
11186+ let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
1110611187 dec,
1110711188 &mut v_coding,
1110811189 chroma_scan,
@@ -11111,6 +11192,7 @@ fn decode_block_rect(
1111111192 v_skip_ctx,
1111211193 dc_sign_ctx(around[2].2),
1111311194 v_default_tx,
11195+ fctx,
1111411196 )?;
1111511197 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1111611198 let (rng, _) = dec.debug_state();
@@ -11441,9 +11523,9 @@ fn decode_leaf_rect(
1144111523 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
1144211524 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
1144311525 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11444- let (u_l, u_tx_type) = read_coeffs_rect(
11526+ let (u_l, u_tx_type) = read_chroma_coeffs_rect(
1144511527 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
11446- dc_sign_ctx(around[1].2), u_default_tx,
11528+ dc_sign_ctx(around[1].2), u_default_tx, fctx,
1144711529 )?;
1144811530 u_levels = u_l;
1144911531 let u_residual = dequant_and_inverse_typed_wh(
@@ -11460,9 +11542,9 @@ fn decode_leaf_rect(
1146011542 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
1146111543 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
1146211544 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11463- let (v_l, v_tx_type) = read_coeffs_rect(
11545+ let (v_l, v_tx_type) = read_chroma_coeffs_rect(
1146411546 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
11465- dc_sign_ctx(around[2].2), v_default_tx,
11547+ dc_sign_ctx(around[2].2), v_default_tx, fctx,
1146611548 )?;
1146711549 v_levels = v_l;
1146811550 let v_residual = dequant_and_inverse_typed_wh(
@@ -11791,7 +11873,7 @@ fn decode_block_rect4(
1179111873 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
1179211874 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
1179311875 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
11794- let (levels, tx_type) = read_coeffs_rect(
11876+ let (levels, tx_type) = read_chroma_coeffs_rect(
1179511877 dec,
1179611878 &mut coding,
1179711879 chroma_scan,
@@ -11800,6 +11882,7 @@ fn decode_block_rect4(
1180011882 skip_ctx,
1180111883 dc_sign_ctx(around[plane].2),
1180211884 default_tx,
11885+ fctx,
1180311886 )?;
1180411887 planes.push((levels, tx_type));
1180511888 }
@@ -12441,7 +12524,7 @@ fn decode_rect4_16_strip(
1244112524 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
1244212525 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
1244312526 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12444- let (levels, tx_type) = read_coeffs_rect(
12527+ let (levels, tx_type) = read_chroma_coeffs_rect(
1244512528 dec,
1244612529 &mut coding,
1244712530 chroma_scan,
@@ -12450,6 +12533,7 @@ fn decode_rect4_16_strip(
1245012533 skip_ctx,
1245112534 dc_sign_ctx(around[plane].2),
1245212535 default_tx,
12536+ fctx,
1245312537 )?;
1245412538 planes.push((levels, tx_type));
1245512539 }
@@ -12965,7 +13049,7 @@ fn decode_block_rect64(
1296513049 let (rng, _) = dec.debug_state();
1296613050 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
1296713051 }
12968- let (u_levels, u_tx_type) = read_coeffs_rect(
13052+ let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
1296913053 dec,
1297013054 &mut u_coding,
1297113055 chroma_scan,
@@ -12974,6 +13058,7 @@ fn decode_block_rect64(
1297413058 u_skip_ctx,
1297513059 dc_sign_ctx(around[1].2),
1297613060 TxType::DctDct,
13061+ fctx,
1297713062 )?;
1297813063 if coeff_trace_on() {
1297913064 let (rng, _) = dec.debug_state();
@@ -13029,7 +13114,7 @@ fn decode_block_rect64(
1302913114 let (rng, _) = dec.debug_state();
1303013115 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
1303113116 }
13032- let (v_levels, v_tx_type) = read_coeffs_rect(
13117+ let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
1303313118 dec,
1303413119 &mut v_coding,
1303513120 chroma_scan,
@@ -13038,6 +13123,7 @@ fn decode_block_rect64(
1303813123 v_skip_ctx,
1303913124 dc_sign_ctx(around[2].2),
1304013125 TxType::DctDct,
13126+ fctx,
1304113127 )?;
1304213128 if coeff_trace_on() {
1304313129 let (rng, _) = dec.debug_state();
@@ -13270,11 +13356,15 @@ fn read_intra_mode(
1327013356 0
1327113357 };
1327213358 istep!("angle_y", angle_delta_y);
13273- // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
13274- // here so every `decode_block` caller (64x64 and 128x128 roots included)
13275- // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
13276- let cfl = cfl && cfl_allowed_px(side, side, fctx);
13277- let uv_mode = if cfl {
13359+ // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
13360+ // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
13361+ // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
13362+ // gates its chroma symbols on.
13363+ let has_chroma = !mono(fctx);
13364+ let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
13365+ let uv_mode = if !has_chroma {
13366+ DC_PRED
13367+ } else if cfl {
1327813368 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1327913369 } else {
1328013370 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
@@ -13375,8 +13465,16 @@ fn read_intra_mode(
1337513465 // scope always reconstructs chroma alongside luma (`decode_block`
1337613466 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
1337713467 // is always true here and does not need threading in.
13468+ //
13469+ // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
13470+ // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
13471+ // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
13472+ // symbol even at this chroma-owning square block.
1337813473 let palette_uv_mode_ctx = usize::from(use_palette_y);
13379- if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
13474+ if has_chroma
13475+ && uv_mode == DC_PRED
13476+ && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
13477+ {
1338013478 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
1338113479 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
1338213480 palette_uv_pending = Some((n, u_colors, v_colors));
@@ -14038,6 +14136,14 @@ fn read_plane(
1403814136 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
1403914137 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
1404014138 ) -> Result<Grid> {
14139+ // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
14140+ // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
14141+ // never reaches a chroma plane -- no u/v coefficient symbol is coded and
14142+ // no chroma write is recorded. Return the all-zero grid the caller's
14143+ // neighbour bookkeeping reads, without consuming a bit.
14144+ if plane_idx > 0 && mono(fctx) {
14145+ return Ok(Grid::Zero(side * side));
14146+ }
1404114147 let skip_ctx = if plane_idx == 0 {
1404214148 luma_skip_ctx.unwrap_or(0)
1404314149 } else {
@@ -15916,6 +16022,9 @@ fn read_intra_mode_sub8(
1591616022 seg_w_mi: usize,
1591716023 seg_h_mi: usize, fctx: &crate::decode::FrameCtx,
1591816024 ) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
16025+ // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
16026+ // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
16027+ let has_chroma = has_chroma && !mono(fctx);
1591916028 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
1592016029 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
1592116030 if ec_istep {
@@ -16131,6 +16240,11 @@ fn decode_leaf_split4(
1613116240 last_uv = chroma;
1613216241 }
1613316242 }
16243+ // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no
16244+ // chroma to reconstruct and no uv_mode was read.
16245+ let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
16246+ (Grid::Zero(16), Grid::Zero(16))
16247+ } else {
1613416248 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
1613516249 let (cpx, cpy) = (gpx / 2, gpy / 2);
1613616250 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
@@ -16172,6 +16286,8 @@ fn decode_leaf_split4(
1617216286 )?;
1617316287 (ug, vg)
1617416288 };
16289+ (u_grid, v_grid)
16290+ };
1617516291 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
1617616292 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
1617716293 // rescaling is wrong for an already-mi-unit position, so this inlines
@@ -16518,6 +16634,12 @@ fn decode_leaf_rect8(
1651816634 last_uv = chroma;
1651916635 }
1652016636 }
16637+ // lane-av1mono: a monochrome frame codes no chroma at all -- no
16638+ // `uv_mode` was read ([`read_intra_mode_sub8`] folds the plane count in),
16639+ // so there is no chroma to reconstruct and no chroma coefficient to read.
16640+ let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
16641+ (Grid::Zero(16), Grid::Zero(16))
16642+ } else {
1652116643 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
1652216644 let (cpx, cpy) = (gpx / 2, gpy / 2);
1652316645 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
@@ -16559,6 +16681,8 @@ fn decode_leaf_rect8(
1655916681 )?;
1656016682 (ug, vg)
1656116683 };
16684+ (u_grid, v_grid)
16685+ };
1656216686 // `update_partition_context` at the 8x8 level writes
1656316687 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
1656416688 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
@@ -18498,6 +18622,11 @@ fn read_inter_plane_rect(
1849818622 inherited_luma_tx_type: Option<TxType>,
1849918623 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
1850018624 ) -> Result<(Grid, TxType)> {
18625+ // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma
18626+ // coefficients (`plane < av1_num_planes == 1`).
18627+ if plane_idx > 0 && mono(fctx) {
18628+ return Ok((Grid::Zero(w * h), TxType::DctDct));
18629+ }
1850118630 let skip_ctx = if plane_idx == 0 {
1850218631 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
1850318632 // block; a var-tx leaf passes its own neighbour-table context.
@@ -24737,6 +24866,11 @@ fn read_inter_plane(
2473724866 // lone-transform-unit 0.
2473824867 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
2473924868 ) -> Result<(Grid, TxType)> {
24869+ // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma
24870+ // coefficients (`plane < av1_num_planes == 1`).
24871+ if plane_idx > 0 && mono(fctx) {
24872+ return Ok((Grid::Zero(side * side), TxType::DctDct));
24873+ }
2474024874 let skip_ctx = if plane_idx == 0 {
2474124875 luma_skip_ctx.unwrap_or(0)
2474224876 } else {
@@ -29747,11 +29881,16 @@ fn decode_inter_block(
2974729881 // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the
2974829882 // arithmetic coder by the wrong interval, desyncing the tile from this
2974929883 // block on.
29750- let cfl_allowed = cfl_allowed_px(write_w, write_h, fctx);
29884+ // lane-av1mono: a monochrome block codes no chroma mode/CFL symbol
29885+ // (libaom `decodemv.c:933`).
29886+ let has_chroma = !mono(fctx);
29887+ let cfl_allowed = has_chroma && cfl_allowed_px(write_w, write_h, fctx);
2975129888 if !cfl_allowed {
2975229889 hit!(NOCFL_UV_MODE_HITS);
2975329890 }
29754- let uv_mode = if cfl_allowed {
29891+ let uv_mode = if !has_chroma {
29892+ DC_PRED
29893+ } else if cfl_allowed {
2975529894 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2975629895 } else {
2975729896 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
@@ -29822,8 +29961,9 @@ fn decode_inter_block(
2982229961 if crate::envflags::env_flag!("EC_PALSYN") {
2982329962 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);
2982429963 }
29825- let use_palette_uv =
29826- uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
29964+ let use_palette_uv = has_chroma
29965+ && uv_mode == DC_PRED
29966+ && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
2982729967 if crate::envflags::env_flag!("EC_PALSYN") {
2982829968 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);
2982929969 }
@@ -31177,6 +31317,9 @@ fn decode_intra_sub8_leaf(
3117731317 tx_select: bool,
3117831318 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
3117931319 ) -> Result<usize> {
31320+ // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
31321+ // `decodemv.c:933`).
31322+ let has_chroma = has_chroma && !mono(fctx);
3118031323 let vert = bw < bh;
3118131324 let (w_mi, h_mi) = (bw / MI, bh / MI);
3118231325 let (gr, gc) = group_mi;
@@ -31499,6 +31642,26 @@ fn decode_intra_sub8_leaf(
3149931642 h.set(s);
3150031643 });
3150131644 }
31645+ // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map
31646+ // needs EVERY writer): a sub-8x8 group published no palette state, so
31647+ // once an 8x8 leaf of the same row can BE a palette block, the group
31648+ // left the row's band holding that earlier block's size and the next
31649+ // intra block read `av1_get_palette_mode_ctx` one too high (measured:
31650+ // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers
31651+ // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette`
31652+ // needs `bsize >= BLOCK_8X8`), so the group always clears.
31653+ //
31654+ // lane-av1mono: this publish is NOT chroma work and must run BEFORE the
31655+ // `!has_chroma` return below. libaom's mi grid holds
31656+ // `palette_size[0] == 0` in every cell of such a group whatever the
31657+ // plane count, and on a monochrome frame EVERY sub-8 leaf passes
31658+ // `has_chroma == false`, so a publish placed after the return never ran
31659+ // at all: the band kept an earlier palette block's size, the next block
31660+ // read `palette_y_mode` off CDF row 1 where libaom reads row 0, decoded
31661+ // a palette libaom never coded, and the tile desynced one block later
31662+ // (measured: gray testsrc2 320x240, decode-order frame 33, mi(42,50),
31663+ // ours ctx 2 where libaom gathers 1).
31664+ record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]);
3150231665 if !has_chroma {
3150331666 return Ok(mode);
3150431667 }
@@ -31517,15 +31680,6 @@ fn decode_intra_sub8_leaf(
3151731680 neighbours.above_uv_mode[c] = uv_predict_mode;
3151831681 neighbours.left_uv_mode[r] = uv_predict_mode;
3151931682 neighbours.record_uv_mode_mi(gr, gc, 2, 2, uv_predict_mode);
31520- // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map
31521- // needs EVERY writer): a sub-8x8 group published no palette state, so
31522- // once an 8x8 leaf of the same row can BE a palette block, the group
31523- // left the row's band holding that earlier block's size and the next
31524- // intra block read `av1_get_palette_mode_ctx` one too high (measured:
31525- // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers
31526- // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette`
31527- // needs `bsize >= BLOCK_8X8`), so the group always clears.
31528- record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]);
3152931683
3153031684 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
3153131685 let (u_grid, v_grid): (Grid, Grid) = if skip {
@@ -33871,7 +34025,12 @@ fn decode_inter_block8(
3387134025 // row (`get_uv_mode`, identity over `V_PRED..=D67_PRED`). Every value
3387234026 // but `DC_PRED` was refused here, which is what blocked the low-cq
3387334027 // CDEF arms and the 10-bit gates.
33874- let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
34028+ let has_chroma = !mono(fctx);
34029+ let uv_mode = if !has_chroma {
34030+ DC_PRED
34031+ } else {
34032+ dec.symbol(&mut cdfs.uv_mode_cfl[mode])
34033+ };
3387534034 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
3387634035 eprintln!(
3387734036 "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}",
@@ -33885,7 +34044,7 @@ fn decode_inter_block8(
3388534044 hit!(SMOOTH_UV_HITS);
3388634045 hit!(INTRA_IN_INTER8_UV_SMOOTH_HITS);
3388734046 }
33888- let alpha = if uv_mode == UV_CFL_PRED {
34047+ let alpha = if has_chroma && uv_mode == UV_CFL_PRED {
3388934048 hit!(INTRA_IN_INTER8_UV_CFL_HITS);
3389034049 Some(read_cfl_alphas(dec, cdfs))
3389134050 } else {
@@ -33942,7 +34101,8 @@ fn decode_inter_block8(
3394234101 }
3394334102 // lane-uv8 r1: `read_palette_mode_info` reads the UV symbol only
3394434103 // when `uv_mode == UV_DC_PRED` (decodemv.c).
33945- let use_palette_uv = uv_mode == DC_PRED
34104+ let use_palette_uv = has_chroma
34105+ && uv_mode == DC_PRED
3394634106 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
3394734107 if crate::envflags::env_flag!("EC_PALSYN") {
3394834108 eprintln!(
crates/ec-av1/src/stream.rsmodified+122 -50
@@ -1243,6 +1243,9 @@ pub(crate) struct SeqFlags {
12431243 pub(crate) enable_interintra_compound: bool,
12441244 pub(crate) use_sb128: bool,
12451245 pub(crate) bit_depth: u8,
1246+ /// lane-av1mono: `color_config.mono_chrome` (spec 5.5.2):
1247+ /// `NumPlanes == 1`, no chroma is coded or reconstructed.
1248+ pub(crate) mono_chrome: bool,
12461249 pub(crate) order_hint_bits: u32,
12471250 pub(crate) mc_identity: bool,
12481251 }
@@ -1259,6 +1262,7 @@ impl SeqFlags {
12591262 enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
12601263 use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
12611264 bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
1265+ mono_chrome: seq.is_some_and(|s| s.color_config.mono_chrome),
12621266 order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
12631267 mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
12641268 }
@@ -1633,6 +1637,10 @@ fn decode_frame(
16331637 // `a_lossless_libaom_inter_frame_decodes_sample_exact`.
16341638 crate::decode::set_lossless(coded_lossless, fctx);
16351639 crate::decode::set_bit_depth(bit_depth, fctx);
1640+ // lane-av1mono: the sequence header's `mono_chrome`, set per frame like
1641+ // the bit depth so a mono frame decoded on a thread that last saw a
1642+ // 4:2:0 one never inherits the wrong plane count.
1643+ crate::decode::set_mono(seq.mono_chrome, fctx);
16361644 // spec 7.16: this frame's superres state, for the filter chain --
16371645 // `decode.rs` upscales between CDEF and loop restoration and sizes
16381646 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
@@ -2016,40 +2024,31 @@ pub(crate) mod tests {
20162024 );
20172025 }
20182026
2019- /// lane-av1-decode (pilot resume, 2026-09-19): a real libaom MONOCHROME key
2020- /// frame is currently REFUSED BY NAME, and this gate pins that as today's
2021- /// measured first stop for a real encoder stream.
2027+ /// lane-av1mono: the INVERSE of the pilot's
2028+ /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the
2029+ /// pilot's merge `d71084ae` landed on `main` (after this lane's base
2030+ /// `7f4e8301`): the very same recipe now decodes, and its luma is
2031+ /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this
2032+ /// lane into `main` must therefore resolve that pinning gate by adopting
2033+ /// this witness in its place.
20222034 ///
2023- /// The parked lane's first wall (64x64 superblock-level partition arms) is
2024- /// ALREADY CLOSED on this tree (both user films decode byte-exact; the
2025- /// SB-level HORZ/VERT/AB/1:4 arms are witness-gated), so the re-measurement
2026- /// this gate belongs to had to find where a real stream stops TODAY. A
2027- /// `-pix_fmt gray` encode of the crate's own fixture recipe does.
2035+ /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`,
2036+ /// so libaom codes NO chroma symbol anywhere in the sequence -- not the
2037+ /// mode syntax, not a coefficient. That reaches all three classes this lane
2038+ /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma
2039+ /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect`
2040+ /// DIRECTLY instead of through `read_plane`'s own plane gate, and the
2041+ /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before
2042+ /// it returns (an uncleared band made the next block read `palette_y_mode`
2043+ /// off the wrong CDF row and silently desynced the rest of the tile --
2044+ /// measured at decode-order frame 33 of this very recipe).
20282045 ///
2029- /// Root cause (localised with `EC_TRACE_MODE_STEP` on the instrumented
2030- /// aomdec oracle vs this decoder, both over the same OBU): on the mono
2031- /// stream ours reads `angle_uv` at `rng=50996`, while aomdec reads NO
2032- /// `uv_mode`/`angle_uv` at all (the guard below); the first divergence at
2033- /// `(0,0)` is aomdec reading `tx_depth ctx=0 cat=1` (`rng=43616`) where
2034- /// ours reads a `uv_mode` (val=13). libaom's
2035- /// `decodemv.c` guards that read with
2036- /// `if (!cm->seq_params->monochrome && xd->is_chroma_ref)`: a monochrome
2037- /// frame codes NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` at all,
2038- /// while this decoder's block layer has no `num_planes`/monochrome notion
2039- /// and reads them for every block. That is the whole desync; the
2040- /// "a Golomb tail longer than this decoder reads" refusal is the SYMPTOM
2041- /// (the reader is left mid-symbol), not the defect -- which is why that
2042- /// string's PROVEN claim ("read_golomb_reads_every_value_a_conformant_stream_can_carry")
2043- /// does not contradict this gate.
2044- ///
2045- /// The twin 4:2:0 encode of the SAME source and recipe decodes, so this is
2046- /// a monochrome defect and not a recipe defect. When monochrome decode
2047- /// lands, flip this gate to a witness (decode BOTH twins pixel-exact
2048- /// against ffmpeg); the refusal string is the tripwire.
2049- #[test]
2050- fn a_real_libaom_monochrome_key_frame_is_refused_by_name() {
2051- const NAME: &str = "a_real_libaom_monochrome_key_frame_is_refused_by_name";
2052- const REFUSAL: &str = "a Golomb tail longer than this decoder reads";
2046+ /// The 4:2:0 twin of the same source and settings is the control: it proves
2047+ /// the recipe is decodable, so a failure here is about the plane count and
2048+ /// not about the source or the encoder settings.
2049+ #[test]
2050+ fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() {
2051+ const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact";
20532052 if !have_ffmpeg() {
20542053 eprintln!("SKIP {NAME}: no ffmpeg");
20552054 return;
@@ -2057,9 +2056,23 @@ pub(crate) mod tests {
20572056 let emit = |pix: &str| -> Vec<u8> {
20582057 let out = Command::new("ffmpeg")
20592058 .args([
2060- "-v", "error", "-f", "lavfi", "-i",
2061- "testsrc2=size=320x240:rate=30:duration=2", "-pix_fmt", pix,
2062- "-c:v", "libaom-av1", "-cpu-used", "8", "-b:v", "300k", "-f", "obu", "-",
2059+ "-v",
2060+ "error",
2061+ "-f",
2062+ "lavfi",
2063+ "-i",
2064+ "testsrc2=size=320x240:rate=30:duration=2",
2065+ "-pix_fmt",
2066+ pix,
2067+ "-c:v",
2068+ "libaom-av1",
2069+ "-cpu-used",
2070+ "8",
2071+ "-b:v",
2072+ "300k",
2073+ "-f",
2074+ "obu",
2075+ "-",
20632076 ])
20642077 .stdin(Stdio::null())
20652078 .stdout(Stdio::piped())
@@ -2073,24 +2086,40 @@ pub(crate) mod tests {
20732086 );
20742087 out.stdout
20752088 };
2076- // CONTROL: the identical recipe at 4:2:0 decodes -- so the refusal below
2077- // is about monochrome, not about the source or the encoder settings.
2089+ // CONTROL: the identical recipe at 4:2:0 still decodes.
20782090 let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode");
20792091 assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames");
2080- let err = decode_stream(&emit("gray"))
2081- .err()
2082- .map(|e| e.to_string())
2083- .unwrap_or_else(|| {
2084- panic!("{NAME}: the monochrome stream now decodes -- flip this gate to a witness")
2085- });
2086- assert!(
2087- err.contains(REFUSAL),
2088- "{NAME}: the monochrome stream stopped without the measured refusal \
2089- {REFUSAL:?} -- the desync moved; re-measure before trusting this gate. got: {err}"
2090- );
2092+ // THE WITNESS: the monochrome stream decodes and every luma sample
2093+ // equals ffmpeg's own decode of the same OBU.
2094+ let gray = emit("gray");
2095+ let ours = decode_stream(&gray)
2096+ .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}"));
2097+ let (width, height) = (320usize, 240usize);
2098+ const FRAMES: usize = 60;
2099+ assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames");
2100+ let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES);
2101+ for (i, plane) in reference.chunks_exact(width * height).enumerate() {
2102+ assert_eq!(ours[i].width, width, "{NAME}: frame {i} width");
2103+ assert_eq!(ours[i].height, height, "{NAME}: frame {i} height");
2104+ assert_eq!(
2105+ ours[i].y.len(),
2106+ width * height,
2107+ "{NAME}: frame {i} luma length"
2108+ );
2109+ for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() {
2110+ assert_eq!(
2111+ *want,
2112+ u16::from(*got),
2113+ "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}",
2114+ j / width,
2115+ j % width
2116+ );
2117+ }
2118+ }
20912119 eprintln!(
2092- "{NAME}: 4:2:0 twin {} frames, monochrome refused by name ({REFUSAL})",
2093- twin.len()
2120+ "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg",
2121+ twin.len(),
2122+ ours.len()
20942123 );
20952124 }
20962125
@@ -3366,6 +3395,49 @@ pub(crate) mod tests {
33663395 .collect()
33673396 }
33683397
3398+ /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
3399+ /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
3400+ /// (lane-av1mono). Fed down a stdin writer thread for the reason the 4:2:0
3401+ /// helper documents.
3402+ fn ffmpeg_decode_gray_sequence(
3403+ stream: &[u8],
3404+ width: usize,
3405+ height: usize,
3406+ frames: usize,
3407+ ) -> Vec<u8> {
3408+ let mut child = Command::new("ffmpeg")
3409+ .args([
3410+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
3411+ ])
3412+ .stdin(Stdio::piped())
3413+ .stdout(Stdio::piped())
3414+ .stderr(Stdio::piped())
3415+ .spawn()
3416+ .expect("ffmpeg failed to start");
3417+ let mut stdin = child.stdin.take().expect("ffmpeg stdin");
3418+ let payload = stream.to_vec();
3419+ let writer = std::thread::Builder::new()
3420+ .name("ec-av1-ffmpeg-gray-in".into())
3421+ .spawn(move || {
3422+ let _ = stdin.write_all(&payload);
3423+ })
3424+ .expect("spawning the ffmpeg stdin writer");
3425+ let out = child.wait_with_output().expect("ffmpeg failed to run");
3426+ writer.join().expect("ffmpeg stdin writer thread");
3427+ assert!(
3428+ out.status.success(),
3429+ "ffmpeg refused the monochrome stream: {}",
3430+ String::from_utf8_lossy(&out.stderr)
3431+ );
3432+ assert_eq!(
3433+ out.stdout.len(),
3434+ width * height * frames,
3435+ "expected {frames} monochrome frames, ffmpeg said: {}",
3436+ String::from_utf8_lossy(&out.stderr)
3437+ );
3438+ out.stdout
3439+ }
3440+
33693441 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
33703442 /// are 2-byte little-endian, one full 16-bit range regardless of the
33713443 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
lanes/av1mono.report.mdadded+593 -0
@@ -0,0 +1,593 @@
1+# lane-av1-mono — monochrome AV1 decode is luma byte-exact (60f kf, 120f inter, mono.ivf)
2+
3+Base: `main` **7f4e8301** (the WIP `av1: WIP monochrome plane model` commit; its
4+parent is `f0727a87`). Worktree `edith_codecs-av1mono`, branch `lane-av1-mono`,
5+`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1mono` (private). No push.
6+Status: **COMPLETE** — a monochrome AV1 stream decodes and its luma is byte-exact
7+against ffmpeg's own decode, on all three witnesses. The luma half of the pilot's
8+first real-stream wall (§3.1 of `lanes/av1decode.report.md`) is closed.
9+
10+## TL;DR
11+
12+The previous continuation (Yunus) died mid-flight on a provider outage, leaving a
13+working tree that *was* the fix but was buried under **24,000+ lines of omp
14+edit-tool rustfmt churn** (`git diff --stat` read 17300/6908 changed lines). This
15+session (1) salvaged a **semantic-only 19-hunk diff** out of that churn, (2)
16+verified it fixes the luma defect, (3) proved the three witnesses, the corpus, the
17+film windows and the suite.
18+
19+- **Salvage:** churn → `decode.rs` 88 lines, `stream.rs` 142 lines (211 insertions,
20+ 19 deletions). Method and proof below.
21+- **Root cause of the luma mismatch:** a **palette-mode neighbour band** that a
22+ mono sub-8x8 leaf left uncleared. The publish (`record_strip_palette`) sat
23+ *after* the `if !has_chroma { return }` early-out; on a monochrome frame EVERY
24+ sub-8 leaf takes that early-out, so the band kept an earlier palette block's
25+ size, the next block read `palette_y_mode` off CDF row 1 where libaom reads row
26+ 0, and the tile silently desynced one block later. (Symptom had been read as a
27+ reconstruction defect; it is an entropy desync.)
28+- **Second class closed:** the rect-strip paths call `read_coeffs_rect` on planes
29+ 1/2 **directly** (bypassing `read_plane`'s own mono gate), so a mono frame
30+ consumed a chroma coefficient symbol libaom never coded. New
31+ `read_chroma_coeffs_rect` gates those 8 call sites.
32+
33+## Salvage (what the dirty tree contained, what was kept/reverted)
34+
35+`git status` at handover: `M crates/ec-av1/src/decode.rs`, `M crates/ec-av1/src/stream.rs`.
36+
37+1. **Hunk classifier first** (`rustfmt-semantic-only-diff` recipe): a hunk is
38+ fmt-only iff its removed/added lines are equal after JOINING + stripping
39+ whitespace + folding trailing commas. Result: 677 hunks decode (609 fmt-only),
40+ 426 hunks stream (406 fmt-only) — *but this classifier is incomplete here*:
41+ the local rustfmt **wraps `ok_or_else(|| expr)` closure bodies in `{ ... }`**,
42+ so 40+ pure reflow hunks were flagged "semantic" (a brace pair my normalizer
43+ cannot fold away). Trusting it would have kept thousands of churn lines.
44+2. **Decisive method instead:** rustfmt the *committed* file and diff it against
45+ the working tree. `rustfmt --edition 2024 <7f4e8301 file>` ≈ the working tree:
46+ decode.rs 43620 vs 43672 lines (52-line residual), stream.rs 38666 vs 38805
47+ (139-line residual). So the working tree **was** `rustfmt(HEAD) + a small
48+ semantic delta` — the previous agent had not left a half-applied edit.
49+3. Extract `S = diff(rustfmt(7f4e8301), W)` (19 + 2 hunks), apply `S` to the
50+ committed file, and prove correctness mechanically: **`rustfmt(HEAD + S) == W`
51+ byte-for-byte** on both files. Whitespace-only home for every non-semantic line
52+ is then guaranteed: applying only `S` to `HEAD` cannot carry churn.
53+4. The `patch` of `S` onto `HEAD` needed fuzz at 5 of the 8 call sites and put
54+ `fctx,`/`let (` at the wrong indent there; fixed by hand (indentation is
55+ HEAD-style; the diff now shows ONLY identifier renames, `fctx` args, the new
56+ fn, the palette move, and the test).
57+5. **Coherence:** the semantic set is coherent — no orphaned variable, no broken
58+ syntax, one self-contained feature (`read_chroma_coeffs_rect` + the palette
59+ move). Nothing had to be reverted.
60+
61+## Root cause
62+
63+`decode_intra_sub8_leaf` (`decode.rs`). libaom's MI grid writes
64+`palette_size[0] == 0` for **every** cell of a sub-8x8 group whatever the plane
65+count (`av1_allow_palette` needs `bsize >= BLOCK_8X8`, so no sub-8 piece is ever
66+a palette block). ec-av1 did publish that clear — but only on the **chroma-reference**
67+path, after `if !has_chroma { return Ok(mode) }`. On a mono frame
68+`has_chroma == false` for every sub-8 leaf (`NumPlanes == 1`), so the publish
69+never ran: the row's band kept an earlier palette block's size, the next intra
70+block read `av1_get_palette_mode_ctx` one too high, decoded a `palette_y_mode`
71+symbol libaom never coded, and the tile desynced.
72+
73+Measured: gray testsrc2 320x240, **decode-order frame 33**, mi(42,50) — ours ctx 2
74+where libaom gathers 1. (First *pixel* divergence on the 60-frame stream lands at
75+frame 0, because the key frame's own early blocks already carry the mismatch.)
76+
77+## Fix
78+
79+- `crates/ec-av1/src/decode.rs`
80+ - **`record_strip_palette(...)` moved BEFORE the `!has_chroma` return** in
81+ `decode_intra_sub8_leaf` — unconditional, matching libaom's MI grid, with the
82+ extended comment. (This is the luma fix.)
83+ - New **`read_chroma_coeffs_rect`**: a mono early-return of `Grid::Zero` +
84+ `TxType::DctDct` before delegating to `read_coeffs_rect`; applied at the 8
85+ chroma call sites that read planes 1/2 directly
86+ (`decode_block_rect`, `decode_leaf_rect`, `decode_block_rect4`,
87+ `decode_rect4_16_strip`, `decode_block_rect64`). Closes the
88+ `reader-gate-not-on-every-path` class.
89+- `crates/ec-av1/src/stream.rs`
90+ - New witness test **`a_real_libaom_monochrome_key_frame_decodes_pixel_exact`**
91+ (the inverted form of the pilot's pinning gate) + `ffmpeg_decode_gray_sequence`
92+ helper.
93+
94+## Semantic-only diff vs 7f4e8301
95+
96+```diff
97+diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs
98+index 6399854a..75cd8aad 100644
99+--- a/crates/ec-av1/src/decode.rs
100++++ b/crates/ec-av1/src/decode.rs
101+@@ -6805,6 +6805,39 @@ fn read_coeffs_rect(
102+ Ok((Grid::Own(grid), tx_type))
103+ }
104+
105++/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
106++/// [`read_plane`] family already has.
107++///
108++/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
109++/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
110++/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
111++/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
112++/// enforces that for every strip that reads its chroma through it, but the rect
113++/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
114++/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
115++/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
116++/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
117++/// chroma read desyncs at the FIRST rect leaf of the frame and every later
118++/// symbol -- and therefore every later pixel -- is decoded from the wrong
119++/// place, without ever tripping a refusal (the desynced values stay inside
120++/// every coded alphabet).
121++fn read_chroma_coeffs_rect(
122++ dec: &mut SymbolDecoder,
123++ coding: &mut TxbTables,
124++ scan: &[u16],
125++ w: usize,
126++ h: usize,
127++ skip_ctx: usize,
128++ sign_ctx: usize,
129++ default_tx_type: TxType,
130++ fctx: &crate::decode::FrameCtx,
131++) -> Result<(Grid, TxType)> {
132++ if mono(fctx) {
133++ return Ok((Grid::Zero(w * h), TxType::DctDct));
134++ }
135++ read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
136++}
137++
138+ /// What one coded block leaves behind for the blocks that read it as a
139+ /// neighbour: whether it coded anything at all, and the sign of its DC —
140+ /// [`crate::tile`]'s own private `Neighbour`.
141+@@ -11106,7 +11139,7 @@ fn decode_block_rect(
142+ let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
143+ let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
144+ let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
145+- let (u_levels, u_tx_type) = read_coeffs_rect(
146++ let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
147+ dec,
148+ &mut u_coding,
149+ chroma_scan,
150+@@ -11115,6 +11148,7 @@ fn decode_block_rect(
151+ u_skip_ctx,
152+ dc_sign_ctx(around[1].2),
153+ u_default_tx,
154++ fctx,
155+ )?;
156+ if crate::envflags::env_flag!("EC_AV1_TRACE") {
157+ let (rng, _) = dec.debug_state();
158+@@ -11149,7 +11183,7 @@ fn decode_block_rect(
159+ let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
160+ let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
161+ let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
162+- let (v_levels, v_tx_type) = read_coeffs_rect(
163++ let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
164+ dec,
165+ &mut v_coding,
166+ chroma_scan,
167+@@ -11158,6 +11192,7 @@ fn decode_block_rect(
168+ v_skip_ctx,
169+ dc_sign_ctx(around[2].2),
170+ v_default_tx,
171++ fctx,
172+ )?;
173+ if crate::envflags::env_flag!("EC_AV1_TRACE") {
174+ let (rng, _) = dec.debug_state();
175+@@ -11488,9 +11523,9 @@ fn decode_leaf_rect(
176+ let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
177+ let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
178+ let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
179+- let (u_l, u_tx_type) = read_coeffs_rect(
180++ let (u_l, u_tx_type) = read_chroma_coeffs_rect(
181+ dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
182+- dc_sign_ctx(around[1].2), u_default_tx,
183++ dc_sign_ctx(around[1].2), u_default_tx, fctx,
184+ )?;
185+ u_levels = u_l;
186+ let u_residual = dequant_and_inverse_typed_wh(
187+@@ -11507,9 +11542,9 @@ fn decode_leaf_rect(
188+ let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
189+ let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
190+ let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
191+- let (v_l, v_tx_type) = read_coeffs_rect(
192++ let (v_l, v_tx_type) = read_chroma_coeffs_rect(
193+ dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
194+- dc_sign_ctx(around[2].2), v_default_tx,
195++ dc_sign_ctx(around[2].2), v_default_tx, fctx,
196+ )?;
197+ v_levels = v_l;
198+ let v_residual = dequant_and_inverse_typed_wh(
199+@@ -11838,7 +11873,7 @@ fn decode_block_rect4(
200+ let default_tx = default_intra_tx_type(uv_predict_mode as u8);
201+ let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
202+ let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
203+- let (levels, tx_type) = read_coeffs_rect(
204++ let (levels, tx_type) = read_chroma_coeffs_rect(
205+ dec,
206+ &mut coding,
207+ chroma_scan,
208+@@ -11847,6 +11882,7 @@ fn decode_block_rect4(
209+ skip_ctx,
210+ dc_sign_ctx(around[plane].2),
211+ default_tx,
212++ fctx,
213+ )?;
214+ planes.push((levels, tx_type));
215+ }
216+@@ -12488,7 +12524,7 @@ fn decode_rect4_16_strip(
217+ let default_tx = default_intra_tx_type(uv_predict_mode as u8);
218+ let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
219+ let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
220+- let (levels, tx_type) = read_coeffs_rect(
221++ let (levels, tx_type) = read_chroma_coeffs_rect(
222+ dec,
223+ &mut coding,
224+ chroma_scan,
225+@@ -12497,6 +12533,7 @@ fn decode_rect4_16_strip(
226+ skip_ctx,
227+ dc_sign_ctx(around[plane].2),
228+ default_tx,
229++ fctx,
230+ )?;
231+ planes.push((levels, tx_type));
232+ }
233+@@ -13012,7 +13049,7 @@ fn decode_block_rect64(
234+ let (rng, _) = dec.debug_state();
235+ eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
236+ }
237+- let (u_levels, u_tx_type) = read_coeffs_rect(
238++ let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
239+ dec,
240+ &mut u_coding,
241+ chroma_scan,
242+@@ -13021,6 +13058,7 @@ fn decode_block_rect64(
243+ u_skip_ctx,
244+ dc_sign_ctx(around[1].2),
245+ TxType::DctDct,
246++ fctx,
247+ )?;
248+ if coeff_trace_on() {
249+ let (rng, _) = dec.debug_state();
250+@@ -13076,7 +13114,7 @@ fn decode_block_rect64(
251+ let (rng, _) = dec.debug_state();
252+ eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
253+ }
254+- let (v_levels, v_tx_type) = read_coeffs_rect(
255++ let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
256+ dec,
257+ &mut v_coding,
258+ chroma_scan,
259+@@ -13085,6 +13123,7 @@ fn decode_block_rect64(
260+ v_skip_ctx,
261+ dc_sign_ctx(around[2].2),
262+ TxType::DctDct,
263++ fctx,
264+ )?;
265+ if coeff_trace_on() {
266+ let (rng, _) = dec.debug_state();
267+@@ -31604,6 +31643,26 @@ fn decode_intra_sub8_leaf(
268+ h.set(s);
269+ });
270+ }
271++ // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map
272++ // needs EVERY writer): a sub-8x8 group published no palette state, so
273++ // once an 8x8 leaf of the same row can BE a palette block, the group
274++ // left the row's band holding that earlier block's size and the next
275++ // intra block read `av1_get_palette_mode_ctx` one too high (measured:
276++ // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers
277++ // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette`
278++ // needs `bsize >= BLOCK_8X8`), so the group always clears.
279++ //
280++ // lane-av1mono: this publish is NOT chroma work and must run BEFORE the
281++ // `!has_chroma` return below. libaom's mi grid holds
282++ // `palette_size[0] == 0` in every cell of such a group whatever the
283++ // plane count, and on a monochrome frame EVERY sub-8 leaf passes
284++ // `has_chroma == false`, so a publish placed after the return never ran
285++ // at all: the band kept an earlier palette block's size, the next block
286++ // read `palette_y_mode` off CDF row 1 where libaom reads row 0, decoded
287++ // a palette libaom never coded, and the tile desynced one block later
288++ // (measured: gray testsrc2 320x240, decode-order frame 33, mi(42,50),
289++ // ours ctx 2 where libaom gathers 1).
290++ record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]);
291+ if !has_chroma {
292+ return Ok(mode);
293+ }
294+@@ -31622,15 +31681,6 @@ fn decode_intra_sub8_leaf(
295+ neighbours.above_uv_mode[c] = uv_predict_mode;
296+ neighbours.left_uv_mode[r] = uv_predict_mode;
297+ neighbours.record_uv_mode_mi(gr, gc, 2, 2, uv_predict_mode);
298+- // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map
299+- // needs EVERY writer): a sub-8x8 group published no palette state, so
300+- // once an 8x8 leaf of the same row can BE a palette block, the group
301+- // left the row's band holding that earlier block's size and the next
302+- // intra block read `av1_get_palette_mode_ctx` one too high (measured:
303+- // mi(30,30) of decode-order frame 1, ours ctx 1 where libaom gathers
304+- // 0). No sub-8x8 piece can itself be a palette (`av1_allow_palette`
305+- // needs `bsize >= BLOCK_8X8`), so the group always clears.
306+- record_strip_palette(neighbours, (gr, gc), 8, 8, 0, [0u16; 8], 0, [0u16; 8]);
307+
308+ let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
309+ let (u_grid, v_grid): (Grid, Grid) = if skip {
310+diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs
311+index a0b1bd43..d361662c 100644
312+--- a/crates/ec-av1/src/stream.rs
313++++ b/crates/ec-av1/src/stream.rs
314+@@ -2024,6 +2024,105 @@ pub(crate) mod tests {
315+ );
316+ }
317+
318++ /// lane-av1mono: the INVERSE of the pilot's
319++ /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the
320++ /// pilot's merge `d71084ae` landed on `main` (after this lane's base
321++ /// `7f4e8301`): the very same recipe now decodes, and its luma is
322++ /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this
323++ /// lane into `main` must therefore resolve that pinning gate by adopting
324++ /// this witness in its place.
325++ ///
326++ /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`,
327++ /// so libaom codes NO chroma symbol anywhere in the sequence -- not the
328++ /// mode syntax, not a coefficient. That reaches all three classes this lane
329++ /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma
330++ /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect`
331++ /// DIRECTLY instead of through `read_plane`'s own plane gate, and the
332++ /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before
333++ /// it returns (an uncleared band made the next block read `palette_y_mode`
334++ /// off the wrong CDF row and silently desynced the rest of the tile --
335++ /// measured at decode-order frame 33 of this very recipe).
336++ ///
337++ /// The 4:2:0 twin of the same source and settings is the control: it proves
338++ /// the recipe is decodable, so a failure here is about the plane count and
339++ /// not about the source or the encoder settings.
340++ #[test]
341++ fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() {
342++ const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact";
343++ if !have_ffmpeg() {
344++ eprintln!("SKIP {NAME}: no ffmpeg");
345++ return;
346++ }
347++ let emit = |pix: &str| -> Vec<u8> {
348++ let out = Command::new("ffmpeg")
349++ .args([
350++ "-v",
351++ "error",
352++ "-f",
353++ "lavfi",
354++ "-i",
355++ "testsrc2=size=320x240:rate=30:duration=2",
356++ "-pix_fmt",
357++ pix,
358++ "-c:v",
359++ "libaom-av1",
360++ "-cpu-used",
361++ "8",
362++ "-b:v",
363++ "300k",
364++ "-f",
365++ "obu",
366++ "-",
367++ ])
368++ .stdin(Stdio::null())
369++ .stdout(Stdio::piped())
370++ .stderr(Stdio::piped())
371++ .output()
372++ .expect("ffmpeg failed to run");
373++ assert!(
374++ out.status.success(),
375++ "{NAME}: ffmpeg ({pix}) failed: {}",
376++ String::from_utf8_lossy(&out.stderr)
377++ );
378++ out.stdout
379++ };
380++ // CONTROL: the identical recipe at 4:2:0 still decodes.
381++ let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode");
382++ assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames");
383++ // THE WITNESS: the monochrome stream decodes and every luma sample
384++ // equals ffmpeg's own decode of the same OBU.
385++ let gray = emit("gray");
386++ let ours = decode_stream(&gray)
387++ .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}"));
388++ let (width, height) = (320usize, 240usize);
389++ const FRAMES: usize = 60;
390++ assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames");
391++ let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES);
392++ for (i, plane) in reference.chunks_exact(width * height).enumerate() {
393++ assert_eq!(ours[i].width, width, "{NAME}: frame {i} width");
394++ assert_eq!(ours[i].height, height, "{NAME}: frame {i} height");
395++ assert_eq!(
396++ ours[i].y.len(),
397++ width * height,
398++ "{NAME}: frame {i} luma length"
399++ );
400++ for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() {
401++ assert_eq!(
402++ *want,
403++ u16::from(*got),
404++ "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}",
405++ j / width,
406++ j % width
407++ );
408++ }
409++ }
410++ eprintln!(
411++ "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg",
412++ twin.len(),
413++ ours.len()
414++ );
415++ }
416++
417+ /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
418+ /// shape the parser cannot hand [`decode_stream`].
419+ ///
420+@@ -3296,6 +3395,49 @@ pub(crate) mod tests {
421+ .collect()
422+ }
423+
424++ /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
425++ /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
426++ /// (lane-av1mono). Fed down a stdin writer thread for the reason the 4:2:0
427++ /// helper documents.
428++ fn ffmpeg_decode_gray_sequence(
429++ stream: &[u8],
430++ width: usize,
431++ height: usize,
432++ frames: usize,
433++ ) -> Vec<u8> {
434++ let mut child = Command::new("ffmpeg")
435++ .args([
436++ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
437++ ])
438++ .stdin(Stdio::piped())
439++ .stdout(Stdio::piped())
440++ .stderr(Stdio::piped())
441++ .spawn()
442++ .expect("ffmpeg failed to start");
443++ let mut stdin = child.stdin.take().expect("ffmpeg stdin");
444++ let payload = stream.to_vec();
445++ let writer = std::thread::Builder::new()
446++ .name("ec-av1-ffmpeg-gray-in".into())
447++ .spawn(move || {
448++ let _ = stdin.write_all(&payload);
449++ })
450++ .expect("spawning the ffmpeg stdin writer");
451++ let out = child.wait_with_output().expect("ffmpeg failed to run");
452++ writer.join().expect("ffmpeg stdin writer thread");
453++ assert!(
454++ out.status.success(),
455++ "ffmpeg refused the monochrome stream: {}",
456++ String::from_utf8_lossy(&out.stderr)
457++ );
458++ assert_eq!(
459++ out.stdout.len(),
460++ width * height * frames,
461++ "expected {frames} monochrome frames, ffmpeg said: {}",
462++ String::from_utf8_lossy(&out.stderr)
463++ );
464++ out.stdout
465++ }
466++
467+ /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
468+ /// are 2-byte little-endian, one full 16-bit range regardless of the
469+ /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
470+```
471+
472+## Witnesses (quoted)
473+
474+All three run on the final tree; the probe is
475+`$HOME/.cache/cargo-target-av1mono/release/examples/decode_probe`.
476+
477+```
478+(a) gray 60f key frame -- ffmpeg testsrc2 320x240 30fps 2s -pix_fmt gray
479+OK: 60 frames decoded, 320x240
480+gray60 EQUAL True
481+
482+(b) gray 120f (inter frames) -- same recipe, duration 4
483+OK: 120 frames decoded, 320x240
484+gray120 EQUAL True
485+
486+(c) fixtures/bitstreams/av1-monochrome.ivf (remuxed to OBU)
487+OK: 60 frames decoded, 320x240
488+mono.ivf EQUAL True
489+```
490+
491+Comparison for (a)/(b)/(c): probe `EC_PROBE_OUT16` writes the 8-bit sample in the
492+**low byte** of each u16, so the check is `probe[0::2] == ffmpeg -pix_fmt gray -f
493+rawvideo`. All three are STRONGER than the charter expected: (c) was expected to
494+stop at the named intrabc-rect refusal, but that refusal was itself a *symptom* of
495+this desync, so with the desync gone the fixture now decodes **all 60 frames
496+byte-exact**. (Class, per the pilot §3.3/3.4: a routing refusal reached only
497+because the desynced read picked wrong block sizes.)
498+
499+Scoped test:
500+```
501+$ cargo test -p ec-av1 --lib a_real_libaom_monochrome_key_frame_decodes_pixel_exact -- --nocapture
502+a_real_libaom_monochrome_key_frame_decodes_pixel_exact: 4:2:0 twin 60 frames, monochrome 60 frames byte-exact vs ffmpeg
503+test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 651 filtered out
504+```
505+
506+## Regression
507+
508+**Corpus (9 `fixtures/bitstreams/av1-*.ivf`), byte-identity vs the LANE BASE
509+(`7f4e8301`, own probe at `$HOME/.cache/cargo-target-av1base`):**
510+
511+```
512+av1-1080p-23.976-10bit IDENTICAL(rc=0) da2b8484b94b244a
513+av1-1080p-23.976-8bit IDENTICAL(rc=0) 407148a9397461fa
514+av1-1080p-60-10bit IDENTICAL(rc=0) 83087317d215b128
515+av1-1080p-60-8bit IDENTICAL(rc=0) 4aff1fdedc0599a8
516+av1-2160p-23.976-8bit IDENTICAL(rc=0) ea683b4a9e2b8891
517+av1-altref IDENTICAL(rc=0) ea2f84d929b52f5e
518+av1-monochrome DIFFER base=49d757b50b8d9175 lane=b869441a9cf29d87 <-- the fix
519+av1-profile1-444 IDENTICAL(rc=0) 6620e894ff971cba
520+av1-tiles-1280 IDENTICAL(rc=0) 5e59dbc445eb4e17
521+```
522+
523+Only the monochrome fixture moves; every non-mono stream is bit-identical to the
524+base. **`av1-profile1-444` is IDENTICAL to the base and is NOT byte-exact vs
525+ffmpeg** — that is the pilot §3.2 4:4:4 block-routing defect, pre-existing and
526+out of this lane's scope (same probe, same output at base and lane).
527+
528+**Against ffmpeg** (correct sample packing per bit depth):
529+`av1-1080p-23.976-10bit`, `av1-1080p-23.976-8bit`, `av1-1080p-60-10bit`,
530+`av1-1080p-60-8bit`, `av1-2160p-23.976-8bit`, `av1-altref`, `av1-monochrome`,
531+`av1-tiles-1280` → all MATCH (sha256). `av1-profile1-444` → differs (above).
532+
533+**Film windows** (the pilot's 13 real 3840x1608 10-bit windows
534+`~/.cache/av1dec-recon/p-*.obu`, compared to the pilot's own ffmpeg `.ref` decodes):
535+
536+```
537+p-reelb2700 MATCH [OK: 104 frames] p-reelb300 MATCH [OK: 136] p-reelb5700 MATCH [OK: 247]
538+p-hgb1500 MATCH [OK: 242] p-hgb2100 MATCH [OK: 173] p-hgb3300 MATCH [OK: 279]
539+p-hgb3900 MATCH [OK: 210] p-hgb4500 MATCH [OK: 141] p-hgb5100 MATCH [OK: 71]
540+p-hgb6300 MATCH [OK: 177] p-hgb6900 MATCH [OK: 108] p-hgb7500 MATCH [OK: 284]
541+p-hgb900 MATCH [OK: 67]
542+```
543+
544+All 13 byte-identical. Refusals were not touched (`refusal_inventory` tests are in
545+the suite below).
546+
547+## Merge interaction (for the orchestrator)
548+
549+`main` now carries the pilot's **`a_real_libaom_monochrome_key_frame_is_refused_by_name`**
550+(merged at `d71084ae`, after this lane's base `7f4e8301`). This lane adds the
551+**inverted witness** `..._decodes_pixel_exact` in the same `stream.rs` test module
552+and does NOT edit the pinning test (per charter). A merge will **conflict in
553+`crates/ec-av1/src/stream.rs`**: the resolution is to DROP the pilot's pinning
554+gate and keep this lane's byte-exact witness (the pinning gate asserts the very
555+behaviour this lane removes, so it must fail once mono decode lands). The
556+witness test's own doc comment records this.
557+
558+## Gates
559+
560+- `cargo check -p ec-av1` (post-salvage) → rc 0.
561+- `cargo check -p ec-av1 --all-targets` → rc 0, **0 warnings** (second target dir
562+ `$HOME/.cache/cargo-target-av1mono-check`).
563+- `cargo test -p ec-av1 --lib` to completion → **592 passed, 0 failed, 60 ignored**
564+ (6724 s), on the final tree.
565+
566+## Repro
567+
568+```
569+ffmpeg -v error -f lavfi -i "testsrc2=size=320x240:rate=30:duration=2" \
570+ -pix_fmt gray -c:v libaom-av1 -cpu-used 8 -b:v 300k -f obu -y /tmp/gray.obu
571+P=$HOME/.cache/cargo-target-av1mono/release/examples/decode_probe
572+EC_PROBE_OUT16=$HOME/m.raw16 $P /tmp/gray.obu # OK: 60 frames
573+ffmpeg -v error -i /tmp/gray.obu -pix_fmt gray -f rawvideo $HOME/ref.gray
574+python3 -c "d=open('$HOME/m.raw16','rb').read()[0::2]; print(bytes(d)==open('$HOME/ref.gray','rb').read())" # True
575+```
576+
577+## Suite
578+
579+```
580+$ cargo test -p ec-av1 --lib
581+test result: ok. 592 passed; 0 failed; 60 ignored; 0 measured; 0 filtered out; finished in 6724.24s
582+```
583+
584+Same count as the pilot's completed run on `main` (592/0/60, 6716 s), so no test
585+regressed, no test was added-but-unrun, and the 60 ignored are the pre-existing
586+single-process-global cases. `cargo check -p ec-av1 --all-targets` → rc 0, 0
587+warnings on the same final bytes.
588+
589+## Deferred / not chased
590+
591+- `av1-profile1-444.ivf` chroma non-exactness (pilot §3.2 4:4:4 block-routing) —
592+ pre-existing, unchanged by this lane.
593+- The pilot's 4:4:4-fast / all-intra / warped-cpu0 recipes — untouched.