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() {
32 Ok(frames) if frames.is_empty() => {32 Ok(frames) if frames.is_empty() => {
33 println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");33 println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");
34 }34 }
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+ }
36 Err(e) => println!("REFUSED: {e}"),51 Err(e) => println!("REFUSED: {e}"),
37 }52 }
38 }53 }
crates/ec-av1/src/cdf.rsmodified+13 -0
@@ -561,6 +561,19 @@ pub const RESTORE_SWITCHABLE: [u16; 4] = [9413, 22581, 32768, 0];
561 /// 4-symbol `delta_q_abs` alphabet read once per superblock when561 /// 4-symbol `delta_q_abs` alphabet read once per superblock when
562 /// `delta_q_present` is set. `default_delta_lf_cdf`/`default_delta_lf_multi_cdf`562 /// `delta_q_present` is set. `default_delta_lf_cdf`/`default_delta_lf_multi_cdf`
563 /// share this same value (verified against libaom's real source).563 /// 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+
564 pub const DELTA_Q: [u16; 5] = [28160, 32120, 32677, 32768, 0];577 pub const DELTA_Q: [u16; 5] = [28160, 32120, 32677, 32768, 0];
565 /// `default_delta_lf_cdf` -- see [`DELTA_Q`]'s doc.578 /// `default_delta_lf_cdf` -- see [`DELTA_Q`]'s doc.
566 pub const DELTA_LF: [u16; 5] = DELTA_Q;579 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 {
420 /// The two motion vector components' own tables: separate owned state,420 /// The two motion vector components' own tables: separate owned state,
421 /// since spec 8.3.2 adapts one component without touching the other.421 /// since spec 8.3.2 adapts one component without touching the other.
422 pub mv_comp: [MvComponentCdfs; 2],422 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],
423 /// The `use_filter_intra` flag, indexed by block-size class (`[0]`=4x4,429 /// The `use_filter_intra` flag, indexed by block-size class (`[0]`=4x4,
424 /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32) --430 /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32) --
425 /// see [`cdf::FILTER_INTRA`].431 /// see [`cdf::FILTER_INTRA`].
@@ -464,6 +470,10 @@ pub(crate) struct Cdfs {
464 /// A `RESTORE_SWITCHABLE`-plane LR unit's `restoration_type` -- see470 /// A `RESTORE_SWITCHABLE`-plane LR unit's `restoration_type` -- see
465 /// [`cdf::RESTORE_SWITCHABLE`].471 /// [`cdf::RESTORE_SWITCHABLE`].
466 pub restore_switchable: [u16; 4],472 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],
467 /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`].477 /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`].
468 pub delta_q: [u16; 5],478 pub delta_q: [u16; 5],
469 /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see479 /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see
@@ -682,6 +692,10 @@ impl Cdfs {
682 reset2(&mut self.ref_mv);692 reset2(&mut self.ref_mv);
683 reset2(&mut self.drl_mode);693 reset2(&mut self.drl_mode);
684 reset1(&mut self.mv_joint);694 reset1(&mut self.mv_joint);
695+ reset1(&mut self.dv_joint);
696+ self.dv_comp
697+ .iter_mut()
698+ .for_each(MvComponentCdfs::reset_counts);
685 self.mv_comp699 self.mv_comp
686 .iter_mut()700 .iter_mut()
687 .for_each(MvComponentCdfs::reset_counts);701 .for_each(MvComponentCdfs::reset_counts);
@@ -701,6 +715,8 @@ impl Cdfs {
701 reset1(&mut self.restore_wiener);715 reset1(&mut self.restore_wiener);
702 reset1(&mut self.restore_sgrproj);716 reset1(&mut self.restore_sgrproj);
703 reset1(&mut self.restore_switchable);717 reset1(&mut self.restore_switchable);
718+ reset2(&mut self.segment_id);
719+ reset2(&mut self.segment_pred);
704 reset1(&mut self.delta_q);720 reset1(&mut self.delta_q);
705 reset1(&mut self.delta_lf);721 reset1(&mut self.delta_lf);
706 reset2(&mut self.delta_lf_multi);722 reset2(&mut self.delta_lf_multi);
@@ -1155,6 +1171,8 @@ impl Cdfs {
1155 drl_mode: cdf::DRL_MODE,1171 drl_mode: cdf::DRL_MODE,
1156 mv_joint: cdf::MV_JOINT,1172 mv_joint: cdf::MV_JOINT,
1157 mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],1173 mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],
1174+ dv_joint: cdf::MV_JOINT,
1175+ dv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],
1158 filter_intra: cdf::FILTER_INTRA,1176 filter_intra: cdf::FILTER_INTRA,
1159 filter_intra_mode: cdf::FILTER_INTRA_MODE,1177 filter_intra_mode: cdf::FILTER_INTRA_MODE,
1160 tx_size_cat0: cdf::TX_SIZE_CAT0,1178 tx_size_cat0: cdf::TX_SIZE_CAT0,
@@ -1172,6 +1190,8 @@ impl Cdfs {
1172 restore_wiener: cdf::RESTORE_WIENER,1190 restore_wiener: cdf::RESTORE_WIENER,
1173 restore_sgrproj: cdf::RESTORE_SGRPROJ,1191 restore_sgrproj: cdf::RESTORE_SGRPROJ,
1174 restore_switchable: cdf::RESTORE_SWITCHABLE,1192 restore_switchable: cdf::RESTORE_SWITCHABLE,
1193+ segment_id: cdf::SEGMENT_ID,
1194+ segment_pred: cdf::SEGMENT_PRED,
1175 delta_q: cdf::DELTA_Q,1195 delta_q: cdf::DELTA_Q,
1176 delta_lf: cdf::DELTA_LF,1196 delta_lf: cdf::DELTA_LF,
1177 delta_lf_multi: [cdf::DELTA_LF; 4],1197 delta_lf_multi: [cdf::DELTA_LF; 4],
crates/ec-av1/src/decode.rsmodified+1097 -62
@@ -22,7 +22,8 @@
22 //! silently miscoding.22 //! silently miscoding.
23 23
24 use ec_av1_syntax::{24 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,
26 };27 };
27 use ec_core::{Error, Result};28 use ec_core::{Error, Result};
28 29
@@ -315,6 +316,353 @@ fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip:
315 }316 }
316 }317 }
317 318
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+
318 // How many key-frame luma blocks resolved `smooth_neighbor` (spec666 // How many key-frame luma blocks resolved `smooth_neighbor` (spec
319 // `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after667 // `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
320 // counter, proving a stream actually put a directional block next to a668 // counter, proving a stream actually put a directional block next to a
@@ -428,6 +776,34 @@ pub(crate) fn horz_vert_intra_hits() -> usize {
428 HORZ_VERT_INTRA_HITS.with(|c| c.get())776 HORZ_VERT_INTRA_HITS.with(|c| c.get())
429 }777 }
430 778
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+
431 // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`807 // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
432 // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every808 // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
433 // call on the current thread -- the same before/after counter pattern as809 // call on the current thread -- the same before/after counter pattern as
@@ -608,6 +984,69 @@ thread_local! {
608 const { std::cell::RefCell::new(None) };984 const { std::cell::RefCell::new(None) };
609 }985 }
610 986
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+
611 // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --1050 // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
612 // proves a real `skip_mode_present` stream actually reached a block that1051 // proves a real `skip_mode_present` stream actually reached a block that
613 // picked it, not just that the frame header bit was set.1052 // picked it, not just that the frame header bit was set.
@@ -1844,6 +2283,16 @@ struct Neighbours {
1844 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal2283 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
1845 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).2284 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
1846 tx_h_grid: Vec<u8>,2285 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>,
1847 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =2296 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
1848 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --2297 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
1849 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)2298 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
@@ -1923,6 +2372,8 @@ impl Neighbours {
1923 skip_grid_cols_mi: cols * (SUB / MI),2372 skip_grid_cols_mi: cols * (SUB / MI),
1924 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],2373 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1925 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],2374 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)],
1926 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],2377 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1927 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],2378 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
1928 above_palette_size: vec![0; cols],2379 above_palette_size: vec![0; cols],
@@ -1945,6 +2396,9 @@ impl Neighbours {
1945 /// regardless of tile ([`Self::start_row`], already called once per SB2396 /// regardless of tile ([`Self::start_row`], already called once per SB
1946 /// row by every caller) so it needs no tile-specific reset here.2397 /// row by every caller) so it needs no tile-specific reset here.
1947 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {2398 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)));
1948 self.tile_row0_mi = row0_mi;2402 self.tile_row0_mi = row0_mi;
1949 self.tile_col0_mi = col0_mi;2403 self.tile_col0_mi = col0_mi;
1950 let end = col1_mi.min(self.above.len());2404 let end = col1_mi.min(self.above.len());
@@ -2176,6 +2630,11 @@ impl Neighbours {
2176 ref_frame: i8,2630 ref_frame: i8,
2177 ) {2631 ) {
2178 let (mi_r, mi_c) = at_mi;2632 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;
2179 let cur = CURRENT_DELTA_LF.with(|c| c.get());2638 let cur = CURRENT_DELTA_LF.with(|c| c.get());
2180 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {2639 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
2181 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)2640 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
@@ -2191,6 +2650,12 @@ impl Neighbours {
2191 if let Some(cell) = self.tx_h_grid.get_mut(idx) {2650 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
2192 *cell = tx_h_px;2651 *cell = tx_h_px;
2193 }2652 }
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+ }
2194 if let Some(cell) = self.ref_grid.get_mut(idx) {2659 if let Some(cell) = self.ref_grid.get_mut(idx) {
2195 *cell = ref_frame;2660 *cell = ref_frame;
2196 }2661 }
@@ -2630,32 +3095,55 @@ impl Neighbours {
2630 mode: usize,3095 mode: usize,
2631 uv_mode: usize,3096 uv_mode: usize,
2632 chroma_grids: [&[i32]; 2],3097 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],
2633 ) {3115 ) {
2634 let (r, c) = at;3116 let (r, c) = at;
2635- for cell in 0..side / SUB {3117+ for cell in 0..w / SUB {
2636 self.above_mode[c + cell] = mode;3118 self.above_mode[c + cell] = mode;
2637- self.left_mode[r + cell] = mode;
2638 self.above_uv_mode[c + cell] = uv_mode;3119 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;
2639 self.left_uv_mode[r + cell] = uv_mode;3124 self.left_uv_mode[r + cell] = uv_mode;
2640- self.above_side[c + cell] = side;3125+ self.left_side[r + cell] = h;
2641- self.left_side[r + cell] = side;
2642 }3126 }
2643 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));3127 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2644- let side_mi = side / MI;3128+ let (w_mi, h_mi) = (w / MI, h / MI);
2645- for cell in 0..side_mi {3129+ for cell in 0..h_mi {
2646- self.left_side_mi[mi_r + cell] = side;3130+ self.left_side_mi[mi_r + cell] = h;
2647- self.above_side_mi[mi_c + cell] = side;3131+ }
3132+ for cell in 0..w_mi {
3133+ self.above_side_mi[mi_c + cell] = w;
2648 }3134 }
2649 let round_up_even = |n: usize| n.div_ceil(2) * 2;3135 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2650 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));3136 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2651 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {3137 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
2652 let plane = plane_idx + 1;3138 let plane = plane_idx + 1;
2653 let state = neighbour_state(grid);3139 let state = neighbour_state(grid);
2654- for cell in 0..side_mi {3140+ for cell in 0..h_mi {
2655- if cell < side_mi.min(bound_h.saturating_sub(mi_r)) {3141+ if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
2656 self.left[mi_r + cell][plane] = state;3142 self.left[mi_r + cell][plane] = state;
2657 }3143 }
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)) {
2659 self.above[mi_c + cell][plane] = state;3147 self.above[mi_c + cell][plane] = state;
2660 }3148 }
2661 }3149 }
@@ -3076,8 +3564,16 @@ fn read_intra_mode_rect(
3076 }3564 }
3077 };3565 };
3078 }3566 }
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+ }
3079 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;3572 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
3080 istep!("skip", skip as i32);3573 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+ }
3081 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);3577 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
3082 istep!("cdef", 0);3578 istep!("cdef", 0);
3083 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never3579 // 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
3245 ac3741 ac
3246 }3742 }
3247 3743
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+
3248 /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip4016 /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
3249 /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's4017 /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
3250 /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/4018 /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
@@ -3270,6 +4038,7 @@ fn decode_block_rect(
3270 allow_screen_content_tools: bool,4038 allow_screen_content_tools: bool,
3271 base_q_idx: u8,4039 base_q_idx: u8,
3272 tx_select: bool,4040 tx_select: bool,
4041+ reduced_tx_set: bool,
3273 ) -> Result<()> {4042 ) -> Result<()> {
3274 let (r, c) = at;4043 let (r, c) = at;
3275 let (px, py) = (c * SUB, r * SUB);4044 let (px, py) = (c * SUB, r * SUB);
@@ -3302,15 +4071,13 @@ fn decode_block_rect(
3302 // `uv_mode`, not the luma one.4071 // `uv_mode`, not the luma one.
3303 let smooth_neighbor_uv =4072 let smooth_neighbor_uv =
3304 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);4073 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.
3305 if filter_intra.is_some() {4079 if filter_intra.is_some() {
3306- // `predict_filter_intra` (spec 7.11.2.3) is square-only in this4080+ FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
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- ));
3314 }4081 }
3315 let uv_predict_mode = if uv_mode == UV_CFL_PRED {4082 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3316 DC_PRED4083 DC_PRED
@@ -3333,15 +4100,40 @@ fn decode_block_rect(
3333 };4100 };
3334 if depth != 0 {4101 if depth != 0 {
3335 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));4102 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
3336- // A split transform is predicted per transform unit, each taking its4103+ // lane-rectsplit r1: a split transform is predicted and reconstructed
3337- // edges from the previous unit's reconstruction (the square path's own4104+ // per transform unit, each unit taking its edges from the previous
3338- // per-TU loop does exactly that). Predicting the whole strip in one4105+ // unit's reconstruction inside this same strip (spec 5.11.36) --
3339- // shot would silently produce different pixels, so refuse by name4106+ // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square
3340- // until that loop is ported for rect strips.4107+ // from the first step on, so `bw.min(bh) >> (depth - 1)` names it.
3341- return Err(unsupported(4108+ let tx = bw.min(bh) >> (depth - 1);
3342- "a HORZ/VERT intra strip with a split transform (per-unit rect \4109+ let modes = RectStripModes {
3343- prediction is not ported)",4110+ skip,
3344- ));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(());
3345 }4137 }
3346 let (tx_w, tx_h) = (bw, bh);4138 let (tx_w, tx_h) = (bw, bh);
3347 let (cpx, cpy) = (px / 2, py / 2);4139 let (cpx, cpy) = (px / 2, py / 2);
@@ -3509,7 +4301,7 @@ fn decode_block_rect(
3509 bw,4301 bw,
3510 bh,4302 bh,
3511 crate::decode::bit_depth(),4303 crate::decode::bit_depth(),
3512- CURRENT_Q_IDX.with(|c| c.get()),4304+ block_q_idx(),
3513 plane_q_delta(0).0,4305 plane_q_delta(0).0,
3514 plane_q_delta(0).1,4306 plane_q_delta(0).1,
3515 luma_tx_type,4307 luma_tx_type,
@@ -3553,7 +4345,7 @@ fn decode_block_rect(
3553 chroma_w,4345 chroma_w,
3554 chroma_h,4346 chroma_h,
3555 crate::decode::bit_depth(),4347 crate::decode::bit_depth(),
3556- CURRENT_Q_IDX.with(|c| c.get()),4348+ block_q_idx(),
3557 plane_q_delta(1).0,4349 plane_q_delta(1).0,
3558 plane_q_delta(1).1,4350 plane_q_delta(1).1,
3559 u_tx_type,4351 u_tx_type,
@@ -3596,7 +4388,7 @@ fn decode_block_rect(
3596 chroma_w,4388 chroma_w,
3597 chroma_h,4389 chroma_h,
3598 crate::decode::bit_depth(),4390 crate::decode::bit_depth(),
3599- CURRENT_Q_IDX.with(|c| c.get()),4391+ block_q_idx(),
3600 plane_q_delta(2).0,4392 plane_q_delta(2).0,
3601 plane_q_delta(2).1,4393 plane_q_delta(2).1,
3602 v_tx_type,4394 v_tx_type,
@@ -3732,7 +4524,7 @@ fn decode_leaf_rect(
3732 };4524 };
3733 if depth != 0 {4525 if depth != 0 {
3734 return Err(unsupported(4526 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 \
3736 prediction is not ported)",4528 prediction is not ported)",
3737 ));4529 ));
3738 }4530 }
@@ -3839,6 +4631,7 @@ fn decode_block_rect64(
3839 allow_screen_content_tools: bool,4631 allow_screen_content_tools: bool,
3840 base_q_idx: u8,4632 base_q_idx: u8,
3841 tx_select: bool,4633 tx_select: bool,
4634+ reduced_tx_set: bool,
3842 ) -> Result<()> {4635 ) -> Result<()> {
3843 let (r, c) = at;4636 let (r, c) = at;
3844 let (px, py) = (c * SUB, r * SUB);4637 let (px, py) = (c * SUB, r * SUB);
@@ -3905,12 +4698,31 @@ fn decode_block_rect64(
3905 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));4698 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3906 let depth = if tx_select {4699 let depth = if tx_select {
3907 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);4700 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])
3909 } else {4709 } else {
3910 04710 0
3911 };4711 };
3912 if depth != 0 {4712 if depth != 0 {
3913 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));4713 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.
3914 return Err(unsupported(4726 return Err(unsupported(
3915 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \4727 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \
3916 prediction is not ported)",4728 prediction is not ported)",
@@ -4017,7 +4829,7 @@ fn decode_block_rect64(
4017 luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]);4829 luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]);
4018 }4830 }
4019 {4831 {
4020- let cur = CURRENT_Q_IDX.with(|c| c.get());4832+ let cur = block_q_idx();
4021 if cur != i32::from(base_q_idx) {4833 if cur != i32::from(base_q_idx) {
4022 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));4834 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4023 }4835 }
@@ -4032,7 +4844,7 @@ fn decode_block_rect64(
4032 bw,4844 bw,
4033 bh,4845 bh,
4034 crate::decode::bit_depth(),4846 crate::decode::bit_depth(),
4035- CURRENT_Q_IDX.with(|c| c.get()),4847+ block_q_idx(),
4036 plane_q_delta(0).0,4848 plane_q_delta(0).0,
4037 plane_q_delta(0).1,4849 plane_q_delta(0).1,
4038 luma_tx_type,4850 luma_tx_type,
@@ -4089,7 +4901,7 @@ fn decode_block_rect64(
4089 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");4901 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
4090 }4902 }
4091 {4903 {
4092- let cur = CURRENT_Q_IDX.with(|c| c.get());4904+ let cur = block_q_idx();
4093 if cur != i32::from(base_q_idx) {4905 if cur != i32::from(base_q_idx) {
4094 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));4906 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4095 }4907 }
@@ -4104,7 +4916,7 @@ fn decode_block_rect64(
4104 chroma_w,4916 chroma_w,
4105 chroma_h,4917 chroma_h,
4106 crate::decode::bit_depth(),4918 crate::decode::bit_depth(),
4107- CURRENT_Q_IDX.with(|c| c.get()),4919+ block_q_idx(),
4108 plane_q_delta(1).0,4920 plane_q_delta(1).0,
4109 plane_q_delta(1).1,4921 plane_q_delta(1).1,
4110 u_tx_type,4922 u_tx_type,
@@ -4143,7 +4955,7 @@ fn decode_block_rect64(
4143 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");4955 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
4144 }4956 }
4145 {4957 {
4146- let cur = CURRENT_Q_IDX.with(|c| c.get());4958+ let cur = block_q_idx();
4147 if cur != i32::from(base_q_idx) {4959 if cur != i32::from(base_q_idx) {
4148 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));4960 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4149 }4961 }
@@ -4158,7 +4970,7 @@ fn decode_block_rect64(
4158 chroma_w,4970 chroma_w,
4159 chroma_h,4971 chroma_h,
4160 crate::decode::bit_depth(),4972 crate::decode::bit_depth(),
4161- CURRENT_Q_IDX.with(|c| c.get()),4973+ block_q_idx(),
4162 plane_q_delta(2).0,4974 plane_q_delta(2).0,
4163 plane_q_delta(2).1,4975 plane_q_delta(2).1,
4164 v_tx_type,4976 v_tx_type,
@@ -4261,11 +5073,20 @@ fn read_intra_mode(
4261 }5073 }
4262 };5074 };
4263 }5075 }
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+ }
4264 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;5082 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
4265 if trace {5083 if trace {
4266 eprintln!("TRACE skip value={}", skip as i32);5084 eprintln!("TRACE skip value={}", skip as i32);
4267 }5085 }
4268 istep!("skip", skip as i32);5086 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+ }
4269 // spec order (see the comment below on `read_intrabc_info`): `skip`,5090 // spec order (see the comment below on `read_intrabc_info`): `skip`,
4270 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.5091 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
4271 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);5092 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
@@ -4288,9 +5109,18 @@ fn read_intra_mode(
4288 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);5109 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
4289 }5110 }
4290 if use_intrabc {5111 if use_intrabc {
4291- return Err(unsupported(5112+ let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
4292- "a block that actually uses intrabc (this decoder never reconstructs one)",5113+ if trace {
4293- ));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));
4294 }5124 }
4295 }5125 }
4296 let above_ctx = INTRA_MODE_CTX[above_mode];5126 let above_ctx = INTRA_MODE_CTX[above_mode];
@@ -4570,6 +5400,20 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
4570 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly5400 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
4571 /// (own-edge and reach clamps both), passing what it gathers straight to5401 /// (own-edge and reach clamps both), passing what it gathers straight to
4572 /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.5402 /// [`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+
4573 #[derive(Clone)]5417 #[derive(Clone)]
4574 struct PlaneBuf {5418 struct PlaneBuf {
4575 data: Vec<u16>,5419 data: Vec<u16>,
@@ -4726,6 +5570,7 @@ impl PlaneBuf {
4726 left.as_deref(),5570 left.as_deref(),
4727 corner,5571 corner,
4728 bw,5572 bw,
5573+ bh,
4729 &mut prediction,5574 &mut prediction,
4730 );5575 );
4731 } else {5576 } else {
@@ -4800,6 +5645,7 @@ impl PlaneBuf {
4800 left.as_deref(),5645 left.as_deref(),
4801 corner,5646 corner,
4802 side,5647 side,
5648+ side,
4803 &mut prediction,5649 &mut prediction,
4804 );5650 );
4805 } else {5651 } else {
@@ -4937,7 +5783,7 @@ fn read_plane(
4937 full5783 full
4938 };5784 };
4939 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);5785 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);
4941 if std::env::var_os("EC_AV1_TRACE").is_some() {5787 if std::env::var_os("EC_AV1_TRACE").is_some() {
4942 eprintln!(5788 eprintln!(
4943 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",5789 "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(
5021 r * (SUB / MI),5867 r * (SUB / MI),
5022 c * (SUB / MI),5868 c * (SUB / MI),
5023 )?;5869 )?;
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+ }
5024 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`5880 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
5025 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the5881 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
5026 // actual chroma-from-luma correlation, same as this decoder always did.5882 // actual chroma-from-luma correlation, same as this decoder always did.
@@ -5060,10 +5916,45 @@ fn decode_block(
5060 } else {5916 } else {
5061 luma_set5917 luma_set
5062 };5918 };
5919+ let luma_set = if intrabc_dv.is_some() {
5920+ txbset_for_inter(logical_tx, reduced_tx_set)
5921+ } else {
5922+ luma_set
5923+ };
5063 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);5924 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
5064 let reach = Reach::of(side, px, py, y.width, y.height);5925 let reach = Reach::of(side, px, py, y.width, y.height);
5065 let (cpx, cpy) = (px / 2, py / 2);5926 let (cpx, cpy) = (px / 2, py / 2);
5066 let chroma_side = side / 2;5927 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+ }
5067 // A palette-Y block's own prediction is the reconstructed colour-index5958 // A palette-Y block's own prediction is the reconstructed colour-index
5068 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it5959 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
5069 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a5960 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
@@ -5099,6 +5990,13 @@ fn decode_block(
5099 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),5990 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5100 )5991 )
5101 });5992 });
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+ };
5102 if skip {6000 if skip {
5103 // A skipped block codes no residual syntax at all (spec 5.11.34):6001 // A skipped block codes no residual syntax at all (spec 5.11.34):
5104 // straight prediction, on every plane.6002 // straight prediction, on every plane.
@@ -5374,6 +6272,7 @@ fn decode_block(
5374 logical_tx as u8,6272 logical_tx as u8,
5375 0,6273 0,
5376 );6274 );
6275+ record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
5377 Ok(())6276 Ok(())
5378 }6277 }
5379 6278
@@ -5956,24 +6855,16 @@ fn plane_to_mi(chroma: bool, coord: usize) -> usize {
5956 /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`6855 /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
5957 /// under 4:2:0 and a block that never splits its own transform).6856 /// under 4:2:0 and a block that never splits its own transform).
5958 fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {6857 fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
5959- let luma_tx = n6858+ let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
5960- .tx_grid6859+ grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
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 }
5965 }6860 }
5966 6861
5967 /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal6862 /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
5968 /// edges step and gate by transform height, which differs from width only6863 /// edges step and gate by transform height, which differs from width only
5969 /// on rect partition strips.6864 /// on rect partition strips.
5970 fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {6865 fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
5971- let luma_tx = n6866+ let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
5972- .tx_h_grid6867+ grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
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 }
5977 }6868 }
5978 6869
5979 /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom6870 /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
@@ -6057,6 +6948,21 @@ fn scan_for<'a>(
6057 /// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past6948 /// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
6058 /// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a6949 /// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
6059 /// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).6950 /// 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+
6060 fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {6966 fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
6061 match tx_px {6967 match tx_px {
6062 64 => TxbSet::Luma64,6968 64 => TxbSet::Luma64,
@@ -6088,7 +6994,14 @@ fn unit_log2(px: u32) -> i32 {
6088 /// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable6994 /// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
6089 /// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`6995 /// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
6090 /// block anywhere aborted the whole stream's decode before comparison).6996 /// 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 {
6092 let base = i32::from(if plane_idx == 0 {7005 let base = i32::from(if plane_idx == 0 {
6093 lf.level[dir]7006 lf.level[dir]
6094 } else if plane_idx == 1 {7007 } else if plane_idx == 1 {
@@ -6100,6 +7013,16 @@ fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8,
6100 // ref/mode delta scaling below, and regardless of `delta_enabled`7013 // ref/mode delta scaling below, and regardless of `delta_enabled`
6101 // (that flag only gates `ref_deltas`/`mode_deltas`).7014 // (that flag only gates `ref_deltas`/`mode_deltas`).
6102 let base = (base + delta_lf).clamp(0, 63);7015 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+ };
6103 if !lf.delta_enabled {7026 if !lf.delta_enabled {
6104 return base;7027 return base;
6105 }7028 }
@@ -6155,8 +7078,15 @@ fn edge_params(
6155 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);7078 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
6156 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);7079 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
6157 7080
6158- let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf);7081+ let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
6159- let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf);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+ );
6160 if cur_level == 0 && pv_level == 0 {7090 if cur_level == 0 && pv_level == 0 {
6161 return None;7091 return None;
6162 }7092 }
@@ -6855,6 +7785,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
6855 }7785 }
6856 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));7786 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
6857 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));7787 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));
6858 CDEF_BITS.with(|c| c.set(cdef.bits));7798 CDEF_BITS.with(|c| c.set(cdef.bits));
6859 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));7799 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
6860 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);7800 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(
7204 allow_screen_content_tools,8144 allow_screen_content_tools,
7205 base_q_idx,8145 base_q_idx,
7206 tx_select,8146 tx_select,
8147+ reduced_tx_set,
7207 )?;8148 )?;
7208 // Two 8x8 squares stacked on the8149 // Two 8x8 squares stacked on the
7209 // right, chained through8150 // right, chained through
@@ -7508,6 +8449,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7508 allow_screen_content_tools,8449 allow_screen_content_tools,
7509 base_q_idx,8450 base_q_idx,
7510 tx_select,8451 tx_select,
8452+ reduced_tx_set,
7511 )?;8453 )?;
7512 decode_block_rect(8454 decode_block_rect(
7513 &mut dec,8455 &mut dec,
@@ -7523,6 +8465,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7523 allow_screen_content_tools,8465 allow_screen_content_tools,
7524 base_q_idx,8466 base_q_idx,
7525 tx_select,8467 tx_select,
8468+ reduced_tx_set,
7526 )?;8469 )?;
7527 }8470 }
7528 PARTITION_VERT => {8471 PARTITION_VERT => {
@@ -7542,6 +8485,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7542 allow_screen_content_tools,8485 allow_screen_content_tools,
7543 base_q_idx,8486 base_q_idx,
7544 tx_select,8487 tx_select,
8488+ reduced_tx_set,
7545 )?;8489 )?;
7546 decode_block_rect(8490 decode_block_rect(
7547 &mut dec,8491 &mut dec,
@@ -7557,6 +8501,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7557 allow_screen_content_tools,8501 allow_screen_content_tools,
7558 base_q_idx,8502 base_q_idx,
7559 tx_select,8503 tx_select,
8504+ reduced_tx_set,
7560 )?;8505 )?;
7561 }8506 }
7562 _ => {8507 _ => {
@@ -7583,6 +8528,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7583 allow_screen_content_tools,8528 allow_screen_content_tools,
7584 base_q_idx,8529 base_q_idx,
7585 tx_select,8530 tx_select,
8531+ reduced_tx_set,
7586 )?;8532 )?;
7587 decode_block_rect64(8533 decode_block_rect64(
7588 &mut dec,8534 &mut dec,
@@ -7598,6 +8544,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7598 allow_screen_content_tools,8544 allow_screen_content_tools,
7599 base_q_idx,8545 base_q_idx,
7600 tx_select,8546 tx_select,
8547+ reduced_tx_set,
7601 )?;8548 )?;
7602 }8549 }
7603 PARTITION_VERT => {8550 PARTITION_VERT => {
@@ -7617,6 +8564,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7617 allow_screen_content_tools,8564 allow_screen_content_tools,
7618 base_q_idx,8565 base_q_idx,
7619 tx_select,8566 tx_select,
8567+ reduced_tx_set,
7620 )?;8568 )?;
7621 decode_block_rect64(8569 decode_block_rect64(
7622 &mut dec,8570 &mut dec,
@@ -7632,6 +8580,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7632 allow_screen_content_tools,8580 allow_screen_content_tools,
7633 base_q_idx,8581 base_q_idx,
7634 tx_select,8582 tx_select,
8583+ reduced_tx_set,
7635 )?;8584 )?;
7636 }8585 }
7637 _ => {8586 _ => {
@@ -7693,7 +8642,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
7693 frame_height as usize,8642 frame_height as usize,
7694 );8643 );
7695 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());8644 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);
7696 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);8649 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
8650+ dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
7697 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);8651 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
7698 8652
7699 let (fw, fh) = (frame_width as usize, frame_height as usize);8653 let (fw, fh) = (frame_width as usize, frame_height as usize);
@@ -7959,6 +8913,58 @@ fn read_mv(
7959 (pred.0 + diff.0, pred.1 + diff.1)8913 (pred.0 + diff.0, pred.1 + diff.1)
7960 }8914 }
7961 8915
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+
7962 /// A 1/8-pel motion vector component converted to the 1/16-pel offset8968 /// A 1/8-pel motion vector component converted to the 1/16-pel offset
7963 /// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`8969 /// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
7964 /// (its own doc comment explains the `*2`/`*1` luma/chroma split).8970 /// (its own doc comment explains the `*2`/`*1` luma/chroma split).
@@ -8062,7 +9068,7 @@ fn read_inter_plane(
8062 None,9068 None,
8063 )?;9069 )?;
8064 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);9070 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);
8066 plane.reconstruct_mc(x, y, side, prediction, &residual);9072 plane.reconstruct_mc(x, y, side, prediction, &residual);
8067 Ok((grid, tx_type))9073 Ok((grid, tx_type))
8068 }9074 }
@@ -9146,6 +10152,11 @@ fn decode_inter_block(
9146 dec.debug_bitpos()10152 dec.debug_bitpos()
9147 );10153 );
9148 }10154 }
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);
9149 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;10160 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
9150 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {10161 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
9151 eprintln!(10162 eprintln!(
@@ -9159,6 +10170,7 @@ fn decode_inter_block(
9159 10170
9160 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);10171 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
9161 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;10172 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);
9162 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);10174 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
9163 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);10175 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
9164 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);10176 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(
10996 }12008 }
10997 let skip_mode_ctx =12009 let skip_mode_ctx =
10998 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);12010 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);
10999 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;12014 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
11000 if skip_mode {12015 if skip_mode {
11001 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));12016 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
@@ -11003,6 +12018,7 @@ fn decode_inter_block8(
11003 12018
11004 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);12019 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
11005 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;12020 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);
11006 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);12022 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
11007 // Always a `BLOCK_8X8` leaf here, never the whole superblock.12023 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
11008 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);12024 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(
13588 frame_height as usize,14604 frame_height as usize,
13589 );14605 );
13590 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());14606 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);
13591 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);14611 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
14612+ dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
13592 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);14613 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
13593 14614
13594 let motion_field = build_motion_field(14615 let motion_field = build_motion_field(
@@ -13952,13 +14973,27 @@ mod tests {
13952 use std::io::Write;14973 use std::io::Write;
13953 use std::process::{Command, Stdio};14974 use std::process::{Command, Stdio};
13954 14975
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).
13955 fn have_ffmpeg() -> bool {14983 fn have_ffmpeg() -> bool {
13956- Command::new("ffmpeg")14984+ let present = Command::new("ffmpeg")
13957 .arg("-version")14985 .arg("-version")
13958 .stdout(Stdio::null())14986 .stdout(Stdio::null())
13959 .stderr(Stdio::null())14987 .stderr(Stdio::null())
13960 .status()14988 .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
13962 }14997 }
13963 14998
13964 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:014999 /// 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 {
3063 use std::io::Write;3063 use std::io::Write;
3064 use std::process::{Command, Stdio};3064 use std::process::{Command, Stdio};
3065 3065
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).
3066 fn have_ffmpeg() -> bool {3073 fn have_ffmpeg() -> bool {
3067- Command::new("ffmpeg")3074+ let present = Command::new("ffmpeg")
3068 .arg("-version")3075 .arg("-version")
3069 .stdout(Stdio::null())3076 .stdout(Stdio::null())
3070 .stderr(Stdio::null())3077 .stderr(Stdio::null())
3071 .status()3078 .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
3073 }3087 }
3074 3088
3075 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.3089 /// 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 {
362 use super::*;362 use super::*;
363 use std::process::{Command, Stdio};363 use std::process::{Command, Stdio};
364 364
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).
365 fn have_ffmpeg() -> bool {372 fn have_ffmpeg() -> bool {
366- Command::new("ffmpeg")373+ let present = Command::new("ffmpeg")
367 .arg("-version")374 .arg("-version")
368 .stdout(Stdio::null())375 .stdout(Stdio::null())
369 .stderr(Stdio::null())376 .stderr(Stdio::null())
370 .status()377 .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
372 }386 }
373 387
374 fn test_card(width: usize, height: usize, shift: usize) -> Picture {388 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
crates/ec-av1/src/film_grain.rsmodified+93 -33
@@ -1,6 +1,6 @@
1 //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's1 //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's
2 //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers),2 //! `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 planar3+//! specialized to this crate's only picture shape: 4:2:0 planar
4 //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every4 //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every
5 //! `<< (1 - subsamp)` in the reference collapses to a no-op and every5 //! `<< (1 - subsamp)` in the reference collapses to a no-op and every
6 //! `>> subsamp` collapses to `>> 1` below).6 //! `>> subsamp` collapses to `>> 1` below).
@@ -43,9 +43,25 @@ const LUMA_BLOCK_W: i32 =
43 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;43 const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD;
44 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;44 const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD;
45 45
46-// bit_depth is always 8 in this crate: grain_center = 128 << (8 - 8) = 128.46+thread_local! {
47-const GRAIN_MIN: i32 = -128;47+ /// `params->bit_depth` of the picture currently being grained. libaom
48-const GRAIN_MAX: i32 = 127;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+}
49 65
50 const MIN_LUMA_LEGAL: i32 = 16;66 const MIN_LUMA_LEGAL: i32 = 16;
51 const MAX_LUMA_LEGAL: i32 = 235;67 const MAX_LUMA_LEGAL: i32 = 235;
@@ -121,11 +137,12 @@ fn generate_luma_grain_block(
121 pred_pos: &[(i32, i32, i32)],137 pred_pos: &[(i32, i32, i32)],
122 rng: &mut Rng,138 rng: &mut Rng,
123 ) -> Vec<i32> {139 ) -> Vec<i32> {
140+ let (grain_min, grain_max) = grain_range();
124 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];141 let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize];
125 if fg.num_y_points == 0 {142 if fg.num_y_points == 0 {
126 return block;143 return block;
127 }144 }
128- let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; // 12 - 8 + grain_scale_shift145+ let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32;
129 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;146 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
130 let rounding_offset = 1i32 << (ar_coeff_shift - 1);147 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
131 148
@@ -143,7 +160,7 @@ fn generate_luma_grain_block(
143 wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx);160 wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx);
144 }161 }
145 let v = (at(&block, LUMA_BLOCK_W, i, j) + ((wsum + rounding_offset) >> ar_coeff_shift))162 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);
147 set_at(&mut block, LUMA_BLOCK_W, i, j, v);164 set_at(&mut block, LUMA_BLOCK_W, i, j, v);
148 }165 }
149 }166 }
@@ -157,9 +174,10 @@ fn generate_chroma_grain_blocks(
157 luma_block: &[i32],174 luma_block: &[i32],
158 seed: u16,175 seed: u16,
159 ) -> (Vec<i32>, Vec<i32>) {176 ) -> (Vec<i32>, Vec<i32>) {
177+ let (grain_min, grain_max) = grain_range();
160 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];178 let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];
161 let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize];179 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;
163 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;181 let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6;
164 let rounding_offset = 1i32 << (ar_coeff_shift - 1);182 let rounding_offset = 1i32 << (ar_coeff_shift - 1);
165 183
@@ -226,13 +244,13 @@ fn generate_chroma_grain_blocks(
226 if apply_cb {244 if apply_cb {
227 let v = (at(&cb, CHROMA_BLOCK_W, i, j)245 let v = (at(&cb, CHROMA_BLOCK_W, i, j)
228 + ((wsum_cb + rounding_offset) >> ar_coeff_shift))246 + ((wsum_cb + rounding_offset) >> ar_coeff_shift))
229- .clamp(GRAIN_MIN, GRAIN_MAX);247+ .clamp(grain_min, grain_max);
230 set_at(&mut cb, CHROMA_BLOCK_W, i, j, v);248 set_at(&mut cb, CHROMA_BLOCK_W, i, j, v);
231 }249 }
232 if apply_cr {250 if apply_cr {
233 let v = (at(&cr, CHROMA_BLOCK_W, i, j)251 let v = (at(&cr, CHROMA_BLOCK_W, i, j)
234 + ((wsum_cr + rounding_offset) >> ar_coeff_shift))252 + ((wsum_cr + rounding_offset) >> ar_coeff_shift))
235- .clamp(GRAIN_MIN, GRAIN_MAX);253+ .clamp(grain_min, grain_max);
236 set_at(&mut cr, CHROMA_BLOCK_W, i, j, v);254 set_at(&mut cr, CHROMA_BLOCK_W, i, j, v);
237 }255 }
238 }256 }
@@ -265,7 +283,21 @@ fn build_scaling_lut(values: &[u8], scaling: &[u8], num_points: usize) -> [i32;
265 lut283 lut
266 }284 }
267 285
268-/// `add_noise_to_block` (spec 7.18.3.5), 8-bit / 4:2:0 only. `(py0, px0)` is286+/// `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
269 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,301 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,
270 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the302 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the
271 /// same function serves both the raw 82x73/44x38 templates and the small303 /// same function serves both the raw 82x73/44x38 templates and the small
@@ -295,13 +327,17 @@ fn add_noise_to_block(
295 let y_stride = picture.width as i32;327 let y_stride = picture.width as i32;
296 let c_stride = (picture.width / 2) as i32;328 let c_stride = (picture.width / 2) as i32;
297 let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8;329 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;
298 334
299 let mut cb_mult = fg.cb_mult as i32 - 128;335 let mut cb_mult = fg.cb_mult as i32 - 128;
300 let mut cb_luma_mult = fg.cb_luma_mult as i32 - 128;336 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);
302 let mut cr_mult = fg.cr_mult as i32 - 128;338 let mut cr_mult = fg.cr_mult as i32 - 128;
303 let mut cr_luma_mult = fg.cr_luma_mult as i32 - 128;339 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);
305 if fg.chroma_scaling_from_luma {341 if fg.chroma_scaling_from_luma {
306 cb_mult = 0;342 cb_mult = 0;
307 cb_luma_mult = 64;343 cb_luma_mult = 64;
@@ -318,21 +354,21 @@ fn add_noise_to_block(
318 let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range {354 let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range {
319 if mc_identity {355 if mc_identity {
320 (356 (
321- MIN_LUMA_LEGAL,357+ MIN_LUMA_LEGAL << bd_shift,
322- MAX_LUMA_LEGAL,358+ MAX_LUMA_LEGAL << bd_shift,
323- MIN_LUMA_LEGAL,359+ MIN_LUMA_LEGAL << bd_shift,
324- MAX_LUMA_LEGAL,360+ MAX_LUMA_LEGAL << bd_shift,
325 )361 )
326 } else {362 } else {
327 (363 (
328- MIN_LUMA_LEGAL,364+ MIN_LUMA_LEGAL << bd_shift,
329- MAX_LUMA_LEGAL,365+ MAX_LUMA_LEGAL << bd_shift,
330- MIN_CHROMA_LEGAL,366+ MIN_CHROMA_LEGAL << bd_shift,
331- MAX_CHROMA_LEGAL,367+ MAX_CHROMA_LEGAL << bd_shift,
332 )368 )
333 }369 }
334 } else {370 } else {
335- (0, 255, 0, 255)371+ (0, index_max, 0, index_max)
336 };372 };
337 373
338 let cy0 = py0 / 2;374 let cy0 = py0 / 2;
@@ -349,8 +385,9 @@ fn add_noise_to_block(
349 let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32)385 let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32)
350 >> 6)386 >> 6)
351 + cb_offset)387 + cb_offset)
352- .clamp(0, 255);388+ .clamp(0, index_max);
353- let delta = (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset)389+ let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx]
390+ + rounding_offset)
354 >> scaling_shift;391 >> scaling_shift;
355 picture.u[cidx] =392 picture.u[cidx] =
356 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;393 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
@@ -359,8 +396,9 @@ fn add_noise_to_block(
359 let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32)396 let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32)
360 >> 6)397 >> 6)
361 + cr_offset)398 + cr_offset)
362- .clamp(0, 255);399+ .clamp(0, index_max);
363- let delta = (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset)400+ let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx]
401+ + rounding_offset)
364 >> scaling_shift;402 >> scaling_shift;
365 picture.v[cidx] =403 picture.v[cidx] =
366 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;404 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
@@ -372,7 +410,8 @@ fn add_noise_to_block(
372 for j in 0..half_w * 2 {410 for j in 0..half_w * 2 {
373 let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize;411 let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize;
374 let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize;412 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]
376 + rounding_offset)415 + rounding_offset)
377 >> scaling_shift;416 >> scaling_shift;
378 picture.y[pidx] =417 picture.y[pidx] =
@@ -398,6 +437,7 @@ fn ver_overlap_inplace(
398 width: i32,437 width: i32,
399 height: i32,438 height: i32,
400 ) {439 ) {
440+ let (grain_min, grain_max) = grain_range();
401 for h in 0..height {441 for h in 0..height {
402 if width == 1 {442 if width == 1 {
403 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);443 let l = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -407,7 +447,7 @@ fn ver_overlap_inplace(
407 dst_stride,447 dst_stride,
408 dst_row0 + h,448 dst_row0 + h,
409 dst_col0,449 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),
411 );451 );
412 } else {452 } else {
413 let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0);453 let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0);
@@ -419,14 +459,14 @@ fn ver_overlap_inplace(
419 dst_stride,459 dst_stride,
420 dst_row0 + h,460 dst_row0 + h,
421 dst_col0,461 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),
423 );463 );
424 set_at(464 set_at(
425 dst,465 dst,
426 dst_stride,466 dst_stride,
427 dst_row0 + h,467 dst_row0 + h,
428 dst_col0 + 1,468 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),
430 );470 );
431 }471 }
432 }472 }
@@ -447,6 +487,7 @@ fn hor_overlap_inplace(
447 width: i32,487 width: i32,
448 height: i32,488 height: i32,
449 ) {489 ) {
490+ let (grain_min, grain_max) = grain_range();
450 if height == 1 {491 if height == 1 {
451 for w in 0..width {492 for w in 0..width {
452 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);493 let t = at(dst, dst_stride, dst_row0, dst_col0 + w);
@@ -456,7 +497,7 @@ fn hor_overlap_inplace(
456 dst_stride,497 dst_stride,
457 dst_row0,498 dst_row0,
458 dst_col0 + w,499 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),
460 );501 );
461 }502 }
462 } else {503 } else {
@@ -470,14 +511,14 @@ fn hor_overlap_inplace(
470 dst_stride,511 dst_stride,
471 dst_row0,512 dst_row0,
472 dst_col0 + w,513 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),
474 );515 );
475 set_at(516 set_at(
476 dst,517 dst,
477 dst_stride,518 dst_stride,
478 dst_row0 + 1,519 dst_row0 + 1,
479 dst_col0 + w,520 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),
481 );522 );
482 }523 }
483 }524 }
@@ -496,6 +537,7 @@ fn copy_area(
496 width: i32,537 width: i32,
497 height: i32,538 height: i32,
498 ) {539 ) {
540+ let (grain_min, grain_max) = grain_range();
499 for h in 0..height {541 for h in 0..height {
500 for w in 0..width {542 for w in 0..width {
501 let v = at(src, src_stride, src_row0 + h, src_col0 + w);543 let v = at(src, src_stride, src_row0 + h, src_col0 + w);
@@ -504,15 +546,33 @@ fn copy_area(
504 }546 }
505 }547 }
506 548
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+
507 /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and560 /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and
508 /// apply film grain to `picture`, returning a new grained picture. `picture`561 /// apply film grain to `picture`, returning a new grained picture. `picture`
509 /// itself is unchanged -- it stays the clean reference-frame-bank copy.562 /// itself is unchanged -- it stays the clean reference-frame-bank copy.
510 /// Returns `picture.clone()` untouched when `apply_grain` is unset.563 /// 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 {
512 let mut out = picture.clone();570 let mut out = picture.clone();
513 if !fg.apply_grain {571 if !fg.apply_grain {
514 return out;572 return out;
515 }573 }
574+ GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth));
575+ GRAIN_HITS.with(|c| c.set(c.get() + 1));
516 let width = out.width as i32;576 let width = out.width as i32;
517 let height = out.height as i32;577 let height = out.height as i32;
518 let y_stride = width;578 let y_stride = width;
crates/ec-av1/src/gate_coverage.rsmodified+7 -1
@@ -33,7 +33,13 @@
33 /// its tool is now covered by a real stream.33 /// its tool is now covered by a real stream.
34 #[cfg(test)]34 #[cfg(test)]
35 const NEVER_EXERCISED: &[(&str, &str)] = &[35 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"),
37 ];43 ];
38 44
39 #[cfg(test)]45 #[cfg(test)]
crates/ec-av1/src/intra.rsmodified+26 -18
@@ -726,37 +726,45 @@ const FILTER_INTRA_SCALE_BITS: u32 = 4;
726 /// though this mode itself never reaches past its own `side` samples of726 /// though this mode itself never reaches past its own `side` samples of
727 /// either edge.727 /// either edge.
728 ///728 ///
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+///
729 /// # Panics735 /// # Panics
730-/// Panics when `dst` is not `side * side` long, or `side` is not a multiple736+/// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4
731-/// of 4 (spec `av1_filter_intra_allowed_bsize` never offers this mode past737+/// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never
732-/// 32x32, and only on square blocks: 4, 8, 16 or 32).738+/// offers this mode past 32x32).
733 pub fn predict_filter_intra(739 pub fn predict_filter_intra(
734 mode: usize,740 mode: usize,
735 above: Option<&[u16]>,741 above: Option<&[u16]>,
736 left: Option<&[u16]>,742 left: Option<&[u16]>,
737 corner: Option<u16>,743 corner: Option<u16>,
738- side: usize,744+ bw: usize,
745+ bh: usize,
739 dst: &mut [u16],746 dst: &mut [u16],
740 ) {747 ) {
741- assert_eq!(dst.len(), side * side, "the destination is the block");748+ assert_eq!(dst.len(), bw * bh, "the destination is the block");
742- assert_eq!(side % 4, 0, "filter intra only offers 4/8/16/32");749+ assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
743- let edges = Edges::build(above, left, corner, side, side);750+ assert_eq!(bh % 2, 0, "filter intra patches are 2 high");
751+ let edges = Edges::build(above, left, corner, bw, bh);
744 let taps = &FILTER_INTRA_TAPS[mode];752 let taps = &FILTER_INTRA_TAPS[mode];
745 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the753 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the
746 // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c).754 // 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)];755+ let mut buffer = vec![0i32; (bh + 1) * (bw + 1)];
748- let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (side + 1) + c];756+ let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (bw + 1) + c];
749 buffer[0] = edges.above(-1);757 buffer[0] = edges.above(-1);
750- for c in 0..side {758+ for c in 0..bw {
751 buffer[c + 1] = edges.above(c as i32);759 buffer[c + 1] = edges.above(c as i32);
752 }760 }
753- for r in 0..side {761+ for r in 0..bh {
754- buffer[(r + 1) * (side + 1)] = edges.left(r as i32);762+ buffer[(r + 1) * (bw + 1)] = edges.left(r as i32);
755 }763 }
756 let mut r = 1;764 let mut r = 1;
757- while r < side + 1 {765+ while r < bh + 1 {
758 let mut c = 1;766 let mut c = 1;
759- while c < side + 1 {767+ while c < bw + 1 {
760 let p0 = at(&buffer, r - 1, c - 1);768 let p0 = at(&buffer, r - 1, c - 1);
761 let p1 = at(&buffer, r - 1, c);769 let p1 = at(&buffer, r - 1, c);
762 let p2 = at(&buffer, r - 1, c + 1);770 let p2 = at(&buffer, r - 1, c + 1);
@@ -769,16 +777,16 @@ pub fn predict_filter_intra(
769 let (r_off, c_off) = (k >> 2, k & 3);777 let (r_off, c_off) = (k >> 2, k & 3);
770 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();778 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();
771 let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max());779 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;
773 buffer[idx] = value;781 buffer[idx] = value;
774 }782 }
775 c += 4;783 c += 4;
776 }784 }
777 r += 2;785 r += 2;
778 }786 }
779- for row in 0..side {787+ for row in 0..bh {
780- for col in 0..side {788+ for col in 0..bw {
781- dst[row * side + col] = at(&buffer, row + 1, col + 1) as u16;789+ dst[row * bw + col] = at(&buffer, row + 1, col + 1) as u16;
782 }790 }
783 }791 }
784 }792 }
crates/ec-av1/src/mvstack.rsmodified+12 -0
@@ -327,6 +327,13 @@ fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32)
327 /// `LAST_FRAME`) pass an all-`false` table, matching this stub's old327 /// `LAST_FRAME`) pass an all-`false` table, matching this stub's old
328 /// always-`false` behaviour exactly.328 /// always-`false` behaviour exactly.
329 fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool {329 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+ }
330 table[(ref_frame - LAST_FRAME) as usize]337 table[(ref_frame - LAST_FRAME) as usize]
331 }338 }
332 339
@@ -359,6 +366,11 @@ pub const NO_GM_MV: GmMvTable = [(0, 0); 7];
359 /// `table[ref_frame - LAST_FRAME]`, [`sign_bias`]'s shape for a366 /// `table[ref_frame - LAST_FRAME]`, [`sign_bias`]'s shape for a
360 /// [`GmMvTable`].367 /// [`GmMvTable`].
361 fn gm_mv(table: &GmMvTable, ref_frame: i8) -> (i32, i32) {368 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+ }
362 table[(ref_frame - LAST_FRAME) as usize]374 table[(ref_frame - LAST_FRAME) as usize]
363 }375 }
364 376
crates/ec-av1/src/refusal_inventory.rsmodified+4 -5
@@ -37,27 +37,26 @@ const REFUSALS: &[&str] = &[
37 "GLOBALMV (round 3)",37 "GLOBALMV (round 3)",
38 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)",38 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)",
39 "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)",39 "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)",
40 "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)",42 "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)",
41 "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",43 "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
42 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",44 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
43 "a 32x32 partition type this decoder does not code (value={part32})",45 "a 32x32 partition type this decoder does not code (value={part32})",
44 "a Golomb tail longer than this decoder reads",46 "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)",
47 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)",47 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)",
48 "a tx_type symbol outside its CDF's own set: {t}",48 "a tx_type symbol outside its CDF's own set: {t}",
49 "an INTER 32x32 partition type this decoder does not code (value={part32})",49 "an INTER 32x32 partition type this decoder does not code (value={part32})",
50 "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)",50 "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)",
52 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",51 "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
53 "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)",52 "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)",
54 "a block that actually uses a palette (UV) -- reconstruction is out of scope",53 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
55 "a block that actually uses a palette (Y) -- reconstruction is out of scope",54 "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)",
57 "a frame OBU with no tile group",56 "a frame OBU with no tile group",
58 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",57 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
59 "a frame with no mode-info grid",58 "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)",
61 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",60 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
62 "a reference frame other than LAST_FRAME (round 2)",61 "a reference frame other than LAST_FRAME (round 2)",
63 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",62 "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 @@
16 //! an implementation detail of how this crate happens to build it).16 //! an implementation detail of how this crate happens to build it).
17 17
18 use ec_av1_syntax::{18 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,
20 WarpModel,21 WarpModel,
21 };22 };
22 use ec_core::{Error, Result};23 use ec_core::{Error, Result};
@@ -74,6 +75,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
74 // own end-of-tile adapted table, or (when the frame set75 // own end-of-tile adapted table, or (when the frame set
75 // `disable_frame_end_update_cdf`) the table it started from, unchanged.76 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
76 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);77 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);
77 84
78 let mut pos = 0usize;85 let mut pos = 0usize;
79 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec86 // 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>> {
124 cdf_slots[i] = cdf_slots[slot].clone();131 cdf_slots[i] = cdf_slots[slot].clone();
125 ref_slots[i] = Some(picture.clone());132 ref_slots[i] = Some(picture.clone());
126 motion_field_slots[i] = motion_field_slots[slot].clone();133 motion_field_slots[i] = motion_field_slots[slot].clone();
134+ seg_map_slots[i] = seg_map_slots[slot].clone();
127 order_hint_slots[i] = order_hint_slots[slot];135 order_hint_slots[i] = order_hint_slots[slot];
128 }136 }
129 }137 }
130 let output = if header.film_grain.apply_grain {138 let output = if header.film_grain.apply_grain {
131- // lane-hbd r5: `film_grain.rs`'s grain LUT and blend are139+ // lane-hbd10 r1: grain synthesis is bit-depth generic
132- // hardcoded 8-bit (`[i32; 256]`, clamps at 255) -- narrowed140+ // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
133- // from the old blanket bit-depth refusal to only the case
134- // that actually reaches unported code.
135 let bit_depth = parser141 let bit_depth = parser
136 .sequence_header()142 .sequence_header()
137 .map_or(8, |seq| seq.color_config.bit_depth);143 .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- }
144 let mc_identity = parser144 let mc_identity = parser
145 .sequence_header()145 .sequence_header()
146 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);146 .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+ )
148 } else {153 } else {
149 picture154 picture
150 };155 };
@@ -245,12 +250,41 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
245 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes250 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
246 // will show up as a real pixel mismatch, not a silent truncation --251 // will show up as a real pixel mismatch, not a silent truncation --
247 // the whole reason the widen (and this wiring) happened.252 // 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`.
248 if header.segmentation.enabled {263 if header.segmentation.enabled {
249- return Err(Error::unsupported(264+ for segment in 0..MAX_SEGMENTS {
250- "AV1 decode_stream",265+ for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
251- "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",266+ if header.segmentation.feature_enabled[segment][feature] {
252- ));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+ }
253 }274 }
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+ );
254 // lane-superres stage 2/3: `use_superres` adds/removes no per-block288 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
255 // symbol (spec 7.16's upscaling is a pixel-domain post-process289 // symbol (spec 7.16's upscaling is a pixel-domain post-process
256 // libaom's `decodeframe.c` runs between CDEF and loop restoration,290 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
@@ -509,20 +543,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
509 // call above, right before anything else can overwrite it) --543 // call above, right before anything else can overwrite it) --
510 // see `decode::take_last_frame_wide_margin`'s doc.544 // see `decode::take_last_frame_wide_margin`'s doc.
511 let wide_margin = crate::decode::take_last_frame_wide_margin();545 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- }
521 let picture = if header.use_superres {546 let picture = if header.use_superres {
522 crate::superres::upscale_picture(547 crate::superres::upscale_picture(
523 &picture,548 &picture,
524 header.upscaled_width as usize,549 header.upscaled_width as usize,
525 wide_margin.as_ref(),550 wide_margin.as_ref(),
551+ bit_depth as u32,
526 )552 )
527 } else {553 } else {
528 picture554 picture
@@ -634,6 +660,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
634 &picture,660 &picture,
635 header.upscaled_width as usize,661 header.upscaled_width as usize,
636 wide_margin.as_ref(),662 wide_margin.as_ref(),
663+ bit_depth as u32,
637 )664 )
638 } else {665 } else {
639 picture666 picture
@@ -696,6 +723,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
696 }723 }
697 }724 }
698 pictures_decoded += 1;725 pictures_decoded += 1;
726+ let decoded_seg_map = decode::take_segment_ids();
699 for i in 0..NUM_REF_FRAMES {727 for i in 0..NUM_REF_FRAMES {
700 if header.refresh_frame_flags & (1 << i) != 0 {728 if header.refresh_frame_flags & (1 << i) != 0 {
701 cdf_slots[i] = Some(stored_cdfs.clone());729 cdf_slots[i] = Some(stored_cdfs.clone());
@@ -705,23 +733,21 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
705 // caller's output below carries the grained picture.733 // caller's output below carries the grained picture.
706 ref_slots[i] = Some(picture.clone());734 ref_slots[i] = Some(picture.clone());
707 motion_field_slots[i] = Some(motion_field.clone());735 motion_field_slots[i] = Some(motion_field.clone());
736+ seg_map_slots[i] = Some(decoded_seg_map.clone());
708 order_hint_slots[i] = header.order_hint;737 order_hint_slots[i] = header.order_hint;
709 }738 }
710 }739 }
711 if header.show_frame {740 if header.show_frame {
712 let output = if header.film_grain.apply_grain {741 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- }
721 let mc_identity = parser742 let mc_identity = parser
722 .sequence_header()743 .sequence_header()
723 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);744 .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+ )
725 } else {751 } else {
726 picture752 picture
727 };753 };
@@ -880,13 +906,27 @@ mod tests {
880 hash906 hash
881 }907 }
882 908
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).
883 fn have_ffmpeg() -> bool {916 fn have_ffmpeg() -> bool {
884- Command::new("ffmpeg")917+ let present = Command::new("ffmpeg")
885 .arg("-version")918 .arg("-version")
886 .stdout(Stdio::null())919 .stdout(Stdio::null())
887 .stderr(Stdio::null())920 .stderr(Stdio::null())
888 .status()921 .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
890 }930 }
891 931
892 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.932 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
@@ -1942,6 +1982,237 @@ mod tests {
1942 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");1982 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
1943 }1983 }
1944 1984
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+
1945 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`2216 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
1946 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive2217 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
1947 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,2218 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
@@ -6705,20 +6976,23 @@ mod tests {
6705 crate::decode::cdef_idx_hits()6976 crate::decode::cdef_idx_hits()
6706 );6977 );
6707 }6978 }
6708- /// lane-tiny r1 diagnostic (not a gate): sweeps tiny key-frame sizes6979+ /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame
6709- /// against real aomenc + ffmpeg to find the exact size boundary of the6980+ /// size real aomenc will encode, decoded pixel-exact against ffmpeg.
6710- /// silent-wrong-pixels defect the sub8 lane's r2 dead-end flagged (a6981+ /// Tiny frames are where every edge/partial-superblock corner case is
6711- /// plain 16x16 stream, no exotic tools). `#[ignore]`d -- prints a6982+ /// forced, and this sweep is what found both r3's filter-intra tx_type
6712- /// pass/fail table, asserts nothing; run manually with `--nocapture`.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.
6713 #[test]6987 #[test]
6714- #[ignore = "diagnostic sweep, run manually with --nocapture"]6988+ fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() {
6715- fn probe_tiny_frame_size_boundary() {
6716 if !have_ffmpeg() || !have_aomenc() {6989 if !have_ffmpeg() || !have_aomenc() {
6717 eprintln!("SKIP: no ffmpeg/aomenc");6990 eprintln!("SKIP: no ffmpeg/aomenc");
6718 return;6991 return;
6719 }6992 }
6720 let sizes: &[(usize, usize)] =6993 let sizes: &[(usize, usize)] =
6721 &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)];6994 &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)];
6995+ let mut total_exact = 0u32;
6722 for &(width, height) in sizes {6996 for &(width, height) in sizes {
6723 let mut ok = 0u32;6997 let mut ok = 0u32;
6724 let mut bad = 0u32;6998 let mut bad = 0u32;
@@ -6767,7 +7041,18 @@ mod tests {
6767 let stream = out.stdout;7041 let stream = out.stdout;
6768 let frames = match decode_stream(&stream) {7042 let frames = match decode_stream(&stream) {
6769 Err(e) => {7043 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}");
6771 refused += 1;7056 refused += 1;
6772 continue;7057 continue;
6773 }7058 }
@@ -6782,6 +7067,12 @@ mod tests {
6782 ok += 1;7067 ok += 1;
6783 } else {7068 } else {
6784 bad += 1;7069 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+ );
6785 let mut first = None;7076 let mut first = None;
6786 for row in 0..height {7077 for row in 0..height {
6787 for col in 0..width {7078 for col in 0..width {
@@ -6802,13 +7093,32 @@ mod tests {
6802 .filter(|(a, b)| a != b)7093 .filter(|(a, b)| a != b)
6803 .count();7094 .count();
6804 eprintln!(7095 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}",
6806 width * height7098 width * height
6807 );7099 );
6808 }7100 }
6809 }7101 }
6810- eprintln!("{width}x{height}: {ok} ok / {bad} mismatch / {refused} refused (of {n})");7102+ assert_eq!(
6811- }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");
6812 }7122 }
6813 7123
6814 /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with7124 /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with
@@ -8988,45 +9298,55 @@ mod tests {
8988 );9298 );
8989 }9299 }
8990 9300
8991- /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without9301+ /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active.
8992- /// -- a real >1-tile-column stream with a genuine INTER frame (not just9302+ /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two
8993- /// the key-frame-only two-column gate above), decoded through9303+ /// paths libaom uses to switch `segmentation_enabled` on by itself
8994- /// `decode_stream` itself. Same recipe as the key-frame gate9304+ /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only
8995- /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the9305+ /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock
8996- /// same feature-disable envelope so the gate isolates the tile loop, not9306+ /// delta-q reader out of the picture so a mismatch points at the segment
8997- /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000`9307+ /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is
8998- /// so frame 1 is a real inter frame, and `gradients_source`'s default9308+ /// what gives variance/complexity AQ different segments to assign --
8999- /// `speed=0.01` rotation (undisturbed -- not overridden by the tail)9309+ /// a flat gradient collapses every block onto one segment, which the
9000- /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_9310+ /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run.
9001- /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually9311+ /// The rest of the recipe is the delta-q gate's own feature-disable
9002- /// have to walk a live MV stack across the tile-column boundary, not9312+ /// envelope, so this gate isolates the segmentation reader.
9003- /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (29313+ fn run_segmentation_gate(
9004- /// frames at rate=25) per the class in ledger9314+ name: &str,
9005- /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole-9315+ aq_mode: &str,
9006- /// file` (never leave an ffmpeg/lavfi generate unbounded).9316+ bit_depth: usize,
9007- #[test]9317+ frame_count: usize,
9008- fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() {9318+ rate_args: &[&str],
9009- const NAME: &str =9319+ ) {
9010- "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact";9320+ let _gate_lock = lock_gate_counters();
9011 if !have_ffmpeg() {9321 if !have_ffmpeg() {
9012- eprintln!("SKIP {NAME}: no ffmpeg");9322+ eprintln!("SKIP {name}: no ffmpeg");
9013 return;9323 return;
9014 }9324 }
9015 if !have_aomenc() {9325 if !have_aomenc() {
9016- eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());9326+ eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
9017 return;9327 return;
9018 }9328 }
9329+ crate::decode::reset_segment_hits();
9019 let (width, height) = (128usize, 64usize);9330 let (width, height) = (128usize, 64usize);
9020- let frames = 2usize;
9021- let mut matched = 0u32;
9022 let mut named_refusals = 0u32;9331 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 {
9024 let seed = 42 + attempt;9338 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" };
9026 let y4m = Command::new("ffmpeg")9346 let y4m = Command::new("ffmpeg")
9027 .args([9347 .args([
9028- "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",9348+ "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
9029- "yuv4mpegpipe", "-",9349+ "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
9030 ])9350 ])
9031 .stdin(Stdio::null())9351 .stdin(Stdio::null())
9032 .stdout(Stdio::piped())9352 .stdout(Stdio::piped())
@@ -9038,43 +9358,310 @@ mod tests {
9038 "ffmpeg fixture: {}",9358 "ffmpeg fixture: {}",
9039 String::from_utf8_lossy(&y4m.stderr)9359 String::from_utf8_lossy(&y4m.stderr)
9040 );9360 );
9041- let mut child = Command::new(aomenc_path())9361+ let depth_args: Vec<String> = if bit_depth == 10 {
9042- .args([9362+ vec!["--input-bit-depth=10".to_owned(), "--bit-depth=10".to_owned()]
9043- "--codec=av1",9363+ } else {
9044- "--passes=1",9364+ Vec::new()
9045- "--end-usage=q",9365+ };
9046- "--cq-level=45",9366+ let aq = format!("--aq-mode={aq_mode}");
9047- "--cpu-used=0",9367+ let mut args: Vec<&str> = vec![
9048- &format!("--limit={frames}"),9368+ "--codec=av1",
9049- "--kf-max-dist=1000",9369+ "--passes=1",
9050- "--lag-in-frames=0",9370+ "--cpu-used=4",
9051- "--auto-alt-ref=0",9371+ &aq,
9052- "--threads=1",9372+ "--deltaq-mode=0",
9053- "--row-mt=0",9373+ "--kf-max-dist=1000",
9054- "--tile-columns=1",9374+ "--threads=1",
9055- "--tile-rows=0",9375+ "--row-mt=0",
9056- "--sb-size=64",9376+ "--sb-size=64",
9057- "--loopfilter-control=0",9377+ "--auto-alt-ref=1",
9058- "--max-reference-frames=3",9378+ "--lag-in-frames=16",
9059- "--reduced-reference-set=1",9379+ "--enable-fwd-kf=0",
9060- "--enable-warped-motion=0",9380+ "--enable-order-hint=1",
9061- "--enable-obmc=0",9381+ "--enable-warped-motion=1",
9062- "--enable-masked-comp=0",9382+ "--enable-global-motion=0",
9063- "--enable-interintra-comp=0",9383+ "--enable-obmc=1",
9064- "--enable-dist-wtd-comp=0",9384+ "--tune-content=default",
9065- "--enable-diff-wtd-comp=0",9385+ "--enable-masked-comp=1",
9066- "--enable-onesided-comp=0",9386+ "--enable-dist-wtd-comp=0",
9067- "--enable-interintra-wedge=0",9387+ "--enable-interintra-comp=1",
9068- "--enable-smooth-interintra=0",9388+ "--enable-onesided-comp=0",
9069- "--enable-ref-frame-mvs=0",9389+ "--enable-interintra-wedge=0",
9070- "--enable-rect-partitions=0",9390+ "--enable-smooth-interintra=1",
9071- "--enable-ab-partitions=0",9391+ "--enable-rect-partitions=0",
9072- "--enable-1to4-partitions=0",9392+ "--enable-ab-partitions=0",
9073- "--enable-filter-intra=0",9393+ "--enable-1to4-partitions=0",
9074- "--enable-smooth-intra=0",9394+ "--enable-filter-intra=0",
9075- "--enable-paeth-intra=0",9395+ "--enable-smooth-intra=0",
9076- "--enable-directional-intra=0",9396+ "--enable-paeth-intra=0",
9077- "--enable-angle-delta=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",
9078 "--enable-tx-size-search=0",9665 "--enable-tx-size-search=0",
9079 "--enable-cdef=0",9666 "--enable-cdef=0",
9080 "--enable-restoration=0",9667 "--enable-restoration=0",
@@ -9677,6 +10264,549 @@ mod tests {
9677 );10264 );
9678 }10265 }
9679 10266
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+
9680 /// lane-rect64q r1: same recipe as10810 /// lane-rect64q r1: same recipe as
9681 /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]10811 /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
9682 /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is10812 /// 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 {
89 /// true, replicating the row's own edge pixels rather than sampling a89 /// true, replicating the row's own edge pixels rather than sampling a
90 /// neighbour tile). `in_width` and `out_width` must both be positive;90 /// neighbour tile). `in_width` and `out_width` must both be positive;
91 /// `row.len() == in_width` and `out.len() == out_width`.91 /// `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+) {
93 let in_width = row.len();102 let in_width = row.len();
94 debug_assert!(in_width > 0 && out_width > 0);103 debug_assert!(in_width > 0 && out_width > 0);
95 debug_assert_eq!(out.len(), out_width);104 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
109 // column-by-column against real libaom via `scripts/superres-pin-118 // column-by-column against real libaom via `scripts/superres-pin-
110 // harness.c`'s `row6-realedgeval` case (r3).119 // harness.c`'s `row6-realedgeval` case (r3).
111 let pad = UPSCALE_NORMATIVE_TAPS + 2;120 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];
113 padded[..pad].fill(row[0]);122 padded[..pad].fill(row[0]);
114 padded[pad..pad + in_width].copy_from_slice(row);123 padded[pad..pad + in_width].copy_from_slice(row);
115 let real_n = real_right_margin.len().min(pad);124 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
131 let idx = base + int_pel + k as i64;140 let idx = base + int_pel + k as i64;
132 sum += padded[idx as usize] as i32 * c as i32;141 sum += padded[idx as usize] as i32 * c as i32;
133 }142 }
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;
135 x_qn += x_step_qn;144 x_qn += x_step_qn;
136 }145 }
137 }146 }
@@ -141,14 +150,15 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize
141 /// spec only widens columns). `rows` is the plane's row-major byte buffer150 /// spec only widens columns). `rows` is the plane's row-major byte buffer
142 /// at `in_width`; returns a new buffer at `out_width`.151 /// at `in_width`; returns a new buffer at `out_width`.
143 pub(crate) fn upscale_plane(152 pub(crate) fn upscale_plane(
144- rows: &[u8],153+ rows: &[u16],
145 height: usize,154 height: usize,
146 in_width: usize,155 in_width: usize,
147 out_width: usize,156 out_width: usize,
148- margin: Option<(&[u8], usize)>,157+ margin: Option<(&[u16], usize)>,
149-) -> Vec<u8> {158+ bit_depth: u32,
159+) -> Vec<u16> {
150 debug_assert_eq!(rows.len(), height * in_width);160 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];
152 for r in 0..height {162 for r in 0..height {
153 let src = &rows[r * in_width..(r + 1) * in_width];163 let src = &rows[r * in_width..(r + 1) * in_width];
154 let dst = &mut out[r * out_width..(r + 1) * out_width];164 let dst = &mut out[r * out_width..(r + 1) * out_width];
@@ -158,7 +168,7 @@ pub(crate) fn upscale_plane(
158 }168 }
159 _ => &[],169 _ => &[],
160 };170 };
161- upscale_row(src, real_right, out_width, dst);171+ upscale_row(src, real_right, out_width, dst, bit_depth);
162 }172 }
163 out173 out
164 }174 }
@@ -185,51 +195,40 @@ pub(crate) fn upscale_picture(
185 picture: &crate::encode::Picture,195 picture: &crate::encode::Picture,
186 upscaled_width: usize,196 upscaled_width: usize,
187 margin: Option<&crate::encode::Picture>,197 margin: Option<&crate::encode::Picture>,
198+ bit_depth: u32,
188 ) -> crate::encode::Picture {199 ) -> crate::encode::Picture {
189 SUPERRES_HITS.with(|c| c.set(c.get() + 1));200 SUPERRES_HITS.with(|c| c.set(c.get() + 1));
190 let height = picture.height;201 let height = picture.height;
191 let chroma_in_w = picture.width.div_ceil(2);202 let chroma_in_w = picture.width.div_ceil(2);
192 let chroma_out_w = upscaled_width.div_ceil(2);203 let chroma_out_w = upscaled_width.div_ceil(2);
193 let chroma_h = height.div_ceil(2);204 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() };
205 crate::encode::Picture {205 crate::encode::Picture {
206 width: upscaled_width,206 width: upscaled_width,
207 height,207 height,
208- y: widen(upscale_plane(208+ y: upscale_plane(
209- &picture_y8,209+ &picture.y,
210 height,210 height,
211 picture.width,211 picture.width,
212 upscaled_width,212 upscaled_width,
213- margin_y8.as_deref().map(|m| (m, margin.unwrap().width)),213+ margin.map(|m| (m.y.as_slice(), m.width)),
214- )),214+ bit_depth,
215- u: widen(upscale_plane(215+ ),
216- &picture_u8,216+ u: upscale_plane(
217+ &picture.u,
217 chroma_h,218 chroma_h,
218 chroma_in_w,219 chroma_in_w,
219 chroma_out_w,220 chroma_out_w,
220- margin_u8221+ margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))),
221- .as_deref()222+ bit_depth,
222- .map(|m| (m, margin.unwrap().width.div_ceil(2))),223+ ),
223- )),224+ v: upscale_plane(
224- v: widen(upscale_plane(225+ &picture.v,
225- &picture_v8,
226 chroma_h,226 chroma_h,
227 chroma_in_w,227 chroma_in_w,
228 chroma_out_w,228 chroma_out_w,
229- margin_v8229+ margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))),
230- .as_deref()230+ bit_depth,
231- .map(|m| (m, margin.unwrap().width.div_ceil(2))),231+ ),
232- )),
233 }232 }
234 }233 }
235 234
@@ -249,17 +248,17 @@ mod tests {
249 /// here independently of this module's own logic.248 /// here independently of this module's own logic.
250 #[test]249 #[test]
251 fn upscale_row_matches_libaom_in8_out12() {250 fn upscale_row_matches_libaom_in8_out12() {
252- let row = [10u8, 20, 30, 40, 50, 60, 70, 80];251+ let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
253- let mut out = [0u8; 12];252+ let mut out = [0u16; 12];
254- upscale_row(&row, &[], 12, &mut out);253+ upscale_row(&row, &[], 12, &mut out, 8);
255 assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]);254 assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]);
256 }255 }
257 256
258 #[test]257 #[test]
259 fn upscale_row_matches_libaom_in8_out16() {258 fn upscale_row_matches_libaom_in8_out16() {
260- let row = [10u8, 20, 30, 40, 50, 60, 70, 80];259+ let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
261- let mut out = [0u8; 16];260+ let mut out = [0u16; 16];
262- upscale_row(&row, &[], 16, &mut out);261+ upscale_row(&row, &[], 16, &mut out, 8);
263 assert_eq!(262 assert_eq!(
264 out,263 out,
265 [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81]264 [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81]
@@ -273,10 +272,10 @@ mod tests {
273 /// captured-row pins above.272 /// captured-row pins above.
274 #[test]273 #[test]
275 fn upscale_row_of_a_flat_input_is_flat() {274 fn upscale_row_of_a_flat_input_is_flat() {
276- let row = [200u8; 8];275+ let row = [200u16; 8];
277- let mut out = [0u8; 12];276+ let mut out = [0u16; 12];
278- upscale_row(&row, &[], 12, &mut out);277+ upscale_row(&row, &[], 12, &mut out, 8);
279- assert_eq!(out, [200u8; 12]);278+ assert_eq!(out, [200u16; 12]);
280 }279 }
281 280
282 /// r3: the real 43->64 failing case, pinned against real libaom281 /// r3: the real 43->64 failing case, pinned against real libaom
@@ -287,14 +286,14 @@ mod tests {
287 /// margin fix.286 /// margin fix.
288 #[test]287 #[test]
289 fn upscale_row_with_real_margin_matches_libaom_in43_out64() {288 fn upscale_row_with_real_margin_matches_libaom_in43_out64() {
290- let row: [u8; 43] = [289+ let row: [u16; 43] = [
291 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,290 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
292 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131,291 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131,
293 133, 134, 136, 137, 138, 139, 140, 140, 141,292 133, 134, 136, 137, 138, 139, 140, 140, 141,
294 ];293 ];
295- let real_margin = [140u8];294+ let real_margin = [140u16];
296- let mut out = [0u8; 64];295+ let mut out = [0u16; 64];
297- upscale_row(&row, &real_margin, 64, &mut out);296+ upscale_row(&row, &real_margin, 64, &mut out, 8);
298 assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140");297 assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140");
299 }298 }
300 }299 }
crates/ec-av1/src/tile.rsmodified+16 -2
@@ -2983,13 +2983,27 @@ mod tests {
2983 }2983 }
2984 }2984 }
2985 2985
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).
2986 fn have_ffmpeg() -> bool {2993 fn have_ffmpeg() -> bool {
2987- Command::new("ffmpeg")2994+ let present = Command::new("ffmpeg")
2988 .arg("-version")2995 .arg("-version")
2989 .stdout(Stdio::null())2996 .stdout(Stdio::null())
2990 .stderr(Stdio::null())2997 .stderr(Stdio::null())
2991 .status()2998 .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
2993 }3007 }
2994 3008
2995 /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.3009 /// 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).