forge
Explore
Log in

Don't you dare go Hollow

Merge main f31a2c5 into lane-palette2, and predict palette per transform unit on a split-tx rect strip

Browse files at this commit

9ad0588092a2c9c3b433d9da0920f6893af89ee9Ahmet Kaan GümüşParent: 588a5542bfe1bb
Merge resolution: decode.rs `reconstruct_rect` keeps this lane's PALETTE_PRED
override and takes main's rect filter-intra call (`bw, bh`); refusal_inventory
loses the two strings both sides lifted ("a HORZ/VERT intra strip in a
screen-content frame", "a HORZ/VERT intra strip with a split transform").

The merge created a combination neither side had: a palette block on a rect
strip whose luma transform SPLITS. `decode_rect_split` (main, lane-rectsplit)
knew nothing about palette, so every transform unit predicted DC while the
coefficients were still read -- the entropy stream stayed in sync and the
block came out flat grey (smptebars 192x192 cq=35: luma x0..63 y0..127 wrong,
max |d| 52, rest of the frame exact). Palette prediction reads no edge pixels,
so a unit's window on the block's colour-mapped map IS its prediction:
RectStripModes now carries the Y map (sliced per unit) and the UV maps (the
chroma transform is never split), and the block bumps PALETTE_SPLIT_TX_HITS.

Both palette gates green: rect-palette 17/70 matched + 21 uncounted-exact,
palette_rect_hits=92; rect-screen-content 19/70 matched (14 through a
split-transform palette block) + 19 uncounted-exact. The r8 chroma-only U
mismatch (rgbtestsrc 128x128 cq=55) is gone -- main's deblocker chroma tx-size
fix (9b1297a) closed it.

19 changed files +3129 -287

crates/ec-av1/examples/decode_probe.rsmodified+16 -1
@@ -32,7 +32,22 @@ fn main() {
3232 Ok(frames) if frames.is_empty() => {
3333 println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");
3434 }
35- Ok(frames) => println!("OK: {} frames decoded", frames.len()),
35+ Ok(frames) => {
36+ println!("OK: {} frames decoded", frames.len());
37+ // Optional second arg: dump the decoded planes as raw yuv420p so a
38+ // pixel diff against `ffmpeg -i s.obu -f rawvideo` needs no test harness.
39+ if let Some(out) = std::env::args().nth(2) {
40+ // 8-bit only: planes are u16, take the low byte.
41+ let mut buf: Vec<u8> = Vec::new();
42+ for f in &frames {
43+ for p in [&f.y, &f.u, &f.v] {
44+ buf.extend(p.iter().map(|&s| s as u8));
45+ }
46+ }
47+ std::fs::write(&out, &buf).expect("writing raw planes");
48+ println!("wrote {} bytes of yuv420p to {out}", buf.len());
49+ }
50+ }
3651 Err(e) => println!("REFUSED: {e}"),
3752 }
3853 }
crates/ec-av1/src/cdf.rsmodified+13 -0
@@ -561,6 +561,19 @@ pub const RESTORE_SWITCHABLE: [u16; 4] = [9413, 22581, 32768, 0];
561561 /// 4-symbol `delta_q_abs` alphabet read once per superblock when
562562 /// `delta_q_present` is set. `default_delta_lf_cdf`/`default_delta_lf_multi_cdf`
563563 /// share this same value (verified against libaom's real source).
564+/// `Default_Segment_Id_Cdf` (spec 9.4, libaom
565+/// `default_spatial_pred_seg_tree_cdf`): the `segment_id` symbol's eight
566+/// segments, indexed by the spec 5.11.8 neighbour-agreement context.
567+pub const SEGMENT_ID: [[u16; 9]; 3] = [
568+ [5622, 7893, 16093, 18233, 27809, 28373, 32533, 32768, 0],
569+ [14274, 18230, 22557, 24935, 29980, 30851, 32344, 32768, 0],
570+ [27527, 28487, 28723, 28890, 32397, 32647, 32679, 32768, 0],
571+];
572+
573+/// `Default_Segment_Pred_Cdf` (spec 9.4, libaom `default_segment_pred_cdf`):
574+/// `seg_id_predicted`, indexed by `AboveSegPredContext + LeftSegPredContext`.
575+pub const SEGMENT_PRED: [[u16; 3]; 3] = [[16384, 32768, 0]; 3];
576+
564577 pub const DELTA_Q: [u16; 5] = [28160, 32120, 32677, 32768, 0];
565578 /// `default_delta_lf_cdf` -- see [`DELTA_Q`]'s doc.
566579 pub const DELTA_LF: [u16; 5] = DELTA_Q;
crates/ec-av1/src/cdf_state.rsmodified+20 -0
@@ -420,6 +420,12 @@ pub(crate) struct Cdfs {
420420 /// The two motion vector components' own tables: separate owned state,
421421 /// since spec 8.3.2 adapts one component without touching the other.
422422 pub mv_comp: [MvComponentCdfs; 2],
423+ /// libaom's `ndvc` (`av1_init_mv_probs`): the block-vector MV context an
424+ /// intrabc block reads (spec's `MV_INTRABC_CONTEXT`). Same spec-8.4
425+ /// defaults as [`Self::mv_joint`]/[`Self::mv_comp`], separate adaptation.
426+ pub dv_joint: [u16; 5],
427+ /// [`Self::dv_joint`]'s per-component half.
428+ pub dv_comp: [MvComponentCdfs; 2],
423429 /// The `use_filter_intra` flag, indexed by block-size class (`[0]`=4x4,
424430 /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32) --
425431 /// see [`cdf::FILTER_INTRA`].
@@ -464,6 +470,10 @@ pub(crate) struct Cdfs {
464470 /// A `RESTORE_SWITCHABLE`-plane LR unit's `restoration_type` -- see
465471 /// [`cdf::RESTORE_SWITCHABLE`].
466472 pub restore_switchable: [u16; 4],
473+ /// `segment_id` (lane-seg, spec 5.11.8) -- see [`cdf::SEGMENT_ID`].
474+ pub segment_id: [[u16; 9]; 3],
475+ /// `seg_id_predicted` (lane-seg, spec 5.11.9) -- see [`cdf::SEGMENT_PRED`].
476+ pub segment_pred: [[u16; 3]; 3],
467477 /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`].
468478 pub delta_q: [u16; 5],
469479 /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see
@@ -682,6 +692,10 @@ impl Cdfs {
682692 reset2(&mut self.ref_mv);
683693 reset2(&mut self.drl_mode);
684694 reset1(&mut self.mv_joint);
695+ reset1(&mut self.dv_joint);
696+ self.dv_comp
697+ .iter_mut()
698+ .for_each(MvComponentCdfs::reset_counts);
685699 self.mv_comp
686700 .iter_mut()
687701 .for_each(MvComponentCdfs::reset_counts);
@@ -701,6 +715,8 @@ impl Cdfs {
701715 reset1(&mut self.restore_wiener);
702716 reset1(&mut self.restore_sgrproj);
703717 reset1(&mut self.restore_switchable);
718+ reset2(&mut self.segment_id);
719+ reset2(&mut self.segment_pred);
704720 reset1(&mut self.delta_q);
705721 reset1(&mut self.delta_lf);
706722 reset2(&mut self.delta_lf_multi);
@@ -1155,6 +1171,8 @@ impl Cdfs {
11551171 drl_mode: cdf::DRL_MODE,
11561172 mv_joint: cdf::MV_JOINT,
11571173 mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],
1174+ dv_joint: cdf::MV_JOINT,
1175+ dv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],
11581176 filter_intra: cdf::FILTER_INTRA,
11591177 filter_intra_mode: cdf::FILTER_INTRA_MODE,
11601178 tx_size_cat0: cdf::TX_SIZE_CAT0,
@@ -1172,6 +1190,8 @@ impl Cdfs {
11721190 restore_wiener: cdf::RESTORE_WIENER,
11731191 restore_sgrproj: cdf::RESTORE_SGRPROJ,
11741192 restore_switchable: cdf::RESTORE_SWITCHABLE,
1193+ segment_id: cdf::SEGMENT_ID,
1194+ segment_pred: cdf::SEGMENT_PRED,
11751195 delta_q: cdf::DELTA_Q,
11761196 delta_lf: cdf::DELTA_LF,
11771197 delta_lf_multi: [cdf::DELTA_LF; 4],
crates/ec-av1/src/decode.rsmodified+1097 -62
@@ -22,7 +22,8 @@
2222 //! silently miscoding.
2323
2424 use ec_av1_syntax::{
25- CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, TileInfo,
25+ CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
26+ SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
2627 };
2728 use ec_core::{Error, Result};
2829
@@ -315,6 +316,353 @@ fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip:
315316 }
316317 }
317318
319+// ---------------------------------------------------------------------------
320+// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
321+// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
322+// the two consumers a real stream exercises: the per-segment quantizer index
323+// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
324+// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
325+// `read_intra_segment_id`/`read_inter_segment_id` and
326+// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
327+// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
328+// is what the oracle every gate here compares against actually does.
329+thread_local! {
330+ static SEG: std::cell::RefCell<SegmentationParams> =
331+ std::cell::RefCell::new(SegmentationParams::default());
332+ /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
333+ /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
334+ static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
335+ /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
336+ /// this frame has no primary reference (spec `load_previous_segment_ids`).
337+ static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
338+ /// `(mi_rows, mi_cols)` for both maps above.
339+ static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
340+ /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
341+ /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
342+ /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
343+ static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
344+ static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
345+ /// The block currently being decoded -- read back by [`block_q_idx`].
346+ static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
347+ /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
348+ static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
349+ /// How many real `segment_id` symbols were read, and the set of segment
350+ /// ids any block ended up with -- the gate's proof the feature fired.
351+ static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
352+ static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
353+ /// How many `seg_id_predicted` symbols were read (temporal update).
354+ static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
355+}
356+
357+/// Installs this frame's segmentation parameters and allocates its map, with
358+/// `prev` the primary reference frame's saved map (spec
359+/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
360+/// slot). Called once per frame, whether or not segmentation is enabled.
361+pub(crate) fn set_segmentation(
362+ seg: SegmentationParams,
363+ mi_rows: usize,
364+ mi_cols: usize,
365+ prev: Option<&[u8]>,
366+) {
367+ SEG.with(|s| *s.borrow_mut() = seg);
368+ SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
369+ SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
370+ PREV_SEG_IDS.with(|m| {
371+ let mut m = m.borrow_mut();
372+ m.clear();
373+ if let Some(p) = prev {
374+ if p.len() == mi_rows * mi_cols {
375+ m.extend_from_slice(p);
376+ }
377+ }
378+ });
379+ ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
380+ LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
381+ CUR_SEGMENT_ID.with(|c| c.set(0));
382+}
383+
384+/// This frame's decoded segment map, to be stored into whichever reference
385+/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
386+pub(crate) fn take_segment_ids() -> Vec<u8> {
387+ SEG_IDS.with(|m| m.borrow().clone())
388+}
389+
390+/// How many `segment_id` symbols have been read (never reset per frame).
391+pub(crate) fn segment_id_hits() -> usize {
392+ SEG_ID_HITS.with(|c| c.get())
393+}
394+
395+/// How many distinct segment ids any decoded block has carried.
396+pub(crate) fn segment_ids_seen() -> usize {
397+ SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
398+}
399+
400+/// How many `seg_id_predicted` symbols have been read (temporal update).
401+pub(crate) fn segment_pred_hits() -> usize {
402+ SEG_PRED_HITS.with(|c| c.get())
403+}
404+
405+/// Resets the segmentation hit counters (gate setup).
406+pub(crate) fn reset_segment_hits() {
407+ SEG_ID_HITS.with(|c| c.set(0));
408+ SEG_IDS_SEEN.with(|c| c.set(0));
409+ SEG_PRED_HITS.with(|c| c.set(0));
410+}
411+
412+/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
413+/// being decoded, with its `FeatureData` value.
414+fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
415+ SEG.with(|s| {
416+ let s = s.borrow();
417+ s.feature_active(segment_id, feature)
418+ .then(|| i32::from(s.feature_data[segment_id][feature]))
419+ })
420+}
421+
422+/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
423+/// `av1_get_qindex`) for the block currently being decoded: the running
424+/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
425+/// Every dequant call site reads the block's quantizer through here.
426+fn block_q_idx() -> i32 {
427+ let base = CURRENT_Q_IDX.with(|c| c.get());
428+ let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
429+ match seg_feature(seg_id, SEG_LVL_ALT_Q) {
430+ Some(data) => (base + data).clamp(0, 255),
431+ None => base,
432+ }
433+}
434+
435+/// The segment id recorded for one mi cell of the current frame's map.
436+fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
437+ let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
438+ if mi_r >= mi_rows || mi_c >= mi_cols {
439+ return 0;
440+ }
441+ SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
442+}
443+
444+/// `set_segment_id`: stamps `id` over every mi cell this block covers.
445+fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
446+ let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
447+ let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
448+ SEG_IDS.with(|m| {
449+ let mut m = m.borrow_mut();
450+ for y in 0..y_mis {
451+ for x in 0..x_mis {
452+ m[(mi_r + y) * mi_cols + mi_c + x] = id;
453+ }
454+ }
455+ });
456+ CUR_SEGMENT_ID.with(|c| c.set(id));
457+ SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
458+}
459+
460+/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
461+/// `last_frame_seg_map`): the minimum previous-frame segment id over the
462+/// block's own mi footprint. `0` when there is no previous map.
463+fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
464+ let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
465+ PREV_SEG_IDS.with(|m| {
466+ let m = m.borrow();
467+ if m.is_empty() {
468+ return 0;
469+ }
470+ let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
471+ let mut id = u8::MAX;
472+ for y in 0..y_mis {
473+ for x in 0..x_mis {
474+ id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
475+ }
476+ }
477+ if id == u8::MAX { 0 } else { id }
478+ })
479+}
480+
481+/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
482+fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
483+ if reference == 0 {
484+ return diff;
485+ }
486+ if reference >= max - 1 {
487+ return max - diff - 1;
488+ }
489+ let half = if 2 * reference < max {
490+ diff <= 2 * reference
491+ } else {
492+ diff <= 2 * (max - reference - 1)
493+ };
494+ if half {
495+ return if diff & 1 != 0 {
496+ reference + ((diff + 1) >> 1)
497+ } else {
498+ reference - (diff >> 1)
499+ };
500+ }
501+ if 2 * reference < max { diff } else { max - (diff + 1) }
502+}
503+
504+/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
505+/// frame's already-decoded above/left/above-left neighbours.
506+fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
507+ let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
508+ let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
509+ let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
510+ let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
511+ let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
512+ let ctx = match prev_ul {
513+ None => 0,
514+ Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
515+ Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
516+ Some(_) => 0,
517+ };
518+ let pred = match (prev_u, prev_l) {
519+ (None, l) => l.unwrap_or(0),
520+ (Some(u), None) => u,
521+ (Some(u), Some(l)) => {
522+ if prev_ul == Some(u) {
523+ u
524+ } else {
525+ l
526+ }
527+ }
528+ };
529+ (pred, ctx)
530+}
531+
532+/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
533+/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
534+/// that prediction. Does NOT write the map -- callers do.
535+fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
536+ let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
537+ if skip {
538+ return pred as u8;
539+ }
540+ let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
541+ SEG_ID_HITS.with(|c| c.set(c.get() + 1));
542+ let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
543+ neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
544+}
545+
546+/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
547+/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
548+/// caller decides which by passing `pre_skip`).
549+fn intra_segment_id(
550+ dec: &mut SymbolDecoder,
551+ cdfs: &mut Cdfs,
552+ mi_r: usize,
553+ mi_c: usize,
554+ w_mi: usize,
555+ h_mi: usize,
556+ skip: bool,
557+) {
558+ if !SEG.with(|s| s.borrow().enabled) {
559+ return;
560+ }
561+ let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
562+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
563+}
564+
565+/// Whether this frame's intra blocks read their `segment_id` before `skip`
566+/// (`SegIdPreSkip`); `false` also when segmentation is off.
567+fn seg_id_pre_skip() -> bool {
568+ SEG.with(|s| {
569+ let s = s.borrow();
570+ s.enabled && s.seg_id_pre_skip
571+ })
572+}
573+
574+/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
575+/// Called at both spec positions of an inter frame's block: `pre_skip = true`
576+/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
577+fn inter_segment_id(
578+ dec: &mut SymbolDecoder,
579+ cdfs: &mut Cdfs,
580+ mi_r: usize,
581+ mi_c: usize,
582+ w_mi: usize,
583+ h_mi: usize,
584+ skip: bool,
585+ pre_skip: bool,
586+) {
587+ let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
588+ let s = s.borrow();
589+ (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
590+ });
591+ if !enabled {
592+ return;
593+ }
594+ if !update_map {
595+ // The map is inherited wholesale from the previous frame.
596+ let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
597+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
598+ return;
599+ }
600+ if pre_skip && !pre_skip_frame {
601+ return;
602+ }
603+ if !pre_skip && skip {
604+ // libaom: a skipped block never codes `seg_id_predicted`, and its
605+ // segment id is the spatial prediction.
606+ stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
607+ let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
608+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
609+ return;
610+ }
611+ let id = if temporal_update {
612+ let ctx = seg_pred_ctx(mi_r, mi_c);
613+ let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
614+ SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
615+ stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
616+ if predicted {
617+ predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
618+ } else {
619+ read_segment_id(dec, cdfs, mi_r, mi_c, false)
620+ }
621+ } else {
622+ read_segment_id(dec, cdfs, mi_r, mi_c, false)
623+ };
624+ write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
625+}
626+
627+/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
628+fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
629+ // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
630+ // so contribute 0) outside the tile -- the availability check here is
631+ // what keeps a previous tile's stamps out of this tile's context.
632+ let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
633+ let above = if mi_r > row0 {
634+ ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
635+ } else {
636+ 0
637+ };
638+ let left = if mi_c > col0 {
639+ LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
640+ } else {
641+ 0
642+ };
643+ usize::from(above + left)
644+}
645+
646+/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
647+fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
648+ ABOVE_SEG_PRED.with(|m| {
649+ let mut m = m.borrow_mut();
650+ for i in 0..w_mi {
651+ if let Some(cell) = m.get_mut(mi_c + i) {
652+ *cell = value;
653+ }
654+ }
655+ });
656+ LEFT_SEG_PRED.with(|m| {
657+ let mut m = m.borrow_mut();
658+ for i in 0..h_mi {
659+ if let Some(cell) = m.get_mut(mi_r + i) {
660+ *cell = value;
661+ }
662+ }
663+ });
664+}
665+
318666 // How many key-frame luma blocks resolved `smooth_neighbor` (spec
319667 // `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
320668 // counter, proving a stream actually put a directional block next to a
@@ -428,6 +776,34 @@ pub(crate) fn horz_vert_intra_hits() -> usize {
428776 HORZ_VERT_INTRA_HITS.with(|c| c.get())
429777 }
430778
779+// How many HORZ/VERT intra strips resolved a SPLIT luma transform
780+// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
781+// the case every rect path here refused by name before, and the first
782+// refusal the user's ReelB extract (600s in) stops at.
783+thread_local! {
784+ static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
785+ const { std::cell::Cell::new(0) };
786+}
787+
788+/// Current value of [`RECT_SPLIT_TX_HITS`].
789+pub(crate) fn rect_split_tx_hits() -> usize {
790+ RECT_SPLIT_TX_HITS.with(|c| c.get())
791+}
792+
793+// How many HORZ/VERT intra strips actually predicted with filter intra
794+// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
795+// ("this decoder predicts square-only") until `predict_filter_intra` took
796+// `bw`x`bh`.
797+thread_local! {
798+ static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
799+ const { std::cell::Cell::new(0) };
800+}
801+
802+/// Current value of [`FILTER_INTRA_RECT_HITS`].
803+pub(crate) fn filter_intra_rect_hits() -> usize {
804+ FILTER_INTRA_RECT_HITS.with(|c| c.get())
805+}
806+
431807 // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
432808 // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
433809 // call on the current thread -- the same before/after counter pattern as
@@ -608,6 +984,69 @@ thread_local! {
608984 const { std::cell::RefCell::new(None) };
609985 }
610986
987+thread_local! {
988+ /// The current frame's `mi` grid, kept only while a frame header set
989+ /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
990+ /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
991+ /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
992+ /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
993+ /// does not allow intrabc (so nothing is paid for it).
994+ ///
995+ /// corner-cut: only [`decode_block`] (the square path) records into it,
996+ /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
997+ /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
998+ /// be wrong there; upgrade = record from the rect/leaf paths too.
999+ static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1000+ const { std::cell::RefCell::new(None) };
1001+ /// The block vector [`read_intra_mode`] just decoded, handed to
1002+ /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1003+ /// which the alternative -- a tenth tuple member through every caller --
1004+ /// already avoids). Always `.take()`n by the block that reads it.
1005+ static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1006+ /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1007+ static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1008+}
1009+
1010+/// Current value of [`INTRABC_HITS`].
1011+pub(crate) fn intrabc_hits() -> usize {
1012+ INTRABC_HITS.with(|c| c.get())
1013+}
1014+
1015+/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1016+pub(crate) fn reset_intrabc_hits() {
1017+ INTRABC_HITS.with(|c| c.set(0));
1018+}
1019+
1020+/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1021+/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1022+/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1023+/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1024+fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1025+ INTRABC_MI_GRID.with(|g| {
1026+ let mut g = g.borrow_mut();
1027+ let Some((grid, _, _)) = g.as_mut() else {
1028+ return;
1029+ };
1030+ let info = crate::mvstack::MiInfo {
1031+ is_inter: dv.is_some(),
1032+ ref_frame: 0,
1033+ ref_frame1: None,
1034+ mv: dv.unwrap_or((0, 0)),
1035+ mv1: None,
1036+ is_new_mv: dv.is_some(),
1037+ is_global_mv0: false,
1038+ is_global_mv1: false,
1039+ size: n4,
1040+ size_h: n4,
1041+ };
1042+ for r in mi_r..mi_r + n4 {
1043+ for c in mi_c..mi_c + n4 {
1044+ grid.set(r, c, info);
1045+ }
1046+ }
1047+ });
1048+}
1049+
6111050 // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
6121051 // proves a real `skip_mode_present` stream actually reached a block that
6131052 // picked it, not just that the frame header bit was set.
@@ -1844,6 +2283,16 @@ struct Neighbours {
18442283 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
18452284 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
18462285 tx_h_grid: Vec<u8>,
2286+ /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
2287+ /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
2288+ /// largest transform covering the subsampled BLOCK, capped at 32x32. It
2289+ /// does NOT follow luma's `tx_depth` split, so deriving it as
2290+ /// `tx_grid / 2` invented chroma transform edges the deblocker then
2291+ /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
2292+ /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
2293+ /// every caller routes through.
2294+ uv_tx_grid: Vec<u8>,
2295+ uv_tx_h_grid: Vec<u8>,
18472296 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
18482297 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
18492298 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
@@ -1923,6 +2372,8 @@ impl Neighbours {
19232372 skip_grid_cols_mi: cols * (SUB / MI),
19242373 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
19252374 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
2375+ uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
2376+ uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
19262377 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
19272378 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
19282379 above_palette_size: vec![0; cols],
@@ -1945,6 +2396,9 @@ impl Neighbours {
19452396 /// regardless of tile ([`Self::start_row`], already called once per SB
19462397 /// row by every caller) so it needs no tile-specific reset here.
19472398 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
2399+ // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
2400+ // are tile-relative, same as every other neighbour lookup here.
2401+ SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
19482402 self.tile_row0_mi = row0_mi;
19492403 self.tile_col0_mi = col0_mi;
19502404 let end = col1_mi.min(self.above.len());
@@ -2176,6 +2630,11 @@ impl Neighbours {
21762630 ref_frame: i8,
21772631 ) {
21782632 let (mi_r, mi_c) = at_mi;
2633+ // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
2634+ // half its luma one (min 4 px, the smallest transform), capped at
2635+ // TX_32X32 -- independent of this block's luma `tx_depth`.
2636+ let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
2637+ let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
21792638 let cur = CURRENT_DELTA_LF.with(|c| c.get());
21802639 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
21812640 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
@@ -2191,6 +2650,12 @@ impl Neighbours {
21912650 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
21922651 *cell = tx_h_px;
21932652 }
2653+ if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
2654+ *cell = uv_tx_w;
2655+ }
2656+ if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
2657+ *cell = uv_tx_h;
2658+ }
21942659 if let Some(cell) = self.ref_grid.get_mut(idx) {
21952660 *cell = ref_frame;
21962661 }
@@ -2630,32 +3095,55 @@ impl Neighbours {
26303095 mode: usize,
26313096 uv_mode: usize,
26323097 chroma_grids: [&[i32]; 2],
3098+ ) {
3099+ self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
3100+ }
3101+
3102+ /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
3103+ /// extents in pixels (lane-rectsplit r1), the same relationship
3104+ /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
3105+ /// luma transform split into several square units needs exactly this
3106+ /// bookkeeping, at its own true rectangular extents.
3107+ fn record_split_luma_rect(
3108+ &mut self,
3109+ at: (usize, usize),
3110+ w: usize,
3111+ h: usize,
3112+ mode: usize,
3113+ uv_mode: usize,
3114+ chroma_grids: [&[i32]; 2],
26333115 ) {
26343116 let (r, c) = at;
2635- for cell in 0..side / SUB {
3117+ for cell in 0..w / SUB {
26363118 self.above_mode[c + cell] = mode;
2637- self.left_mode[r + cell] = mode;
26383119 self.above_uv_mode[c + cell] = uv_mode;
3120+ self.above_side[c + cell] = w;
3121+ }
3122+ for cell in 0..h / SUB {
3123+ self.left_mode[r + cell] = mode;
26393124 self.left_uv_mode[r + cell] = uv_mode;
2640- self.above_side[c + cell] = side;
2641- self.left_side[r + cell] = side;
3125+ self.left_side[r + cell] = h;
26423126 }
26433127 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2644- let side_mi = side / MI;
2645- for cell in 0..side_mi {
2646- self.left_side_mi[mi_r + cell] = side;
2647- self.above_side_mi[mi_c + cell] = side;
3128+ let (w_mi, h_mi) = (w / MI, h / MI);
3129+ for cell in 0..h_mi {
3130+ self.left_side_mi[mi_r + cell] = h;
3131+ }
3132+ for cell in 0..w_mi {
3133+ self.above_side_mi[mi_c + cell] = w;
26483134 }
26493135 let round_up_even = |n: usize| n.div_ceil(2) * 2;
26503136 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
26513137 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
26523138 let plane = plane_idx + 1;
26533139 let state = neighbour_state(grid);
2654- for cell in 0..side_mi {
2655- if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {
3140+ for cell in 0..h_mi {
3141+ if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
26563142 self.left[mi_r + cell][plane] = state;
26573143 }
2658- if cell < side_mi.min(bound_w.saturating_sub(mi_c)) {
3144+ }
3145+ for cell in 0..w_mi {
3146+ if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
26593147 self.above[mi_c + cell][plane] = state;
26603148 }
26613149 }
@@ -3076,8 +3564,16 @@ fn read_intra_mode_rect(
30763564 }
30773565 };
30783566 }
3567+ // Same `intra_segment_id` placement as the square reader above.
3568+ let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
3569+ if seg_id_pre_skip() {
3570+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
3571+ }
30793572 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
30803573 istep!("skip", skip as i32);
3574+ if !seg_id_pre_skip() {
3575+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
3576+ }
30813577 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
30823578 istep!("cdef", 0);
30833579 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
@@ -3245,6 +3741,278 @@ fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> V
32453741 ac
32463742 }
32473743
3744+/// Everything a rect strip already read out of the stream before its luma
3745+/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
3746+/// (nine values that would otherwise be nine more parameters).
3747+struct RectStripModes {
3748+ skip: bool,
3749+ mode: usize,
3750+ angle_delta_y: i32,
3751+ uv_predict_mode: usize,
3752+ angle_delta_uv: i32,
3753+ alpha: Option<(i32, i32)>,
3754+ filter_intra: Option<usize>,
3755+ smooth_neighbor: bool,
3756+ smooth_neighbor_uv: bool,
3757+ /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
3758+ /// mapped through the colour table), sliced per transform unit below --
3759+ /// palette prediction reads no edge pixels, so a unit's slice of the
3760+ /// whole-block map IS its prediction. Without this a palette strip whose
3761+ /// transform splits predicted DC and came out flat grey while the entropy
3762+ /// stream stayed in sync (the coefficients are read either way).
3763+ palette_y: Option<Vec<u16>>,
3764+ /// As `palette_y`, for the un-split chroma transform (U, V).
3765+ palette_uv: Option<(Vec<u16>, Vec<u16>)>,
3766+}
3767+
3768+/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
3769+/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
3770+/// rect path here refused by name until now ("per-unit rect prediction is not
3771+/// ported").
3772+///
3773+/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
3774+/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
3775+/// strip the very first step already lands on a SQUARE transform
3776+/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
3777+/// every further step halves a square) -- so each unit is square and reads
3778+/// through the ordinary square [`read_plane`]. What is genuinely rectangular
3779+/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
3780+/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
3781+/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
3782+/// split by luma's depth.
3783+///
3784+/// Each unit predicts off whatever the earlier units of this same block
3785+/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
3786+/// inside `av1_foreach_transformed_block`, raster order), which is exactly
3787+/// what predicting the whole strip in one shot got wrong.
3788+#[allow(clippy::too_many_arguments)]
3789+fn decode_rect_split(
3790+ dec: &mut SymbolDecoder,
3791+ cdfs: &mut Cdfs,
3792+ neighbours: &mut Neighbours,
3793+ at: (usize, usize),
3794+ bw: usize,
3795+ bh: usize,
3796+ tx: usize,
3797+ m: &RectStripModes,
3798+ y: &mut PlaneBuf,
3799+ u: &mut PlaneBuf,
3800+ v: &mut PlaneBuf,
3801+ base_q_idx: u8,
3802+ reduced_tx_set: bool,
3803+) -> Result<()> {
3804+ let (r, c) = at;
3805+ let (px, py) = (c * SUB, r * SUB);
3806+ let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3807+ let (cpx, cpy) = (px / 2, py / 2);
3808+ let (chroma_w, chroma_h) = (bw / 2, bh / 2);
3809+ // The chroma transform is picked before any symbol is read, so an
3810+ // unsupported chroma shape refuses before this strip desyncs the tile.
3811+ let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
3812+ (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
3813+ (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
3814+ (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
3815+ (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
3816+ _ => None,
3817+ };
3818+ if !m.skip && chroma.is_none() {
3819+ return Err(unsupported(
3820+ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
3821+ ));
3822+ }
3823+ RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
3824+ // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
3825+ let luma_set = txbset_for(tx, reduced_tx_set);
3826+ let luma_scan = default_scan(tx);
3827+ let zero_tu = vec![0i32; tx * tx];
3828+ // The strip's OWN edge availability, the fallback for a transform unit
3829+ // whose top-right/bottom-left pixels fall outside the strip.
3830+ let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
3831+ for tu_row in 0..bh / tx {
3832+ for tu_col in 0..bw / tx {
3833+ let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
3834+ let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx);
3835+ let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3836+ // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3837+ // transform unit INSIDE a block, which is a different rule from
3838+ // the standalone-block table [`Reach::of`] applies -- and the
3839+ // reason a depth-2 superblock strip came out one sample off
3840+ // before this: `Reach::of(tx, ..)` answered as if the unit were
3841+ // its own block at that superblock position.
3842+ // * top-right: if the unit's right neighbour is still inside the
3843+ // strip the pixels are already reconstructed (`col_off +
3844+ // tx_wide < plane_bw`); otherwise only the strip's own top row
3845+ // of units can reach past it, through the block-level answer.
3846+ // * bottom-left: a unit that is not in the strip's left column
3847+ // has none (`col_off > 0` returns 0); inside the strip
3848+ // (`row_off + tx_high < plane_bh`) they are the left
3849+ // neighbour's, already reconstructed; the last row falls back
3850+ // to the block-level answer.
3851+ let tu_reach = Reach {
3852+ above_right: if col_off + tx < bw {
3853+ true
3854+ } else {
3855+ row_off == 0 && block_reach.above_right
3856+ },
3857+ below_left: if col_off > 0 {
3858+ false
3859+ } else if row_off + tx < bh {
3860+ true
3861+ } else {
3862+ block_reach.below_left
3863+ },
3864+ };
3865+ // The unit's own window on the block's palette prediction.
3866+ if let Some(buf) = &m.palette_y {
3867+ let tu_buf: Vec<u16> = (0..tx)
3868+ .flat_map(|i| {
3869+ let base = (row_off + i) * bw + col_off;
3870+ buf[base..base + tx].iter().copied()
3871+ })
3872+ .collect();
3873+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(tu_buf));
3874+ }
3875+ if m.skip {
3876+ y.reconstruct(
3877+ tu_px,
3878+ tu_py,
3879+ tx,
3880+ m.mode,
3881+ m.angle_delta_y,
3882+ tu_reach,
3883+ &zero_tu,
3884+ None,
3885+ m.filter_intra,
3886+ m.smooth_neighbor,
3887+ );
3888+ neighbours.record_mi_luma(tu_mi, tx, &zero_tu);
3889+ } else {
3890+ let tu_around = neighbours.around_mi(tu_mi, tx)[0];
3891+ // This unit is smaller than the block it sits in, so
3892+ // `txb_skip_ctx` is the neighbour-magnitude table, not the
3893+ // lone-TU 0 (spec `get_txb_ctx_general`).
3894+ let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI);
3895+ let tu_grid = read_plane(
3896+ dec,
3897+ cdfs,
3898+ luma_set,
3899+ &luma_scan,
3900+ 0,
3901+ tu_around,
3902+ m.mode,
3903+ m.mode,
3904+ m.angle_delta_y,
3905+ tu_reach,
3906+ y,
3907+ tu_px,
3908+ tu_py,
3909+ tx,
3910+ tx,
3911+ base_q_idx,
3912+ None,
3913+ m.filter_intra,
3914+ Some(tu_skip_ctx),
3915+ m.smooth_neighbor,
3916+ )?;
3917+ neighbours.record_mi_luma(tu_mi, tx, &tu_grid);
3918+ }
3919+ }
3920+ }
3921+ // CHROMA: one un-split rect transform for the whole strip.
3922+ let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
3923+ let reach = block_reach;
3924+ let (u_grid, v_grid) = if m.skip {
3925+ let zero = vec![0i32; chroma_w * chroma_h];
3926+ if let Some((ub, _)) = &m.palette_uv {
3927+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
3928+ }
3929+ u.reconstruct_rect(
3930+ cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
3931+ m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
3932+ );
3933+ if let Some((_, vb)) = &m.palette_uv {
3934+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
3935+ }
3936+ v.reconstruct_rect(
3937+ cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
3938+ m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
3939+ );
3940+ (zero.clone(), zero)
3941+ } else {
3942+ let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
3943+ // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
3944+ // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
3945+ // so only the 16x8/8x16 pair takes the mode-indexed default.
3946+ let default_tx = if chroma_w.max(chroma_h) >= 32 {
3947+ TxType::DctDct
3948+ } else {
3949+ default_intra_tx_type(m.uv_predict_mode as u8)
3950+ };
3951+ let around = neighbours.around_rect(at, bw, bh);
3952+ let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
3953+ for plane_idx in 1..=2 {
3954+ let skip_ctx =
3955+ usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
3956+ let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
3957+ let (levels, tx_type) = read_coeffs_rect(
3958+ dec,
3959+ &mut coding,
3960+ chroma_scan,
3961+ chroma_w,
3962+ chroma_h,
3963+ skip_ctx,
3964+ dc_sign_ctx(around[plane_idx].2),
3965+ default_tx,
3966+ )?;
3967+ let residual = dequant_and_inverse_typed_wh(
3968+ &levels,
3969+ chroma_w,
3970+ chroma_h,
3971+ crate::decode::bit_depth(),
3972+ CURRENT_Q_IDX.with(|c| c.get()),
3973+ plane_q_delta(plane_idx).0,
3974+ plane_q_delta(plane_idx).1,
3975+ tx_type,
3976+ );
3977+ let cfl = m
3978+ .alpha
3979+ .zip(ac.as_deref())
3980+ .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
3981+ let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
3982+ if let Some((ub, vb)) = &m.palette_uv {
3983+ let buf = if plane_idx == 1 { ub } else { vb };
3984+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf.clone()));
3985+ }
3986+ plane.reconstruct_rect(
3987+ cpx,
3988+ cpy,
3989+ chroma_w,
3990+ chroma_h,
3991+ m.uv_predict_mode,
3992+ m.angle_delta_uv,
3993+ reach,
3994+ &residual,
3995+ cfl,
3996+ None,
3997+ m.smooth_neighbor_uv,
3998+ );
3999+ grids.push(levels);
4000+ }
4001+ let mut it = grids.into_iter();
4002+ (it.next().unwrap(), it.next().unwrap())
4003+ };
4004+ neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]);
4005+ neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
4006+ neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0);
4007+ if std::env::var_os("EC_AV1_TRACE").is_some() {
4008+ let (rng, _) = dec.debug_state();
4009+ eprintln!(
4010+ "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}"
4011+ );
4012+ }
4013+ Ok(())
4014+}
4015+
32484016 /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
32494017 /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
32504018 /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
@@ -3270,6 +4038,7 @@ fn decode_block_rect(
32704038 allow_screen_content_tools: bool,
32714039 base_q_idx: u8,
32724040 tx_select: bool,
4041+ reduced_tx_set: bool,
32734042 ) -> Result<()> {
32744043 let (r, c) = at;
32754044 let (px, py) = (c * SUB, r * SUB);
@@ -3302,15 +4071,13 @@ fn decode_block_rect(
33024071 // `uv_mode`, not the luma one.
33034072 let smooth_neighbor_uv =
33044073 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
4074+ // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
4075+ // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
4076+ // rectangle just as happily), so a `use_filter_intra` strip at this level
4077+ // predicts instead of refusing. The below-16x16 leaf arm
4078+ // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
33054079 if filter_intra.is_some() {
3306- // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
3307- // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
3308- // already read above so the stream stays in sync, this only refuses
3309- // the *pixel* decode of a rare case (`use_filter_intra` on a rect
3310- // strip).
3311- return Err(unsupported(
3312- "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
3313- ));
4080+ FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
33144081 }
33154082 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
33164083 DC_PRED
@@ -3333,15 +4100,40 @@ fn decode_block_rect(
33334100 };
33344101 if depth != 0 {
33354102 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
3336- // A split transform is predicted per transform unit, each taking its
3337- // edges from the previous unit's reconstruction (the square path's own
3338- // per-TU loop does exactly that). Predicting the whole strip in one
3339- // shot would silently produce different pixels, so refuse by name
3340- // until that loop is ported for rect strips.
3341- return Err(unsupported(
3342- "a HORZ/VERT intra strip with a split transform (per-unit rect \
3343- prediction is not ported)",
3344- ));
4103+ // lane-rectsplit r1: a split transform is predicted and reconstructed
4104+ // per transform unit, each unit taking its edges from the previous
4105+ // unit's reconstruction inside this same strip (spec 5.11.36) --
4106+ // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square
4107+ // from the first step on, so `bw.min(bh) >> (depth - 1)` names it.
4108+ let tx = bw.min(bh) >> (depth - 1);
4109+ let modes = RectStripModes {
4110+ skip,
4111+ mode,
4112+ angle_delta_y,
4113+ uv_predict_mode,
4114+ angle_delta_uv,
4115+ alpha,
4116+ filter_intra,
4117+ smooth_neighbor,
4118+ smooth_neighbor_uv,
4119+ palette_y: palette_y
4120+ .as_ref()
4121+ .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
4122+ palette_uv: palette_uv.as_ref().map(|p| {
4123+ (
4124+ p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
4125+ p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
4126+ )
4127+ }),
4128+ };
4129+ if palette_y.is_some() || palette_uv.is_some() {
4130+ PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
4131+ }
4132+ decode_rect_split(
4133+ dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
4134+ )?;
4135+ RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
4136+ return Ok(());
33454137 }
33464138 let (tx_w, tx_h) = (bw, bh);
33474139 let (cpx, cpy) = (px / 2, py / 2);
@@ -3509,7 +4301,7 @@ fn decode_block_rect(
35094301 bw,
35104302 bh,
35114303 crate::decode::bit_depth(),
3512- CURRENT_Q_IDX.with(|c| c.get()),
4304+ block_q_idx(),
35134305 plane_q_delta(0).0,
35144306 plane_q_delta(0).1,
35154307 luma_tx_type,
@@ -3553,7 +4345,7 @@ fn decode_block_rect(
35534345 chroma_w,
35544346 chroma_h,
35554347 crate::decode::bit_depth(),
3556- CURRENT_Q_IDX.with(|c| c.get()),
4348+ block_q_idx(),
35574349 plane_q_delta(1).0,
35584350 plane_q_delta(1).1,
35594351 u_tx_type,
@@ -3596,7 +4388,7 @@ fn decode_block_rect(
35964388 chroma_w,
35974389 chroma_h,
35984390 crate::decode::bit_depth(),
3599- CURRENT_Q_IDX.with(|c| c.get()),
4391+ block_q_idx(),
36004392 plane_q_delta(2).0,
36014393 plane_q_delta(2).1,
36024394 v_tx_type,
@@ -3732,7 +4524,7 @@ fn decode_leaf_rect(
37324524 };
37334525 if depth != 0 {
37344526 return Err(unsupported(
3735- "a HORZ/VERT intra strip with a split transform (per-unit rect \
4527+ "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \
37364528 prediction is not ported)",
37374529 ));
37384530 }
@@ -3839,6 +4631,7 @@ fn decode_block_rect64(
38394631 allow_screen_content_tools: bool,
38404632 base_q_idx: u8,
38414633 tx_select: bool,
4634+ reduced_tx_set: bool,
38424635 ) -> Result<()> {
38434636 let (r, c) = at;
38444637 let (px, py) = (c * SUB, r * SUB);
@@ -3905,12 +4698,31 @@ fn decode_block_rect64(
39054698 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
39064699 let depth = if tx_select {
39074700 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
3908- dec.symbol(&mut cdfs.tx_size_cat2[ctx])
4701+ // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
4702+ // counts `sub_tx_size_map` steps from the block's own max rect
4703+ // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
4704+ // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
4705+ // steps, so this level's category is 3 (the same one a 64x64 square
4706+ // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
4707+ // here was a wrong-table read of a real symbol.
4708+ dec.symbol(&mut cdfs.tx_size_cat3[ctx])
39094709 } else {
39104710 0
39114711 };
39124712 if depth != 0 {
39134713 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
4714+ // lane-rectsplit r1: [`decode_rect_split`] handles this shape too
4715+ // (`sub_tx_size_map[TX_64X32]` is `TX_32X32`, so a depth-1 unit here
4716+ // is a plain square 32x32) and its 32x32-level sibling arm in
4717+ // [`decode_block_rect`] is gated pixel-exact -- but at the SUPERBLOCK
4718+ // level the gate
4719+ // (`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`,
4720+ // `#[ignore]`d with its measurement) still comes out ONE sample off
4721+ // (seed 50, luma (171,56) ours 147 vs ffmpeg 148, inside a 64x32
4722+ // strip whose transform resolved to depth 2 / TX_16X16). A refusal
4723+ // this lane could not lift is not a refusal it may silently ship
4724+ // wrong pixels past, so the named refusal stays until that gate is
4725+ // green.
39144726 return Err(unsupported(
39154727 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \
39164728 prediction is not ported)",
@@ -4017,7 +4829,7 @@ fn decode_block_rect64(
40174829 luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]);
40184830 }
40194831 {
4020- let cur = CURRENT_Q_IDX.with(|c| c.get());
4832+ let cur = block_q_idx();
40214833 if cur != i32::from(base_q_idx) {
40224834 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
40234835 }
@@ -4032,7 +4844,7 @@ fn decode_block_rect64(
40324844 bw,
40334845 bh,
40344846 crate::decode::bit_depth(),
4035- CURRENT_Q_IDX.with(|c| c.get()),
4847+ block_q_idx(),
40364848 plane_q_delta(0).0,
40374849 plane_q_delta(0).1,
40384850 luma_tx_type,
@@ -4089,7 +4901,7 @@ fn decode_block_rect64(
40894901 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
40904902 }
40914903 {
4092- let cur = CURRENT_Q_IDX.with(|c| c.get());
4904+ let cur = block_q_idx();
40934905 if cur != i32::from(base_q_idx) {
40944906 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
40954907 }
@@ -4104,7 +4916,7 @@ fn decode_block_rect64(
41044916 chroma_w,
41054917 chroma_h,
41064918 crate::decode::bit_depth(),
4107- CURRENT_Q_IDX.with(|c| c.get()),
4919+ block_q_idx(),
41084920 plane_q_delta(1).0,
41094921 plane_q_delta(1).1,
41104922 u_tx_type,
@@ -4143,7 +4955,7 @@ fn decode_block_rect64(
41434955 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
41444956 }
41454957 {
4146- let cur = CURRENT_Q_IDX.with(|c| c.get());
4958+ let cur = block_q_idx();
41474959 if cur != i32::from(base_q_idx) {
41484960 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
41494961 }
@@ -4158,7 +4970,7 @@ fn decode_block_rect64(
41584970 chroma_w,
41594971 chroma_h,
41604972 crate::decode::bit_depth(),
4161- CURRENT_Q_IDX.with(|c| c.get()),
4973+ block_q_idx(),
41624974 plane_q_delta(2).0,
41634975 plane_q_delta(2).1,
41644976 v_tx_type,
@@ -4261,11 +5073,20 @@ fn read_intra_mode(
42615073 }
42625074 };
42635075 }
5076+ // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
5077+ // `skip` when `SegIdPreSkip`, and after it otherwise.
5078+ let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
5079+ if seg_id_pre_skip() {
5080+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
5081+ }
42645082 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
42655083 if trace {
42665084 eprintln!("TRACE skip value={}", skip as i32);
42675085 }
42685086 istep!("skip", skip as i32);
5087+ if !seg_id_pre_skip() {
5088+ intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
5089+ }
42695090 // spec order (see the comment below on `read_intrabc_info`): `skip`,
42705091 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
42715092 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
@@ -4288,9 +5109,18 @@ fn read_intra_mode(
42885109 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
42895110 }
42905111 if use_intrabc {
4291- return Err(unsupported(
4292- "a block that actually uses intrabc (this decoder never reconstructs one)",
4293- ));
5112+ let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
5113+ if trace {
5114+ eprintln!("TRACE intrabc dv={dv:?}");
5115+ }
5116+ INTRABC_DV.with(|c| c.set(Some(dv)));
5117+ INTRABC_HITS.with(|c| c.set(c.get() + 1));
5118+ // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
5119+ // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
5120+ // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
5121+ // `DC_PRED` (which is also what the neighbour mode contexts and
5122+ // the loop filter then see).
5123+ return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
42945124 }
42955125 }
42965126 let above_ctx = INTRA_MODE_CTX[above_mode];
@@ -4570,6 +5400,20 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
45705400 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
45715401 /// (own-edge and reach clamps both), passing what it gathers straight to
45725402 /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
5403+/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
5404+/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
5405+fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
5406+ use std::io::Write;
5407+ if let Ok(path) = std::env::var(var)
5408+ && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
5409+ {
5410+ for p in [y, u, v] {
5411+ let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
5412+ let _ = f.write_all(&narrow);
5413+ }
5414+ }
5415+}
5416+
45735417 #[derive(Clone)]
45745418 struct PlaneBuf {
45755419 data: Vec<u16>,
@@ -4726,6 +5570,7 @@ impl PlaneBuf {
47265570 left.as_deref(),
47275571 corner,
47285572 bw,
5573+ bh,
47295574 &mut prediction,
47305575 );
47315576 } else {
@@ -4800,6 +5645,7 @@ impl PlaneBuf {
48005645 left.as_deref(),
48015646 corner,
48025647 side,
5648+ side,
48035649 &mut prediction,
48045650 );
48055651 } else {
@@ -4937,7 +5783,7 @@ fn read_plane(
49375783 full
49385784 };
49395785 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
4940- let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type);
5786+ let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
49415787 if std::env::var_os("EC_AV1_TRACE").is_some() {
49425788 eprintln!(
49435789 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
@@ -5021,6 +5867,16 @@ fn decode_block(
50215867 r * (SUB / MI),
50225868 c * (SUB / MI),
50235869 )?;
5870+ let intrabc_dv = INTRABC_DV.with(|c| c.take());
5871+ // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
5872+ // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
5873+ // partition tree (`read_var_tx_size`), a syntax element this decoder has
5874+ // nowhere -- reading the intra `tx_depth` symbol instead would desync.
5875+ if intrabc_dv.is_some() && tx_select && !skip {
5876+ return Err(unsupported(
5877+ "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
5878+ ));
5879+ }
50245880 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
50255881 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
50265882 // actual chroma-from-luma correlation, same as this decoder always did.
@@ -5060,10 +5916,45 @@ fn decode_block(
50605916 } else {
50615917 luma_set
50625918 };
5919+ let luma_set = if intrabc_dv.is_some() {
5920+ txbset_for_inter(logical_tx, reduced_tx_set)
5921+ } else {
5922+ luma_set
5923+ };
50635924 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
50645925 let reach = Reach::of(side, px, py, y.width, y.height);
50655926 let (cpx, cpy) = (px / 2, py / 2);
50665927 let chroma_side = side / 2;
5928+ // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
5929+ // frame's own pre-loop-filter reconstruction (all loop filters are off
5930+ // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
5931+ // block vector, with the BILINEAR kernel libaom forces for intrabc --
5932+ // luma is a straight copy, chroma lands half-pel whenever the luma DV is
5933+ // odd, which is exactly what the bilinear taps then interpolate.
5934+ let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
5935+ let mut yb = vec![0u16; side * side];
5936+ mc::predict_with_filter(
5937+ &y.data, y.width, y.true_width, y.true_height,
5938+ mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
5939+ side, side, mc::InterpFilterKind::Bilinear, &mut yb,
5940+ );
5941+ let mut ub = vec![0u16; chroma_side * chroma_side];
5942+ mc::predict_with_filter(
5943+ &u.data, u.width, u.true_width, u.true_height,
5944+ mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
5945+ chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
5946+ );
5947+ let mut vb = vec![0u16; chroma_side * chroma_side];
5948+ mc::predict_with_filter(
5949+ &v.data, v.width, v.true_width, v.true_height,
5950+ mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
5951+ chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
5952+ );
5953+ (yb, ub, vb)
5954+ });
5955+ if let Some((yb, _, _)) = &intrabc_bufs {
5956+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(yb.clone()));
5957+ }
50675958 // A palette-Y block's own prediction is the reconstructed colour-index
50685959 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
50695960 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
@@ -5099,6 +5990,13 @@ fn decode_block(
50995990 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
51005991 )
51015992 });
5993+ // The chroma half of the intrabc prediction rides the same per-plane
5994+ // override slot the UV-palette buffers do (set fresh before each plane's
5995+ // own `reconstruct`/`read_plane` call below).
5996+ let palette_uv_bufs = match &intrabc_bufs {
5997+ Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
5998+ None => palette_uv_bufs,
5999+ };
51026000 if skip {
51036001 // A skipped block codes no residual syntax at all (spec 5.11.34):
51046002 // straight prediction, on every plane.
@@ -5374,6 +6272,7 @@ fn decode_block(
53746272 logical_tx as u8,
53756273 0,
53766274 );
6275+ record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
53776276 Ok(())
53786277 }
53796278
@@ -5956,24 +6855,16 @@ fn plane_to_mi(chroma: bool, coord: usize) -> usize {
59566855 /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
59576856 /// under 4:2:0 and a block that never splits its own transform).
59586857 fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
5959- let luma_tx = n
5960- .tx_grid
5961- .get(mi_r * n.skip_grid_cols_mi + mi_c)
5962- .copied()
5963- .unwrap_or(0) as u32;
5964- if chroma { luma_tx / 2 } else { luma_tx }
6858+ let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
6859+ grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
59656860 }
59666861
59676862 /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
59686863 /// edges step and gate by transform height, which differs from width only
59696864 /// on rect partition strips.
59706865 fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
5971- let luma_tx = n
5972- .tx_h_grid
5973- .get(mi_r * n.skip_grid_cols_mi + mi_c)
5974- .copied()
5975- .unwrap_or(0) as u32;
5976- if chroma { luma_tx / 2 } else { luma_tx }
6866+ let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
6867+ grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
59776868 }
59786869
59796870 /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
@@ -6057,6 +6948,21 @@ fn scan_for<'a>(
60576948 /// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
60586949 /// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
60596950 /// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
6951+/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
6952+/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
6953+/// inter `ext_tx` sets, never the mode-indexed intra ones.
6954+fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
6955+ match tx_px {
6956+ 64 => TxbSet::Luma64,
6957+ 32 => TxbSet::Luma32Inter,
6958+ 16 if reduced_tx_set => TxbSet::Luma16Inter,
6959+ 16 => TxbSet::Luma16InterSet1,
6960+ 8 if reduced_tx_set => TxbSet::Luma8Inter,
6961+ 8 => TxbSet::Luma8InterSet1,
6962+ _ => TxbSet::Luma64,
6963+ }
6964+}
6965+
60606966 fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
60616967 match tx_px {
60626968 64 => TxbSet::Luma64,
@@ -6088,7 +6994,14 @@ fn unit_log2(px: u32) -> i32 {
60886994 /// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
60896995 /// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
60906996 /// block anywhere aborted the whole stream's decode before comparison).
6091-fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8, delta_lf: i32) -> i32 {
6997+fn lf_level(
6998+ lf: &LoopFilterParams,
6999+ plane_idx: usize,
7000+ dir: usize,
7001+ ref_frame: i8,
7002+ delta_lf: i32,
7003+ segment_id: u8,
7004+) -> i32 {
60927005 let base = i32::from(if plane_idx == 0 {
60937006 lf.level[dir]
60947007 } else if plane_idx == 1 {
@@ -6100,6 +7013,16 @@ fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8,
61007013 // ref/mode delta scaling below, and regardless of `delta_enabled`
61017014 // (that flag only gates `ref_deltas`/`mode_deltas`).
61027015 let base = (base + delta_lf).clamp(0, 63);
7016+ // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
7017+ // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
7018+ // per-superblock `DeltaLF` term and before the ref/mode deltas below.
7019+ // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
7020+ // for chroma.
7021+ let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
7022+ let base = match seg_feature(usize::from(segment_id), feature) {
7023+ Some(data) => (base + data).clamp(0, 63),
7024+ None => base,
7025+ };
61037026 if !lf.delta_enabled {
61047027 return base;
61057028 }
@@ -6155,8 +7078,15 @@ fn edge_params(
61557078 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
61567079 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
61577080
6158- let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf);
6159- let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf);
7081+ let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
7082+ let pv_level = lf_level(
7083+ lf,
7084+ plane_idx,
7085+ dir,
7086+ pv_ref,
7087+ pv_delta_lf,
7088+ segment_id_at(pv_mi_r, pv_mi_c),
7089+ );
61607090 if cur_level == 0 && pv_level == 0 {
61617091 return None;
61627092 }
@@ -6855,6 +7785,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
68557785 }
68567786 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
68577787 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
7788+ INTRABC_MI_GRID.with(|g| {
7789+ *g.borrow_mut() = allow_intrabc.then(|| {
7790+ (
7791+ crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
7792+ mi_cols as usize,
7793+ mi_rows as usize,
7794+ )
7795+ });
7796+ });
7797+ INTRABC_DV.with(|c| c.set(None));
68587798 CDEF_BITS.with(|c| c.set(cdef.bits));
68597799 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
68607800 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
@@ -7204,6 +8144,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
72048144 allow_screen_content_tools,
72058145 base_q_idx,
72068146 tx_select,
8147+ reduced_tx_set,
72078148 )?;
72088149 // Two 8x8 squares stacked on the
72098150 // right, chained through
@@ -7508,6 +8449,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
75088449 allow_screen_content_tools,
75098450 base_q_idx,
75108451 tx_select,
8452+ reduced_tx_set,
75118453 )?;
75128454 decode_block_rect(
75138455 &mut dec,
@@ -7523,6 +8465,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
75238465 allow_screen_content_tools,
75248466 base_q_idx,
75258467 tx_select,
8468+ reduced_tx_set,
75268469 )?;
75278470 }
75288471 PARTITION_VERT => {
@@ -7542,6 +8485,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
75428485 allow_screen_content_tools,
75438486 base_q_idx,
75448487 tx_select,
8488+ reduced_tx_set,
75458489 )?;
75468490 decode_block_rect(
75478491 &mut dec,
@@ -7557,6 +8501,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
75578501 allow_screen_content_tools,
75588502 base_q_idx,
75598503 tx_select,
8504+ reduced_tx_set,
75608505 )?;
75618506 }
75628507 _ => {
@@ -7583,6 +8528,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
75838528 allow_screen_content_tools,
75848529 base_q_idx,
75858530 tx_select,
8531+ reduced_tx_set,
75868532 )?;
75878533 decode_block_rect64(
75888534 &mut dec,
@@ -7598,6 +8544,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
75988544 allow_screen_content_tools,
75998545 base_q_idx,
76008546 tx_select,
8547+ reduced_tx_set,
76018548 )?;
76028549 }
76038550 PARTITION_VERT => {
@@ -7617,6 +8564,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
76178564 allow_screen_content_tools,
76188565 base_q_idx,
76198566 tx_select,
8567+ reduced_tx_set,
76208568 )?;
76218569 decode_block_rect64(
76228570 &mut dec,
@@ -7632,6 +8580,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
76328580 allow_screen_content_tools,
76338581 base_q_idx,
76348582 tx_select,
8583+ reduced_tx_set,
76358584 )?;
76368585 }
76378586 _ => {
@@ -7693,7 +8642,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
76938642 frame_height as usize,
76948643 );
76958644 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
8645+ // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
8646+ // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
8647+ // dump above these bisect WHICH filter stage introduced a mismatch.
8648+ dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
76968649 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
8650+ dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
76978651 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
76988652
76998653 let (fw, fh) = (frame_width as usize, frame_height as usize);
@@ -7959,6 +8913,58 @@ fn read_mv(
79598913 (pred.0 + diff.0, pred.1 + diff.1)
79608914 }
79618915
8916+/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
8917+/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
8918+///
8919+/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
8920+/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
8921+/// when that is zero, or -- when both are -- the fixed fallback DV one
8922+/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
8923+/// left when this is the tile's first superblock row. The predictor is then
8924+/// rounded to full pel, and the difference reads off the *dv* nmv context
8925+/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
8926+/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
8927+/// symbol is coded for a DV, so none of this can move the bitstream
8928+/// position -- only the reconstructed vector.
8929+fn read_intrabc_dv(
8930+ dec: &mut SymbolDecoder,
8931+ cdfs: &mut Cdfs,
8932+ mi_r: usize,
8933+ mi_c: usize,
8934+ side: usize,
8935+) -> (i32, i32) {
8936+ const INTRABC_DELAY_PIXELS: i32 = 256;
8937+ let n4 = side / MI;
8938+ let stack_pred = INTRABC_MI_GRID.with(|g| {
8939+ let g = g.borrow();
8940+ g.as_ref().map(|(grid, mi_cols, mi_rows)| {
8941+ let stack = crate::mvstack::find_mv_stack(
8942+ grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
8943+ *mi_cols, *mi_rows,
8944+ );
8945+ if stack.nearest_mv == (0, 0) {
8946+ stack.near_mv
8947+ } else {
8948+ stack.nearest_mv
8949+ }
8950+ })
8951+ });
8952+ let mut pred = stack_pred.unwrap_or((0, 0));
8953+ if pred == (0, 0) {
8954+ // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
8955+ // single-tile-row case every intrabc gate stream is).
8956+ let sb_px = SB_MI as i32 * MI as i32;
8957+ pred = if mi_r < SB_MI as usize {
8958+ (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
8959+ } else {
8960+ (-sb_px * 8, 0)
8961+ };
8962+ }
8963+ // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
8964+ let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
8965+ read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
8966+}
8967+
79628968 /// A 1/8-pel motion vector component converted to the 1/16-pel offset
79638969 /// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
79648970 /// (its own doc comment explains the `*2`/`*1` luma/chroma split).
@@ -8062,7 +9068,7 @@ fn read_inter_plane(
80629068 None,
80639069 )?;
80649070 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
8065- let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type);
9071+ let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
80669072 plane.reconstruct_mc(x, y, side, prediction, &residual);
80679073 Ok((grid, tx_type))
80689074 }
@@ -9146,6 +10152,11 @@ fn decode_inter_block(
914610152 dec.debug_bitpos()
914710153 );
914810154 }
10155+ // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
10156+ // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
10157+ let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
10158+ let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
10159+ inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
914910160 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
915010161 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
915110162 eprintln!(
@@ -9159,6 +10170,7 @@ fn decode_inter_block(
915910170
916010171 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
916110172 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
10173+ inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
916210174 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
916310175 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
916410176 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
@@ -10996,6 +12008,9 @@ fn decode_inter_block8(
1099612008 }
1099712009 let skip_mode_ctx =
1099812010 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
12011+ // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
12012+ // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
12013+ inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
1099912014 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
1100012015 if skip_mode {
1100112016 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
@@ -11003,6 +12018,7 @@ fn decode_inter_block8(
1100312018
1100412019 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
1100512020 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
12021+ inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
1100612022 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
1100712023 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
1100812024 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
@@ -13588,7 +14604,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1358814604 frame_height as usize,
1358914605 );
1359014606 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
14607+ // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
14608+ // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
14609+ // dump above these bisect WHICH filter stage introduced a mismatch.
14610+ dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
1359114611 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
14612+ dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
1359214613 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
1359314614
1359414615 let motion_field = build_motion_field(
@@ -13952,13 +14973,27 @@ mod tests {
1395214973 use std::io::Write;
1395314974 use std::process::{Command, Stdio};
1395414975
14976+ /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
14977+ /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
14978+ /// aomenc gate decodes its stream through ffmpeg and is meaningless
14979+ /// without it -- turns it into a hard failure. Without this the require
14980+ /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
14981+ /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
14982+ /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
1395514983 fn have_ffmpeg() -> bool {
13956- Command::new("ffmpeg")
14984+ let present = Command::new("ffmpeg")
1395714985 .arg("-version")
1395814986 .stdout(Stdio::null())
1395914987 .stderr(Stdio::null())
1396014988 .status()
13961- .is_ok_and(|s| s.success())
14989+ .is_ok_and(|s| s.success());
14990+ assert!(
14991+ present
14992+ || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
14993+ && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
14994+ "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
14995+ );
14996+ present
1396214997 }
1396314998
1396414999 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
crates/ec-av1/src/encode.rsmodified+16 -2
@@ -3063,13 +3063,27 @@ mod tests {
30633063 use std::io::Write;
30643064 use std::process::{Command, Stdio};
30653065
3066+ /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
3067+ /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
3068+ /// aomenc gate decodes its stream through ffmpeg and is meaningless
3069+ /// without it -- turns it into a hard failure. Without this the require
3070+ /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
3071+ /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
3072+ /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
30663073 fn have_ffmpeg() -> bool {
3067- Command::new("ffmpeg")
3074+ let present = Command::new("ffmpeg")
30683075 .arg("-version")
30693076 .stdout(Stdio::null())
30703077 .stderr(Stdio::null())
30713078 .status()
3072- .is_ok_and(|s| s.success())
3079+ .is_ok_and(|s| s.success());
3080+ assert!(
3081+ present
3082+ || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
3083+ && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
3084+ "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3085+ );
3086+ present
30733087 }
30743088
30753089 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
crates/ec-av1/src/encoder.rsmodified+16 -2
@@ -362,13 +362,27 @@ mod tests {
362362 use super::*;
363363 use std::process::{Command, Stdio};
364364
365+ /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
366+ /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
367+ /// aomenc gate decodes its stream through ffmpeg and is meaningless
368+ /// without it -- turns it into a hard failure. Without this the require
369+ /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
370+ /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
371+ /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
365372 fn have_ffmpeg() -> bool {
366- Command::new("ffmpeg")
373+ let present = Command::new("ffmpeg")
367374 .arg("-version")
368375 .stdout(Stdio::null())
369376 .stderr(Stdio::null())
370377 .status()
371- .is_ok_and(|s| s.success())
378+ .is_ok_and(|s| s.success());
379+ assert!(
380+ present
381+ || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
382+ && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
383+ "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
384+ );
385+ present
372386 }
373387
374388 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
crates/ec-av1/src/film_grain.rsmodified+93 -33
@@ -1,6 +1,6 @@
11 //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's
22 //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers),
3-//! specialized to this crate's only picture shape: 8-bit, 4:2:0 planar
3+//! specialized to this crate's only picture shape: 4:2:0 planar
44 //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every
55 //! `<< (1 - subsamp)` in the reference collapses to a no-op and every
66 //! `>> subsamp` collapses to `>> 1` below).
@@ -43,9 +43,25 @@ const LUMA_BLOCK_W: i32 =
4343 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;
4444 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;
4545
46-// bit_depth is always 8 in this crate: grain_center = 128 << (8 - 8) = 128.
47-const GRAIN_MIN: i32 = -128;
48-const GRAIN_MAX: i32 = 127;
46+thread_local! {
47+ /// `params->bit_depth` of the picture currently being grained. libaom
48+ /// keeps `grain_min`/`grain_max` as file statics set once per
49+ /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors
50+ /// that rather than threading a parameter through every helper.
51+ static GRAIN_BIT_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(8) };
52+}
53+
54+/// `params->bit_depth` for the [`apply_grain`] call in progress.
55+fn grain_bit_depth() -> u32 {
56+ GRAIN_BIT_DEPTH.with(|c| c.get())
57+}
58+
59+/// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`):
60+/// `grain_center = 128 << (bit_depth - 8)`.
61+fn grain_range() -> (i32, i32) {
62+ let center = 128i32 << (grain_bit_depth() - 8);
63+ (-center, center - 1)
64+}
4965
5066 const MIN_LUMA_LEGAL: i32 = 16;
5167 const MAX_LUMA_LEGAL: i32 = 235;
@@ -121,11 +137,12 @@ fn generate_luma_grain_block(
121137 pred_pos: &[(i32, i32, i32)],
122138 rng: &mut Rng,
123139 ) -> Vec<i32> {
140+ let (grain_min, grain_max) = grain_range();
124141 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
125142 if fg.num_y_points == 0 {
126143 return block;
127144 }
128- let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; // 12 - 8 + grain_scale_shift
145+ let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;
129146 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
130147 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
131148
@@ -143,7 +160,7 @@ fn generate_luma_grain_block(
143160 wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx);
144161 }
145162 let v = (at(&block, LUMA_BLOCK_W, i, j) + ((wsum + rounding_offset) >> ar_coeff_shift))
146- .clamp(GRAIN_MIN, GRAIN_MAX);
163+ .clamp(grain_min, grain_max);
147164 set_at(&mut block, LUMA_BLOCK_W, i, j, v);
148165 }
149166 }
@@ -157,9 +174,10 @@ fn generate_chroma_grain_blocks(
157174 luma_block: &[i32],
158175 seed: u16,
159176 ) -> (Vec<i32>, Vec<i32>) {
177+ let (grain_min, grain_max) = grain_range();
160178 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
161179 let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
162- let gauss_sec_shift = 4 + fg.grain_scale_shift as i32;
180+ let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;
163181 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
164182 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
165183
@@ -226,13 +244,13 @@ fn generate_chroma_grain_blocks(
226244 if apply_cb {
227245 let v = (at(&cb, CHROMA_BLOCK_W, i, j)
228246 + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
229- .clamp(GRAIN_MIN, GRAIN_MAX);
247+ .clamp(grain_min, grain_max);
230248 set_at(&mut cb, CHROMA_BLOCK_W, i, j, v);
231249 }
232250 if apply_cr {
233251 let v = (at(&cr, CHROMA_BLOCK_W, i, j)
234252 + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
235- .clamp(GRAIN_MIN, GRAIN_MAX);
253+ .clamp(grain_min, grain_max);
236254 set_at(&mut cr, CHROMA_BLOCK_W, i, j, v);
237255 }
238256 }
@@ -265,7 +283,21 @@ fn build_scaling_lut(values: &[u8], scaling: &[u8], num_points: usize) -> [i32;
265283 lut
266284 }
267285
268-/// `add_noise_to_block` (spec 7.18.3.5), 8-bit / 4:2:0 only. `(py0, px0)` is
286+/// `scale_LUT` (`grain_synthesis.c:616`): the scaling LUT has 256 entries
287+/// regardless of bit depth, so at 10/12 bit the index is shifted down and the
288+/// two neighbouring entries are interpolated with the dropped low bits.
289+fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 {
290+ let shift = bit_depth - 8;
291+ let x = (index >> shift) as usize;
292+ if shift == 0 || x == 255 {
293+ lut[x]
294+ } else {
295+ lut[x] + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1)))
296+ >> shift)
297+ }
298+}
299+
300+/// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is
269301 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,
270302 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the
271303 /// same function serves both the raw 82x73/44x38 templates and the small
@@ -295,13 +327,17 @@ fn add_noise_to_block(
295327 let y_stride = picture.width as i32;
296328 let c_stride = (picture.width / 2) as i32;
297329 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;
330+ let bit_depth = grain_bit_depth();
331+ let bd_shift = bit_depth - 8;
332+ // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp.
333+ let index_max = (256i32 << bd_shift) - 1;
298334
299335 let mut cb_mult = fg.cb_mult as i32 - 128;
300336 let mut cb_luma_mult = fg.cb_luma_mult as i32 - 128;
301- let mut cb_offset = fg.cb_offset as i32 - 256;
337+ let mut cb_offset = ((fg.cb_offset as i32) << bd_shift) - (1 << bit_depth);
302338 let mut cr_mult = fg.cr_mult as i32 - 128;
303339 let mut cr_luma_mult = fg.cr_luma_mult as i32 - 128;
304- let mut cr_offset = fg.cr_offset as i32 - 256;
340+ let mut cr_offset = ((fg.cr_offset as i32) << bd_shift) - (1 << bit_depth);
305341 if fg.chroma_scaling_from_luma {
306342 cb_mult = 0;
307343 cb_luma_mult = 64;
@@ -318,21 +354,21 @@ fn add_noise_to_block(
318354 let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range {
319355 if mc_identity {
320356 (
321- MIN_LUMA_LEGAL,
322- MAX_LUMA_LEGAL,
323- MIN_LUMA_LEGAL,
324- MAX_LUMA_LEGAL,
357+ MIN_LUMA_LEGAL << bd_shift,
358+ MAX_LUMA_LEGAL << bd_shift,
359+ MIN_LUMA_LEGAL << bd_shift,
360+ MAX_LUMA_LEGAL << bd_shift,
325361 )
326362 } else {
327363 (
328- MIN_LUMA_LEGAL,
329- MAX_LUMA_LEGAL,
330- MIN_CHROMA_LEGAL,
331- MAX_CHROMA_LEGAL,
364+ MIN_LUMA_LEGAL << bd_shift,
365+ MAX_LUMA_LEGAL << bd_shift,
366+ MIN_CHROMA_LEGAL << bd_shift,
367+ MAX_CHROMA_LEGAL << bd_shift,
332368 )
333369 }
334370 } else {
335- (0, 255, 0, 255)
371+ (0, index_max, 0, index_max)
336372 };
337373
338374 let cy0 = py0 / 2;
@@ -349,8 +385,9 @@ fn add_noise_to_block(
349385 let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32)
350386 >> 6)
351387 + cb_offset)
352- .clamp(0, 255);
353- let delta = (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset)
388+ .clamp(0, index_max);
389+ let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx]
390+ + rounding_offset)
354391 >> scaling_shift;
355392 picture.u[cidx] =
356393 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
@@ -359,8 +396,9 @@ fn add_noise_to_block(
359396 let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32)
360397 >> 6)
361398 + cr_offset)
362- .clamp(0, 255);
363- let delta = (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset)
399+ .clamp(0, index_max);
400+ let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx]
401+ + rounding_offset)
364402 >> scaling_shift;
365403 picture.v[cidx] =
366404 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
@@ -372,7 +410,8 @@ fn add_noise_to_block(
372410 for j in 0..half_w * 2 {
373411 let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize;
374412 let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize;
375- let delta = (scaling_y[picture.y[pidx] as usize] * luma_grain[gidx]
413+ let delta = (scale_lut(scaling_y, picture.y[pidx] as i32, bit_depth)
414+ * luma_grain[gidx]
376415 + rounding_offset)
377416 >> scaling_shift;
378417 picture.y[pidx] =
@@ -398,6 +437,7 @@ fn ver_overlap_inplace(
398437 width: i32,
399438 height: i32,
400439 ) {
440+ let (grain_min, grain_max) = grain_range();
401441 for h in 0..height {
402442 if width == 1 {
403443 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -407,7 +447,7 @@ fn ver_overlap_inplace(
407447 dst_stride,
408448 dst_row0 + h,
409449 dst_col0,
410- ((l * 23 + r * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),
450+ ((l * 23 + r * 22 + 16) >> 5).clamp(grain_min, grain_max),
411451 );
412452 } else {
413453 let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -419,14 +459,14 @@ fn ver_overlap_inplace(
419459 dst_stride,
420460 dst_row0 + h,
421461 dst_col0,
422- ((27 * l0 + 17 * r0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),
462+ ((27 * l0 + 17 * r0 + 16) >> 5).clamp(grain_min, grain_max),
423463 );
424464 set_at(
425465 dst,
426466 dst_stride,
427467 dst_row0 + h,
428468 dst_col0 + 1,
429- ((17 * l1 + 27 * r1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),
469+ ((17 * l1 + 27 * r1 + 16) >> 5).clamp(grain_min, grain_max),
430470 );
431471 }
432472 }
@@ -447,6 +487,7 @@ fn hor_overlap_inplace(
447487 width: i32,
448488 height: i32,
449489 ) {
490+ let (grain_min, grain_max) = grain_range();
450491 if height == 1 {
451492 for w in 0..width {
452493 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);
@@ -456,7 +497,7 @@ fn hor_overlap_inplace(
456497 dst_stride,
457498 dst_row0,
458499 dst_col0 + w,
459- ((t * 23 + b * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),
500+ ((t * 23 + b * 22 + 16) >> 5).clamp(grain_min, grain_max),
460501 );
461502 }
462503 } else {
@@ -470,14 +511,14 @@ fn hor_overlap_inplace(
470511 dst_stride,
471512 dst_row0,
472513 dst_col0 + w,
473- ((27 * t0 + 17 * b0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),
514+ ((27 * t0 + 17 * b0 + 16) >> 5).clamp(grain_min, grain_max),
474515 );
475516 set_at(
476517 dst,
477518 dst_stride,
478519 dst_row0 + 1,
479520 dst_col0 + w,
480- ((17 * t1 + 27 * b1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX),
521+ ((17 * t1 + 27 * b1 + 16) >> 5).clamp(grain_min, grain_max),
481522 );
482523 }
483524 }
@@ -496,6 +537,7 @@ fn copy_area(
496537 width: i32,
497538 height: i32,
498539 ) {
540+ let (grain_min, grain_max) = grain_range();
499541 for h in 0..height {
500542 for w in 0..width {
501543 let v = at(src, src_stride, src_row0 + h, src_col0 + w);
@@ -504,15 +546,33 @@ fn copy_area(
504546 }
505547 }
506548
549+thread_local! {
550+ /// Firing count for the film-grain gates (class `gate-blind-to-feature`):
551+ /// how many pictures actually ran through grain synthesis.
552+ static GRAIN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
553+}
554+
555+/// Current value of [`GRAIN_HITS`].
556+pub(crate) fn grain_hits() -> usize {
557+ GRAIN_HITS.with(|c| c.get())
558+}
559+
507560 /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and
508561 /// apply film grain to `picture`, returning a new grained picture. `picture`
509562 /// itself is unchanged -- it stays the clean reference-frame-bank copy.
510563 /// Returns `picture.clone()` untouched when `apply_grain` is unset.
511-pub(crate) fn apply_grain(picture: &Picture, fg: &FilmGrainParams, mc_identity: bool) -> Picture {
564+pub(crate) fn apply_grain(
565+ picture: &Picture,
566+ fg: &FilmGrainParams,
567+ mc_identity: bool,
568+ bit_depth: u32,
569+) -> Picture {
512570 let mut out = picture.clone();
513571 if !fg.apply_grain {
514572 return out;
515573 }
574+ GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth));
575+ GRAIN_HITS.with(|c| c.set(c.get() + 1));
516576 let width = out.width as i32;
517577 let height = out.height as i32;
518578 let y_stride = width;
crates/ec-av1/src/gate_coverage.rsmodified+7 -1
@@ -33,7 +33,13 @@
3333 /// its tool is now covered by a real stream.
3434 #[cfg(test)]
3535 const NEVER_EXERCISED: &[(&str, &str)] = &[
36- ("enable-intrabc", "intra block copy syntax is consumed but no block is reconstructed from it"),
36+ // lane-intrabc r1: the DV itself (mv stack against INTRA_FRAME, `ndvc`
37+ // full-pel read, `av1_find_ref_dv` fallback) and the block-copy
38+ // prediction are now decoded, but every real aomenc intrabc block this
39+ // lane could produce sits under TX_MODE_SELECT, whose inter var-tx
40+ // partition tree is unread -- so no stream reconstructs one end to end
41+ // yet and this entry stays.
42+ ("enable-intrabc", "the block vector is decoded and predicted from, but every real stream's intrabc block needs the unread inter var-tx transform tree"),
3743 ];
3844
3945 #[cfg(test)]
crates/ec-av1/src/intra.rsmodified+26 -18
@@ -726,37 +726,45 @@ const FILTER_INTRA_SCALE_BITS: u32 = 4;
726726 /// though this mode itself never reaches past its own `side` samples of
727727 /// either edge.
728728 ///
729+/// `bw`x`bh` is the block, not necessarily square (lane-rectsplit r1):
730+/// `av1_filter_intra_predictor_c` walks the same 4x2 patches over a
731+/// rectangular block, and `av1_filter_intra_allowed_bsize` genuinely offers
732+/// this mode on every HORZ/VERT strip whose sides are both <= 32 (16x8,
733+/// 8x16, 32x16, 16x32, ...), which the square-only assert refused before.
734+///
729735 /// # Panics
730-/// Panics when `dst` is not `side * side` long, or `side` is not a multiple
731-/// of 4 (spec `av1_filter_intra_allowed_bsize` never offers this mode past
732-/// 32x32, and only on square blocks: 4, 8, 16 or 32).
736+/// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4
737+/// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never
738+/// offers this mode past 32x32).
733739 pub fn predict_filter_intra(
734740 mode: usize,
735741 above: Option<&[u16]>,
736742 left: Option<&[u16]>,
737743 corner: Option<u16>,
738- side: usize,
744+ bw: usize,
745+ bh: usize,
739746 dst: &mut [u16],
740747 ) {
741- assert_eq!(dst.len(), side * side, "the destination is the block");
742- assert_eq!(side % 4, 0, "filter intra only offers 4/8/16/32");
743- let edges = Edges::build(above, left, corner, side, side);
748+ assert_eq!(dst.len(), bw * bh, "the destination is the block");
749+ assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
750+ assert_eq!(bh % 2, 0, "filter intra patches are 2 high");
751+ let edges = Edges::build(above, left, corner, bw, bh);
744752 let taps = &FILTER_INTRA_TAPS[mode];
745753 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the
746754 // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c).
747- let mut buffer = vec![0i32; (side + 1) * (side + 1)];
748- let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (side + 1) + c];
755+ let mut buffer = vec![0i32; (bh + 1) * (bw + 1)];
756+ let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (bw + 1) + c];
749757 buffer[0] = edges.above(-1);
750- for c in 0..side {
758+ for c in 0..bw {
751759 buffer[c + 1] = edges.above(c as i32);
752760 }
753- for r in 0..side {
754- buffer[(r + 1) * (side + 1)] = edges.left(r as i32);
761+ for r in 0..bh {
762+ buffer[(r + 1) * (bw + 1)] = edges.left(r as i32);
755763 }
756764 let mut r = 1;
757- while r < side + 1 {
765+ while r < bh + 1 {
758766 let mut c = 1;
759- while c < side + 1 {
767+ while c < bw + 1 {
760768 let p0 = at(&buffer, r - 1, c - 1);
761769 let p1 = at(&buffer, r - 1, c);
762770 let p2 = at(&buffer, r - 1, c + 1);
@@ -769,16 +777,16 @@ pub fn predict_filter_intra(
769777 let (r_off, c_off) = (k >> 2, k & 3);
770778 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();
771779 let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max());
772- let idx = (r + r_off) * (side + 1) + c + c_off;
780+ let idx = (r + r_off) * (bw + 1) + c + c_off;
773781 buffer[idx] = value;
774782 }
775783 c += 4;
776784 }
777785 r += 2;
778786 }
779- for row in 0..side {
780- for col in 0..side {
781- dst[row * side + col] = at(&buffer, row + 1, col + 1) as u16;
787+ for row in 0..bh {
788+ for col in 0..bw {
789+ dst[row * bw + col] = at(&buffer, row + 1, col + 1) as u16;
782790 }
783791 }
784792 }
crates/ec-av1/src/mvstack.rsmodified+12 -0
@@ -327,6 +327,13 @@ fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32)
327327 /// `LAST_FRAME`) pass an all-`false` table, matching this stub's old
328328 /// always-`false` behaviour exactly.
329329 fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool {
330+ // lane-intrabc: `INTRA_FRAME` (0) and `NONE` (-1) sit *below* the table's
331+ // own `LAST_FRAME` base and have no sign bias at all -- an intrabc block
332+ // queries the stack with `ref_frame == INTRA_FRAME`, which indexed this
333+ // table at `usize::MAX` before.
334+ if ref_frame < LAST_FRAME {
335+ return false;
336+ }
330337 table[(ref_frame - LAST_FRAME) as usize]
331338 }
332339
@@ -359,6 +366,11 @@ pub const NO_GM_MV: GmMvTable = [(0, 0); 7];
359366 /// `table[ref_frame - LAST_FRAME]`, [`sign_bias`]'s shape for a
360367 /// [`GmMvTable`].
361368 fn gm_mv(table: &GmMvTable, ref_frame: i8) -> (i32, i32) {
369+ // Same below-`LAST_FRAME` guard as [`sign_bias`]: `INTRA_FRAME` (the
370+ // intrabc query's own ref) has no global motion model.
371+ if ref_frame < LAST_FRAME {
372+ return (0, 0);
373+ }
362374 table[(ref_frame - LAST_FRAME) as usize]
363375 }
364376
crates/ec-av1/src/refusal_inventory.rsmodified+4 -5
@@ -37,27 +37,26 @@ const REFUSALS: &[&str] = &[
3737 "GLOBALMV (round 3)",
3838 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)",
3939 "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)",
40+ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
41+ "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)",
4042 "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)",
4143 "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
4244 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
4345 "a 32x32 partition type this decoder does not code (value={part32})",
4446 "a Golomb tail longer than this decoder reads",
45- "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)",
46- "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)",
4747 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)",
4848 "a tx_type symbol outside its CDF's own set: {t}",
4949 "an INTER 32x32 partition type this decoder does not code (value={part32})",
5050 "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)",
51- "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)",
5251 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
5352 "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)",
5453 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
5554 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
56- "a block that actually uses intrabc (this decoder never reconstructs one)",
55+ "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
5756 "a frame OBU with no tile group",
5857 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
5958 "a frame with no mode-info grid",
60- "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
59+ "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
6160 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
6261 "a reference frame other than LAST_FRAME (round 2)",
6362 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
crates/ec-av1/src/stream.rsmodified+1242 -112
@@ -16,7 +16,8 @@
1616 //! an implementation detail of how this crate happens to build it).
1717
1818 use ec_av1_syntax::{
19- Av1Parser, FrameHeader, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, Tile, TxMode,
19+ Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE,
20+ SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode,
2021 WarpModel,
2122 };
2223 use ec_core::{Error, Result};
@@ -74,6 +75,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
7475 // own end-of-tile adapted table, or (when the frame set
7576 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
7677 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
78+ // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
79+ // remembers the segment map the frame stored there decoded, which is what
80+ // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
81+ // (spec `load_previous_segment_ids`) for temporal segment-id prediction
82+ // and for a `segmentation_update_map == 0` frame's inherited map.
83+ let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
7784
7885 let mut pos = 0usize;
7986 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
@@ -124,27 +131,25 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
124131 cdf_slots[i] = cdf_slots[slot].clone();
125132 ref_slots[i] = Some(picture.clone());
126133 motion_field_slots[i] = motion_field_slots[slot].clone();
134+ seg_map_slots[i] = seg_map_slots[slot].clone();
127135 order_hint_slots[i] = order_hint_slots[slot];
128136 }
129137 }
130138 let output = if header.film_grain.apply_grain {
131- // lane-hbd r5: `film_grain.rs`'s grain LUT and blend are
132- // hardcoded 8-bit (`[i32; 256]`, clamps at 255) -- narrowed
133- // from the old blanket bit-depth refusal to only the case
134- // that actually reaches unported code.
139+ // lane-hbd10 r1: grain synthesis is bit-depth generic
140+ // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
135141 let bit_depth = parser
136142 .sequence_header()
137143 .map_or(8, |seq| seq.color_config.bit_depth);
138- if bit_depth != 8 {
139- return Err(Error::unsupported(
140- "AV1 decode_stream",
141- "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)",
142- ));
143- }
144144 let mc_identity = parser
145145 .sequence_header()
146146 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
147- crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
147+ crate::film_grain::apply_grain(
148+ &picture,
149+ &header.film_grain,
150+ mc_identity,
151+ bit_depth as u32,
152+ )
148153 } else {
149154 picture
150155 };
@@ -245,12 +250,41 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
245250 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
246251 // will show up as a real pixel mismatch, not a silent truncation --
247252 // the whole reason the widen (and this wiring) happened.
253+ // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
254+ // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
255+ // per-segment quantizer (spec 7.12.2) and loop-filter level
256+ // (spec 7.14.4). The three features that instead REWRITE a block's
257+ // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
258+ // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
259+ // symbols `decode_inter_block` unconditionally reads) -- have no
260+ // reader on the inter path, so they still refuse by name rather than
261+ // desyncing. aomenc's `--aq-mode` segmentation only ever sets
262+ // `SEG_LVL_ALT_Q`.
248263 if header.segmentation.enabled {
249- return Err(Error::unsupported(
250- "AV1 decode_stream",
251- "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
252- ));
264+ for segment in 0..MAX_SEGMENTS {
265+ for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
266+ if header.segmentation.feature_enabled[segment][feature] {
267+ return Err(Error::unsupported(
268+ "AV1 decode_stream",
269+ "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
270+ ));
271+ }
272+ }
273+ }
253274 }
275+ // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
276+ // primary reference frame's slot, and is all-zero without one.
277+ let prev_seg_map = if header.primary_ref_frame == PRIMARY_REF_NONE {
278+ None
279+ } else {
280+ seg_map_slots[header.ref_frame_idx[header.primary_ref_frame as usize] as usize].clone()
281+ };
282+ decode::set_segmentation(
283+ header.segmentation,
284+ header.mi_rows as usize,
285+ header.mi_cols as usize,
286+ prev_seg_map.as_deref(),
287+ );
254288 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
255289 // symbol (spec 7.16's upscaling is a pixel-domain post-process
256290 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
@@ -509,20 +543,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
509543 // call above, right before anything else can overwrite it) --
510544 // see `decode::take_last_frame_wide_margin`'s doc.
511545 let wide_margin = crate::decode::take_last_frame_wide_margin();
512- // lane-hbd r5: `upscale_row` (superres.rs) is `&[u8]`, clamping at
513- // 255 -- narrowed from the old blanket bit-depth refusal to only
514- // the case that actually reaches unported code.
515- if header.use_superres && bit_depth != 8 {
516- return Err(Error::unsupported(
517- "AV1 decode_stream",
518- "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)",
519- ));
520- }
521546 let picture = if header.use_superres {
522547 crate::superres::upscale_picture(
523548 &picture,
524549 header.upscaled_width as usize,
525550 wide_margin.as_ref(),
551+ bit_depth as u32,
526552 )
527553 } else {
528554 picture
@@ -634,6 +660,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
634660 &picture,
635661 header.upscaled_width as usize,
636662 wide_margin.as_ref(),
663+ bit_depth as u32,
637664 )
638665 } else {
639666 picture
@@ -696,6 +723,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
696723 }
697724 }
698725 pictures_decoded += 1;
726+ let decoded_seg_map = decode::take_segment_ids();
699727 for i in 0..NUM_REF_FRAMES {
700728 if header.refresh_frame_flags & (1 << i) != 0 {
701729 cdf_slots[i] = Some(stored_cdfs.clone());
@@ -705,23 +733,21 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
705733 // caller's output below carries the grained picture.
706734 ref_slots[i] = Some(picture.clone());
707735 motion_field_slots[i] = Some(motion_field.clone());
736+ seg_map_slots[i] = Some(decoded_seg_map.clone());
708737 order_hint_slots[i] = header.order_hint;
709738 }
710739 }
711740 if header.show_frame {
712741 let output = if header.film_grain.apply_grain {
713- // lane-hbd r5: same 8-bit-only LUT/blend as the
714- // show_existing_frame arm above.
715- if bit_depth != 8 {
716- return Err(Error::unsupported(
717- "AV1 decode_stream",
718- "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)",
719- ));
720- }
721742 let mc_identity = parser
722743 .sequence_header()
723744 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
724- crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
745+ crate::film_grain::apply_grain(
746+ &picture,
747+ &header.film_grain,
748+ mc_identity,
749+ bit_depth as u32,
750+ )
725751 } else {
726752 picture
727753 };
@@ -880,13 +906,27 @@ mod tests {
880906 hash
881907 }
882908
909+ /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
910+ /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
911+ /// aomenc gate decodes its stream through ffmpeg and is meaningless
912+ /// without it -- turns it into a hard failure. Without this the require
913+ /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
914+ /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
915+ /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
883916 fn have_ffmpeg() -> bool {
884- Command::new("ffmpeg")
917+ let present = Command::new("ffmpeg")
885918 .arg("-version")
886919 .stdout(Stdio::null())
887920 .stderr(Stdio::null())
888921 .status()
889- .is_ok_and(|s| s.success())
922+ .is_ok_and(|s| s.success());
923+ assert!(
924+ present
925+ || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
926+ && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
927+ "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
928+ );
929+ present
890930 }
891931
892932 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
@@ -1942,6 +1982,237 @@ mod tests {
19421982 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
19431983 }
19441984
1985+ /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
1986+ /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
1987+ /// identical bytes (ffmpeg synthesizes grain by default -- no
1988+ /// grain-disable flag is passed anywhere in this file). Proves the
1989+ /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
1990+ /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
1991+ /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
1992+ /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
1993+ /// silent 8-bit fallback nor a stream aomenc emitted without
1994+ /// `apply_grain` can make it pass vacuously.
1995+ #[test]
1996+ fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
1997+ const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
1998+ if !have_ffmpeg() {
1999+ eprintln!("SKIP {NAME}: no ffmpeg");
2000+ return;
2001+ }
2002+ if !have_aomenc() {
2003+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2004+ return;
2005+ }
2006+ let (width, height) = (64usize, 64usize);
2007+ let stream = encode_10bit_gradients(
2008+ NAME,
2009+ width,
2010+ height,
2011+ 1,
2012+ &["--film-grain-test=1", "--limit=1"],
2013+ );
2014+ assert_eq!(
2015+ parsed_bit_depth(&stream),
2016+ 10,
2017+ "{NAME}: aomenc did not actually write a 10-bit sequence header"
2018+ );
2019+ let mut probe = Av1Parser::new();
2020+ let mut pos = 0usize;
2021+ let mut saw_grain = false;
2022+ while pos < stream.len() {
2023+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
2024+ pos += obu.total_size;
2025+ if let ObuKind::Frame(header, _) = obu.kind
2026+ && header.film_grain.apply_grain
2027+ {
2028+ // A grain block whose scaling LUT is empty would blend a
2029+ // zero delta into every pixel and let this gate pass without
2030+ // the bit-depth math mattering at all.
2031+ assert!(
2032+ header.film_grain.num_y_points > 0,
2033+ "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
2034+ );
2035+ saw_grain = true;
2036+ }
2037+ }
2038+ assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
2039+ let before = crate::film_grain::grain_hits();
2040+ let frames = match decode_stream(&stream) {
2041+ Ok(frames) => frames,
2042+ Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2043+ };
2044+ assert!(
2045+ crate::film_grain::grain_hits() > before,
2046+ "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
2047+ );
2048+ let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2049+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2050+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2051+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2052+ eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
2053+ }
2054+
2055+ /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
2056+ /// --superres-denominator=12` key frame, decoded pixel-exact against
2057+ /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
2058+ /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
2059+ /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
2060+ /// `bit_depth == 10` and `superres_hits > 0`.
2061+ #[test]
2062+ fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
2063+ const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
2064+ if !have_ffmpeg() {
2065+ eprintln!("SKIP {NAME}: no ffmpeg");
2066+ return;
2067+ }
2068+ if !have_aomenc() {
2069+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2070+ return;
2071+ }
2072+ let (width, height) = (64usize, 64usize);
2073+ let stream = encode_10bit_gradients(
2074+ NAME,
2075+ width,
2076+ height,
2077+ 1,
2078+ &[
2079+ "--limit=1",
2080+ "--kf-max-dist=0",
2081+ "--superres-mode=1",
2082+ "--superres-denominator=12",
2083+ "--superres-kf-denominator=12",
2084+ "--enable-rect-partitions=0",
2085+ "--enable-ab-partitions=0",
2086+ "--enable-1to4-partitions=0",
2087+ "--enable-filter-intra=0",
2088+ "--enable-smooth-intra=0",
2089+ "--enable-paeth-intra=0",
2090+ "--enable-directional-intra=0",
2091+ "--enable-angle-delta=0",
2092+ "--enable-tx-size-search=0",
2093+ "--enable-cdef=0",
2094+ "--enable-restoration=0",
2095+ "--max-partition-size=32",
2096+ "--min-partition-size=32",
2097+ "--enable-palette=0",
2098+ "--enable-intrabc=0",
2099+ "--enable-cfl-intra=0",
2100+ ],
2101+ );
2102+ assert_eq!(
2103+ parsed_bit_depth(&stream),
2104+ 10,
2105+ "{NAME}: aomenc did not actually write a 10-bit sequence header"
2106+ );
2107+ let before = crate::superres::superres_hits();
2108+ let frames = match decode_stream(&stream) {
2109+ Ok(frames) => frames,
2110+ Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2111+ };
2112+ assert!(
2113+ crate::superres::superres_hits() > before,
2114+ "{NAME}: matched but zero superres_hits -- the upscaler never ran"
2115+ );
2116+ let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2117+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2118+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2119+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2120+ eprintln!(
2121+ "{NAME}: pixel-exact, superres_hits={}",
2122+ crate::superres::superres_hits()
2123+ );
2124+ }
2125+
2126+ /// `bit_depth` of the first sequence header in `stream`.
2127+ fn parsed_bit_depth(stream: &[u8]) -> u8 {
2128+ let mut probe = Av1Parser::new();
2129+ let mut pos = 0usize;
2130+ while pos < stream.len() && probe.sequence_header().is_none() {
2131+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
2132+ pos += obu.total_size;
2133+ }
2134+ probe
2135+ .sequence_header()
2136+ .expect("stream has a sequence header OBU")
2137+ .color_config
2138+ .bit_depth
2139+ }
2140+
2141+ /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
2142+ /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
2143+ /// `extra` carries the tool flags under test.
2144+ fn encode_10bit_gradients(
2145+ name: &str,
2146+ width: usize,
2147+ height: usize,
2148+ frames: usize,
2149+ extra: &[&str],
2150+ ) -> Vec<u8> {
2151+ let duration = frames as f64 / 25.0;
2152+ let y4m = Command::new("ffmpeg")
2153+ .args([
2154+ "-v",
2155+ "error",
2156+ "-f",
2157+ "lavfi",
2158+ "-i",
2159+ &gradients_source(42, width, height, &format!("duration={duration}:rate=25")),
2160+ "-pix_fmt",
2161+ "yuv420p10le",
2162+ "-strict",
2163+ "-1",
2164+ "-t",
2165+ &format!("{duration}"),
2166+ "-f",
2167+ "yuv4mpegpipe",
2168+ "-",
2169+ ])
2170+ .stdin(Stdio::null())
2171+ .stdout(Stdio::piped())
2172+ .stderr(Stdio::piped())
2173+ .output()
2174+ .expect("ffmpeg failed to run");
2175+ assert!(
2176+ y4m.status.success(),
2177+ "{name}: ffmpeg failed to render the 10-bit fixture: {}",
2178+ String::from_utf8_lossy(&y4m.stderr)
2179+ );
2180+ let mut args: Vec<&str> = vec![
2181+ "--codec=av1",
2182+ "--passes=1",
2183+ "--end-usage=q",
2184+ "--cq-level=30",
2185+ "--cpu-used=0",
2186+ "--threads=1",
2187+ "--row-mt=0",
2188+ "--sb-size=64",
2189+ "--input-bit-depth=10",
2190+ "--bit-depth=10",
2191+ ];
2192+ args.extend_from_slice(extra);
2193+ args.extend_from_slice(&["--obu", "-o", "-", "-"]);
2194+ let mut child = Command::new(aomenc_path())
2195+ .args(&args)
2196+ .stdin(Stdio::piped())
2197+ .stdout(Stdio::piped())
2198+ .stderr(Stdio::piped())
2199+ .spawn()
2200+ .expect("aomenc failed to start");
2201+ child
2202+ .stdin
2203+ .take()
2204+ .expect("aomenc stdin")
2205+ .write_all(&y4m.stdout)
2206+ .expect("writing y4m to aomenc");
2207+ let out = child.wait_with_output().expect("aomenc failed to run");
2208+ assert!(
2209+ out.status.success(),
2210+ "{name}: aomenc refused the 10-bit fixture: {}",
2211+ String::from_utf8_lossy(&out.stderr)
2212+ );
2213+ out.stdout
2214+ }
2215+
19452216 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
19462217 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
19472218 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
@@ -6705,20 +6976,23 @@ mod tests {
67056976 crate::decode::cdef_idx_hits()
67066977 );
67076978 }
6708- /// lane-tiny r1 diagnostic (not a gate): sweeps tiny key-frame sizes
6709- /// against real aomenc + ffmpeg to find the exact size boundary of the
6710- /// silent-wrong-pixels defect the sub8 lane's r2 dead-end flagged (a
6711- /// plain 16x16 stream, no exotic tools). `#[ignore]`d -- prints a
6712- /// pass/fail table, asserts nothing; run manually with `--nocapture`.
6979+ /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame
6980+ /// size real aomenc will encode, decoded pixel-exact against ffmpeg.
6981+ /// Tiny frames are where every edge/partial-superblock corner case is
6982+ /// forced, and this sweep is what found both r3's filter-intra tx_type
6983+ /// CDF row and r4's chroma-transform-size deblock defect -- so it
6984+ /// hard-asserts now: a decode error, a refusal, or one differing sample
6985+ /// at any size/seed fails. Only a genuinely absent oracle skips, and
6986+ /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too.
67136987 #[test]
6714- #[ignore = "diagnostic sweep, run manually with --nocapture"]
6715- fn probe_tiny_frame_size_boundary() {
6988+ fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() {
67166989 if !have_ffmpeg() || !have_aomenc() {
67176990 eprintln!("SKIP: no ffmpeg/aomenc");
67186991 return;
67196992 }
67206993 let sizes: &[(usize, usize)] =
67216994 &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)];
6995+ let mut total_exact = 0u32;
67226996 for &(width, height) in sizes {
67236997 let mut ok = 0u32;
67246998 let mut bad = 0u32;
@@ -6767,7 +7041,18 @@ mod tests {
67677041 let stream = out.stdout;
67687042 let frames = match decode_stream(&stream) {
67697043 Err(e) => {
6770- eprintln!(" {width}x{height} seed {seed}: REFUSED {e}");
7044+ // A NAMED refusal is the only non-exact outcome this
7045+ // gate tolerates (8x8 still needs a rectangular
7046+ // transform); anything else is a hard failure, and
7047+ // the floor assert below keeps that from going
7048+ // vacuous.
7049+ let msg = e.to_string();
7050+ assert!(
7051+ msg.contains("unsupported"),
7052+ "{width}x{height} seed {seed}: failed outright, not a named \
7053+ refusal: {msg}"
7054+ );
7055+ eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}");
67717056 refused += 1;
67727057 continue;
67737058 }
@@ -6782,6 +7067,12 @@ mod tests {
67827067 ok += 1;
67837068 } else {
67847069 bad += 1;
7070+ let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count();
7071+ let (ndy, ndu, ndv) = (
7072+ nd(&frames[0].y, &ffmpeg_frames[0].y),
7073+ nd(&frames[0].u, &ffmpeg_frames[0].u),
7074+ nd(&frames[0].v, &ffmpeg_frames[0].v),
7075+ );
67857076 let mut first = None;
67867077 for row in 0..height {
67877078 for col in 0..width {
@@ -6802,13 +7093,32 @@ mod tests {
68027093 .filter(|(a, b)| a != b)
68037094 .count();
68047095 eprintln!(
6805- " {width}x{height} seed {seed}: MISMATCH luma first_diff={first:?} ndiff_luma={ndiff}/{}",
7096+ " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \
7097+ ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}",
68067098 width * height
68077099 );
68087100 }
68097101 }
6810- eprintln!("{width}x{height}: {ok} ok / {bad} mismatch / {refused} refused (of {n})");
6811- }
7102+ assert_eq!(
7103+ bad, 0,
7104+ "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \
7105+ {refused} named refusals)"
7106+ );
7107+ eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals");
7108+ total_exact += ok;
7109+ }
7110+ // Hit counter: the sweep proved nothing unless every size x seed
7111+ // attempt really ran end to end (aomenc -> us -> ffmpeg compare).
7112+ // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds
7113+ // pixel-exact -- only 8x8 is allowed to refuse outright today. If a
7114+ // future change makes sizes refuse instead of decode, this fails
7115+ // rather than passing on refusals alone.
7116+ assert!(
7117+ total_exact >= 70,
7118+ "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \
7119+ refusals cannot substitute for decodes"
7120+ );
7121+ eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts");
68127122 }
68137123
68147124 /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with
@@ -8988,45 +9298,55 @@ mod tests {
89889298 );
89899299 }
89909300
8991- /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without
8992- /// -- a real >1-tile-column stream with a genuine INTER frame (not just
8993- /// the key-frame-only two-column gate above), decoded through
8994- /// `decode_stream` itself. Same recipe as the key-frame gate
8995- /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the
8996- /// same feature-disable envelope so the gate isolates the tile loop, not
8997- /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000`
8998- /// so frame 1 is a real inter frame, and `gradients_source`'s default
8999- /// `speed=0.01` rotation (undisturbed -- not overridden by the tail)
9000- /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_
9001- /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually
9002- /// have to walk a live MV stack across the tile-column boundary, not
9003- /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2
9004- /// frames at rate=25) per the class in ledger
9005- /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole-
9006- /// file` (never leave an ffmpeg/lavfi generate unbounded).
9007- #[test]
9008- fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() {
9009- const NAME: &str =
9010- "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact";
9301+ /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active.
9302+ /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two
9303+ /// paths libaom uses to switch `segmentation_enabled` on by itself
9304+ /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only
9305+ /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock
9306+ /// delta-q reader out of the picture so a mismatch points at the segment
9307+ /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is
9308+ /// what gives variance/complexity AQ different segments to assign --
9309+ /// a flat gradient collapses every block onto one segment, which the
9310+ /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run.
9311+ /// The rest of the recipe is the delta-q gate's own feature-disable
9312+ /// envelope, so this gate isolates the segmentation reader.
9313+ fn run_segmentation_gate(
9314+ name: &str,
9315+ aq_mode: &str,
9316+ bit_depth: usize,
9317+ frame_count: usize,
9318+ rate_args: &[&str],
9319+ ) {
9320+ let _gate_lock = lock_gate_counters();
90119321 if !have_ffmpeg() {
9012- eprintln!("SKIP {NAME}: no ffmpeg");
9322+ eprintln!("SKIP {name}: no ffmpeg");
90139323 return;
90149324 }
90159325 if !have_aomenc() {
9016- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9326+ eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
90179327 return;
90189328 }
9329+ crate::decode::reset_segment_hits();
90199330 let (width, height) = (128usize, 64usize);
9020- let frames = 2usize;
9021- let mut matched = 0u32;
90229331 let mut named_refusals = 0u32;
9023- for attempt in 0..20u32 {
9332+ let mut matched = 0u32;
9333+ let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS")
9334+ .ok()
9335+ .and_then(|s| s.parse().ok())
9336+ .unwrap_or(10);
9337+ for attempt in 0..n_attempts {
90249338 let seed = 42 + attempt;
9025- let source = gradients_source(seed, width, height, "duration=0.08:rate=25");
9339+ let duration = frame_count as f64 / 25.0;
9340+ let source = format!(
9341+ "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
9342+ sx = -0.6 + 0.005 * (attempt as f64),
9343+ sy = -0.4 + 0.005 * (attempt as f64)
9344+ );
9345+ let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
90269346 let y4m = Command::new("ffmpeg")
90279347 .args([
9028- "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
9029- "yuv4mpegpipe", "-",
9348+ "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
9349+ "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
90309350 ])
90319351 .stdin(Stdio::null())
90329352 .stdout(Stdio::piped())
@@ -9038,43 +9358,310 @@ mod tests {
90389358 "ffmpeg fixture: {}",
90399359 String::from_utf8_lossy(&y4m.stderr)
90409360 );
9041- let mut child = Command::new(aomenc_path())
9042- .args([
9043- "--codec=av1",
9044- "--passes=1",
9045- "--end-usage=q",
9046- "--cq-level=45",
9047- "--cpu-used=0",
9048- &format!("--limit={frames}"),
9049- "--kf-max-dist=1000",
9050- "--lag-in-frames=0",
9051- "--auto-alt-ref=0",
9052- "--threads=1",
9053- "--row-mt=0",
9054- "--tile-columns=1",
9055- "--tile-rows=0",
9056- "--sb-size=64",
9057- "--loopfilter-control=0",
9058- "--max-reference-frames=3",
9059- "--reduced-reference-set=1",
9060- "--enable-warped-motion=0",
9061- "--enable-obmc=0",
9062- "--enable-masked-comp=0",
9063- "--enable-interintra-comp=0",
9064- "--enable-dist-wtd-comp=0",
9065- "--enable-diff-wtd-comp=0",
9066- "--enable-onesided-comp=0",
9067- "--enable-interintra-wedge=0",
9068- "--enable-smooth-interintra=0",
9069- "--enable-ref-frame-mvs=0",
9070- "--enable-rect-partitions=0",
9071- "--enable-ab-partitions=0",
9072- "--enable-1to4-partitions=0",
9073- "--enable-filter-intra=0",
9074- "--enable-smooth-intra=0",
9075- "--enable-paeth-intra=0",
9076- "--enable-directional-intra=0",
9077- "--enable-angle-delta=0",
9361+ let depth_args: Vec<String> = if bit_depth == 10 {
9362+ vec!["--input-bit-depth=10".to_owned(), "--bit-depth=10".to_owned()]
9363+ } else {
9364+ Vec::new()
9365+ };
9366+ let aq = format!("--aq-mode={aq_mode}");
9367+ let mut args: Vec<&str> = vec![
9368+ "--codec=av1",
9369+ "--passes=1",
9370+ "--cpu-used=4",
9371+ &aq,
9372+ "--deltaq-mode=0",
9373+ "--kf-max-dist=1000",
9374+ "--threads=1",
9375+ "--row-mt=0",
9376+ "--sb-size=64",
9377+ "--auto-alt-ref=1",
9378+ "--lag-in-frames=16",
9379+ "--enable-fwd-kf=0",
9380+ "--enable-order-hint=1",
9381+ "--enable-warped-motion=1",
9382+ "--enable-global-motion=0",
9383+ "--enable-obmc=1",
9384+ "--tune-content=default",
9385+ "--enable-masked-comp=1",
9386+ "--enable-dist-wtd-comp=0",
9387+ "--enable-interintra-comp=1",
9388+ "--enable-onesided-comp=0",
9389+ "--enable-interintra-wedge=0",
9390+ "--enable-smooth-interintra=1",
9391+ "--enable-rect-partitions=0",
9392+ "--enable-ab-partitions=0",
9393+ "--enable-1to4-partitions=0",
9394+ "--enable-filter-intra=0",
9395+ "--enable-smooth-intra=0",
9396+ "--enable-paeth-intra=0",
9397+ "--enable-directional-intra=0",
9398+ "--enable-angle-delta=0",
9399+ "--enable-tx-size-search=0",
9400+ "--enable-cdef=1",
9401+ "--enable-restoration=0",
9402+ "--max-partition-size=32",
9403+ "--min-partition-size=32",
9404+ "--enable-palette=0",
9405+ "--enable-intrabc=0",
9406+ "--enable-cfl-intra=0",
9407+ "--enable-ref-frame-mvs=0",
9408+ ];
9409+ args.extend(rate_args.iter().copied());
9410+ args.extend(depth_args.iter().map(String::as_str));
9411+ args.extend(["--obu", "-o", "-", "-"]);
9412+ let mut child = Command::new(aomenc_path())
9413+ .args(&args)
9414+ .stdin(Stdio::piped())
9415+ .stdout(Stdio::piped())
9416+ .stderr(Stdio::piped())
9417+ .spawn()
9418+ .expect("aomenc failed to start");
9419+ child
9420+ .stdin
9421+ .take()
9422+ .expect("aomenc stdin")
9423+ .write_all(&y4m.stdout)
9424+ .expect("writing y4m to aomenc");
9425+ let out = child.wait_with_output().expect("aomenc failed to run");
9426+ assert!(
9427+ out.status.success(),
9428+ "aomenc refused the fixture: {}",
9429+ String::from_utf8_lossy(&out.stderr)
9430+ );
9431+ let stream = out.stdout;
9432+ // The stream must really carry `segmentation_enabled`, or the
9433+ // gate proves nothing about the reader.
9434+ let mut seg_frames = 0u32;
9435+ {
9436+ let mut probe = Av1Parser::new();
9437+ let mut pos = 0usize;
9438+ while pos < stream.len() {
9439+ let obu = probe.parse_obu(&stream[pos..]).expect("parsing the gate stream");
9440+ pos += obu.total_size;
9441+ match &obu.kind {
9442+ ObuKind::Frame(h, _) => {
9443+ if h.segmentation.enabled {
9444+ seg_frames += 1;
9445+ }
9446+ }
9447+ ObuKind::FrameHeader(h) => {
9448+ if h.segmentation.enabled {
9449+ seg_frames += 1;
9450+ }
9451+ }
9452+ _ => {}
9453+ }
9454+ }
9455+ }
9456+ if seg_frames == 0 {
9457+ eprintln!("seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt");
9458+ continue;
9459+ }
9460+ let frames = match decode_stream(&stream) {
9461+ Err(e) => {
9462+ let msg = e.to_string();
9463+ assert!(
9464+ msg.contains("unsupported"),
9465+ "{name} failed outright, not a named refusal (seed {seed}): {msg}"
9466+ );
9467+ assert!(
9468+ !msg.contains("segment_id symbol"),
9469+ "{name} refused on the segmentation reader itself (seed {seed}): {msg}"
9470+ );
9471+ named_refusals += 1;
9472+ eprintln!("seed {seed} refusal: {msg}");
9473+ continue;
9474+ }
9475+ Ok(frames) => frames,
9476+ };
9477+ let ffmpeg_frames = if bit_depth == 10 {
9478+ ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
9479+ } else {
9480+ ffmpeg_decode_sequence(&stream, width, height, frame_count)
9481+ };
9482+ assert_eq!(frames.len(), frame_count);
9483+ let mismatched = frames
9484+ .iter()
9485+ .zip(&ffmpeg_frames)
9486+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
9487+ if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
9488+ std::fs::write(&path, &stream).expect("writing pinned stream");
9489+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
9490+ }
9491+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9492+ assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (seed {seed})");
9493+ assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
9494+ assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
9495+ }
9496+ matched += 1;
9497+ }
9498+ assert!(
9499+ matched > 0,
9500+ "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \
9501+ the gate never exercised segmentation"
9502+ );
9503+ assert!(
9504+ crate::decode::segment_id_hits() > 0,
9505+ "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \
9506+ the reader is unexercised"
9507+ );
9508+ assert!(
9509+ crate::decode::segment_ids_seen() >= 2,
9510+ "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \
9511+ every block landed in one segment, so nothing was actually segmented",
9512+ crate::decode::segment_ids_seen()
9513+ );
9514+ // An inter-frame run must also have exercised the TEMPORAL path
9515+ // (`seg_id_predicted` against the primary reference's saved map);
9516+ // the key-frame-only run has no previous map by construction.
9517+ if frame_count > 1 {
9518+ assert!(
9519+ crate::decode::segment_pred_hits() > 0,
9520+ "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \
9521+ seg_id_predicted symbols -- the temporal_update path is unexercised"
9522+ );
9523+ }
9524+ eprintln!(
9525+ "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
9526+ out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \
9527+ seg_id_predicted symbols={}",
9528+ crate::decode::segment_id_hits(),
9529+ crate::decode::segment_ids_seen(),
9530+ crate::decode::segment_pred_hits()
9531+ );
9532+ }
9533+
9534+ #[test]
9535+ fn a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact() {
9536+ run_segmentation_gate(
9537+ "a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact",
9538+ "1",
9539+ 8,
9540+ 16,
9541+ &["--end-usage=q", "--cq-level=45"],
9542+ );
9543+ }
9544+
9545+ // lane-seg r1 DEFERRED: an `--aq-mode=2` (complexity AQ) twin of the gate
9546+ // above. libaom only switches segmentation on for complexity AQ once the
9547+ // target bits per 64x64 superblock clear `sb64_target_rate >= 256`
9548+ // (`aq_complexity.c:is_sb_aq_enabled`), which needs `--end-usage=vbr`;
9549+ // every VBR recipe tried (cpu-used 0 and 4, 32x32 and 64x64 fixed
9550+ // partitions) makes aomenc pick partition shapes OTHER lanes still refuse
9551+ // (AB below 16x16, SB-level HORZ/VERT, part32 values 4/6), so 10/10
9552+ // attempts refuse before a pixel is compared. The syntax exercised would
9553+ // be identical to variance AQ's (both features only ever set
9554+ // `SEG_LVL_ALT_Q` via `update_map`), so this is coverage, not capability.
9555+ // Unblocked by the sub-16x16 rect/AB partition lanes.
9556+
9557+ /// His two AV1 films are both `yuv420p10le`, so every capability lands
9558+ /// with a 10-bit twin (memory `his-av1-library-is-10-bit`). KEY FRAME
9559+ /// ONLY (`frame_count = 1`): a 10-bit INTER frame does not decode
9560+ /// pixel-exact in this crate yet, segmentation or not -- lane-seg r1 ran
9561+ /// this same recipe with `--aq-mode=0` (segmentation off entirely) and it
9562+ /// still mismatched at frame 2, so the 16-frame 10-bit variant would be
9563+ /// gating an unrelated pre-existing gap. Variance AQ segments the key
9564+ /// frame too (`aq_variance.c`, `is_frame_aq_enabled` includes
9565+ /// `frame_is_intra_only`), so this still proves the 10-bit segment-id
9566+ /// read and the per-segment 10-bit dequant.
9567+ #[test]
9568+ fn a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact() {
9569+ run_segmentation_gate(
9570+ "a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact",
9571+ "1",
9572+ 10,
9573+ 1,
9574+ &["--end-usage=q", "--cq-level=45"],
9575+ );
9576+ }
9577+
9578+ /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without
9579+ /// -- a real >1-tile-column stream with a genuine INTER frame (not just
9580+ /// the key-frame-only two-column gate above), decoded through
9581+ /// `decode_stream` itself. Same recipe as the key-frame gate
9582+ /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the
9583+ /// same feature-disable envelope so the gate isolates the tile loop, not
9584+ /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000`
9585+ /// so frame 1 is a real inter frame, and `gradients_source`'s default
9586+ /// `speed=0.01` rotation (undisturbed -- not overridden by the tail)
9587+ /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_
9588+ /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually
9589+ /// have to walk a live MV stack across the tile-column boundary, not
9590+ /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2
9591+ /// frames at rate=25) per the class in ledger
9592+ /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole-
9593+ /// file` (never leave an ffmpeg/lavfi generate unbounded).
9594+ #[test]
9595+ fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() {
9596+ const NAME: &str =
9597+ "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact";
9598+ if !have_ffmpeg() {
9599+ eprintln!("SKIP {NAME}: no ffmpeg");
9600+ return;
9601+ }
9602+ if !have_aomenc() {
9603+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9604+ return;
9605+ }
9606+ let (width, height) = (128usize, 64usize);
9607+ let frames = 2usize;
9608+ let mut matched = 0u32;
9609+ let mut named_refusals = 0u32;
9610+ for attempt in 0..20u32 {
9611+ let seed = 42 + attempt;
9612+ let source = gradients_source(seed, width, height, "duration=0.08:rate=25");
9613+ let y4m = Command::new("ffmpeg")
9614+ .args([
9615+ "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
9616+ "yuv4mpegpipe", "-",
9617+ ])
9618+ .stdin(Stdio::null())
9619+ .stdout(Stdio::piped())
9620+ .stderr(Stdio::piped())
9621+ .output()
9622+ .expect("ffmpeg failed to run");
9623+ assert!(
9624+ y4m.status.success(),
9625+ "ffmpeg fixture: {}",
9626+ String::from_utf8_lossy(&y4m.stderr)
9627+ );
9628+ let mut child = Command::new(aomenc_path())
9629+ .args([
9630+ "--codec=av1",
9631+ "--passes=1",
9632+ "--end-usage=q",
9633+ "--cq-level=45",
9634+ "--cpu-used=0",
9635+ &format!("--limit={frames}"),
9636+ "--kf-max-dist=1000",
9637+ "--lag-in-frames=0",
9638+ "--auto-alt-ref=0",
9639+ "--threads=1",
9640+ "--row-mt=0",
9641+ "--tile-columns=1",
9642+ "--tile-rows=0",
9643+ "--sb-size=64",
9644+ "--loopfilter-control=0",
9645+ "--max-reference-frames=3",
9646+ "--reduced-reference-set=1",
9647+ "--enable-warped-motion=0",
9648+ "--enable-obmc=0",
9649+ "--enable-masked-comp=0",
9650+ "--enable-interintra-comp=0",
9651+ "--enable-dist-wtd-comp=0",
9652+ "--enable-diff-wtd-comp=0",
9653+ "--enable-onesided-comp=0",
9654+ "--enable-interintra-wedge=0",
9655+ "--enable-smooth-interintra=0",
9656+ "--enable-ref-frame-mvs=0",
9657+ "--enable-rect-partitions=0",
9658+ "--enable-ab-partitions=0",
9659+ "--enable-1to4-partitions=0",
9660+ "--enable-filter-intra=0",
9661+ "--enable-smooth-intra=0",
9662+ "--enable-paeth-intra=0",
9663+ "--enable-directional-intra=0",
9664+ "--enable-angle-delta=0",
90789665 "--enable-tx-size-search=0",
90799666 "--enable-cdef=0",
90809667 "--enable-restoration=0",
@@ -9677,6 +10264,549 @@ mod tests {
967710264 );
967810265 }
967910266
10267+ /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32
10268+ /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the
10269+ /// tx-size search left at aomenc's own default (ON) -- every sibling
10270+ /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly
10271+ /// why the split-transform strip was never exercised. RD is then free to
10272+ /// give a strip a transform smaller than its own size, the case
10273+ /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT
10274+ /// intra strip with a split transform (per-unit rect prediction is not
10275+ /// ported)") until this round ported the per-transform-unit predict-and-
10276+ /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta:
10277+ /// without it a stream that resolved every `tx_depth` to 0 would
10278+ /// pixel-match by construction and prove nothing. A decode error that is
10279+ /// not a named refusal, and any pixel mismatch, FAIL -- only a missing
10280+ /// tool skips.
10281+ #[test]
10282+ fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() {
10283+ const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact";
10284+ let _gate_lock = lock_gate_counters();
10285+ if !have_ffmpeg() {
10286+ eprintln!("SKIP {NAME}: no ffmpeg");
10287+ return;
10288+ }
10289+ if !have_aomenc() {
10290+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10291+ return;
10292+ }
10293+ let (width, height) = (192usize, 128usize);
10294+ let before = crate::decode::rect_split_tx_hits();
10295+ let mut named_refusals = 0u32;
10296+ let mut matched = 0u32;
10297+ let mut split_so_far = 0usize;
10298+ // Bounded sweep: see this gate's own doc for the seed-77 residue and
10299+ // why extending it is a diagnosis knob, not a pass/fail one.
10300+ let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
10301+ .ok()
10302+ .and_then(|s| s.parse().ok())
10303+ .unwrap_or(20);
10304+ for attempt in 0..n_attempts {
10305+ let seed = 42 + attempt;
10306+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10307+ let y4m = Command::new("ffmpeg")
10308+ .args([
10309+ "-v", "error", "-f", "lavfi", "-i", &source,
10310+ // Desaturated (`hue=s=0`, the same guard
10311+ // `a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact`
10312+ // uses): with the tx-size search ON, a real chroma
10313+ // gradient hits a PRE-EXISTING chroma defect on the plain
10314+ // SQUARE path -- measured this round with
10315+ // `--enable-rect-partitions=0` on this very recipe, seed
10316+ // 42, U plane, i.e. with no rect strip in the stream at
10317+ // all. Flat chroma keeps that unrelated defect out of
10318+ // this gate (gate-recipe-confound class); it is open
10319+ // residue in lanes/rectsplit-r1.report.md, not fixed here.
10320+ "-vf", "hue=s=0",
10321+ "-pix_fmt", "yuv420p", "-f",
10322+ "yuv4mpegpipe", "-",
10323+ ])
10324+ .stdin(Stdio::null())
10325+ .stdout(Stdio::piped())
10326+ .stderr(Stdio::piped())
10327+ .output()
10328+ .expect("ffmpeg failed to run");
10329+ assert!(
10330+ y4m.status.success(),
10331+ "ffmpeg fixture: {}",
10332+ String::from_utf8_lossy(&y4m.stderr)
10333+ );
10334+ // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
10335+ // own default (search ON) is the entire point of this gate.
10336+ let args: Vec<&str> = vec![
10337+ "--codec=av1",
10338+ "--passes=1",
10339+ "--end-usage=q",
10340+ "--cq-level=45",
10341+ "--cpu-used=0",
10342+ "--threads=1",
10343+ "--row-mt=0",
10344+ "--sb-size=64",
10345+ "--enable-rect-partitions=1",
10346+ "--enable-ab-partitions=0",
10347+ "--enable-1to4-partitions=0",
10348+ "--min-partition-size=16",
10349+ "--max-partition-size=32",
10350+ "--enable-restoration=0",
10351+ "--enable-palette=0",
10352+ "--deltaq-mode=0",
10353+ "--enable-filter-intra=0",
10354+ "--enable-cfl-intra=0",
10355+ "--enable-intrabc=0",
10356+ "--obu",
10357+ "-o",
10358+ "-",
10359+ "-",
10360+ ];
10361+ let mut child = Command::new(aomenc_path())
10362+ .args(&args)
10363+ .stdin(Stdio::piped())
10364+ .stdout(Stdio::piped())
10365+ .stderr(Stdio::piped())
10366+ .spawn()
10367+ .expect("aomenc failed to start");
10368+ child
10369+ .stdin
10370+ .take()
10371+ .expect("aomenc stdin")
10372+ .write_all(&y4m.stdout)
10373+ .expect("writing y4m to aomenc");
10374+ let out = child.wait_with_output().expect("aomenc failed to run");
10375+ assert!(
10376+ out.status.success(),
10377+ "aomenc refused the fixture: {}",
10378+ String::from_utf8_lossy(&out.stderr)
10379+ );
10380+ let stream = out.stdout;
10381+ assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
10382+ let frames = match decode_stream(&stream) {
10383+ Err(e) => {
10384+ let msg = e.to_string();
10385+ assert!(
10386+ msg.contains("unsupported"),
10387+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10388+ );
10389+ named_refusals += 1;
10390+ continue;
10391+ }
10392+ Ok(frames) => frames,
10393+ };
10394+ let after = crate::decode::rect_split_tx_hits();
10395+ eprintln!(
10396+ "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
10397+ after - before - split_so_far
10398+ );
10399+ split_so_far = after - before;
10400+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10401+ assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
10402+ if let Some(i) = frames[0]
10403+ .y
10404+ .iter()
10405+ .zip(&ffmpeg_frames[0].y)
10406+ .position(|(a, b)| a != b)
10407+ {
10408+ eprintln!(
10409+ "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}",
10410+ i % width,
10411+ i / width,
10412+ frames[0].y[i],
10413+ ffmpeg_frames[0].y[i]
10414+ );
10415+ }
10416+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10417+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10418+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10419+ matched += 1;
10420+ }
10421+ let split_hits = crate::decode::rect_split_tx_hits() - before;
10422+ assert!(
10423+ matched > 0,
10424+ "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
10425+ );
10426+ assert!(
10427+ split_hits > 0,
10428+ "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
10429+ matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
10430+ this run"
10431+ );
10432+ eprintln!(
10433+ "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
10434+ rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts"
10435+ );
10436+ }
10437+
10438+ /// lane-rectsplit r1 gate (c): gate (a)'s recipe with
10439+ /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so
10440+ /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip
10441+ /// -- the case [`crate::decode::decode_block_rect`] refused by name
10442+ /// ("filter intra on a HORZ/VERT strip (this decoder predicts
10443+ /// square-only)") until this round gave `predict_filter_intra` its own
10444+ /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta:
10445+ /// a stream where RD never picked filter intra on a strip would
10446+ /// pixel-match by construction and prove nothing.
10447+ #[test]
10448+ fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() {
10449+ const NAME: &str =
10450+ "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact";
10451+ let _gate_lock = lock_gate_counters();
10452+ if !have_ffmpeg() {
10453+ eprintln!("SKIP {NAME}: no ffmpeg");
10454+ return;
10455+ }
10456+ if !have_aomenc() {
10457+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10458+ return;
10459+ }
10460+ let (width, height) = (192usize, 128usize);
10461+ let before = crate::decode::filter_intra_rect_hits();
10462+ let rect_before = crate::decode::rect_partition_hits();
10463+ let fi_square_before = crate::decode::filter_intra_hits();
10464+ let mut named_refusals = 0u32;
10465+ let mut matched = 0u32;
10466+ let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
10467+ .ok()
10468+ .and_then(|s| s.parse().ok())
10469+ .unwrap_or(40);
10470+ for attempt in 0..n_attempts {
10471+ let seed = 42 + attempt;
10472+ // Diagnosis knob: which content makes RD pick a HORZ/VERT strip
10473+ // AND filter intra on it is a search (see this round's report).
10474+ let source = match std::env::var("EC_RECTSPLIT_SRC").unwrap_or_default().as_str() {
10475+ "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
10476+ "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
10477+ _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
10478+ };
10479+ let y4m = Command::new("ffmpeg")
10480+ .args([
10481+ "-v", "error", "-f", "lavfi", "-i", &source,
10482+ // Same `hue=s=0` guard as gate (a): a real chroma gradient
10483+ // under the tx-size search hits a PRE-EXISTING square-path
10484+ // chroma defect that has nothing to do with this lane.
10485+ "-vf", "hue=s=0",
10486+ "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
10487+ ])
10488+ .stdin(Stdio::null())
10489+ .stdout(Stdio::piped())
10490+ .stderr(Stdio::piped())
10491+ .output()
10492+ .expect("ffmpeg failed to run");
10493+ assert!(
10494+ y4m.status.success(),
10495+ "ffmpeg fixture: {}",
10496+ String::from_utf8_lossy(&y4m.stderr)
10497+ );
10498+ // Diagnosis knob only (default is the gate's pinned recipe):
10499+ // which `--cq-level` makes aomenc's RD reach for filter intra on
10500+ // a strip is a search, and the sweep that found this one is in
10501+ // lanes/rectsplit-r1.report.md.
10502+ let cq = format!(
10503+ "--cq-level={}",
10504+ // Pinned by the sweep in lanes/rectsplit-r1.report.md: at
10505+ // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and
10506+ // filter intra on none of them; at cq 25 strips are common
10507+ // (130/100 seeds) and filter intra lands on one every ~13
10508+ // seeds.
10509+ std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into())
10510+ );
10511+ let args: Vec<&str> = vec![
10512+ "--codec=av1",
10513+ "--passes=1",
10514+ "--end-usage=q",
10515+ &cq,
10516+ "--cpu-used=0",
10517+ "--threads=1",
10518+ "--row-mt=0",
10519+ "--sb-size=64",
10520+ "--enable-rect-partitions=1",
10521+ "--enable-ab-partitions=0",
10522+ "--enable-1to4-partitions=0",
10523+ "--min-partition-size=16",
10524+ "--max-partition-size=32",
10525+ "--enable-restoration=0",
10526+ "--enable-palette=0",
10527+ "--deltaq-mode=0",
10528+ // The point of this gate.
10529+ "--enable-filter-intra=1",
10530+ // The square filter-intra gate's own way of making RD reach
10531+ // for filter intra at all: with the directional/smooth/paeth
10532+ // competitors off, DC_PRED + filter intra is what is left
10533+ // (recipe borrowed from
10534+ // `a_real_aomenc_filter_intra_stream_decodes_pixel_exact`;
10535+ // without them 20/20 streams picked filter intra zero times
10536+ // on a strip -- measured this round).
10537+ "--enable-cfl-intra=0",
10538+ "--enable-intrabc=0",
10539+ "--obu",
10540+ "-o",
10541+ "-",
10542+ "-",
10543+ ];
10544+ // Diagnosis knob (default: every intra mode on): turning the
10545+ // directional/smooth/paeth competitors off is how the square
10546+ // filter-intra gate makes RD reach for filter intra, but with all
10547+ // four off aomenc stops picking rect partitions here entirely
10548+ // (rect strips=0, filter-intra blocks=28, measured this round),
10549+ // so the firing recipe is a search over subsets.
10550+ let mut args = args;
10551+ let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default();
10552+ for tool in off.split(',').filter(|t| !t.is_empty()) {
10553+ args.push(match tool {
10554+ "smooth" => "--enable-smooth-intra=0",
10555+ "paeth" => "--enable-paeth-intra=0",
10556+ "dir" => "--enable-directional-intra=0",
10557+ "angle" => "--enable-angle-delta=0",
10558+ other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"),
10559+ });
10560+ }
10561+ let mut child = Command::new(aomenc_path())
10562+ .args(&args)
10563+ .stdin(Stdio::piped())
10564+ .stdout(Stdio::piped())
10565+ .stderr(Stdio::piped())
10566+ .spawn()
10567+ .expect("aomenc failed to start");
10568+ child
10569+ .stdin
10570+ .take()
10571+ .expect("aomenc stdin")
10572+ .write_all(&y4m.stdout)
10573+ .expect("writing y4m to aomenc");
10574+ let out = child.wait_with_output().expect("aomenc failed to run");
10575+ assert!(
10576+ out.status.success(),
10577+ "aomenc refused the fixture: {}",
10578+ String::from_utf8_lossy(&out.stderr)
10579+ );
10580+ let stream = out.stdout;
10581+ assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
10582+ let frames = match decode_stream(&stream) {
10583+ Err(e) => {
10584+ let msg = e.to_string();
10585+ assert!(
10586+ msg.contains("unsupported"),
10587+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10588+ );
10589+ named_refusals += 1;
10590+ continue;
10591+ }
10592+ Ok(frames) => frames,
10593+ };
10594+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10595+ assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
10596+ if let Some(i) = frames[0]
10597+ .y
10598+ .iter()
10599+ .zip(&ffmpeg_frames[0].y)
10600+ .position(|(a, b)| a != b)
10601+ {
10602+ eprintln!(
10603+ "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}",
10604+ i % width,
10605+ i / width,
10606+ frames[0].y[i],
10607+ ffmpeg_frames[0].y[i]
10608+ );
10609+ }
10610+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10611+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10612+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10613+ matched += 1;
10614+ }
10615+ let fi_hits = crate::decode::filter_intra_rect_hits() - before;
10616+ eprintln!(
10617+ "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}",
10618+ crate::decode::rect_partition_hits() - rect_before,
10619+ crate::decode::filter_intra_hits() - fi_square_before
10620+ );
10621+ assert!(
10622+ matched > 0,
10623+ "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
10624+ );
10625+ assert!(
10626+ fi_hits > 0,
10627+ "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \
10628+ {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
10629+ );
10630+ eprintln!(
10631+ "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
10632+ filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts"
10633+ );
10634+ }
10635+
10636+ /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s
10637+ /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every
10638+ /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its
10639+ /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then
10640+ /// carry a split transform, which [`crate::decode::decode_block_rect64`]
10641+ /// refused by name ("a superblock-level HORZ/VERT strip with a split
10642+ /// transform") until this round. Same hard `rect_split_tx_hits()` delta
10643+ /// assert as gate (a).
10644+ /// lane-rectsplit r1 MEASURED RED, `#[ignore]`d with its number (the
10645+ /// `rect64q` gate's own precedent): with the per-transform-unit port
10646+ /// wired at the superblock level, seed 50 decodes one sample off --
10647+ /// luma (171, 56), ours 147 vs ffmpeg 148, inside the 64x32 strip at
10648+ /// mi=(8,32) whose transform resolved to depth 2 (TX_16X16). Seeds 42-49
10649+ /// with depth-1 (TX_32X32) units were pixel-exact. The refusal in
10650+ /// `decode_block_rect64` was therefore RESTORED rather than lifted; run
10651+ /// this gate (`--ignored`) after any fix to that arm.
10652+ #[ignore = "lane-rectsplit r1: measured RED, seed 50 luma (171,56) off by one; refusal kept"]
10653+ #[test]
10654+ fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() {
10655+ const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact";
10656+ let _gate_lock = lock_gate_counters();
10657+ if !have_ffmpeg() {
10658+ eprintln!("SKIP {NAME}: no ffmpeg");
10659+ return;
10660+ }
10661+ if !have_aomenc() {
10662+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10663+ return;
10664+ }
10665+ let (width, height) = (192usize, 128usize);
10666+ let before = crate::decode::rect_split_tx_hits();
10667+ let mut named_refusals = 0u32;
10668+ let mut matched = 0u32;
10669+ let mut split_so_far = 0usize;
10670+ // Bounded sweep: see this gate's own doc for the seed-77 residue and
10671+ // why extending it is a diagnosis knob, not a pass/fail one.
10672+ let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
10673+ .ok()
10674+ .and_then(|s| s.parse().ok())
10675+ .unwrap_or(20);
10676+ for attempt in 0..n_attempts {
10677+ let seed = 42 + attempt;
10678+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10679+ let y4m = Command::new("ffmpeg")
10680+ .args([
10681+ "-v", "error", "-f", "lavfi", "-i", &source,
10682+ // Desaturated (`hue=s=0`, the same guard
10683+ // `a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact`
10684+ // uses): with the tx-size search ON, a real chroma
10685+ // gradient hits a PRE-EXISTING chroma defect on the plain
10686+ // SQUARE path -- measured this round with
10687+ // `--enable-rect-partitions=0` on this very recipe, seed
10688+ // 42, U plane, i.e. with no rect strip in the stream at
10689+ // all. Flat chroma keeps that unrelated defect out of
10690+ // this gate (gate-recipe-confound class); it is open
10691+ // residue in lanes/rectsplit-r1.report.md, not fixed here.
10692+ "-vf", "hue=s=0",
10693+ "-pix_fmt", "yuv420p", "-f",
10694+ "yuv4mpegpipe", "-",
10695+ ])
10696+ .stdin(Stdio::null())
10697+ .stdout(Stdio::piped())
10698+ .stderr(Stdio::piped())
10699+ .output()
10700+ .expect("ffmpeg failed to run");
10701+ assert!(
10702+ y4m.status.success(),
10703+ "ffmpeg fixture: {}",
10704+ String::from_utf8_lossy(&y4m.stderr)
10705+ );
10706+ // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
10707+ // own default (search ON) is the entire point of this gate.
10708+ let args: Vec<&str> = vec![
10709+ "--codec=av1",
10710+ "--passes=1",
10711+ "--end-usage=q",
10712+ "--cq-level=45",
10713+ "--cpu-used=0",
10714+ "--threads=1",
10715+ "--row-mt=0",
10716+ "--sb-size=64",
10717+ "--enable-rect-partitions=1",
10718+ "--enable-ab-partitions=0",
10719+ "--enable-1to4-partitions=0",
10720+ "--min-partition-size=32",
10721+ "--max-partition-size=64",
10722+ "--enable-restoration=0",
10723+ "--enable-palette=0",
10724+ "--deltaq-mode=0",
10725+ "--enable-filter-intra=0",
10726+ "--enable-cfl-intra=0",
10727+ "--enable-intrabc=0",
10728+ "--obu",
10729+ "-o",
10730+ "-",
10731+ "-",
10732+ ];
10733+ let mut child = Command::new(aomenc_path())
10734+ .args(&args)
10735+ .stdin(Stdio::piped())
10736+ .stdout(Stdio::piped())
10737+ .stderr(Stdio::piped())
10738+ .spawn()
10739+ .expect("aomenc failed to start");
10740+ child
10741+ .stdin
10742+ .take()
10743+ .expect("aomenc stdin")
10744+ .write_all(&y4m.stdout)
10745+ .expect("writing y4m to aomenc");
10746+ let out = child.wait_with_output().expect("aomenc failed to run");
10747+ assert!(
10748+ out.status.success(),
10749+ "aomenc refused the fixture: {}",
10750+ String::from_utf8_lossy(&out.stderr)
10751+ );
10752+ let stream = out.stdout;
10753+ assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
10754+ let frames = match decode_stream(&stream) {
10755+ Err(e) => {
10756+ let msg = e.to_string();
10757+ assert!(
10758+ msg.contains("unsupported"),
10759+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10760+ );
10761+ named_refusals += 1;
10762+ continue;
10763+ }
10764+ Ok(frames) => frames,
10765+ };
10766+ let after = crate::decode::rect_split_tx_hits();
10767+ eprintln!(
10768+ "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
10769+ after - before - split_so_far
10770+ );
10771+ split_so_far = after - before;
10772+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10773+ assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
10774+ if let Some(i) = frames[0]
10775+ .y
10776+ .iter()
10777+ .zip(&ffmpeg_frames[0].y)
10778+ .position(|(a, b)| a != b)
10779+ {
10780+ eprintln!(
10781+ "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}",
10782+ i % width,
10783+ i / width,
10784+ frames[0].y[i],
10785+ ffmpeg_frames[0].y[i]
10786+ );
10787+ }
10788+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10789+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10790+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10791+ matched += 1;
10792+ }
10793+ let split_hits = crate::decode::rect_split_tx_hits() - before;
10794+ assert!(
10795+ matched > 0,
10796+ "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
10797+ );
10798+ assert!(
10799+ split_hits > 0,
10800+ "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
10801+ matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
10802+ this run"
10803+ );
10804+ eprintln!(
10805+ "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
10806+ rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts"
10807+ );
10808+ }
10809+
968010810 /// lane-rect64q r1: same recipe as
968110811 /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
968210812 /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is
crates/ec-av1/src/superres.rsmodified+48 -49
@@ -89,7 +89,16 @@ fn round_power_of_two(sum: i32, bits: u32) -> i32 {
8989 /// true, replicating the row's own edge pixels rather than sampling a
9090 /// neighbour tile). `in_width` and `out_width` must both be positive;
9191 /// `row.len() == in_width` and `out.len() == out_width`.
92-pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize, out: &mut [u8]) {
92+/// `bit_depth` only picks the output clamp (`clip_pixel`/`clip_pixel_highbd`
93+/// in libaom's `av1_convolve_horiz_rs_c`); the filter, its `Round2` and the
94+/// edge padding are bit-depth independent (spec 7.16).
95+pub(crate) fn upscale_row(
96+ row: &[u16],
97+ real_right_margin: &[u16],
98+ out_width: usize,
99+ out: &mut [u16],
100+ bit_depth: u32,
101+) {
93102 let in_width = row.len();
94103 debug_assert!(in_width > 0 && out_width > 0);
95104 debug_assert_eq!(out.len(), out_width);
@@ -109,7 +118,7 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
109118 // column-by-column against real libaom via `scripts/superres-pin-
110119 // harness.c`'s `row6-realedgeval` case (r3).
111120 let pad = UPSCALE_NORMATIVE_TAPS + 2;
112- let mut padded = vec![0u8; in_width + 2 * pad];
121+ let mut padded = vec![0u16; in_width + 2 * pad];
113122 padded[..pad].fill(row[0]);
114123 padded[pad..pad + in_width].copy_from_slice(row);
115124 let real_n = real_right_margin.len().min(pad);
@@ -131,7 +140,7 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
131140 let idx = base + int_pel + k as i64;
132141 sum += padded[idx as usize] as i32 * c as i32;
133142 }
134- *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, 255) as u8;
143+ *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, (1 << bit_depth) - 1) as u16;
135144 x_qn += x_step_qn;
136145 }
137146 }
@@ -141,14 +150,15 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
141150 /// spec only widens columns). `rows` is the plane's row-major byte buffer
142151 /// at `in_width`; returns a new buffer at `out_width`.
143152 pub(crate) fn upscale_plane(
144- rows: &[u8],
153+ rows: &[u16],
145154 height: usize,
146155 in_width: usize,
147156 out_width: usize,
148- margin: Option<(&[u8], usize)>,
149-) -> Vec<u8> {
157+ margin: Option<(&[u16], usize)>,
158+ bit_depth: u32,
159+) -> Vec<u16> {
150160 debug_assert_eq!(rows.len(), height * in_width);
151- let mut out = vec![0u8; height * out_width];
161+ let mut out = vec![0u16; height * out_width];
152162 for r in 0..height {
153163 let src = &rows[r * in_width..(r + 1) * in_width];
154164 let dst = &mut out[r * out_width..(r + 1) * out_width];
@@ -158,7 +168,7 @@ pub(crate) fn upscale_plane(
158168 }
159169 _ => &[],
160170 };
161- upscale_row(src, real_right, out_width, dst);
171+ upscale_row(src, real_right, out_width, dst, bit_depth);
162172 }
163173 out
164174 }
@@ -185,51 +195,40 @@ pub(crate) fn upscale_picture(
185195 picture: &crate::encode::Picture,
186196 upscaled_width: usize,
187197 margin: Option<&crate::encode::Picture>,
198+ bit_depth: u32,
188199 ) -> crate::encode::Picture {
189200 SUPERRES_HITS.with(|c| c.set(c.get() + 1));
190201 let height = picture.height;
191202 let chroma_in_w = picture.width.div_ceil(2);
192203 let chroma_out_w = upscaled_width.div_ceil(2);
193204 let chroma_h = height.div_ceil(2);
194- // lane-hbd r4: superres is 8-bit by construction (`upscale_row` clamps
195- // to 255) -- narrow at this boundary; callers refuse `bit_depth != 8`
196- // before ever reaching here (see `stream.rs`).
197- let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
198- let picture_y8 = narrow(&picture.y);
199- let picture_u8 = narrow(&picture.u);
200- let picture_v8 = narrow(&picture.v);
201- let margin_y8 = margin.map(|m| narrow(&m.y));
202- let margin_u8 = margin.map(|m| narrow(&m.u));
203- let margin_v8 = margin.map(|m| narrow(&m.v));
204- let widen = |v: Vec<u8>| -> Vec<u16> { v.into_iter().map(u16::from).collect() };
205205 crate::encode::Picture {
206206 width: upscaled_width,
207207 height,
208- y: widen(upscale_plane(
209- &picture_y8,
208+ y: upscale_plane(
209+ &picture.y,
210210 height,
211211 picture.width,
212212 upscaled_width,
213- margin_y8.as_deref().map(|m| (m, margin.unwrap().width)),
214- )),
215- u: widen(upscale_plane(
216- &picture_u8,
213+ margin.map(|m| (m.y.as_slice(), m.width)),
214+ bit_depth,
215+ ),
216+ u: upscale_plane(
217+ &picture.u,
217218 chroma_h,
218219 chroma_in_w,
219220 chroma_out_w,
220- margin_u8
221- .as_deref()
222- .map(|m| (m, margin.unwrap().width.div_ceil(2))),
223- )),
224- v: widen(upscale_plane(
225- &picture_v8,
221+ margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))),
222+ bit_depth,
223+ ),
224+ v: upscale_plane(
225+ &picture.v,
226226 chroma_h,
227227 chroma_in_w,
228228 chroma_out_w,
229- margin_v8
230- .as_deref()
231- .map(|m| (m, margin.unwrap().width.div_ceil(2))),
232- )),
229+ margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))),
230+ bit_depth,
231+ ),
233232 }
234233 }
235234
@@ -249,17 +248,17 @@ mod tests {
249248 /// here independently of this module's own logic.
250249 #[test]
251250 fn upscale_row_matches_libaom_in8_out12() {
252- let row = [10u8, 20, 30, 40, 50, 60, 70, 80];
253- let mut out = [0u8; 12];
254- upscale_row(&row, &[], 12, &mut out);
251+ let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
252+ let mut out = [0u16; 12];
253+ upscale_row(&row, &[], 12, &mut out, 8);
255254 assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]);
256255 }
257256
258257 #[test]
259258 fn upscale_row_matches_libaom_in8_out16() {
260- let row = [10u8, 20, 30, 40, 50, 60, 70, 80];
261- let mut out = [0u8; 16];
262- upscale_row(&row, &[], 16, &mut out);
259+ let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
260+ let mut out = [0u16; 16];
261+ upscale_row(&row, &[], 16, &mut out, 8);
263262 assert_eq!(
264263 out,
265264 [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81]
@@ -273,10 +272,10 @@ mod tests {
273272 /// captured-row pins above.
274273 #[test]
275274 fn upscale_row_of_a_flat_input_is_flat() {
276- let row = [200u8; 8];
277- let mut out = [0u8; 12];
278- upscale_row(&row, &[], 12, &mut out);
279- assert_eq!(out, [200u8; 12]);
275+ let row = [200u16; 8];
276+ let mut out = [0u16; 12];
277+ upscale_row(&row, &[], 12, &mut out, 8);
278+ assert_eq!(out, [200u16; 12]);
280279 }
281280
282281 /// r3: the real 43->64 failing case, pinned against real libaom
@@ -287,14 +286,14 @@ mod tests {
287286 /// margin fix.
288287 #[test]
289288 fn upscale_row_with_real_margin_matches_libaom_in43_out64() {
290- let row: [u8; 43] = [
289+ let row: [u16; 43] = [
291290 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
292291 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131,
293292 133, 134, 136, 137, 138, 139, 140, 140, 141,
294293 ];
295- let real_margin = [140u8];
296- let mut out = [0u8; 64];
297- upscale_row(&row, &real_margin, 64, &mut out);
294+ let real_margin = [140u16];
295+ let mut out = [0u16; 64];
296+ upscale_row(&row, &real_margin, 64, &mut out, 8);
298297 assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140");
299298 }
300299 }
crates/ec-av1/src/tile.rsmodified+16 -2
@@ -2983,13 +2983,27 @@ mod tests {
29832983 }
29842984 }
29852985
2986+ /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
2987+ /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
2988+ /// aomenc gate decodes its stream through ffmpeg and is meaningless
2989+ /// without it -- turns it into a hard failure. Without this the require
2990+ /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
2991+ /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
2992+ /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
29862993 fn have_ffmpeg() -> bool {
2987- Command::new("ffmpeg")
2994+ let present = Command::new("ffmpeg")
29882995 .arg("-version")
29892996 .stdout(Stdio::null())
29902997 .stderr(Stdio::null())
29912998 .status()
2992- .is_ok_and(|s| s.success())
2999+ .is_ok_and(|s| s.success());
3000+ assert!(
3001+ present
3002+ || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
3003+ && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
3004+ "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3005+ );
3006+ present
29933007 }
29943008
29953009 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
lanes/hbd10-r1.report.mdadded+123 -0
@@ -0,0 +1,123 @@
1+# lane-hbd10 round 1 report
2+
3+Branch `lane-hbd10`, worktree `edith_codecs-hbd10`, off main `3808cf8` (no rebase
4+needed -- branch was already at main's HEAD, `git log --oneline -1 main` = 3808cf8).
5+
6+## Refusals lifted (2)
7+
8+Both removed from `crates/ec-av1/src/refusal_inventory.rs` and from their
9+`stream.rs` guard sites, each with a real-aomenc 10-bit gate in the same commit:
10+
11+- `"a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)"`
12+- `"a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)"`
13+
14+## What changed
15+
16+- `crates/ec-av1/src/film_grain.rs:180` -- `GRAIN_MIN`/`GRAIN_MAX` consts replaced by
17+ `GRAIN_BIT_DEPTH` (thread-local, set once per `apply_grain`) + `grain_range()`:
18+ `grain_center = 128 << (bit_depth - 8)`, mirroring libaom's file statics
19+ (`grain_synthesis.c:1043-1045`). All 10 clamp sites (luma/chroma AR filter,
20+ ver/hor overlap blending) now read the runtime range.
21+- `crates/ec-av1/src/film_grain.rs:230,265` -- `gauss_sec_shift` was hardcoded
22+ `4 + grain_scale_shift` (i.e. `12 - 8 + ...`); now `12 - bit_depth + grain_scale_shift`
23+ (`grain_synthesis.c:468,503`).
24+- `crates/ec-av1/src/film_grain.rs:~296` -- new `scale_lut()`, a verbatim port of
25+ `scale_LUT` (`grain_synthesis.c:616-626`): the scaling LUT stays 256 entries at
26+ every bit depth, so the index is `>> (bit_depth-8)` and the two neighbouring
27+ entries are interpolated with the dropped low bits (`x == 255` short-circuits).
28+ Used at all three blend sites (Y, Cb, Cr) in `add_noise_to_block`.
29+- `crates/ec-av1/src/film_grain.rs` `add_noise_to_block` -- `cb_offset`/`cr_offset`
30+ now `(offset << (bd-8)) - (1 << bit_depth)` (was `- 256`); the scaling-index clamp
31+ is `(256 << (bd-8)) - 1` (was `255`); `clip_to_restricted_range` legal ranges and
32+ the unrestricted max are `<< (bd-8)` (`grain_synthesis.c:752-795`).
33+- `crates/ec-av1/src/film_grain.rs:551` -- new `GRAIN_HITS` counter + `grain_hits()`
34+ (class `gate-blind-to-feature`), incremented once per grained picture.
35+- `crates/ec-av1/src/superres.rs` -- `upscale_row`/`upscale_plane`/`upscale_picture`
36+ take `&[u16]`/`bit_depth` instead of narrowing the (already `u16`) `Picture` planes
37+ to `u8` and back; the only bit-depth-dependent step in spec 7.16 is the output
38+ clamp, now `clamp(0, (1 << bit_depth) - 1)` (`clip_pixel_highbd`). Filter table,
39+ `Round2`, step/x0 and the real-margin edge padding are unchanged. The three
40+ libaom-pinned unit tests were retyped to `u16` and pass `bit_depth = 8`, so the
41+ 8-bit pins still hold byte-for-byte.
42+- `crates/ec-av1/src/stream.rs` -- both `bit_depth != 8` refusal blocks deleted;
43+ `apply_grain` (2 call sites) and `upscale_picture` (2 call sites) now receive the
44+ sequence header's real `bit_depth`.
45+- `crates/ec-av1/src/gate_coverage.rs` -- unchanged, deliberately: it derives its set
46+ from `--enable-*` flags only, and neither new gate enables or disables a tool that
47+ was not already covered. `every_gate_disabling_a_tool_is_a_listed_coverage_hole`
48+ stays green with the two new gates in the derived gate set.
49+
50+## Gates added (both hard-asserting, neither can SKIP on a mismatch)
51+
52+`crates/ec-av1/src/stream.rs`:
53+
54+1. `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact` --
55+ `aomenc --bit-depth=10 --input-bit-depth=10 --film-grain-test=1` over a
56+ `yuv420p10le` lavfi gradients source, pixel-exact vs `ffmpeg_decode_sequence_10bit`
57+ (ffmpeg synthesizes grain by default; no grain-disable flag exists anywhere in
58+ this file). Hard-asserts the parsed `bit_depth == 10`, `apply_grain == true`,
59+ `num_y_points > 0` (an empty scaling LUT would blend a zero delta and make the
60+ gate vacuous), and `grain_hits()` moved.
61+2. `a_real_aomenc_10bit_superres_stream_decodes_pixel_exact` --
62+ `aomenc --bit-depth=10 --superres-mode=1 --superres-denominator=12
63+ --superres-kf-denominator=12`, same tool-disable envelope as the existing 8-bit
64+ superres gate. Hard-asserts `bit_depth == 10` and `superres_hits()` moved.
65+
66+Shared helpers `encode_10bit_gradients` / `parsed_bit_depth` factored out next to them.
67+
68+EVIDENCE: /tmp/claude-1000/.../tasks (test stdout) | `EC_AV1_REQUIRE_AOMENC=1 cargo test -j3 -p ec-av1 --lib 10bit_ -- --nocapture` | `test result: ok. 3 passed; 0 failed` -- `grain_hits=1`, `superres_hits=1`, all three planes exact
69+
70+### Sensitivity check (the gates are not vacuous)
71+
72+Temporarily passed a literal `8u32` instead of the real `bit_depth` at both call
73+sites (mutation reverted before commit):
74+- film-grain gate: panics in `film_grain.rs` `scale_lut` (a 10-bit sample indexes
75+ past the 256-entry LUT) -- proves the grain path really runs over 10-bit samples.
76+- superres gate: `assertion left == right failed: luma vs ffmpeg`, ours saturated at
77+ `255` where ffmpeg has 10-bit values -- proves the clamp is the thing under test.
78+
79+EVIDENCE: /home/user/.claude/projects/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/tool-results/b1odbi79e.txt | forced `bit_depth = 8` at both call sites, ran the two gates | both FAILED (LUT overrun / luma saturated at 255), both pass again with the mutation reverted
80+
81+## His films: does either actually use grain or superres?
82+
83+Extracted 2s (`-t 2 -c:v copy -an -f obu`, bounded) of each and counted header
84+flags with a throwaway `examples/hbd10_headers.rs` (deleted after the run; the
85+0.4s extract the charter names is only 1.8 KB / a handful of OBUs at 2160p, too
86+short to be representative, so the window was widened to 2s).
87+
88+| film | seq bit_depth | film_grain_params_present | enable_superres | frames | apply_grain | num_y_points>0 | use_superres |
89+|---|---|---|---|---|---|---|---|
90+| ReelB (Ballad, 2160p HDR10) | 10 | true | **false** | 50 | **25** | 25 | 0 |
91+| ReelC (Director's Cut, 1080p) | 10 | true | false | 49 | 0 | 0 | 0 |
92+
93+**ReelB really does carry film grain**: half its frames in the first 2s set
94+`apply_grain` with a non-empty luma scaling LUT, at 10 bit. That refusal was a real
95+blocker-in-waiting for his library, and it is gone. **Neither film uses superres**
96+(`enable_superres = false` in both sequence headers, `use_superres = 0` on every
97+frame) -- the superres refusal is lifted and gated, but it is not on his films' path.
98+
99+`decode_probe` on those extracts (this branch): both films still stop earlier than
100+grain/superres, at partition coverage -- unchanged by this lane, as expected:
101+- ReelB: `REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes no leaf smaller than 8x8))`
102+- ReelC: `REFUSED: unsupported: AV1 tile (a 32x32 partition type this decoder does not code (value=4))`
103+
104+EVIDENCE: scratchpad reelb2.obu / reelc2.obu | `ffmpeg -t 2 -c:v copy -f obu` then `cargo run -p ec-av1 --example decode_probe` | ReelB apply_grain 25/50 frames, use_superres 0/50; both films' first refusal is the pre-existing partition gap
105+
106+## Test totals
107+
108+`EC_AV1_REQUIRE_AOMENC=1 nice -n 10 cargo test -j3 -p ec-av1 --lib`
109+-> **269 passed, 0 failed, 23 ignored, 0 filtered out, 334.60s.**
110+
111+EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/tasks/bsumuvd86.output | `EC_AV1_REQUIRE_AOMENC=1 cargo test -j3 -p ec-av1 --lib` | test result: ok. 269 passed; 0 failed; 23 ignored; 334.60s
112+
113+## Residue
114+
115+- accepted: 12-bit is code-generic (every formula is `bit_depth`-parameterised, not
116+ `10`-specialised) but ungated -- no 12-bit gate was written and none of his files
117+ is 12-bit. A 12-bit stream would decode, not refuse; that is a claim no test backs.
118+- accepted: grain at 4:2:2/4:4:4 stays out of scope -- `film_grain.rs` is 4:2:0 by
119+ construction (documented at the top of the module), unchanged by this lane.
120+- deferred: chroma-only grain params (`num_y_points == 0`, `chroma_scaling_from_luma`)
121+ at 10 bit are exercised by neither gate -- `--film-grain-test=1` sets luma points --
122+ what unblocks it: a `--film-grain-table` fixture that pins a chroma-only parameter
123+ set.
lanes/intrabc-r1.report.mdadded+114 -0
@@ -0,0 +1,114 @@
1+# lane-intrabc r1 — the block vector decodes; the transform tree does not
2+
3+## Verdict
4+
5+The headline refusal `a block that actually uses intrabc (this decoder never
6+reconstructs one)` is **replaced, not lifted**. Its successor names the real
7+remaining wall:
8+
9+```
10+an intrabc block under TxMode::Select (its transform size is coded by the
11+inter var-tx partition tree, which this decoder never reads)
12+```
13+
14+Everything the charter listed *before* the residual is implemented and runs on
15+real aomenc streams: `use_intrabc`, the DV's own mv stack, the `ndvc` full-pel
16+`read_mv`, `av1_find_ref_dv`'s fallback, and the block-copy prediction. No
17+pixel-exact gate exists yet, because no aomenc recipe found this round produces
18+an intrabc block that does *not* also need `read_var_tx_size`.
19+
20+## What changed (worktree `edith_codecs-intrabc`, branch `lane-intrabc`)
21+
22+- `crates/ec-av1/src/cdf_state.rs:422` — `dv_joint`/`dv_comp`: libaom's `ndvc`
23+ (`av1_init_mv_probs` gives it the same spec-8.4 defaults as `nmvc`, separate
24+ adaptation), added to the per-frame counter-reset list at `:684`.
25+- `crates/ec-av1/src/decode.rs:590` — `INTRABC_MI_GRID` / `INTRABC_DV` /
26+ `INTRABC_HITS` thread-locals + `intrabc_hits()`, `reset_intrabc_hits()`,
27+ `record_intrabc_mi()`. The mi grid exists only while a frame header set
28+ `allow_intrabc`.
29+- `crates/ec-av1/src/decode.rs:4046` (`read_intra_mode`) — `use_intrabc == 1`
30+ now reads the DV instead of refusing, and returns immediately with
31+ `YMode`/`UVMode` forced `DC_PRED` (libaom `read_intra_frame_mode_info`
32+ returns at `decodemv.c:895`, so no mode/angle/palette/CFL/filter-intra
33+ syntax follows).
34+- `crates/ec-av1/src/decode.rs:7681` — `read_intrabc_dv`: MV stack against
35+ `INTRA_FRAME`, `nearest` else `near`, else `av1_find_ref_dv`
36+ (`(0, -(64+256)*8)` in the first SB row, else `(-64*8, 0)`), predictor
37+ floored to full pel, then `read_mv` on `dv_comp`/`dv_joint` with
38+ `MV_SUBPEL_NONE` semantics (`force_integer_mv=true`,
39+ `allow_high_precision_mv=false`). No DRL symbol is coded for a DV, so a
40+ wrong predictor can only move pixels, never the bitstream position.
41+- `crates/ec-av1/src/decode.rs` (`decode_block`) — takes the DV, refuses
42+ var-tx by name, switches the luma `TxbSet` to the **inter** ext-tx sets
43+ (`txbset_for_inter`, since libaom's `is_inter_block` is true for intrabc,
44+ `blockd.h:373`), builds the Y/U/V block-copy prediction with
45+ `mc::predict_with_filter(.., Bilinear, ..)` off the *current* planes and
46+ ships it through the existing `PALETTE_PRED` per-block prediction override,
47+ and records the block into the mi grid.
48+- `crates/ec-av1/src/mvstack.rs:330,368` — **two real index bugs**:
49+ `sign_bias()` and `gm_mv()` both indexed `table[ref_frame - LAST_FRAME]`
50+ with no lower guard, so any query with `ref_frame == INTRA_FRAME` (0), which
51+ is exactly what an intrabc block does, panicked with
52+ `index out of bounds: the len is 7 but the index is 18446744073709551615`.
53+ Both now return the neutral value below `LAST_FRAME`. Same-shape sweep: those
54+ are the only two `- LAST_FRAME` table indexes in the crate.
55+- `crates/ec-av1/src/refusal_inventory.rs:55`, `gate_coverage.rs:36` — refusal
56+ string replaced; `enable-intrabc` stays in `NEVER_EXERCISED` with its reason
57+ rewritten to the true state.
58+
59+## Fixture recipe (the round's most reusable finding)
60+
61+Intra block copy is **impossible in a 64x64 frame**: a valid DV must clear
62+`INTRABC_DELAY_PIXELS` (256) plus one superblock, so a single-SB frame can
63+never contain one. Every 64x64 sweep this lane ran (3 sources x 6 cq) produced
64+zero intrabc blocks. A 512-wide frame with horizontally repeated content does:
65+
66+```
67+ffmpeg -f lavfi -i "testsrc2=size=64x64:rate=1" -t 0.04 \
68+ -vf "tile=8x1,scale=512:64" -pix_fmt yuv420p -f rawvideo wide512.yuv
69+~/.cache/aom-oracle/build/aomenc --codec=av1 -w 512 -h 64 --i420 --limit=1 \
70+ --kf-max-dist=1 --cpu-used=1 --passes=1 --end-usage=q --cq-level=20 \
71+ --enable-intrabc=1 --tune-content=screen --enable-palette=0 \
72+ --enable-rect-partitions=0 --enable-ab-partitions=0 \
73+ --enable-1to4-partitions=0 --min-partition-size=16 --max-partition-size=32 \
74+ --obu -o w.obu wide512.yuv
75+cargo run -p ec-av1 --release --example decode_probe -- w.obu
76+```
77+
78+`--enable-palette=0` and the partition switches are a **deviation from the
79+charter's gate recipe** (`--enable-palette=1`): with palette on, or with rect/AB
80+partitions available, the stream refuses on palette or on a sub-16x16 AB
81+partition *before* the first intrabc block, so it cannot isolate this lane's
82+capability at all. `cpu-used` must be <= 2 — at 3 and above aomenc's speed
83+features stop searching intrabc entirely (sweep: cpu 3/5/6/8 x cq 20/40, all 8
84+decode clean, i.e. no intrabc block at all).
85+
86+## EVIDENCE
87+
88+EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/w.obu | recipe above, cpu-used 1 and 2 x cq 20/40, decode_probe before vs after | before: `REFUSED: ... a block that actually uses intrabc`; after: `REFUSED: ... an intrabc block under TxMode::Select` — the `use_intrabc` symbol, the DV read and the prediction all ran, 4/4 streams
89+EVIDENCE: same streams | sweep cpu-used 0,1,2,3,5,6,8 x cq 20,40,55 | intrabc only appears at cpu-used <= 2; cpu 0 stops earlier on an SB-level partition type
90+
91+## Residue
92+
93+- fix-now (next round, needs its own charter): `read_var_tx_size` — the
94+ `txfm_partition` CDF (21 contexts) does not exist anywhere in the crate, nor
95+ do the above/left txfm-context arrays it needs, nor does the residual loop
96+ handle a non-uniform TU tree. This is the single blocker between here and a
97+ pixel-exact intrabc gate.
98+- deferred(var-tx): the pixel-exact 8-bit/10-bit gate the charter asks for, and
99+ the `gate_coverage.rs` entry retirement — no stream can reach reconstruction
100+ until var-tx reads.
101+- accepted, documented as corner-cuts in source: only `decode_block` (square
102+ path) records into the intrabc mi grid; a frame mixing intrabc with rect or
103+ sub-8x8 leaves would predict off an incomplete grid (DV value only, never the
104+ parse). Chroma of an inter/intrabc block should inherit the co-located luma
105+ `tx_type` (libaom `av1_get_tx_type`), while `read_plane` still derives
106+ `DCT_DCT` for chroma — no symbol difference, but a suspected pixel difference
107+ the moment luma picks a non-DCT type. Both are prime suspects for the first
108+ pixel mismatch once var-tx lands.
109+
110+## Test totals
111+
112+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (worktree, commit 09d6ff9):
113+**267 passed, 0 failed, 23 ignored**, 1125 s. `refusal_inventory` and
114+`gate_coverage` are green with the rewritten entries.
lanes/rectsplit-r1.report.mdadded+93 -0
@@ -0,0 +1,93 @@
1+# lane-rectsplit r1 — HORZ/VERT strips with a split transform, and filter intra on a strip
2+
3+Branch `lane-rectsplit` off main `3808cf8`; continues the orchestrator's WIP snapshot
4+`c5de1b6` (previous builder's uncommitted state), commit `16baa0f` is this round.
5+
6+## What changed
7+
8+- `crates/ec-av1/src/decode.rs:3159` `decode_rect_split` (from the WIP snapshot, kept):
9+ a HORZ/VERT strip with `tx_depth != 0` predicts and reconstructs PER TRANSFORM UNIT in
10+ raster order (spec 5.11.36), each unit taking its edges from the units already
11+ reconstructed inside the same strip, with per-unit `has_top_right`/`has_bottom_left`
12+ (libaom `reconintra.c`) instead of the standalone-block table; chroma stays one un-split
13+ rect transform. `sub_tx_size_map[TX_32X16] == TX_16X16`, so every unit is square and reads
14+ through the ordinary square `read_plane`.
15+- `crates/ec-av1/src/decode.rs:3453` — refusal "filter intra on a HORZ/VERT strip (this
16+ decoder predicts square-only)" REMOVED from `decode_block_rect`, replaced by the
17+ `FILTER_INTRA_RECT_HITS` counter.
18+- `crates/ec-av1/src/intra.rs:733` `predict_filter_intra` now takes `bw`x`bh` instead of one
19+ square `side` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a rectangle just
20+ as happily; `av1_filter_intra_allowed_bsize` genuinely allows every strip with both sides
21+ <= 32). Two call sites updated (`reconstruct_rect` passes `bw, bh`, `reconstruct` passes
22+ `side, side`).
23+- `crates/ec-av1/src/decode.rs:3833` — the below-16x16 leaf arm (`decode_leaf_rect`) keeps
24+ BOTH refusals; its split-transform one is renamed to name the size ("a HORZ/VERT intra
25+ strip below 16x16 with a split transform ...") because the 32x32-level string it shared is
26+ now lifted, and it is added to `refusal_inventory.rs:41`.
27+- `crates/ec-av1/src/stream.rs:9337` gate (a), `:9503` gate (c), `:9700` gate (b, `#[ignore]`d
28+ RED, from the WIP snapshot).
29+
30+## Refusals lifted (each with its gate)
31+
32+| refusal | gate | result |
33+| --- | --- | --- |
34+| "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)" | `a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact` | GREEN, 20/20 pixel-exact, `rect_split_tx_hits` > 0 |
35+| "filter intra on a HORZ/VERT strip (this decoder predicts square-only)" (at the 32x32 level only) | `a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact` | GREEN, 40/40 pixel-exact, `filter_intra_rect_hits`=3 |
36+
37+Not lifted:
38+- "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not
39+ ported)" — the port itself is wired at that level too, but gate (b)
40+ `a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact` is
41+ MEASURED RED: seed 50 decodes one sample off, luma (171, 56) ours 147 vs ffmpeg 148, inside
42+ the 64x32 strip at mi=(8,32) whose transform resolved to depth 2 (TX_16X16). Seeds 42-49
43+ (depth 1 / TX_32X32 units) are pixel-exact. `#[ignore]`d with that number.
44+ disposition: deferred(a range-ladder/prefilt-dump bisection of that one TU's top-right edge
45+ availability) — the refusal stays, so no wrong pixels ship.
46+- "filter intra on a HORZ/VERT strip" / "a HORZ/VERT intra strip below 16x16 with a split
47+ transform" at `decode_leaf_rect` (below 16x16): that arm only ports the skip case and has no
48+ gate of its own. disposition: deferred(a below-16x16 strip gate, lane-sub8's territory).
49+
50+## Gate-recipe search (the part that cost the round)
51+
52+`--enable-filter-intra=1` alone never fires filter intra on a strip. Measured, 192x128
53+`gradients` + `hue=s=0`, `--min/max-partition-size=16/32`, `--threads=1 --row-mt=0`:
54+
55+| recipe | rect strips | filter-intra blocks (any shape) | filter intra ON a strip |
56+| --- | --- | --- | --- |
57+| cq 45, smooth/paeth/directional/angle-delta all OFF (the square filter-intra gate's recipe), 20 seeds | 0 | 23 | 0 |
58+| cq 45, every intra mode ON, 100 seeds | 18 | 136 | 0 |
59+| cq 25, every intra mode ON, 100 seeds | 130 | 61 | 5 |
60+| cq 25, every intra mode ON, 40 seeds (PINNED) | 56 | 16 | 3 |
61+
62+Disabling the directional/smooth/paeth competitors — the trick the square filter-intra gate
63+uses — makes aomenc stop choosing rect partitions altogether (class `gate-recipe-confound`).
64+The knob that actually works is the quantiser: at cq 25 strips are ~7x more common. `smptebars`
65+and `testsrc2` sources were tried and are unusable here (every attempt refused, 0 decodes).
66+`EC_RECTSPLIT_CQ` / `EC_RECTSPLIT_OFF` / `EC_RECTSPLIT_GATE_ATTEMPTS` stay as diagnosis knobs
67+with the pinned recipe as default.
68+
69+## Evidence
70+
71+EVIDENCE: `cargo test -p ec-av1 --lib -- a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact` | aomenc `--enable-rect-partitions=1`, tx-size search ON, 20 seeds, each decoded by ours and by ffmpeg | 20 pixel-exact matches, 0 refusals, `rect_split_tx_hits` delta > 0, test ok
72+EVIDENCE: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact` | aomenc `--enable-filter-intra=1 --cq-level=25`, 40 seeds | 40 pixel-exact matches, 0 refusals, `filter_intra_rect_hits` delta=3, test ok
73+
74+## Film check (ReelB)
75+
76+```
77+ffmpeg -v error -t 0.4 -i ".../reelb.mkv" -c:v copy -f obu hg.obu # 1817 bytes
78+cargo run -p ec-av1 --example decode_probe -- hg.obu
79+REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes no leaf smaller than 8x8))
80+```
81+
82+EVIDENCE: /tmp/.../scratchpad/hg.obu | `ffmpeg -t 0.4 -c:v copy -f obu` then `decode_probe` on this branch | stops at "a partition below 8x8", NOT at any refusal this lane owns
83+
84+The charter's premise that this extract stops at a rect-split refusal is stale for the film's
85+first 0.4s: the blocker there is the below-8x8 partition refusal (lane-sub8's, still open per
86+`memory/`). "Before" was not re-measured on main — the refusal reached is upstream of every
87+line this lane touched, so the branch cannot have moved it.
88+disposition: deferred(lane-sub8's below-8x8 leaf) — nothing this lane can do about it.
89+
90+## Suite
91+
92+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3` (crate lib only, never the workspace):
93+**269 passed, 0 failed, 24 ignored**, 1062s. `refusal_inventory` and `gate_coverage` green.
lanes/seg-r1.report.mdadded+67 -0
@@ -0,0 +1,67 @@
1+# lane-seg r1 — per-block `segment_id` and its consumers
2+
3+Branch `lane-seg`, off main `3808cf8` (WIP snapshot `51581d3` continued, not restarted).
4+
5+## What changed
6+
7+- `crates/ec-av1/src/cdf.rs:564` — `SEGMENT_ID` (`default_spatial_pred_seg_tree_cdf`, 3 ctx x 8 symbols)
8+ and `SEGMENT_PRED` (`seg_id_predicted`, 3 ctx) default CDFs.
9+- `crates/ec-av1/src/cdf_state.rs:467` — both tables in `Cdfs`, in `reset_counters` (class
10+ `cdf-counter-not-reset`) and in the default-table constructor, so they adapt and reset like every
11+ other per-tile table.
12+- `crates/ec-av1/src/decode.rs:319-655` — the reader: `set_segmentation` (per-frame install +
13+ `load_previous_segment_ids`), `CurrentSegmentIds`/`PrevSegmentIds` maps, `AboveSegPredContext`/
14+ `LeftSegPredContext`, `av1_neg_deinterleave`, `av1_get_spatial_seg_pred` (ctx + prediction),
15+ `read_segment_id`, `intra_segment_id` (spec 5.11.7) and `inter_segment_id` (5.11.9, both
16+ pre-skip and post-skip positions, `seg_id_predicted` under `temporal_update`, inherited map when
17+ `update_map == 0`), `set_segment_id` stamping the block's whole mi footprint.
18+- Call sites: `read_intra_mode` (decode.rs:4375) and `read_intra_mode_rect` (3332) read
19+ `intra_segment_id` before `skip` when `SegIdPreSkip`, after it otherwise;
20+ `decode_inter_block` (9250/9268) and `decode_inter_block8` (11106/11116) read both spec positions.
21+- Consumers: `block_q_idx()` (decode.rs:400, spec 7.12.2 `get_qindex` with `SEG_LVL_ALT_Q`) replaces
22+ the raw `CURRENT_Q_IDX` read at all 10 dequant sites; `lf_level` (decode.rs:6168) takes the block's
23+ segment id and applies `SEG_LVL_ALT_LF_Y_V/H`/`_U`/`_V` (spec 7.14.4) between the `DeltaLF` term and
24+ the ref/mode deltas; `edge_params` passes the per-side segment ids.
25+- `crates/ec-av1/src/stream.rs:266-291` — frame-level: narrowed refusal (below), spec
26+ `load_previous_segment_ids` from the primary reference's slot, `set_segmentation` per frame;
27+ `stream.rs:736` stores the decoded map into every slot `refresh_frame_flags` names.
28+- `crates/ec-av1/src/refusal_inventory.rs:59` — refusal replaced.
29+
30+## Refusal
31+
32+LIFTED: `"a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)"`.
33+REPLACED BY (narrower): `"a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this
34+decoder reads segment_id but never lets a segment override a block's reference, skip or mode)"` —
35+those three features rewrite mode/reference decisions and suppress symbols `decode_inter_block` reads
36+unconditionally; aomenc's `--aq-mode` only ever sets `SEG_LVL_ALT_Q`, so no gate here can exercise
37+them. `gate_coverage.rs` needed no edit: it derives coverage from `--enable-*` flags and segmentation
38+is driven by `--aq-mode`, not an `--enable-*` flag; its two tests stay green.
39+
40+## Gates (both hard-assert; no decode error or mismatch becomes SKIP)
41+
42+`stream.rs:8698 run_segmentation_gate` — mandelbrot fixture (varying local contrast so AQ has
43+something to segment), `--aq-mode=1 --deltaq-mode=0`, 10 attempts, pixel-exact vs ffmpeg over every
44+decoded frame including hidden alt-refs (`--auto-alt-ref=1 --lag-in-frames=16`), asserting
45+`segment_id_hits > 0`, `segment_ids_seen >= 2`, and — for multi-frame runs — `segment_pred_hits > 0`
46+(the `temporal_update` path).
47+
48+Command: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib aq_segmentation -- --nocapture`
49+
50+EVIDENCE: crates/ec-av1/src/stream.rs:8908 a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact | aomenc --aq-mode=1 --deltaq-mode=0, 16 frames 128x64 8-bit, 10 seeds, decode_stream vs ffmpeg per plane | 10/10 pixel-exact, segment_id_hits=223, distinct segment ids=6, seg_id_predicted symbols=35
51+EVIDENCE: crates/ec-av1/src/stream.rs:8941 a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact | same recipe, yuv420p10le, key frame only, 10 seeds | 10/10 pixel-exact, segment_id_hits=80, distinct segment ids=5
52+EVIDENCE: cargo test -p ec-av1 --lib (EC_AV1_REQUIRE_AOMENC=1) | full ec-av1 lib suite | 269 passed, 0 failed, 23 ignored, 494s
53+EVIDENCE: scratchpad reelc.obu / hg.obu (ffmpeg -t 0.4 -c:v copy -f obu) | cargo run -p ec-av1 --example decode_probe | ReelC stops at "a 32x32 partition type this decoder does not code (value=4)", ReelB at "a partition below 8x8" — neither stops on segmentation
54+
55+## Residue
56+
57+- deferred(sub-16x16 rect/AB partition lanes): an `--aq-mode=2` (complexity AQ) twin. libaom only
58+ enables segmentation for complexity AQ under `--end-usage=vbr` (`aq_complexity.c:is_sb_aq_enabled`,
59+ `sb64_target_rate >= 256`), and every VBR recipe tried makes aomenc pick partition shapes other
60+ lanes still refuse (AB below 16x16, SB-level HORZ/VERT, part32 value 4/6) — 10/10 attempts refuse
61+ before a pixel is compared. Coverage, not capability: complexity AQ sets exactly the same
62+ `SEG_LVL_ALT_Q`/`update_map` syntax variance AQ does. Comment at stream.rs:8919.
63+- deferred(a 10-bit inter-frame decode defect unrelated to this lane): the 10-bit gate is key-frame
64+ only. Measured: the same recipe with `--aq-mode=0` (segmentation entirely off) also mismatches at
65+ frame 2, so a 16-frame 10-bit variant would gate a pre-existing gap. Comment at stream.rs:8933.
66+- accepted: `SEG_LVL_REF_FRAME`/`SKIP`/`GLOBALMV` stay refused by name (see above) — no aomenc
67+ `--aq-mode` path writes them, so a gate cannot be built from this oracle today.
lanes/tiny-r4.report.mdadded+106 -0
@@ -0,0 +1,106 @@
1+# lane-tiny r4 report
2+
3+Rebased onto main `3808cf8` first (r3 was already merged there); branch head `9b1297a`.
4+
5+## Residue closed: 32x16 seeds 42 and 47, chroma-only
6+
7+### Fixture determinism (charter step 1)
8+The sweep's "seed" is not an encoder seed -- it is `attempt`, which shifts
9+`mandelbrot` start_x/start_y. Regenerated both failing 32x16 fixtures twice
10+each and hashed:
11+
12+ attempt 0 (seed 42): c72a6a1b...5659 both runs, 152 bytes
13+ attempt 5 (seed 47): fcbf0894...c388 both runs, 151 bytes
14+
15+So the sweep is genuinely reproducible and no binary fixture needed pinning
16+(per `seeded-fixture-not-reproducible.md`, checked rather than assumed).
17+
18+### Bisection (charter step 2)
19+Not an entropy defect -- the range ladder was never needed. Stage dumps
20+settled it in one step:
21+
22+| stage | Y | U | V |
23+|---|---|---|---|
24+| pre-filter recon (`EC_AV1_PREFILT_DUMP`, ours vs aomdec) | 0 diff | **0 diff** | 0 diff |
25+| post-deblock (`EC_AV1_POSTDEBLOCK_DUMP`, ours vs aomdec) | 0 diff | **5 diff** | 0 diff |
26+
27+Reconstruction (and therefore the whole entropy/prediction path) is exact;
28+the deblocker introduces the mismatch. Printing the U plane rows 0..7 shows
29+the oracle leaves the horizontal edge at chroma row 4 **completely
30+unfiltered**, while we filter it and move rows 3/4 at columns 1, 2, 15.
31+
32+## Root cause
33+
34+`av1_get_max_uv_txsize`: a block's chroma transform is the largest transform
35+covering the **subsampled BLOCK**, capped at 32x32. It does **not** follow
36+luma's `tx_depth` split. `tx_px_at`/`tx_h_px_at` (decode.rs) computed it as
37+`tx_grid[...] / 2` -- half the *resolved luma* transform. A 16x16 block whose
38+luma transform split to 8x8 therefore read a 4-pixel chroma transform, and the
39+deblocker filtered a chroma transform edge that does not exist in the stream.
40+
41+Reconstruction was never wrong because it derives chroma from the block side
42+(`chroma_side = side / 2`, decode.rs 4313/4850/8881) -- which is exactly why
43+the symptom was luma-bit-exact, chroma-only, +-1, and seed-dependent (the
44+phantom edge only changes pixels on the seeds where the filter masks pass).
45+V was clean on both seeds for the same reason: its masks did not pass.
46+
47+**Fix** (decode.rs): `Neighbours::uv_tx_grid` / `uv_tx_h_grid`, written per-mi
48+from the block's own mi span inside `fill_lf_grid_rect` -- the single writer
49+every `fill_lf_grid*` caller routes through -- as
50+`((span_mi * MI / 2).max(4).min(32))`; `tx_px_at`/`tx_h_px_at` read those
51+grids for chroma instead of halving luma's.
52+
53+**Class sweep**: grepped every other chroma-from-luma derivation.
54+`tx_px_at`/`tx_h_px_at` were the only sites deriving chroma tx from the luma
55+*transform*; 4313/4850/8881 derive from the block *side* and are correct.
56+No sibling instances.
57+
58+## Gate (charter step 4)
59+
60+`probe_tiny_frame_size_boundary` -> `stream.rs`
61+`a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact`, no `#[ignore]`:
62+- wrong pixels at any size/seed = panic (was: an eprintln)
63+- a decode error that is not a NAMED `unsupported:` refusal = panic
64+- floor assert `total_exact >= 70` so refusals can never make it vacuous
65+ (per `gate-skips-on-its-own-failure.md` / `refusal-lifted-without-a-gate.md`)
66+- `EC_AV1_REQUIRE_AOMENC=1` makes an absent oracle fail, not skip.
67+
68+`gate_coverage.rs` needed no change: it derives the tool set from `stream.rs`
69+source and this gate's `--enable-*` flags are unchanged (it was already in the
70+derived gate set while `#[ignore]`d). `gate_coverage` + `refusal_inventory`
71+are green.
72+
73+| size | r3 | r4 |
74+|---|---|---|
75+| 8x8 | refused 10/10 | refused 10/10 (named: 16x16 block whose true edge cuts both axes needs a rect transform) |
76+| 16x16, 32x32, 16x32, 48x48, 64x64, 24x24 | 10/10 | 10/10 |
77+| **32x16** | **8/10** | **10/10** |
78+
79+No refusal string was lifted this round (the 8x8 rect-transform refusal stays;
80+it is a genuine missing capability, now pinned by the gate).
81+
82+## Instruments added
83+- `EC_AV1_POSTDEBLOCK_DUMP` / `EC_AV1_POSTCDEF_DUMP` (decode.rs `dump_stage`),
84+ mirroring aomdec's own `EC_AV1_POSTDEBLOCK_DUMP` (decodeframe.c ~5404) -- with
85+ the existing pre-filter dump these bisect which filter stage broke a frame.
86+- `decode_probe <stream.obu> [out.yuv]` now writes the decoded planes as raw
87+ yuv420p, so a pixel diff against `ffmpeg -f rawvideo` needs no test harness.
88+
89+## Verification
90+
91+- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib`: **268 passed, 0 failed,
92+ 22 ignored** (362s).
93+- New gate alone: 9.5s.
94+
95+EVIDENCE: $SCRATCH/pre0.bin.f0 vs oracle0.bin.f0, pd0.bin.f0 vs opd0.bin.f0 | EC_AV1_PREFILT_DUMP + EC_AV1_POSTDEBLOCK_DUMP on ours and instrumented aomdec, same 32x16 seed-42 stream | pre-filter U diff 0, post-deblock U diff 5 -> defect is in deblock, not recon
96+EVIDENCE: $SCRATCH/ours0.yuv vs ff0.yuv, ours5.yuv vs ff5.yuv | decode_probe a{0,5}.obu out.yuv, cmp against ffmpeg rawvideo | both byte-identical after the fix (before: U 4 and 5 differing samples)
97+EVIDENCE: cargo test -p ec-av1 --lib a_real_aomenc_tiny_frame_size_sweep -- --nocapture | 8 sizes x 10 seeds, real aomenc -> ours -> ffmpeg | 32x16 8/10 -> 10/10; 70 pixel-exact + 10 named 8x8 refusals; gate green
98+
99+## Open
100+
101+- 8x8 frames: `deferred(a real rectangular TX_4X8/TX_8X4 coefficient path)` --
102+ refused by name, now pinned by the gate; the same square-only-transform
103+ ceiling `square-only-transform-ceiling.md` already tracks.
104+- Repo-wide `cargo fmt --check` drift exists in `cdf.rs` and elsewhere and
105+ predates this lane: `accepted`, not touched (formatting the crate would bury
106+ this diff).