diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index a7edca41..8b0452a7 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -32,7 +32,22 @@ fn main() { Ok(frames) if frames.is_empty() => { println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?"); } - Ok(frames) => println!("OK: {} frames decoded", frames.len()), + Ok(frames) => { + println!("OK: {} frames decoded", frames.len()); + // Optional second arg: dump the decoded planes as raw yuv420p so a + // pixel diff against `ffmpeg -i s.obu -f rawvideo` needs no test harness. + if let Some(out) = std::env::args().nth(2) { + // 8-bit only: planes are u16, take the low byte. + let mut buf: Vec = Vec::new(); + for f in &frames { + for p in [&f.y, &f.u, &f.v] { + buf.extend(p.iter().map(|&s| s as u8)); + } + } + std::fs::write(&out, &buf).expect("writing raw planes"); + println!("wrote {} bytes of yuv420p to {out}", buf.len()); + } + } Err(e) => println!("REFUSED: {e}"), } } diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index a097ea79..e1a55089 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -561,6 +561,19 @@ pub const RESTORE_SWITCHABLE: [u16; 4] = [9413, 22581, 32768, 0]; /// 4-symbol `delta_q_abs` alphabet read once per superblock when /// `delta_q_present` is set. `default_delta_lf_cdf`/`default_delta_lf_multi_cdf` /// share this same value (verified against libaom's real source). +/// `Default_Segment_Id_Cdf` (spec 9.4, libaom +/// `default_spatial_pred_seg_tree_cdf`): the `segment_id` symbol's eight +/// segments, indexed by the spec 5.11.8 neighbour-agreement context. +pub const SEGMENT_ID: [[u16; 9]; 3] = [ + [5622, 7893, 16093, 18233, 27809, 28373, 32533, 32768, 0], + [14274, 18230, 22557, 24935, 29980, 30851, 32344, 32768, 0], + [27527, 28487, 28723, 28890, 32397, 32647, 32679, 32768, 0], +]; + +/// `Default_Segment_Pred_Cdf` (spec 9.4, libaom `default_segment_pred_cdf`): +/// `seg_id_predicted`, indexed by `AboveSegPredContext + LeftSegPredContext`. +pub const SEGMENT_PRED: [[u16; 3]; 3] = [[16384, 32768, 0]; 3]; + pub const DELTA_Q: [u16; 5] = [28160, 32120, 32677, 32768, 0]; /// `default_delta_lf_cdf` -- see [`DELTA_Q`]'s doc. pub const DELTA_LF: [u16; 5] = DELTA_Q; diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 330dcad8..53f1c13b 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -420,6 +420,12 @@ pub(crate) struct Cdfs { /// The two motion vector components' own tables: separate owned state, /// since spec 8.3.2 adapts one component without touching the other. pub mv_comp: [MvComponentCdfs; 2], + /// libaom's `ndvc` (`av1_init_mv_probs`): the block-vector MV context an + /// intrabc block reads (spec's `MV_INTRABC_CONTEXT`). Same spec-8.4 + /// defaults as [`Self::mv_joint`]/[`Self::mv_comp`], separate adaptation. + pub dv_joint: [u16; 5], + /// [`Self::dv_joint`]'s per-component half. + pub dv_comp: [MvComponentCdfs; 2], /// The `use_filter_intra` flag, indexed by block-size class (`[0]`=4x4, /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32) -- /// see [`cdf::FILTER_INTRA`]. @@ -464,6 +470,10 @@ pub(crate) struct Cdfs { /// A `RESTORE_SWITCHABLE`-plane LR unit's `restoration_type` -- see /// [`cdf::RESTORE_SWITCHABLE`]. pub restore_switchable: [u16; 4], + /// `segment_id` (lane-seg, spec 5.11.8) -- see [`cdf::SEGMENT_ID`]. + pub segment_id: [[u16; 9]; 3], + /// `seg_id_predicted` (lane-seg, spec 5.11.9) -- see [`cdf::SEGMENT_PRED`]. + pub segment_pred: [[u16; 3]; 3], /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`]. pub delta_q: [u16; 5], /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see @@ -682,6 +692,10 @@ impl Cdfs { reset2(&mut self.ref_mv); reset2(&mut self.drl_mode); reset1(&mut self.mv_joint); + reset1(&mut self.dv_joint); + self.dv_comp + .iter_mut() + .for_each(MvComponentCdfs::reset_counts); self.mv_comp .iter_mut() .for_each(MvComponentCdfs::reset_counts); @@ -701,6 +715,8 @@ impl Cdfs { reset1(&mut self.restore_wiener); reset1(&mut self.restore_sgrproj); reset1(&mut self.restore_switchable); + reset2(&mut self.segment_id); + reset2(&mut self.segment_pred); reset1(&mut self.delta_q); reset1(&mut self.delta_lf); reset2(&mut self.delta_lf_multi); @@ -1155,6 +1171,8 @@ impl Cdfs { drl_mode: cdf::DRL_MODE, mv_joint: cdf::MV_JOINT, mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()], + dv_joint: cdf::MV_JOINT, + dv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()], filter_intra: cdf::FILTER_INTRA, filter_intra_mode: cdf::FILTER_INTRA_MODE, tx_size_cat0: cdf::TX_SIZE_CAT0, @@ -1172,6 +1190,8 @@ impl Cdfs { restore_wiener: cdf::RESTORE_WIENER, restore_sgrproj: cdf::RESTORE_SGRPROJ, restore_switchable: cdf::RESTORE_SWITCHABLE, + segment_id: cdf::SEGMENT_ID, + segment_pred: cdf::SEGMENT_PRED, delta_q: cdf::DELTA_Q, delta_lf: cdf::DELTA_LF, delta_lf_multi: [cdf::DELTA_LF; 4], diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 24330075..a9a09f31 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -22,7 +22,8 @@ //! silently miscoding. use ec_av1_syntax::{ - CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, TileInfo, + CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, + SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo, }; use ec_core::{Error, Result}; @@ -315,6 +316,353 @@ fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: } } +// --------------------------------------------------------------------------- +// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`; +// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus +// the two consumers a real stream exercises: the per-segment quantizer index +// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level +// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/ +// `read_intra_segment_id`/`read_inter_segment_id` and +// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL +// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which +// is what the oracle every gate here compares against actually does. +thread_local! { + static SEG: std::cell::RefCell = + std::cell::RefCell::new(SegmentationParams::default()); + /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries + /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride). + static SEG_IDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// `PrevSegmentIds`: the primary reference frame's saved map, empty when + /// this frame has no primary reference (spec `load_previous_segment_ids`). + static PREV_SEG_IDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// `(mi_rows, mi_cols)` for both maps above. + static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; + /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi + /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which + /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead. + static ABOVE_SEG_PRED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + static LEFT_SEG_PRED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// The block currently being decoded -- read back by [`block_q_idx`]. + static CUR_SEGMENT_ID: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The tile's own top-left mi position, for `AvailU`/`AvailL`. + static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; + /// How many real `segment_id` symbols were read, and the set of segment + /// ids any block ended up with -- the gate's proof the feature fired. + static SEG_ID_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SEG_IDS_SEEN: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many `seg_id_predicted` symbols were read (temporal update). + static SEG_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Installs this frame's segmentation parameters and allocates its map, with +/// `prev` the primary reference frame's saved map (spec +/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty +/// slot). Called once per frame, whether or not segmentation is enabled. +pub(crate) fn set_segmentation( + seg: SegmentationParams, + mi_rows: usize, + mi_cols: usize, + prev: Option<&[u8]>, +) { + SEG.with(|s| *s.borrow_mut() = seg); + SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols))); + SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]); + PREV_SEG_IDS.with(|m| { + let mut m = m.borrow_mut(); + m.clear(); + if let Some(p) = prev { + if p.len() == mi_rows * mi_cols { + m.extend_from_slice(p); + } + } + }); + ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]); + LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]); + CUR_SEGMENT_ID.with(|c| c.set(0)); +} + +/// This frame's decoded segment map, to be stored into whichever reference +/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`). +pub(crate) fn take_segment_ids() -> Vec { + SEG_IDS.with(|m| m.borrow().clone()) +} + +/// How many `segment_id` symbols have been read (never reset per frame). +pub(crate) fn segment_id_hits() -> usize { + SEG_ID_HITS.with(|c| c.get()) +} + +/// How many distinct segment ids any decoded block has carried. +pub(crate) fn segment_ids_seen() -> usize { + SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize) +} + +/// How many `seg_id_predicted` symbols have been read (temporal update). +pub(crate) fn segment_pred_hits() -> usize { + SEG_PRED_HITS.with(|c| c.get()) +} + +/// Resets the segmentation hit counters (gate setup). +pub(crate) fn reset_segment_hits() { + SEG_ID_HITS.with(|c| c.set(0)); + SEG_IDS_SEEN.with(|c| c.set(0)); + SEG_PRED_HITS.with(|c| c.set(0)); +} + +/// `seg_feature_active_idx(segment_id, feature)` for the frame currently +/// being decoded, with its `FeatureData` value. +fn seg_feature(segment_id: usize, feature: usize) -> Option { + SEG.with(|s| { + let s = s.borrow(); + s.feature_active(segment_id, feature) + .then(|| i32::from(s.feature_data[segment_id][feature])) + }) +} + +/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom +/// `av1_get_qindex`) for the block currently being decoded: the running +/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data. +/// Every dequant call site reads the block's quantizer through here. +fn block_q_idx() -> i32 { + let base = CURRENT_Q_IDX.with(|c| c.get()); + let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize; + match seg_feature(seg_id, SEG_LVL_ALT_Q) { + Some(data) => (base + data).clamp(0, 255), + None => base, + } +} + +/// The segment id recorded for one mi cell of the current frame's map. +fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 { + let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get()); + if mi_r >= mi_rows || mi_c >= mi_cols { + return 0; + } + SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c]) +} + +/// `set_segment_id`: stamps `id` over every mi cell this block covers. +fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) { + let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get()); + let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); + SEG_IDS.with(|m| { + let mut m = m.borrow_mut(); + for y in 0..y_mis { + for x in 0..x_mis { + m[(mi_r + y) * mi_cols + mi_c + x] = id; + } + } + }); + CUR_SEGMENT_ID.with(|c| c.set(id)); + SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id)); +} + +/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over +/// `last_frame_seg_map`): the minimum previous-frame segment id over the +/// block's own mi footprint. `0` when there is no previous map. +fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 { + let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get()); + PREV_SEG_IDS.with(|m| { + let m = m.borrow(); + if m.is_empty() { + return 0; + } + let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r))); + let mut id = u8::MAX; + for y in 0..y_mis { + for x in 0..x_mis { + id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]); + } + } + if id == u8::MAX { 0 } else { id } + }) +} + +/// `av1_neg_deinterleave` (libaom `decodemv.c:258`). +fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 { + if reference == 0 { + return diff; + } + if reference >= max - 1 { + return max - diff - 1; + } + let half = if 2 * reference < max { + diff <= 2 * reference + } else { + diff <= 2 * (max - reference - 1) + }; + if half { + return if diff & 1 != 0 { + reference + ((diff + 1) >> 1) + } else { + reference - (diff >> 1) + }; + } + if 2 * reference < max { diff } else { max - (diff + 1) } +} + +/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current +/// frame's already-decoded above/left/above-left neighbours. +fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) { + let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get()); + let (avail_u, avail_l) = (mi_r > row0, mi_c > col0); + let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1))); + let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c))); + let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1))); + let ctx = match prev_ul { + None => 0, + Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2, + Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1, + Some(_) => 0, + }; + let pred = match (prev_u, prev_l) { + (None, l) => l.unwrap_or(0), + (Some(u), None) => u, + (Some(u), Some(l)) => { + if prev_ul == Some(u) { + u + } else { + l + } + } + }; + (pred, ctx) +} + +/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id +/// when `skip`, otherwise one `segment_id` symbol de-interleaved against +/// that prediction. Does NOT write the map -- callers do. +fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 { + let (pred, ctx) = spatial_seg_pred(mi_r, mi_c); + if skip { + return pred as u8; + } + let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32; + SEG_ID_HITS.with(|c| c.set(c.get() + 1)); + let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id)); + neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8 +} + +/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block +/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the +/// caller decides which by passing `pre_skip`). +fn intra_segment_id( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + mi_r: usize, + mi_c: usize, + w_mi: usize, + h_mi: usize, + skip: bool, +) { + if !SEG.with(|s| s.borrow().enabled) { + return; + } + let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip); + write_segment_id(mi_r, mi_c, w_mi, h_mi, id); +} + +/// Whether this frame's intra blocks read their `segment_id` before `skip` +/// (`SegIdPreSkip`); `false` also when segmentation is off. +fn seg_id_pre_skip() -> bool { + SEG.with(|s| { + let s = s.borrow(); + s.enabled && s.seg_id_pre_skip + }) +} + +/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`). +/// Called at both spec positions of an inter frame's block: `pre_skip = true` +/// before `skip_mode`/`skip`, and `pre_skip = false` after them. +fn inter_segment_id( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + mi_r: usize, + mi_c: usize, + w_mi: usize, + h_mi: usize, + skip: bool, + pre_skip: bool, +) { + let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| { + let s = s.borrow(); + (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip) + }); + if !enabled { + return; + } + if !update_map { + // The map is inherited wholesale from the previous frame. + let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi); + write_segment_id(mi_r, mi_c, w_mi, h_mi, id); + return; + } + if pre_skip && !pre_skip_frame { + return; + } + if !pre_skip && skip { + // libaom: a skipped block never codes `seg_id_predicted`, and its + // segment id is the spatial prediction. + stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0); + let id = read_segment_id(dec, cdfs, mi_r, mi_c, true); + write_segment_id(mi_r, mi_c, w_mi, h_mi, id); + return; + } + let id = if temporal_update { + let ctx = seg_pred_ctx(mi_r, mi_c); + let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0; + SEG_PRED_HITS.with(|c| c.set(c.get() + 1)); + stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted)); + if predicted { + predicted_segment_id(mi_r, mi_c, w_mi, h_mi) + } else { + read_segment_id(dec, cdfs, mi_r, mi_c, false) + } + } else { + read_segment_id(dec, cdfs, mi_r, mi_c, false) + }; + write_segment_id(mi_r, mi_c, w_mi, h_mi, id); +} + +/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags. +fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize { + // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and + // so contribute 0) outside the tile -- the availability check here is + // what keeps a previous tile's stamps out of this tile's context. + let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get()); + let above = if mi_r > row0 { + ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0)) + } else { + 0 + }; + let left = if mi_c > col0 { + LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0)) + } else { + 0 + }; + usize::from(above + left) +} + +/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update. +fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) { + ABOVE_SEG_PRED.with(|m| { + let mut m = m.borrow_mut(); + for i in 0..w_mi { + if let Some(cell) = m.get_mut(mi_c + i) { + *cell = value; + } + } + }); + LEFT_SEG_PRED.with(|m| { + let mut m = m.borrow_mut(); + for i in 0..h_mi { + if let Some(cell) = m.get_mut(mi_r + i) { + *cell = value; + } + } + }); +} + // How many key-frame luma blocks resolved `smooth_neighbor` (spec // `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after // counter, proving a stream actually put a directional block next to a @@ -428,6 +776,34 @@ pub(crate) fn horz_vert_intra_hits() -> usize { HORZ_VERT_INTRA_HITS.with(|c| c.get()) } +// How many HORZ/VERT intra strips resolved a SPLIT luma transform +// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- +// the case every rect path here refused by name before, and the first +// refusal the user's ReelB extract (600s in) stops at. +thread_local! { + static RECT_SPLIT_TX_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT_SPLIT_TX_HITS`]. +pub(crate) fn rect_split_tx_hits() -> usize { + RECT_SPLIT_TX_HITS.with(|c| c.get()) +} + +// How many HORZ/VERT intra strips actually predicted with filter intra +// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name +// ("this decoder predicts square-only") until `predict_filter_intra` took +// `bw`x`bh`. +thread_local! { + static FILTER_INTRA_RECT_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`FILTER_INTRA_RECT_HITS`]. +pub(crate) fn filter_intra_rect_hits() -> usize { + FILTER_INTRA_RECT_HITS.with(|c| c.get()) +} + // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every // call on the current thread -- the same before/after counter pattern as @@ -608,6 +984,69 @@ thread_local! { const { std::cell::RefCell::new(None) }; } +thread_local! { + /// The current frame's `mi` grid, kept only while a frame header set + /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary + /// MV stack ([`crate::mvstack::find_mv_stack`]) built against + /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise + /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that + /// does not allow intrabc (so nothing is paid for it). + /// + /// corner-cut: only [`decode_block`] (the square path) records into it, + /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off + /// an incomplete grid. Ceiling: the DV *value* (never the parse) would + /// be wrong there; upgrade = record from the rect/leaf paths too. + static INTRABC_MI_GRID: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; + /// The block vector [`read_intra_mode`] just decoded, handed to + /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`], + /// which the alternative -- a tenth tuple member through every caller -- + /// already avoids). Always `.take()`n by the block that reads it. + static INTRABC_DV: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter. + static INTRABC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`INTRABC_HITS`]. +pub(crate) fn intrabc_hits() -> usize { + INTRABC_HITS.with(|c| c.get()) +} + +/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode). +pub(crate) fn reset_intrabc_hits() { + INTRABC_HITS.with(|c| c.set(0)); +} + +/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes +/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any +/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an +/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`). +fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) { + INTRABC_MI_GRID.with(|g| { + let mut g = g.borrow_mut(); + let Some((grid, _, _)) = g.as_mut() else { + return; + }; + let info = crate::mvstack::MiInfo { + is_inter: dv.is_some(), + ref_frame: 0, + ref_frame1: None, + mv: dv.unwrap_or((0, 0)), + mv1: None, + is_new_mv: dv.is_some(), + is_global_mv0: false, + is_global_mv1: false, + size: n4, + size_h: n4, + }; + for r in mi_r..mi_r + n4 { + for c in mi_c..mi_c + n4 { + grid.set(r, c, info); + } + } + }); +} + // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) -- // proves a real `skip_mode_present` stream actually reached a block that // picked it, not just that the frame header bit was set. @@ -1844,6 +2283,16 @@ struct Neighbours { /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT). tx_h_grid: Vec, + /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4. + /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the + /// largest transform covering the subsampled BLOCK, capped at 32x32. It + /// does NOT follow luma's `tx_depth` split, so deriving it as + /// `tx_grid / 2` invented chroma transform edges the deblocker then + /// filtered (32x16 frames, U plane, seeds 42/47). Written from the + /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place + /// every caller routes through. + uv_tx_grid: Vec, + uv_tx_h_grid: Vec, /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` = /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` -- /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2) @@ -1923,6 +2372,8 @@ impl Neighbours { skip_grid_cols_mi: cols * (SUB / MI), tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], + uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], + uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)], delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)], above_palette_size: vec![0; cols], @@ -1945,6 +2396,9 @@ impl Neighbours { /// regardless of tile ([`Self::start_row`], already called once per SB /// row by every caller) so it needs no tile-specific reset here. fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) { + // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction + // are tile-relative, same as every other neighbour lookup here. + SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi))); self.tile_row0_mi = row0_mi; self.tile_col0_mi = col0_mi; let end = col1_mi.min(self.above.len()); @@ -2176,6 +2630,11 @@ impl Neighbours { ref_frame: i8, ) { let (mi_r, mi_c) = at_mi; + // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is + // half its luma one (min 4 px, the smallest transform), capped at + // TX_32X32 -- independent of this block's luma `tx_depth`. + let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8; + let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8; let cur = CURRENT_DELTA_LF.with(|c| c.get()); let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) { std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8) @@ -2191,6 +2650,12 @@ impl Neighbours { if let Some(cell) = self.tx_h_grid.get_mut(idx) { *cell = tx_h_px; } + if let Some(cell) = self.uv_tx_grid.get_mut(idx) { + *cell = uv_tx_w; + } + if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) { + *cell = uv_tx_h; + } if let Some(cell) = self.ref_grid.get_mut(idx) { *cell = ref_frame; } @@ -2630,32 +3095,55 @@ impl Neighbours { mode: usize, uv_mode: usize, chroma_grids: [&[i32]; 2], + ) { + self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids); + } + + /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`) + /// extents in pixels (lane-rectsplit r1), the same relationship + /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose + /// luma transform split into several square units needs exactly this + /// bookkeeping, at its own true rectangular extents. + fn record_split_luma_rect( + &mut self, + at: (usize, usize), + w: usize, + h: usize, + mode: usize, + uv_mode: usize, + chroma_grids: [&[i32]; 2], ) { let (r, c) = at; - for cell in 0..side / SUB { + for cell in 0..w / SUB { self.above_mode[c + cell] = mode; - self.left_mode[r + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; + self.above_side[c + cell] = w; + } + for cell in 0..h / SUB { + self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; - self.above_side[c + cell] = side; - self.left_side[r + cell] = side; + self.left_side[r + cell] = h; } let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); - let side_mi = side / MI; - for cell in 0..side_mi { - self.left_side_mi[mi_r + cell] = side; - self.above_side_mi[mi_c + cell] = side; + let (w_mi, h_mi) = (w / MI, h / MI); + for cell in 0..h_mi { + self.left_side_mi[mi_r + cell] = h; + } + for cell in 0..w_mi { + self.above_side_mi[mi_c + cell] = w; } let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); for (plane_idx, grid) in chroma_grids.into_iter().enumerate() { let plane = plane_idx + 1; let state = neighbour_state(grid); - for cell in 0..side_mi { - if cell < side_mi.min(bound_h.saturating_sub(mi_r)) { + for cell in 0..h_mi { + if cell < h_mi.min(bound_h.saturating_sub(mi_r)) { self.left[mi_r + cell][plane] = state; } - if cell < side_mi.min(bound_w.saturating_sub(mi_c)) { + } + for cell in 0..w_mi { + if cell < w_mi.min(bound_w.saturating_sub(mi_c)) { self.above[mi_c + cell][plane] = state; } } @@ -3076,8 +3564,16 @@ fn read_intra_mode_rect( } }; } + // Same `intra_segment_id` placement as the square reader above. + let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4); + if seg_id_pre_skip() { + intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false); + } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; istep!("skip", skip as i32); + if !seg_id_pre_skip() { + intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip); + } maybe_read_cdef_idx(dec, mi_r, mi_c, skip); istep!("cdef", 0); // 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 ac } +/// Everything a rect strip already read out of the stream before its luma +/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle +/// (nine values that would otherwise be nine more parameters). +struct RectStripModes { + skip: bool, + mode: usize, + angle_delta_y: i32, + uv_predict_mode: usize, + angle_delta_uv: i32, + alpha: Option<(i32, i32)>, + filter_intra: Option, + smooth_neighbor: bool, + smooth_neighbor_uv: bool, + /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already + /// mapped through the colour table), sliced per transform unit below -- + /// palette prediction reads no edge pixels, so a unit's slice of the + /// whole-block map IS its prediction. Without this a palette strip whose + /// transform splits predicted DC and came out flat grey while the entropy + /// stream stayed in sync (the coefficients are read either way). + palette_y: Option>, + /// As `palette_y`, for the un-split chroma transform (U, V). + palette_uv: Option<(Vec, Vec)>, +} + +/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma +/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every +/// rect path here refused by name until now ("per-unit rect prediction is not +/// ported"). +/// +/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth` +/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1 +/// strip the very first step already lands on a SQUARE transform +/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and +/// every further step halves a square) -- so each unit is square and reads +/// through the ordinary square [`read_plane`]. What is genuinely rectangular +/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as +/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose +/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never +/// split by luma's depth. +/// +/// Each unit predicts off whatever the earlier units of this same block +/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block` +/// inside `av1_foreach_transformed_block`, raster order), which is exactly +/// what predicting the whole strip in one shot got wrong. +#[allow(clippy::too_many_arguments)] +fn decode_rect_split( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at: (usize, usize), + bw: usize, + bh: usize, + tx: usize, + m: &RectStripModes, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + base_q_idx: u8, + reduced_tx_set: bool, +) -> Result<()> { + let (r, c) = at; + let (px, py) = (c * SUB, r * SUB); + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + let (cpx, cpy) = (px / 2, py / 2); + let (chroma_w, chroma_h) = (bw / 2, bh / 2); + // The chroma transform is picked before any symbol is read, so an + // unsupported chroma shape refuses before this strip desyncs the tile. + let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) { + (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])), + (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])), + (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])), + (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])), + _ => None, + }; + if !m.skip && chroma.is_none() { + return Err(unsupported( + "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", + )); + } + RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + // LUMA: `bw/tx` x `bh/tx` square transform units, raster order. + let luma_set = txbset_for(tx, reduced_tx_set); + let luma_scan = default_scan(tx); + let zero_tu = vec![0i32; tx * tx]; + // The strip's OWN edge availability, the fallback for a transform unit + // whose top-right/bottom-left pixels fall outside the strip. + let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + for tu_row in 0..bh / tx { + for tu_col in 0..bw / tx { + let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI)); + let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx); + let (col_off, row_off) = (tu_col * tx, tu_row * tx); + // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a + // transform unit INSIDE a block, which is a different rule from + // the standalone-block table [`Reach::of`] applies -- and the + // reason a depth-2 superblock strip came out one sample off + // before this: `Reach::of(tx, ..)` answered as if the unit were + // its own block at that superblock position. + // * top-right: if the unit's right neighbour is still inside the + // strip the pixels are already reconstructed (`col_off + + // tx_wide < plane_bw`); otherwise only the strip's own top row + // of units can reach past it, through the block-level answer. + // * bottom-left: a unit that is not in the strip's left column + // has none (`col_off > 0` returns 0); inside the strip + // (`row_off + tx_high < plane_bh`) they are the left + // neighbour's, already reconstructed; the last row falls back + // to the block-level answer. + let tu_reach = Reach { + above_right: if col_off + tx < bw { + true + } else { + row_off == 0 && block_reach.above_right + }, + below_left: if col_off > 0 { + false + } else if row_off + tx < bh { + true + } else { + block_reach.below_left + }, + }; + // The unit's own window on the block's palette prediction. + if let Some(buf) = &m.palette_y { + let tu_buf: Vec = (0..tx) + .flat_map(|i| { + let base = (row_off + i) * bw + col_off; + buf[base..base + tx].iter().copied() + }) + .collect(); + PALETTE_PRED.with(|c| *c.borrow_mut() = Some(tu_buf)); + } + if m.skip { + y.reconstruct( + tu_px, + tu_py, + tx, + m.mode, + m.angle_delta_y, + tu_reach, + &zero_tu, + None, + m.filter_intra, + m.smooth_neighbor, + ); + neighbours.record_mi_luma(tu_mi, tx, &zero_tu); + } else { + let tu_around = neighbours.around_mi(tu_mi, tx)[0]; + // This unit is smaller than the block it sits in, so + // `txb_skip_ctx` is the neighbour-magnitude table, not the + // lone-TU 0 (spec `get_txb_ctx_general`). + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI); + let tu_grid = read_plane( + dec, + cdfs, + luma_set, + &luma_scan, + 0, + tu_around, + m.mode, + m.mode, + m.angle_delta_y, + tu_reach, + y, + tu_px, + tu_py, + tx, + tx, + base_q_idx, + None, + m.filter_intra, + Some(tu_skip_ctx), + m.smooth_neighbor, + )?; + neighbours.record_mi_luma(tu_mi, tx, &tu_grid); + } + } + } + // CHROMA: one un-split rect transform for the whole strip. + let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + let reach = block_reach; + let (u_grid, v_grid) = if m.skip { + let zero = vec![0i32; chroma_w * chroma_h]; + if let Some((ub, _)) = &m.palette_uv { + PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone())); + } + u.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, + m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, + ); + if let Some((_, vb)) = &m.palette_uv { + PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone())); + } + v.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, + m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, + ); + (zero.clone(), zero) + } else { + let (chroma_set, chroma_scan) = chroma.expect("refused above when None"); + // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size + // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra, + // so only the 16x8/8x16 pair takes the mode-indexed default. + let default_tx = if chroma_w.max(chroma_h) >= 32 { + TxType::DctDct + } else { + default_intra_tx_type(m.uv_predict_mode as u8) + }; + let around = neighbours.around_rect(at, bw, bh); + let mut grids: Vec> = Vec::with_capacity(2); + for plane_idx in 1..=2 { + let skip_ctx = + usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); + let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + chroma_scan, + chroma_w, + chroma_h, + skip_ctx, + dc_sign_ctx(around[plane_idx].2), + default_tx, + )?; + let residual = dequant_and_inverse_typed_wh( + &levels, + chroma_w, + chroma_h, + crate::decode::bit_depth(), + CURRENT_Q_IDX.with(|c| c.get()), + plane_q_delta(plane_idx).0, + plane_q_delta(plane_idx).1, + tx_type, + ); + let cfl = m + .alpha + .zip(ac.as_deref()) + .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); + let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; + if let Some((ub, vb)) = &m.palette_uv { + let buf = if plane_idx == 1 { ub } else { vb }; + PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf.clone())); + } + plane.reconstruct_rect( + cpx, + cpy, + chroma_w, + chroma_h, + m.uv_predict_mode, + m.angle_delta_uv, + reach, + &residual, + cfl, + None, + m.smooth_neighbor_uv, + ); + grids.push(levels); + } + let mut it = grids.into_iter(); + (it.next().unwrap(), it.next().unwrap()) + }; + neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]); + neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip); + neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0); + if std::env::var_os("EC_AV1_TRACE").is_some() { + let (rng, _) = dec.debug_state(); + eprintln!( + "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}" + ); + } + Ok(()) +} + /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ @@ -3270,6 +4038,7 @@ fn decode_block_rect( allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, + reduced_tx_set: bool, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -3302,15 +4071,13 @@ fn decode_block_rect( // `uv_mode`, not the luma one. let smooth_neighbor_uv = is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]); + // lane-rectsplit r1: `predict_filter_intra` now takes the block's own + // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a + // rectangle just as happily), so a `use_filter_intra` strip at this level + // predicts instead of refusing. The below-16x16 leaf arm + // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own. if filter_intra.is_some() { - // `predict_filter_intra` (spec 7.11.2.3) is square-only in this - // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was - // already read above so the stream stays in sync, this only refuses - // the *pixel* decode of a rare case (`use_filter_intra` on a rect - // strip). - return Err(unsupported( - "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", - )); + FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1)); } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED @@ -3333,15 +4100,40 @@ fn decode_block_rect( }; if depth != 0 { TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); - // A split transform is predicted per transform unit, each taking its - // edges from the previous unit's reconstruction (the square path's own - // per-TU loop does exactly that). Predicting the whole strip in one - // shot would silently produce different pixels, so refuse by name - // until that loop is ported for rect strips. - return Err(unsupported( - "a HORZ/VERT intra strip with a split transform (per-unit rect \ - prediction is not ported)", - )); + // lane-rectsplit r1: a split transform is predicted and reconstructed + // per transform unit, each unit taking its edges from the previous + // unit's reconstruction inside this same strip (spec 5.11.36) -- + // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square + // from the first step on, so `bw.min(bh) >> (depth - 1)` names it. + let tx = bw.min(bh) >> (depth - 1); + let modes = RectStripModes { + skip, + mode, + angle_delta_y, + uv_predict_mode, + angle_delta_uv, + alpha, + filter_intra, + smooth_neighbor, + smooth_neighbor_uv, + palette_y: palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), + palette_uv: palette_uv.as_ref().map(|p| { + ( + p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), + p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), + ) + }), + }; + if palette_y.is_some() || palette_uv.is_some() { + PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + } + decode_rect_split( + dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set, + )?; + RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); + return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px / 2, py / 2); @@ -3509,7 +4301,7 @@ fn decode_block_rect( bw, bh, crate::decode::bit_depth(), - CURRENT_Q_IDX.with(|c| c.get()), + block_q_idx(), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type, @@ -3553,7 +4345,7 @@ fn decode_block_rect( chroma_w, chroma_h, crate::decode::bit_depth(), - CURRENT_Q_IDX.with(|c| c.get()), + block_q_idx(), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type, @@ -3596,7 +4388,7 @@ fn decode_block_rect( chroma_w, chroma_h, crate::decode::bit_depth(), - CURRENT_Q_IDX.with(|c| c.get()), + block_q_idx(), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type, @@ -3732,7 +4524,7 @@ fn decode_leaf_rect( }; if depth != 0 { return Err(unsupported( - "a HORZ/VERT intra strip with a split transform (per-unit rect \ + "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \ prediction is not ported)", )); } @@ -3839,6 +4631,7 @@ fn decode_block_rect64( allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, + reduced_tx_set: bool, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -3905,12 +4698,31 @@ fn decode_block_rect64( let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let depth = if tx_select { let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh); - dec.symbol(&mut cdfs.tx_size_cat2[ctx]) + // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`) + // counts `sub_tx_size_map` steps from the block's own max rect + // transform down to TX_4X4, minus one -- BLOCK_64X32's chain + // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four + // steps, so this level's category is 3 (the same one a 64x64 square + // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF + // here was a wrong-table read of a real symbol. + dec.symbol(&mut cdfs.tx_size_cat3[ctx]) } else { 0 }; if depth != 0 { TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); + // lane-rectsplit r1: [`decode_rect_split`] handles this shape too + // (`sub_tx_size_map[TX_64X32]` is `TX_32X32`, so a depth-1 unit here + // is a plain square 32x32) and its 32x32-level sibling arm in + // [`decode_block_rect`] is gated pixel-exact -- but at the SUPERBLOCK + // level the gate + // (`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`, + // `#[ignore]`d with its measurement) still comes out ONE sample off + // (seed 50, luma (171,56) ours 147 vs ffmpeg 148, inside a 64x32 + // strip whose transform resolved to depth 2 / TX_16X16). A refusal + // this lane could not lift is not a refusal it may silently ship + // wrong pixels past, so the named refusal stays until that gate is + // green. return Err(unsupported( "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \ prediction is not ported)", @@ -4017,7 +4829,7 @@ fn decode_block_rect64( luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]); } { - let cur = CURRENT_Q_IDX.with(|c| c.get()); + let cur = block_q_idx(); if cur != i32::from(base_q_idx) { RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); } @@ -4032,7 +4844,7 @@ fn decode_block_rect64( bw, bh, crate::decode::bit_depth(), - CURRENT_Q_IDX.with(|c| c.get()), + block_q_idx(), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type, @@ -4089,7 +4901,7 @@ fn decode_block_rect64( eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}"); } { - let cur = CURRENT_Q_IDX.with(|c| c.get()); + let cur = block_q_idx(); if cur != i32::from(base_q_idx) { RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); } @@ -4104,7 +4916,7 @@ fn decode_block_rect64( chroma_w, chroma_h, crate::decode::bit_depth(), - CURRENT_Q_IDX.with(|c| c.get()), + block_q_idx(), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type, @@ -4143,7 +4955,7 @@ fn decode_block_rect64( eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}"); } { - let cur = CURRENT_Q_IDX.with(|c| c.get()); + let cur = block_q_idx(); if cur != i32::from(base_q_idx) { RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); } @@ -4158,7 +4970,7 @@ fn decode_block_rect64( chroma_w, chroma_h, crate::decode::bit_depth(), - CURRENT_Q_IDX.with(|c| c.get()), + block_q_idx(), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type, @@ -4261,11 +5073,20 @@ fn read_intra_mode( } }; } + // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE + // `skip` when `SegIdPreSkip`, and after it otherwise. + let (seg_w_mi, seg_h_mi) = (side / 4, side / 4); + if seg_id_pre_skip() { + intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false); + } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; if trace { eprintln!("TRACE skip value={}", skip as i32); } istep!("skip", skip as i32); + if !seg_id_pre_skip() { + intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip); + } // spec order (see the comment below on `read_intrabc_info`): `skip`, // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here. maybe_read_cdef_idx(dec, mi_r, mi_c, skip); @@ -4288,9 +5109,18 @@ fn read_intra_mode( eprintln!("TRACE use_intrabc value={}", use_intrabc as i32); } if use_intrabc { - return Err(unsupported( - "a block that actually uses intrabc (this decoder never reconstructs one)", - )); + let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side); + if trace { + eprintln!("TRACE intrabc dv={dv:?}"); + } + INTRABC_DV.with(|c| c.set(Some(dv))); + INTRABC_HITS.with(|c| c.set(c.get() + 1)); + // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the + // moment `is_intrabc_block`: no y/uv mode, angle delta, palette, + // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced + // `DC_PRED` (which is also what the neighbour mode contexts and + // the loop filter then see). + return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None)); } } let above_ctx = INTRA_MODE_CTX[above_mode]; @@ -4570,6 +5400,20 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly /// (own-edge and reach clamps both), passing what it gathers straight to /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. +/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written +/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. +fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) { + use std::io::Write; + if let Ok(path) = std::env::var(var) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f0")) + { + for p in [y, u, v] { + let narrow: Vec = p.data.iter().map(|&s| s as u8).collect(); + let _ = f.write_all(&narrow); + } + } +} + #[derive(Clone)] struct PlaneBuf { data: Vec, @@ -4726,6 +5570,7 @@ impl PlaneBuf { left.as_deref(), corner, bw, + bh, &mut prediction, ); } else { @@ -4800,6 +5645,7 @@ impl PlaneBuf { left.as_deref(), corner, side, + side, &mut prediction, ); } else { @@ -4937,7 +5783,7 @@ fn read_plane( full }; let (dc_delta, ac_delta) = plane_q_delta(plane_idx); - let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type); + let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( "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( r * (SUB / MI), c * (SUB / MI), )?; + let intrabc_dv = INTRABC_DV.with(|c| c.take()); + // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so + // under `TX_MODE_SELECT` its transform size comes from the inter var-tx + // partition tree (`read_var_tx_size`), a syntax element this decoder has + // nowhere -- reading the intra `tx_depth` symbol instead would desync. + if intrabc_dv.is_some() && tx_select && !skip { + return Err(unsupported( + "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)", + )); + } // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED` // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the // actual chroma-from-luma correlation, same as this decoder always did. @@ -5060,10 +5916,45 @@ fn decode_block( } else { luma_set }; + let luma_set = if intrabc_dv.is_some() { + txbset_for_inter(logical_tx, reduced_tx_set) + } else { + luma_set + }; let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4); let reach = Reach::of(side, px, py, y.width, y.height); let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; + // spec 7.11.3.4 with `use_intrabc`: the reference is the *current* + // frame's own pre-loop-filter reconstruction (all loop filters are off + // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel + // block vector, with the BILINEAR kernel libaom forces for intrabc -- + // luma is a straight copy, chroma lands half-pel whenever the luma DV is + // odd, which is exactly what the bilinear taps then interpolate. + let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| { + let mut yb = vec![0u16; side * side]; + mc::predict_with_filter( + &y.data, y.width, y.true_width, y.true_height, + mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true), + side, side, mc::InterpFilterKind::Bilinear, &mut yb, + ); + let mut ub = vec![0u16; chroma_side * chroma_side]; + mc::predict_with_filter( + &u.data, u.width, u.true_width, u.true_height, + mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), + chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, + ); + let mut vb = vec![0u16; chroma_side * chroma_side]; + mc::predict_with_filter( + &v.data, v.width, v.true_width, v.true_height, + mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), + chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, + ); + (yb, ub, vb) + }); + if let Some((yb, _, _)) = &intrabc_bufs { + PALETTE_PRED.with(|c| *c.borrow_mut() = Some(yb.clone())); + } // A palette-Y block's own prediction is the reconstructed colour-index // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it // to [`PlaneBuf::reconstruct`]'s next call rather than threading a @@ -5099,6 +5990,13 @@ fn decode_block( puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), ) }); + // The chroma half of the intrabc prediction rides the same per-plane + // override slot the UV-palette buffers do (set fresh before each plane's + // own `reconstruct`/`read_plane` call below). + let palette_uv_bufs = match &intrabc_bufs { + Some((_, ub, vb)) => Some((ub.clone(), vb.clone())), + None => palette_uv_bufs, + }; if skip { // A skipped block codes no residual syntax at all (spec 5.11.34): // straight prediction, on every plane. @@ -5374,6 +6272,7 @@ fn decode_block( logical_tx as u8, 0, ); + record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv); Ok(()) } @@ -5956,24 +6855,16 @@ fn plane_to_mi(chroma: bool, coord: usize) -> usize { /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize` /// under 4:2:0 and a block that never splits its own transform). fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { - let luma_tx = n - .tx_grid - .get(mi_r * n.skip_grid_cols_mi + mi_c) - .copied() - .unwrap_or(0) as u32; - if chroma { luma_tx / 2 } else { luma_tx } + let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid }; + grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 } /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal /// edges step and gate by transform height, which differs from width only /// on rect partition strips. fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { - let luma_tx = n - .tx_h_grid - .get(mi_r * n.skip_grid_cols_mi + mi_c) - .copied() - .unwrap_or(0) as u32; - if chroma { luma_tx / 2 } else { luma_tx } + let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid }; + grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 } /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom @@ -6057,6 +6948,21 @@ fn scan_for<'a>( /// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past /// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a /// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]). +/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which +/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the +/// inter `ext_tx` sets, never the mode-indexed intra ones. +fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet { + match tx_px { + 64 => TxbSet::Luma64, + 32 => TxbSet::Luma32Inter, + 16 if reduced_tx_set => TxbSet::Luma16Inter, + 16 => TxbSet::Luma16InterSet1, + 8 if reduced_tx_set => TxbSet::Luma8Inter, + 8 => TxbSet::Luma8InterSet1, + _ => TxbSet::Luma64, + } +} + fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { match tx_px { 64 => TxbSet::Luma64, @@ -6088,7 +6994,14 @@ fn unit_log2(px: u32) -> i32 { /// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable /// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME` /// block anywhere aborted the whole stream's decode before comparison). -fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8, delta_lf: i32) -> i32 { +fn lf_level( + lf: &LoopFilterParams, + plane_idx: usize, + dir: usize, + ref_frame: i8, + delta_lf: i32, + segment_id: u8, +) -> i32 { let base = i32::from(if plane_idx == 0 { lf.level[dir] } else if plane_idx == 1 { @@ -6100,6 +7013,16 @@ fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8, // ref/mode delta scaling below, and regardless of `delta_enabled` // (that flag only gates `ref_deltas`/`mode_deltas`). let base = (base + delta_lf).clamp(0, 63); + // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this + // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the + // per-superblock `DeltaLF` term and before the ref/mode deltas below. + // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4) + // for chroma. + let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 }; + let base = match seg_feature(usize::from(segment_id), feature) { + Some(data) => (base + data).clamp(0, 63), + None => base, + }; if !lf.delta_enabled { return base; } @@ -6155,8 +7078,15 @@ fn edge_params( let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]); let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]); - let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf); - let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf); + let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c)); + let pv_level = lf_level( + lf, + plane_idx, + dir, + pv_ref, + pv_delta_lf, + segment_id_at(pv_mi_r, pv_mi_c), + ); if cur_level == 0 && pv_level == 0 { return None; } @@ -6855,6 +7785,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter)); let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI)); + INTRABC_MI_GRID.with(|g| { + *g.borrow_mut() = allow_intrabc.then(|| { + ( + crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize), + mi_cols as usize, + mi_rows as usize, + ) + }); + }); + INTRABC_DV.with(|c| c.set(None)); CDEF_BITS.with(|c| c.set(cdef.bits)); CDEF_SB_COLS.with(|c| c.set(sb_cols as usize)); 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( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; // Two 8x8 squares stacked on the // right, chained through @@ -7508,6 +8449,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect( &mut dec, @@ -7523,6 +8465,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } PARTITION_VERT => { @@ -7542,6 +8485,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect( &mut dec, @@ -7557,6 +8501,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } _ => { @@ -7583,6 +8528,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect64( &mut dec, @@ -7598,6 +8544,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } PARTITION_VERT => { @@ -7617,6 +8564,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect64( &mut dec, @@ -7632,6 +8580,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } _ => { @@ -7693,7 +8642,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_height as usize, ); let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone()); + // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own + // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter + // dump above these bisect WHICH filter stage introduced a mismatch. + dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let (fw, fh) = (frame_width as usize, frame_height as usize); @@ -7959,6 +8913,58 @@ fn read_mv( (pred.0 + diff.0, pred.1 + diff.1) } +/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` -> +/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`). +/// +/// The predictor is the ordinary MV stack built against `INTRA_FRAME` +/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv` +/// when that is zero, or -- when both are -- the fixed fallback DV one +/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the +/// left when this is the tile's first superblock row. The predictor is then +/// rounded to full pel, and the difference reads off the *dv* nmv context +/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp` +/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL +/// symbol is coded for a DV, so none of this can move the bitstream +/// position -- only the reconstructed vector. +fn read_intrabc_dv( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + mi_r: usize, + mi_c: usize, + side: usize, +) -> (i32, i32) { + const INTRABC_DELAY_PIXELS: i32 = 256; + let n4 = side / MI; + let stack_pred = INTRABC_MI_GRID.with(|g| { + let g = g.borrow(); + g.as_ref().map(|(grid, mi_cols, mi_rows)| { + let stack = crate::mvstack::find_mv_stack( + grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */ + *mi_cols, *mi_rows, + ); + if stack.nearest_mv == (0, 0) { + stack.near_mv + } else { + stack.nearest_mv + } + }) + }); + let mut pred = stack_pred.unwrap_or((0, 0)); + if pred == (0, 0) { + // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the + // single-tile-row case every intrabc gate stream is). + let sb_px = SB_MI as i32 * MI as i32; + pred = if mi_r < SB_MI as usize { + (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8) + } else { + (-sb_px * 8, 0) + }; + } + // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel. + let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8); + read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true) +} + /// A 1/8-pel motion vector component converted to the 1/16-pel offset /// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4` /// (its own doc comment explains the `*2`/`*1` luma/chroma split). @@ -8062,7 +9068,7 @@ fn read_inter_plane( None, )?; let (dc_delta, ac_delta) = plane_q_delta(plane_idx); - let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), dc_delta, ac_delta, tx_type); + let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type); plane.reconstruct_mc(x, y, side, prediction, &residual); Ok((grid, tx_type)) } @@ -9146,6 +10152,11 @@ fn decode_inter_block( dec.debug_bitpos() ); } + // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before + // `skip_mode`/`skip`, `inter_segment_id(0)` after them. + let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4); + inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() { eprintln!( @@ -9159,6 +10170,7 @@ fn decode_inter_block( let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false); maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip); maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); 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( } let skip_mode_ctx = usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]); + // Same two `inter_segment_id` positions as [`decode_inter_block`]; this + // leaf is always `BLOCK_8X8`, i.e. 2x2 mi. + inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; if skip_mode { SKIP_MODE_HITS.with(|c| c.set(c.get() + 1)); @@ -11003,6 +12018,7 @@ fn decode_inter_block8( let skip_ctx = usize::from(above_skip) + usize::from(left_skip); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false); maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip); // Always a `BLOCK_8X8` leaf here, never the whole superblock. 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( frame_height as usize, ); let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone()); + // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own + // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter + // dump above these bisect WHICH filter stage introduced a mismatch. + dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let motion_field = build_motion_field( @@ -13952,13 +14973,27 @@ mod tests { use std::io::Write; use std::process::{Command, Stdio}; + /// Whether ffmpeg is on PATH. Absence normally SKIPs, but + /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every + /// aomenc gate decodes its stream through ffmpeg and is meaningless + /// without it -- turns it into a hard failure. Without this the require + /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first + /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg + /// printed SKIP and reported green (class gate-skips-on-its-own-failure). fn have_ffmpeg() -> bool { - Command::new("ffmpeg") + let present = Command::new("ffmpeg") .arg("-version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() - .is_ok_and(|s| s.success()) + .is_ok_and(|s| s.success()); + assert!( + present + || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() + && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), + "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" + ); + present } /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0 diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index b84fdf92..2c12a1e7 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3063,13 +3063,27 @@ mod tests { use std::io::Write; use std::process::{Command, Stdio}; + /// Whether ffmpeg is on PATH. Absence normally SKIPs, but + /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every + /// aomenc gate decodes its stream through ffmpeg and is meaningless + /// without it -- turns it into a hard failure. Without this the require + /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first + /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg + /// printed SKIP and reported green (class gate-skips-on-its-own-failure). fn have_ffmpeg() -> bool { - Command::new("ffmpeg") + let present = Command::new("ffmpeg") .arg("-version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() - .is_ok_and(|s| s.success()) + .is_ok_and(|s| s.success()); + assert!( + present + || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() + && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), + "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" + ); + present } /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes. diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 06b07c32..0aabdf12 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -362,13 +362,27 @@ mod tests { use super::*; use std::process::{Command, Stdio}; + /// Whether ffmpeg is on PATH. Absence normally SKIPs, but + /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every + /// aomenc gate decodes its stream through ffmpeg and is meaningless + /// without it -- turns it into a hard failure. Without this the require + /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first + /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg + /// printed SKIP and reported green (class gate-skips-on-its-own-failure). fn have_ffmpeg() -> bool { - Command::new("ffmpeg") + let present = Command::new("ffmpeg") .arg("-version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() - .is_ok_and(|s| s.success()) + .is_ok_and(|s| s.success()); + assert!( + present + || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() + && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), + "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" + ); + present } fn test_card(width: usize, height: usize, shift: usize) -> Picture { diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index a7472358..4ebaad44 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -1,6 +1,6 @@ //! AV1 film grain synthesis (spec 7.18.3), ported bit-exact from libaom's //! `av1/decoder/grain_synthesis.c` (`add_film_grain_run` and its helpers), -//! specialized to this crate's only picture shape: 8-bit, 4:2:0 planar +//! specialized to this crate's only picture shape: 4:2:0 planar //! (`chroma_subsamp_x = chroma_subsamp_y = 1` throughout, which is why every //! `<< (1 - subsamp)` in the reference collapses to a no-op and every //! `>> subsamp` collapses to `>> 1` below). @@ -43,9 +43,25 @@ const LUMA_BLOCK_W: i32 = const CHROMA_BLOCK_H: i32 = TOP_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + BOTTOM_PAD; const CHROMA_BLOCK_W: i32 = LEFT_PAD + AR_PADDING + CHROMA_SUBBLOCK * 2 + AR_PADDING + RIGHT_PAD; -// bit_depth is always 8 in this crate: grain_center = 128 << (8 - 8) = 128. -const GRAIN_MIN: i32 = -128; -const GRAIN_MAX: i32 = 127; +thread_local! { + /// `params->bit_depth` of the picture currently being grained. libaom + /// keeps `grain_min`/`grain_max` as file statics set once per + /// `av1_add_film_grain_run` (`grain_synthesis.c:1041-1045`); this mirrors + /// that rather than threading a parameter through every helper. + static GRAIN_BIT_DEPTH: std::cell::Cell = const { std::cell::Cell::new(8) }; +} + +/// `params->bit_depth` for the [`apply_grain`] call in progress. +fn grain_bit_depth() -> u32 { + GRAIN_BIT_DEPTH.with(|c| c.get()) +} + +/// `grain_min`/`grain_max` (`grain_synthesis.c:1043-1045`): +/// `grain_center = 128 << (bit_depth - 8)`. +fn grain_range() -> (i32, i32) { + let center = 128i32 << (grain_bit_depth() - 8); + (-center, center - 1) +} const MIN_LUMA_LEGAL: i32 = 16; const MAX_LUMA_LEGAL: i32 = 235; @@ -121,11 +137,12 @@ fn generate_luma_grain_block( pred_pos: &[(i32, i32, i32)], rng: &mut Rng, ) -> Vec { + let (grain_min, grain_max) = grain_range(); let mut block = vec![0i32; (LUMA_BLOCK_H * LUMA_BLOCK_W) as usize]; if fg.num_y_points == 0 { return block; } - let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; // 12 - 8 + grain_scale_shift + let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32; let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6; let rounding_offset = 1i32 << (ar_coeff_shift - 1); @@ -143,7 +160,7 @@ fn generate_luma_grain_block( wsum += fg.ar_coeffs_y[idx] as i32 * at(&block, LUMA_BLOCK_W, i + dy, j + dx); } let v = (at(&block, LUMA_BLOCK_W, i, j) + ((wsum + rounding_offset) >> ar_coeff_shift)) - .clamp(GRAIN_MIN, GRAIN_MAX); + .clamp(grain_min, grain_max); set_at(&mut block, LUMA_BLOCK_W, i, j, v); } } @@ -157,9 +174,10 @@ fn generate_chroma_grain_blocks( luma_block: &[i32], seed: u16, ) -> (Vec, Vec) { + let (grain_min, grain_max) = grain_range(); let mut cb = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize]; let mut cr = vec![0i32; (CHROMA_BLOCK_H * CHROMA_BLOCK_W) as usize]; - let gauss_sec_shift = 4 + fg.grain_scale_shift as i32; + let gauss_sec_shift = 12 - grain_bit_depth() as i32 + fg.grain_scale_shift as i32; let ar_coeff_shift = fg.ar_coeff_shift_minus_6 as i32 + 6; let rounding_offset = 1i32 << (ar_coeff_shift - 1); @@ -226,13 +244,13 @@ fn generate_chroma_grain_blocks( if apply_cb { let v = (at(&cb, CHROMA_BLOCK_W, i, j) + ((wsum_cb + rounding_offset) >> ar_coeff_shift)) - .clamp(GRAIN_MIN, GRAIN_MAX); + .clamp(grain_min, grain_max); set_at(&mut cb, CHROMA_BLOCK_W, i, j, v); } if apply_cr { let v = (at(&cr, CHROMA_BLOCK_W, i, j) + ((wsum_cr + rounding_offset) >> ar_coeff_shift)) - .clamp(GRAIN_MIN, GRAIN_MAX); + .clamp(grain_min, grain_max); set_at(&mut cr, CHROMA_BLOCK_W, i, j, v); } } @@ -265,7 +283,21 @@ fn build_scaling_lut(values: &[u8], scaling: &[u8], num_points: usize) -> [i32; lut } -/// `add_noise_to_block` (spec 7.18.3.5), 8-bit / 4:2:0 only. `(py0, px0)` is +/// `scale_LUT` (`grain_synthesis.c:616`): the scaling LUT has 256 entries +/// regardless of bit depth, so at 10/12 bit the index is shifted down and the +/// two neighbouring entries are interpolated with the dropped low bits. +fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 { + let shift = bit_depth - 8; + let x = (index >> shift) as usize; + if shift == 0 || x == 255 { + lut[x] + } else { + lut[x] + (((lut[x + 1] - lut[x]) * (index & ((1 << shift) - 1)) + (1 << (shift - 1))) + >> shift) + } +} + +/// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is /// the luma-plane pixel origin; the matching chroma origin is `(py0/2, /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the /// same function serves both the raw 82x73/44x38 templates and the small @@ -295,13 +327,17 @@ fn add_noise_to_block( let y_stride = picture.width as i32; let c_stride = (picture.width / 2) as i32; let scaling_shift = fg.grain_scaling_minus_8 as i32 + 8; + let bit_depth = grain_bit_depth(); + let bd_shift = bit_depth - 8; + // `(256 << (bit_depth - 8)) - 1`, the scaling-LUT index clamp. + let index_max = (256i32 << bd_shift) - 1; let mut cb_mult = fg.cb_mult as i32 - 128; let mut cb_luma_mult = fg.cb_luma_mult as i32 - 128; - let mut cb_offset = fg.cb_offset as i32 - 256; + let mut cb_offset = ((fg.cb_offset as i32) << bd_shift) - (1 << bit_depth); let mut cr_mult = fg.cr_mult as i32 - 128; let mut cr_luma_mult = fg.cr_luma_mult as i32 - 128; - let mut cr_offset = fg.cr_offset as i32 - 256; + let mut cr_offset = ((fg.cr_offset as i32) << bd_shift) - (1 << bit_depth); if fg.chroma_scaling_from_luma { cb_mult = 0; cb_luma_mult = 64; @@ -318,21 +354,21 @@ fn add_noise_to_block( let (min_luma, max_luma, min_chroma, max_chroma) = if fg.clip_to_restricted_range { if mc_identity { ( - MIN_LUMA_LEGAL, - MAX_LUMA_LEGAL, - MIN_LUMA_LEGAL, - MAX_LUMA_LEGAL, + MIN_LUMA_LEGAL << bd_shift, + MAX_LUMA_LEGAL << bd_shift, + MIN_LUMA_LEGAL << bd_shift, + MAX_LUMA_LEGAL << bd_shift, ) } else { ( - MIN_LUMA_LEGAL, - MAX_LUMA_LEGAL, - MIN_CHROMA_LEGAL, - MAX_CHROMA_LEGAL, + MIN_LUMA_LEGAL << bd_shift, + MAX_LUMA_LEGAL << bd_shift, + MIN_CHROMA_LEGAL << bd_shift, + MAX_CHROMA_LEGAL << bd_shift, ) } } else { - (0, 255, 0, 255) + (0, index_max, 0, index_max) }; let cy0 = py0 / 2; @@ -349,8 +385,9 @@ fn add_noise_to_block( let scaled = (((average_luma * cb_luma_mult + cb_mult * picture.u[cidx] as i32) >> 6) + cb_offset) - .clamp(0, 255); - let delta = (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset) + .clamp(0, index_max); + let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx] + + rounding_offset) >> scaling_shift; picture.u[cidx] = ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16; @@ -359,8 +396,9 @@ fn add_noise_to_block( let scaled = (((average_luma * cr_luma_mult + cr_mult * picture.v[cidx] as i32) >> 6) + cr_offset) - .clamp(0, 255); - let delta = (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset) + .clamp(0, index_max); + let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx] + + rounding_offset) >> scaling_shift; picture.v[cidx] = ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16; @@ -372,7 +410,8 @@ fn add_noise_to_block( for j in 0..half_w * 2 { let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize; let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize; - let delta = (scaling_y[picture.y[pidx] as usize] * luma_grain[gidx] + let delta = (scale_lut(scaling_y, picture.y[pidx] as i32, bit_depth) + * luma_grain[gidx] + rounding_offset) >> scaling_shift; picture.y[pidx] = @@ -398,6 +437,7 @@ fn ver_overlap_inplace( width: i32, height: i32, ) { + let (grain_min, grain_max) = grain_range(); for h in 0..height { if width == 1 { let l = at(dst, dst_stride, dst_row0 + h, dst_col0); @@ -407,7 +447,7 @@ fn ver_overlap_inplace( dst_stride, dst_row0 + h, dst_col0, - ((l * 23 + r * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((l * 23 + r * 22 + 16) >> 5).clamp(grain_min, grain_max), ); } else { let l0 = at(dst, dst_stride, dst_row0 + h, dst_col0); @@ -419,14 +459,14 @@ fn ver_overlap_inplace( dst_stride, dst_row0 + h, dst_col0, - ((27 * l0 + 17 * r0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((27 * l0 + 17 * r0 + 16) >> 5).clamp(grain_min, grain_max), ); set_at( dst, dst_stride, dst_row0 + h, dst_col0 + 1, - ((17 * l1 + 27 * r1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((17 * l1 + 27 * r1 + 16) >> 5).clamp(grain_min, grain_max), ); } } @@ -447,6 +487,7 @@ fn hor_overlap_inplace( width: i32, height: i32, ) { + let (grain_min, grain_max) = grain_range(); if height == 1 { for w in 0..width { let t = at(dst, dst_stride, dst_row0, dst_col0 + w); @@ -456,7 +497,7 @@ fn hor_overlap_inplace( dst_stride, dst_row0, dst_col0 + w, - ((t * 23 + b * 22 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((t * 23 + b * 22 + 16) >> 5).clamp(grain_min, grain_max), ); } } else { @@ -470,14 +511,14 @@ fn hor_overlap_inplace( dst_stride, dst_row0, dst_col0 + w, - ((27 * t0 + 17 * b0 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((27 * t0 + 17 * b0 + 16) >> 5).clamp(grain_min, grain_max), ); set_at( dst, dst_stride, dst_row0 + 1, dst_col0 + w, - ((17 * t1 + 27 * b1 + 16) >> 5).clamp(GRAIN_MIN, GRAIN_MAX), + ((17 * t1 + 27 * b1 + 16) >> 5).clamp(grain_min, grain_max), ); } } @@ -496,6 +537,7 @@ fn copy_area( width: i32, height: i32, ) { + let (grain_min, grain_max) = grain_range(); for h in 0..height { for w in 0..width { let v = at(src, src_stride, src_row0 + h, src_col0 + w); @@ -504,15 +546,33 @@ fn copy_area( } } +thread_local! { + /// Firing count for the film-grain gates (class `gate-blind-to-feature`): + /// how many pictures actually ran through grain synthesis. + static GRAIN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`GRAIN_HITS`]. +pub(crate) fn grain_hits() -> usize { + GRAIN_HITS.with(|c| c.get()) +} + /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and /// apply film grain to `picture`, returning a new grained picture. `picture` /// itself is unchanged -- it stays the clean reference-frame-bank copy. /// Returns `picture.clone()` untouched when `apply_grain` is unset. -pub(crate) fn apply_grain(picture: &Picture, fg: &FilmGrainParams, mc_identity: bool) -> Picture { +pub(crate) fn apply_grain( + picture: &Picture, + fg: &FilmGrainParams, + mc_identity: bool, + bit_depth: u32, +) -> Picture { let mut out = picture.clone(); if !fg.apply_grain { return out; } + GRAIN_BIT_DEPTH.with(|c| c.set(bit_depth)); + GRAIN_HITS.with(|c| c.set(c.get() + 1)); let width = out.width as i32; let height = out.height as i32; let y_stride = width; diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 5b60712b..53165792 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -33,7 +33,13 @@ /// its tool is now covered by a real stream. #[cfg(test)] const NEVER_EXERCISED: &[(&str, &str)] = &[ - ("enable-intrabc", "intra block copy syntax is consumed but no block is reconstructed from it"), + // lane-intrabc r1: the DV itself (mv stack against INTRA_FRAME, `ndvc` + // full-pel read, `av1_find_ref_dv` fallback) and the block-copy + // prediction are now decoded, but every real aomenc intrabc block this + // lane could produce sits under TX_MODE_SELECT, whose inter var-tx + // partition tree is unread -- so no stream reconstructs one end to end + // yet and this entry stays. + ("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"), ]; #[cfg(test)] diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index 818779d2..0d6f3ebe 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -726,37 +726,45 @@ const FILTER_INTRA_SCALE_BITS: u32 = 4; /// though this mode itself never reaches past its own `side` samples of /// either edge. /// +/// `bw`x`bh` is the block, not necessarily square (lane-rectsplit r1): +/// `av1_filter_intra_predictor_c` walks the same 4x2 patches over a +/// rectangular block, and `av1_filter_intra_allowed_bsize` genuinely offers +/// this mode on every HORZ/VERT strip whose sides are both <= 32 (16x8, +/// 8x16, 32x16, 16x32, ...), which the square-only assert refused before. +/// /// # Panics -/// Panics when `dst` is not `side * side` long, or `side` is not a multiple -/// of 4 (spec `av1_filter_intra_allowed_bsize` never offers this mode past -/// 32x32, and only on square blocks: 4, 8, 16 or 32). +/// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4 +/// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never +/// offers this mode past 32x32). pub fn predict_filter_intra( mode: usize, above: Option<&[u16]>, left: Option<&[u16]>, corner: Option, - side: usize, + bw: usize, + bh: usize, dst: &mut [u16], ) { - assert_eq!(dst.len(), side * side, "the destination is the block"); - assert_eq!(side % 4, 0, "filter intra only offers 4/8/16/32"); - let edges = Edges::build(above, left, corner, side, side); + assert_eq!(dst.len(), bw * bh, "the destination is the block"); + assert_eq!(bw % 4, 0, "filter intra patches are 4 wide"); + assert_eq!(bh % 2, 0, "filter intra patches are 2 high"); + let edges = Edges::build(above, left, corner, bw, bh); let taps = &FILTER_INTRA_TAPS[mode]; // A (side+1)-square buffer: row 0 / column 0 hold the corner and the // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c). - let mut buffer = vec![0i32; (side + 1) * (side + 1)]; - let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (side + 1) + c]; + let mut buffer = vec![0i32; (bh + 1) * (bw + 1)]; + let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (bw + 1) + c]; buffer[0] = edges.above(-1); - for c in 0..side { + for c in 0..bw { buffer[c + 1] = edges.above(c as i32); } - for r in 0..side { - buffer[(r + 1) * (side + 1)] = edges.left(r as i32); + for r in 0..bh { + buffer[(r + 1) * (bw + 1)] = edges.left(r as i32); } let mut r = 1; - while r < side + 1 { + while r < bh + 1 { let mut c = 1; - while c < side + 1 { + while c < bw + 1 { let p0 = at(&buffer, r - 1, c - 1); let p1 = at(&buffer, r - 1, c); let p2 = at(&buffer, r - 1, c + 1); @@ -769,16 +777,16 @@ pub fn predict_filter_intra( let (r_off, c_off) = (k >> 2, k & 3); let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum(); let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max()); - let idx = (r + r_off) * (side + 1) + c + c_off; + let idx = (r + r_off) * (bw + 1) + c + c_off; buffer[idx] = value; } c += 4; } r += 2; } - for row in 0..side { - for col in 0..side { - dst[row * side + col] = at(&buffer, row + 1, col + 1) as u16; + for row in 0..bh { + for col in 0..bw { + dst[row * bw + col] = at(&buffer, row + 1, col + 1) as u16; } } } diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 96284d7c..8c0fd438 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -327,6 +327,13 @@ fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) /// `LAST_FRAME`) pass an all-`false` table, matching this stub's old /// always-`false` behaviour exactly. fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool { + // lane-intrabc: `INTRA_FRAME` (0) and `NONE` (-1) sit *below* the table's + // own `LAST_FRAME` base and have no sign bias at all -- an intrabc block + // queries the stack with `ref_frame == INTRA_FRAME`, which indexed this + // table at `usize::MAX` before. + if ref_frame < LAST_FRAME { + return false; + } table[(ref_frame - LAST_FRAME) as usize] } @@ -359,6 +366,11 @@ pub const NO_GM_MV: GmMvTable = [(0, 0); 7]; /// `table[ref_frame - LAST_FRAME]`, [`sign_bias`]'s shape for a /// [`GmMvTable`]. fn gm_mv(table: &GmMvTable, ref_frame: i8) -> (i32, i32) { + // Same below-`LAST_FRAME` guard as [`sign_bias`]: `INTRA_FRAME` (the + // intrabc query's own ref) has no global motion model. + if ref_frame < LAST_FRAME { + return (0, 0); + } table[(ref_frame - LAST_FRAME) as usize] } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 20ccbda8..a8742b3b 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -37,27 +37,26 @@ const REFUSALS: &[&str] = &[ "GLOBALMV (round 3)", "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)", + "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", + "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)", "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)", "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 32x32 partition type this decoder does not code (value={part32})", "a Golomb tail longer than this decoder reads", - "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", - "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)", "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)", "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)", - "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)", "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)", "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)", "a block that actually uses a palette (UV) -- reconstruction is out of scope", "a block that actually uses a palette (Y) -- reconstruction is out of scope", - "a block that actually uses intrabc (this decoder never reconstructs one)", + "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)", "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", "a frame with no mode-info grid", - "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", + "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)", "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", "a reference frame other than LAST_FRAME (round 2)", "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index d5c743ff..46363170 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -16,7 +16,8 @@ //! an implementation detail of how this crate happens to build it). use ec_av1_syntax::{ - Av1Parser, FrameHeader, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, Tile, TxMode, + Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, + SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode, WarpModel, }; use ec_core::{Error, Result}; @@ -74,6 +75,12 @@ pub fn decode_stream(data: &[u8]) -> Result> { // own end-of-tile adapted table, or (when the frame set // `disable_frame_end_update_cdf`) the table it started from, unchanged. let mut cdf_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); + // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also + // remembers the segment map the frame stored there decoded, which is what + // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds` + // (spec `load_previous_segment_ids`) for temporal segment-id prediction + // and for a `segmentation_update_map == 0` frame's inherited map. + let mut seg_map_slots: [Option>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); let mut pos = 0usize; // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec @@ -124,27 +131,25 @@ pub fn decode_stream(data: &[u8]) -> Result> { cdf_slots[i] = cdf_slots[slot].clone(); ref_slots[i] = Some(picture.clone()); motion_field_slots[i] = motion_field_slots[slot].clone(); + seg_map_slots[i] = seg_map_slots[slot].clone(); order_hint_slots[i] = order_hint_slots[slot]; } } let output = if header.film_grain.apply_grain { - // lane-hbd r5: `film_grain.rs`'s grain LUT and blend are - // hardcoded 8-bit (`[i32; 256]`, clamps at 255) -- narrowed - // from the old blanket bit-depth refusal to only the case - // that actually reaches unported code. + // lane-hbd10 r1: grain synthesis is bit-depth generic + // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). let bit_depth = parser .sequence_header() .map_or(8, |seq| seq.color_config.bit_depth); - if bit_depth != 8 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", - )); - } let mc_identity = parser .sequence_header() .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) + crate::film_grain::apply_grain( + &picture, + &header.film_grain, + mc_identity, + bit_depth as u32, + ) } else { picture }; @@ -245,12 +250,41 @@ pub fn decode_stream(data: &[u8]) -> Result> { // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes // will show up as a real pixel mismatch, not a silent truncation -- // the whole reason the widen (and this wiring) happened. + // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9, + // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the + // per-segment quantizer (spec 7.12.2) and loop-filter level + // (spec 7.14.4). The three features that instead REWRITE a block's + // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the + // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress + // symbols `decode_inter_block` unconditionally reads) -- have no + // reader on the inter path, so they still refuse by name rather than + // desyncing. aomenc's `--aq-mode` segmentation only ever sets + // `SEG_LVL_ALT_Q`. if header.segmentation.enabled { - return Err(Error::unsupported( - "AV1 decode_stream", - "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", - )); + for segment in 0..MAX_SEGMENTS { + for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { + if header.segmentation.feature_enabled[segment][feature] { + return Err(Error::unsupported( + "AV1 decode_stream", + "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)", + )); + } + } + } } + // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the + // primary reference frame's slot, and is all-zero without one. + let prev_seg_map = if header.primary_ref_frame == PRIMARY_REF_NONE { + None + } else { + seg_map_slots[header.ref_frame_idx[header.primary_ref_frame as usize] as usize].clone() + }; + decode::set_segmentation( + header.segmentation, + header.mi_rows as usize, + header.mi_cols as usize, + prev_seg_map.as_deref(), + ); // lane-superres stage 2/3: `use_superres` adds/removes no per-block // symbol (spec 7.16's upscaling is a pixel-domain post-process // libaom's `decodeframe.c` runs between CDEF and loop restoration, @@ -509,20 +543,12 @@ pub fn decode_stream(data: &[u8]) -> Result> { // call above, right before anything else can overwrite it) -- // see `decode::take_last_frame_wide_margin`'s doc. let wide_margin = crate::decode::take_last_frame_wide_margin(); - // lane-hbd r5: `upscale_row` (superres.rs) is `&[u8]`, clamping at - // 255 -- narrowed from the old blanket bit-depth refusal to only - // the case that actually reaches unported code. - if header.use_superres && bit_depth != 8 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)", - )); - } let picture = if header.use_superres { crate::superres::upscale_picture( &picture, header.upscaled_width as usize, wide_margin.as_ref(), + bit_depth as u32, ) } else { picture @@ -634,6 +660,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { &picture, header.upscaled_width as usize, wide_margin.as_ref(), + bit_depth as u32, ) } else { picture @@ -696,6 +723,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { } } pictures_decoded += 1; + let decoded_seg_map = decode::take_segment_ids(); for i in 0..NUM_REF_FRAMES { if header.refresh_frame_flags & (1 << i) != 0 { cdf_slots[i] = Some(stored_cdfs.clone()); @@ -705,23 +733,21 @@ pub fn decode_stream(data: &[u8]) -> Result> { // caller's output below carries the grained picture. ref_slots[i] = Some(picture.clone()); motion_field_slots[i] = Some(motion_field.clone()); + seg_map_slots[i] = Some(decoded_seg_map.clone()); order_hint_slots[i] = header.order_hint; } } if header.show_frame { let output = if header.film_grain.apply_grain { - // lane-hbd r5: same 8-bit-only LUT/blend as the - // show_existing_frame arm above. - if bit_depth != 8 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", - )); - } let mc_identity = parser .sequence_header() .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) + crate::film_grain::apply_grain( + &picture, + &header.film_grain, + mc_identity, + bit_depth as u32, + ) } else { picture }; @@ -880,13 +906,27 @@ mod tests { hash } + /// Whether ffmpeg is on PATH. Absence normally SKIPs, but + /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every + /// aomenc gate decodes its stream through ffmpeg and is meaningless + /// without it -- turns it into a hard failure. Without this the require + /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first + /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg + /// printed SKIP and reported green (class gate-skips-on-its-own-failure). fn have_ffmpeg() -> bool { - Command::new("ffmpeg") + let present = Command::new("ffmpeg") .arg("-version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() - .is_ok_and(|s| s.success()) + .is_ok_and(|s| s.success()); + assert!( + present + || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() + && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), + "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" + ); + present } /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. @@ -1942,6 +1982,237 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)"); } + /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1` + /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the + /// identical bytes (ffmpeg synthesizes grain by default -- no + /// grain-disable flag is passed anywhere in this file). Proves the + /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`, + /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather + /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed + /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a + /// silent 8-bit fallback nor a stream aomenc emitted without + /// `apply_grain` can make it pass vacuously. + #[test] + fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (64usize, 64usize); + let stream = encode_10bit_gradients( + NAME, + width, + height, + 1, + &["--film-grain-test=1", "--limit=1"], + ); + assert_eq!( + parsed_bit_depth(&stream), + 10, + "{NAME}: aomenc did not actually write a 10-bit sequence header" + ); + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + let mut saw_grain = false; + while pos < stream.len() { + let obu = probe.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + if let ObuKind::Frame(header, _) = obu.kind + && header.film_grain.apply_grain + { + // A grain block whose scaling LUT is empty would blend a + // zero delta into every pixel and let this gate pass without + // the bit-depth math mattering at all. + assert!( + header.film_grain.num_y_points > 0, + "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op" + ); + saw_grain = true; + } + } + assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain"); + let before = crate::film_grain::grain_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused: {e}"), + }; + assert!( + crate::film_grain::grain_hits() > before, + "{NAME}: matched but zero grain_hits -- grain synthesis never ran" + ); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); + eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits()); + } + + /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1 + /// --superres-denominator=12` key frame, decoded pixel-exact against + /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s + /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit + /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts + /// `bit_depth == 10` and `superres_hits > 0`. + #[test] + fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (64usize, 64usize); + let stream = encode_10bit_gradients( + NAME, + width, + height, + 1, + &[ + "--limit=1", + "--kf-max-dist=0", + "--superres-mode=1", + "--superres-denominator=12", + "--superres-kf-denominator=12", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + ], + ); + assert_eq!( + parsed_bit_depth(&stream), + 10, + "{NAME}: aomenc did not actually write a 10-bit sequence header" + ); + let before = crate::superres::superres_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused: {e}"), + }; + assert!( + crate::superres::superres_hits() > before, + "{NAME}: matched but zero superres_hits -- the upscaler never ran" + ); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); + eprintln!( + "{NAME}: pixel-exact, superres_hits={}", + crate::superres::superres_hits() + ); + } + + /// `bit_depth` of the first sequence header in `stream`. + fn parsed_bit_depth(stream: &[u8]) -> u8 { + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + while pos < stream.len() && probe.sequence_header().is_none() { + let obu = probe.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + } + probe + .sequence_header() + .expect("stream has a sequence header OBU") + .color_config + .bit_depth + } + + /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and + /// encode it with a real 10-bit `aomenc`, returning the OBU stream. + /// `extra` carries the tool flags under test. + fn encode_10bit_gradients( + name: &str, + width: usize, + height: usize, + frames: usize, + extra: &[&str], + ) -> Vec { + let duration = frames as f64 / 25.0; + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(42, width, height, &format!("duration={duration}:rate=25")), + "-pix_fmt", + "yuv420p10le", + "-strict", + "-1", + "-t", + &format!("{duration}"), + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{name}: ffmpeg failed to render the 10-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=30", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--input-bit-depth=10", + "--bit-depth=10", + ]; + args.extend_from_slice(extra); + args.extend_from_slice(&["--obu", "-o", "-", "-"]); + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{name}: aomenc refused the 10-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + } + /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2` /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above, @@ -6705,20 +6976,23 @@ mod tests { crate::decode::cdef_idx_hits() ); } - /// lane-tiny r1 diagnostic (not a gate): sweeps tiny key-frame sizes - /// against real aomenc + ffmpeg to find the exact size boundary of the - /// silent-wrong-pixels defect the sub8 lane's r2 dead-end flagged (a - /// plain 16x16 stream, no exotic tools). `#[ignore]`d -- prints a - /// pass/fail table, asserts nothing; run manually with `--nocapture`. + /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame + /// size real aomenc will encode, decoded pixel-exact against ffmpeg. + /// Tiny frames are where every edge/partial-superblock corner case is + /// forced, and this sweep is what found both r3's filter-intra tx_type + /// CDF row and r4's chroma-transform-size deblock defect -- so it + /// hard-asserts now: a decode error, a refusal, or one differing sample + /// at any size/seed fails. Only a genuinely absent oracle skips, and + /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too. #[test] - #[ignore = "diagnostic sweep, run manually with --nocapture"] - fn probe_tiny_frame_size_boundary() { + fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() { if !have_ffmpeg() || !have_aomenc() { eprintln!("SKIP: no ffmpeg/aomenc"); return; } let sizes: &[(usize, usize)] = &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)]; + let mut total_exact = 0u32; for &(width, height) in sizes { let mut ok = 0u32; let mut bad = 0u32; @@ -6767,7 +7041,18 @@ mod tests { let stream = out.stdout; let frames = match decode_stream(&stream) { Err(e) => { - eprintln!(" {width}x{height} seed {seed}: REFUSED {e}"); + // A NAMED refusal is the only non-exact outcome this + // gate tolerates (8x8 still needs a rectangular + // transform); anything else is a hard failure, and + // the floor assert below keeps that from going + // vacuous. + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{width}x{height} seed {seed}: failed outright, not a named \ + refusal: {msg}" + ); + eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}"); refused += 1; continue; } @@ -6782,6 +7067,12 @@ mod tests { ok += 1; } else { bad += 1; + let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count(); + let (ndy, ndu, ndv) = ( + nd(&frames[0].y, &ffmpeg_frames[0].y), + nd(&frames[0].u, &ffmpeg_frames[0].u), + nd(&frames[0].v, &ffmpeg_frames[0].v), + ); let mut first = None; for row in 0..height { for col in 0..width { @@ -6802,13 +7093,32 @@ mod tests { .filter(|(a, b)| a != b) .count(); eprintln!( - " {width}x{height} seed {seed}: MISMATCH luma first_diff={first:?} ndiff_luma={ndiff}/{}", + " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \ + ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}", width * height ); } } - eprintln!("{width}x{height}: {ok} ok / {bad} mismatch / {refused} refused (of {n})"); - } + assert_eq!( + bad, 0, + "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \ + {refused} named refusals)" + ); + eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals"); + total_exact += ok; + } + // Hit counter: the sweep proved nothing unless every size x seed + // attempt really ran end to end (aomenc -> us -> ffmpeg compare). + // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds + // pixel-exact -- only 8x8 is allowed to refuse outright today. If a + // future change makes sizes refuse instead of decode, this fails + // rather than passing on refusals alone. + assert!( + total_exact >= 70, + "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \ + refusals cannot substitute for decodes" + ); + eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts"); } /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with @@ -8988,45 +9298,55 @@ mod tests { ); } - /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without - /// -- a real >1-tile-column stream with a genuine INTER frame (not just - /// the key-frame-only two-column gate above), decoded through - /// `decode_stream` itself. Same recipe as the key-frame gate - /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the - /// same feature-disable envelope so the gate isolates the tile loop, not - /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000` - /// so frame 1 is a real inter frame, and `gradients_source`'s default - /// `speed=0.01` rotation (undisturbed -- not overridden by the tail) - /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_ - /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually - /// have to walk a live MV stack across the tile-column boundary, not - /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2 - /// frames at rate=25) per the class in ledger - /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole- - /// file` (never leave an ffmpeg/lavfi generate unbounded). - #[test] - fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact"; + /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active. + /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two + /// paths libaom uses to switch `segmentation_enabled` on by itself + /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only + /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock + /// delta-q reader out of the picture so a mismatch points at the segment + /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is + /// what gives variance/complexity AQ different segments to assign -- + /// a flat gradient collapses every block onto one segment, which the + /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run. + /// The rest of the recipe is the delta-q gate's own feature-disable + /// envelope, so this gate isolates the segmentation reader. + fn run_segmentation_gate( + name: &str, + aq_mode: &str, + bit_depth: usize, + frame_count: usize, + rate_args: &[&str], + ) { + let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { - eprintln!("SKIP {NAME}: no ffmpeg"); + eprintln!("SKIP {name}: no ffmpeg"); return; } if !have_aomenc() { - eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); return; } + crate::decode::reset_segment_hits(); let (width, height) = (128usize, 64usize); - let frames = 2usize; - let mut matched = 0u32; let mut named_refusals = 0u32; - for attempt in 0..20u32 { + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(10); + for attempt in 0..n_attempts { let seed = 42 + attempt; - let source = gradients_source(seed, width, height, "duration=0.08:rate=25"); + let duration = frame_count as f64 / 25.0; + let source = format!( + "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", + sx = -0.6 + 0.005 * (attempt as f64), + sy = -0.4 + 0.005 * (attempt as f64) + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; let y4m = Command::new("ffmpeg") .args([ - "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f", - "yuv4mpegpipe", "-", + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", ]) .stdin(Stdio::null()) .stdout(Stdio::piped()) @@ -9038,43 +9358,310 @@ mod tests { "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr) ); - let mut child = Command::new(aomenc_path()) - .args([ - "--codec=av1", - "--passes=1", - "--end-usage=q", - "--cq-level=45", - "--cpu-used=0", - &format!("--limit={frames}"), - "--kf-max-dist=1000", - "--lag-in-frames=0", - "--auto-alt-ref=0", - "--threads=1", - "--row-mt=0", - "--tile-columns=1", - "--tile-rows=0", - "--sb-size=64", - "--loopfilter-control=0", - "--max-reference-frames=3", - "--reduced-reference-set=1", - "--enable-warped-motion=0", - "--enable-obmc=0", - "--enable-masked-comp=0", - "--enable-interintra-comp=0", - "--enable-dist-wtd-comp=0", - "--enable-diff-wtd-comp=0", - "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", - "--enable-smooth-interintra=0", - "--enable-ref-frame-mvs=0", - "--enable-rect-partitions=0", - "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=0", - "--enable-paeth-intra=0", - "--enable-directional-intra=0", - "--enable-angle-delta=0", + let depth_args: Vec = if bit_depth == 10 { + vec!["--input-bit-depth=10".to_owned(), "--bit-depth=10".to_owned()] + } else { + Vec::new() + }; + let aq = format!("--aq-mode={aq_mode}"); + let mut args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--cpu-used=4", + &aq, + "--deltaq-mode=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=1", + "--enable-global-motion=0", + "--enable-obmc=1", + "--tune-content=default", + "--enable-masked-comp=1", + "--enable-dist-wtd-comp=0", + "--enable-interintra-comp=1", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=1", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=1", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + ]; + args.extend(rate_args.iter().copied()); + args.extend(depth_args.iter().map(String::as_str)); + args.extend(["--obu", "-o", "-", "-"]); + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + // The stream must really carry `segmentation_enabled`, or the + // gate proves nothing about the reader. + let mut seg_frames = 0u32; + { + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + while pos < stream.len() { + let obu = probe.parse_obu(&stream[pos..]).expect("parsing the gate stream"); + pos += obu.total_size; + match &obu.kind { + ObuKind::Frame(h, _) => { + if h.segmentation.enabled { + seg_frames += 1; + } + } + ObuKind::FrameHeader(h) => { + if h.segmentation.enabled { + seg_frames += 1; + } + } + _ => {} + } + } + } + if seg_frames == 0 { + eprintln!("seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt"); + continue; + } + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{name} failed outright, not a named refusal (seed {seed}): {msg}" + ); + assert!( + !msg.contains("segment_id symbol"), + "{name} refused on the segmentation reader itself (seed {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})"); + } + matched += 1; + } + assert!( + matched > 0, + "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \ + the gate never exercised segmentation" + ); + assert!( + crate::decode::segment_id_hits() > 0, + "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \ + the reader is unexercised" + ); + assert!( + crate::decode::segment_ids_seen() >= 2, + "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \ + every block landed in one segment, so nothing was actually segmented", + crate::decode::segment_ids_seen() + ); + // An inter-frame run must also have exercised the TEMPORAL path + // (`seg_id_predicted` against the primary reference's saved map); + // the key-frame-only run has no previous map by construction. + if frame_count > 1 { + assert!( + crate::decode::segment_pred_hits() > 0, + "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \ + seg_id_predicted symbols -- the temporal_update path is unexercised" + ); + } + eprintln!( + "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \ + out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \ + seg_id_predicted symbols={}", + crate::decode::segment_id_hits(), + crate::decode::segment_ids_seen(), + crate::decode::segment_pred_hits() + ); + } + + #[test] + fn a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact() { + run_segmentation_gate( + "a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact", + "1", + 8, + 16, + &["--end-usage=q", "--cq-level=45"], + ); + } + + // lane-seg r1 DEFERRED: an `--aq-mode=2` (complexity AQ) twin of the gate + // above. libaom only switches segmentation on for complexity AQ once the + // target bits per 64x64 superblock clear `sb64_target_rate >= 256` + // (`aq_complexity.c:is_sb_aq_enabled`), which needs `--end-usage=vbr`; + // every VBR recipe tried (cpu-used 0 and 4, 32x32 and 64x64 fixed + // partitions) makes aomenc pick partition shapes OTHER lanes still refuse + // (AB below 16x16, SB-level HORZ/VERT, part32 values 4/6), so 10/10 + // attempts refuse before a pixel is compared. The syntax exercised would + // be identical to variance AQ's (both features only ever set + // `SEG_LVL_ALT_Q` via `update_map`), so this is coverage, not capability. + // Unblocked by the sub-16x16 rect/AB partition lanes. + + /// His two AV1 films are both `yuv420p10le`, so every capability lands + /// with a 10-bit twin (memory `his-av1-library-is-10-bit`). KEY FRAME + /// ONLY (`frame_count = 1`): a 10-bit INTER frame does not decode + /// pixel-exact in this crate yet, segmentation or not -- lane-seg r1 ran + /// this same recipe with `--aq-mode=0` (segmentation off entirely) and it + /// still mismatched at frame 2, so the 16-frame 10-bit variant would be + /// gating an unrelated pre-existing gap. Variance AQ segments the key + /// frame too (`aq_variance.c`, `is_frame_aq_enabled` includes + /// `frame_is_intra_only`), so this still proves the 10-bit segment-id + /// read and the per-segment 10-bit dequant. + #[test] + fn a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact() { + run_segmentation_gate( + "a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact", + "1", + 10, + 1, + &["--end-usage=q", "--cq-level=45"], + ); + } + + /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without + /// -- a real >1-tile-column stream with a genuine INTER frame (not just + /// the key-frame-only two-column gate above), decoded through + /// `decode_stream` itself. Same recipe as the key-frame gate + /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the + /// same feature-disable envelope so the gate isolates the tile loop, not + /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000` + /// so frame 1 is a real inter frame, and `gradients_source`'s default + /// `speed=0.01` rotation (undisturbed -- not overridden by the tail) + /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_ + /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually + /// have to walk a live MV stack across the tile-column boundary, not + /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2 + /// frames at rate=25) per the class in ledger + /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole- + /// file` (never leave an ffmpeg/lavfi generate unbounded). + #[test] + fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (128usize, 64usize); + let frames = 2usize; + let mut matched = 0u32; + let mut named_refusals = 0u32; + for attempt in 0..20u32 { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.08:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + &format!("--limit={frames}"), + "--kf-max-dist=1000", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--threads=1", + "--row-mt=0", + "--tile-columns=1", + "--tile-rows=0", + "--sb-size=64", + "--loopfilter-control=0", + "--max-reference-frames=3", + "--reduced-reference-set=1", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-ref-frame-mvs=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", "--enable-tx-size-search=0", "--enable-cdef=0", "--enable-restoration=0", @@ -9677,6 +10264,549 @@ mod tests { ); } + /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32 + /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the + /// tx-size search left at aomenc's own default (ON) -- every sibling + /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly + /// why the split-transform strip was never exercised. RD is then free to + /// give a strip a transform smaller than its own size, the case + /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT + /// intra strip with a split transform (per-unit rect prediction is not + /// ported)") until this round ported the per-transform-unit predict-and- + /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta: + /// without it a stream that resolved every `tx_depth` to 0 would + /// pixel-match by construction and prove nothing. A decode error that is + /// not a named refusal, and any pixel mismatch, FAIL -- only a missing + /// tool skips. + #[test] + fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (192usize, 128usize); + let before = crate::decode::rect_split_tx_hits(); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let mut split_so_far = 0usize; + // Bounded sweep: see this gate's own doc for the seed-77 residue and + // why extending it is a diagnosis knob, not a pass/fail one. + let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(20); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, + // Desaturated (`hue=s=0`, the same guard + // `a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact` + // uses): with the tx-size search ON, a real chroma + // gradient hits a PRE-EXISTING chroma defect on the plain + // SQUARE path -- measured this round with + // `--enable-rect-partitions=0` on this very recipe, seed + // 42, U plane, i.e. with no rect strip in the stream at + // all. Flat chroma keeps that unrelated defect out of + // this gate (gate-recipe-confound class); it is open + // residue in lanes/rectsplit-r1.report.md, not fixed here. + "-vf", "hue=s=0", + "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's + // own default (search ON) is the entire point of this gate. + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=16", + "--max-partition-size=32", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + continue; + } + Ok(frames) => frames, + }; + let after = crate::decode::rect_split_tx_hits(); + eprintln!( + "{NAME}: seed {seed} decoded, split-tx strips this stream: {}", + after - before - split_so_far + ); + split_so_far = after - before; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); + if let Some(i) = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .position(|(a, b)| a != b) + { + eprintln!( + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + i % width, + i / width, + frames[0].y[i], + ffmpeg_frames[0].y[i] + ); + } + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + let split_hits = crate::decode::rect_split_tx_hits() - before; + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" + ); + assert!( + split_hits > 0, + "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \ + matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \ + this run" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ + rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts" + ); + } + + /// lane-rectsplit r1 gate (c): gate (a)'s recipe with + /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so + /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip + /// -- the case [`crate::decode::decode_block_rect`] refused by name + /// ("filter intra on a HORZ/VERT strip (this decoder predicts + /// square-only)") until this round gave `predict_filter_intra` its own + /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta: + /// a stream where RD never picked filter intra on a strip would + /// pixel-match by construction and prove nothing. + #[test] + fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (192usize, 128usize); + let before = crate::decode::filter_intra_rect_hits(); + let rect_before = crate::decode::rect_partition_hits(); + let fi_square_before = crate::decode::filter_intra_hits(); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + // Diagnosis knob: which content makes RD pick a HORZ/VERT strip + // AND filter intra on it is a search (see this round's report). + let source = match std::env::var("EC_RECTSPLIT_SRC").unwrap_or_default().as_str() { + "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"), + "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"), + _ => gradients_source(seed, width, height, "duration=0.04:rate=25"), + }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, + // Same `hue=s=0` guard as gate (a): a real chroma gradient + // under the tx-size search hits a PRE-EXISTING square-path + // chroma defect that has nothing to do with this lane. + "-vf", "hue=s=0", + "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + // Diagnosis knob only (default is the gate's pinned recipe): + // which `--cq-level` makes aomenc's RD reach for filter intra on + // a strip is a search, and the sweep that found this one is in + // lanes/rectsplit-r1.report.md. + let cq = format!( + "--cq-level={}", + // Pinned by the sweep in lanes/rectsplit-r1.report.md: at + // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and + // filter intra on none of them; at cq 25 strips are common + // (130/100 seeds) and filter intra lands on one every ~13 + // seeds. + std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into()) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq, + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=16", + "--max-partition-size=32", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + // The point of this gate. + "--enable-filter-intra=1", + // The square filter-intra gate's own way of making RD reach + // for filter intra at all: with the directional/smooth/paeth + // competitors off, DC_PRED + filter intra is what is left + // (recipe borrowed from + // `a_real_aomenc_filter_intra_stream_decodes_pixel_exact`; + // without them 20/20 streams picked filter intra zero times + // on a strip -- measured this round). + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--obu", + "-o", + "-", + "-", + ]; + // Diagnosis knob (default: every intra mode on): turning the + // directional/smooth/paeth competitors off is how the square + // filter-intra gate makes RD reach for filter intra, but with all + // four off aomenc stops picking rect partitions here entirely + // (rect strips=0, filter-intra blocks=28, measured this round), + // so the firing recipe is a search over subsets. + let mut args = args; + let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default(); + for tool in off.split(',').filter(|t| !t.is_empty()) { + args.push(match tool { + "smooth" => "--enable-smooth-intra=0", + "paeth" => "--enable-paeth-intra=0", + "dir" => "--enable-directional-intra=0", + "angle" => "--enable-angle-delta=0", + other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"), + }); + } + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); + if let Some(i) = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .position(|(a, b)| a != b) + { + eprintln!( + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + i % width, + i / width, + frames[0].y[i], + ffmpeg_frames[0].y[i] + ); + } + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + let fi_hits = crate::decode::filter_intra_rect_hits() - before; + eprintln!( + "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}", + crate::decode::rect_partition_hits() - rect_before, + crate::decode::filter_intra_hits() - fi_square_before + ); + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" + ); + assert!( + fi_hits > 0, + "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \ + {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ + filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts" + ); + } + + /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s + /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every + /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its + /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then + /// carry a split transform, which [`crate::decode::decode_block_rect64`] + /// refused by name ("a superblock-level HORZ/VERT strip with a split + /// transform") until this round. Same hard `rect_split_tx_hits()` delta + /// assert as gate (a). + /// lane-rectsplit r1 MEASURED RED, `#[ignore]`d with its number (the + /// `rect64q` gate's own precedent): with the per-transform-unit port + /// wired at the superblock level, seed 50 decodes one sample off -- + /// luma (171, 56), ours 147 vs ffmpeg 148, inside the 64x32 strip at + /// mi=(8,32) whose transform resolved to depth 2 (TX_16X16). Seeds 42-49 + /// with depth-1 (TX_32X32) units were pixel-exact. The refusal in + /// `decode_block_rect64` was therefore RESTORED rather than lifted; run + /// this gate (`--ignored`) after any fix to that arm. + #[ignore = "lane-rectsplit r1: measured RED, seed 50 luma (171,56) off by one; refusal kept"] + #[test] + fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (192usize, 128usize); + let before = crate::decode::rect_split_tx_hits(); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let mut split_so_far = 0usize; + // Bounded sweep: see this gate's own doc for the seed-77 residue and + // why extending it is a diagnosis knob, not a pass/fail one. + let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(20); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, + // Desaturated (`hue=s=0`, the same guard + // `a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact` + // uses): with the tx-size search ON, a real chroma + // gradient hits a PRE-EXISTING chroma defect on the plain + // SQUARE path -- measured this round with + // `--enable-rect-partitions=0` on this very recipe, seed + // 42, U plane, i.e. with no rect strip in the stream at + // all. Flat chroma keeps that unrelated defect out of + // this gate (gate-recipe-confound class); it is open + // residue in lanes/rectsplit-r1.report.md, not fixed here. + "-vf", "hue=s=0", + "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's + // own default (search ON) is the entire point of this gate. + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=32", + "--max-partition-size=64", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + continue; + } + Ok(frames) => frames, + }; + let after = crate::decode::rect_split_tx_hits(); + eprintln!( + "{NAME}: seed {seed} decoded, split-tx strips this stream: {}", + after - before - split_so_far + ); + split_so_far = after - before; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); + if let Some(i) = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .position(|(a, b)| a != b) + { + eprintln!( + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + i % width, + i / width, + frames[0].y[i], + ffmpeg_frames[0].y[i] + ); + } + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + let split_hits = crate::decode::rect_split_tx_hits() - before; + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" + ); + assert!( + split_hits > 0, + "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \ + matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \ + this run" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ + rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts" + ); + } + /// lane-rect64q r1: same recipe as /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`] /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is diff --git a/crates/ec-av1/src/superres.rs b/crates/ec-av1/src/superres.rs index 6affd094..d49f2196 100644 --- a/crates/ec-av1/src/superres.rs +++ b/crates/ec-av1/src/superres.rs @@ -89,7 +89,16 @@ fn round_power_of_two(sum: i32, bits: u32) -> i32 { /// true, replicating the row's own edge pixels rather than sampling a /// neighbour tile). `in_width` and `out_width` must both be positive; /// `row.len() == in_width` and `out.len() == out_width`. -pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize, out: &mut [u8]) { +/// `bit_depth` only picks the output clamp (`clip_pixel`/`clip_pixel_highbd` +/// in libaom's `av1_convolve_horiz_rs_c`); the filter, its `Round2` and the +/// edge padding are bit-depth independent (spec 7.16). +pub(crate) fn upscale_row( + row: &[u16], + real_right_margin: &[u16], + out_width: usize, + out: &mut [u16], + bit_depth: u32, +) { let in_width = row.len(); debug_assert!(in_width > 0 && out_width > 0); 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 // column-by-column against real libaom via `scripts/superres-pin- // harness.c`'s `row6-realedgeval` case (r3). let pad = UPSCALE_NORMATIVE_TAPS + 2; - let mut padded = vec![0u8; in_width + 2 * pad]; + let mut padded = vec![0u16; in_width + 2 * pad]; padded[..pad].fill(row[0]); padded[pad..pad + in_width].copy_from_slice(row); 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 let idx = base + int_pel + k as i64; sum += padded[idx as usize] as i32 * c as i32; } - *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, 255) as u8; + *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, (1 << bit_depth) - 1) as u16; x_qn += x_step_qn; } } @@ -141,14 +150,15 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize /// spec only widens columns). `rows` is the plane's row-major byte buffer /// at `in_width`; returns a new buffer at `out_width`. pub(crate) fn upscale_plane( - rows: &[u8], + rows: &[u16], height: usize, in_width: usize, out_width: usize, - margin: Option<(&[u8], usize)>, -) -> Vec { + margin: Option<(&[u16], usize)>, + bit_depth: u32, +) -> Vec { debug_assert_eq!(rows.len(), height * in_width); - let mut out = vec![0u8; height * out_width]; + let mut out = vec![0u16; height * out_width]; for r in 0..height { let src = &rows[r * in_width..(r + 1) * in_width]; let dst = &mut out[r * out_width..(r + 1) * out_width]; @@ -158,7 +168,7 @@ pub(crate) fn upscale_plane( } _ => &[], }; - upscale_row(src, real_right, out_width, dst); + upscale_row(src, real_right, out_width, dst, bit_depth); } out } @@ -185,51 +195,40 @@ pub(crate) fn upscale_picture( picture: &crate::encode::Picture, upscaled_width: usize, margin: Option<&crate::encode::Picture>, + bit_depth: u32, ) -> crate::encode::Picture { SUPERRES_HITS.with(|c| c.set(c.get() + 1)); let height = picture.height; let chroma_in_w = picture.width.div_ceil(2); let chroma_out_w = upscaled_width.div_ceil(2); let chroma_h = height.div_ceil(2); - // lane-hbd r4: superres is 8-bit by construction (`upscale_row` clamps - // to 255) -- narrow at this boundary; callers refuse `bit_depth != 8` - // before ever reaching here (see `stream.rs`). - let narrow = |v: &[u16]| -> Vec { v.iter().map(|&s| s as u8).collect() }; - let picture_y8 = narrow(&picture.y); - let picture_u8 = narrow(&picture.u); - let picture_v8 = narrow(&picture.v); - let margin_y8 = margin.map(|m| narrow(&m.y)); - let margin_u8 = margin.map(|m| narrow(&m.u)); - let margin_v8 = margin.map(|m| narrow(&m.v)); - let widen = |v: Vec| -> Vec { v.into_iter().map(u16::from).collect() }; crate::encode::Picture { width: upscaled_width, height, - y: widen(upscale_plane( - &picture_y8, + y: upscale_plane( + &picture.y, height, picture.width, upscaled_width, - margin_y8.as_deref().map(|m| (m, margin.unwrap().width)), - )), - u: widen(upscale_plane( - &picture_u8, + margin.map(|m| (m.y.as_slice(), m.width)), + bit_depth, + ), + u: upscale_plane( + &picture.u, chroma_h, chroma_in_w, chroma_out_w, - margin_u8 - .as_deref() - .map(|m| (m, margin.unwrap().width.div_ceil(2))), - )), - v: widen(upscale_plane( - &picture_v8, + margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))), + bit_depth, + ), + v: upscale_plane( + &picture.v, chroma_h, chroma_in_w, chroma_out_w, - margin_v8 - .as_deref() - .map(|m| (m, margin.unwrap().width.div_ceil(2))), - )), + margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))), + bit_depth, + ), } } @@ -249,17 +248,17 @@ mod tests { /// here independently of this module's own logic. #[test] fn upscale_row_matches_libaom_in8_out12() { - let row = [10u8, 20, 30, 40, 50, 60, 70, 80]; - let mut out = [0u8; 12]; - upscale_row(&row, &[], 12, &mut out); + let row = [10u16, 20, 30, 40, 50, 60, 70, 80]; + let mut out = [0u16; 12]; + upscale_row(&row, &[], 12, &mut out, 8); assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]); } #[test] fn upscale_row_matches_libaom_in8_out16() { - let row = [10u8, 20, 30, 40, 50, 60, 70, 80]; - let mut out = [0u8; 16]; - upscale_row(&row, &[], 16, &mut out); + let row = [10u16, 20, 30, 40, 50, 60, 70, 80]; + let mut out = [0u16; 16]; + upscale_row(&row, &[], 16, &mut out, 8); assert_eq!( out, [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81] @@ -273,10 +272,10 @@ mod tests { /// captured-row pins above. #[test] fn upscale_row_of_a_flat_input_is_flat() { - let row = [200u8; 8]; - let mut out = [0u8; 12]; - upscale_row(&row, &[], 12, &mut out); - assert_eq!(out, [200u8; 12]); + let row = [200u16; 8]; + let mut out = [0u16; 12]; + upscale_row(&row, &[], 12, &mut out, 8); + assert_eq!(out, [200u16; 12]); } /// r3: the real 43->64 failing case, pinned against real libaom @@ -287,14 +286,14 @@ mod tests { /// margin fix. #[test] fn upscale_row_with_real_margin_matches_libaom_in43_out64() { - let row: [u8; 43] = [ + let row: [u16; 43] = [ 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131, 133, 134, 136, 137, 138, 139, 140, 140, 141, ]; - let real_margin = [140u8]; - let mut out = [0u8; 64]; - upscale_row(&row, &real_margin, 64, &mut out); + let real_margin = [140u16]; + let mut out = [0u16; 64]; + upscale_row(&row, &real_margin, 64, &mut out, 8); assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140"); } } diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index ab0b3b7c..60fcc201 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -2983,13 +2983,27 @@ mod tests { } } + /// Whether ffmpeg is on PATH. Absence normally SKIPs, but + /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every + /// aomenc gate decodes its stream through ffmpeg and is meaningless + /// without it -- turns it into a hard failure. Without this the require + /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first + /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg + /// printed SKIP and reported green (class gate-skips-on-its-own-failure). fn have_ffmpeg() -> bool { - Command::new("ffmpeg") + let present = Command::new("ffmpeg") .arg("-version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() - .is_ok_and(|s| s.success()) + .is_ok_and(|s| s.success()); + assert!( + present + || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() + && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), + "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" + ); + present } /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes. diff --git a/lanes/hbd10-r1.report.md b/lanes/hbd10-r1.report.md new file mode 100644 index 00000000..3f46f67f --- /dev/null +++ b/lanes/hbd10-r1.report.md @@ -0,0 +1,123 @@ +# lane-hbd10 round 1 report + +Branch `lane-hbd10`, worktree `edith_codecs-hbd10`, off main `3808cf8` (no rebase +needed -- branch was already at main's HEAD, `git log --oneline -1 main` = 3808cf8). + +## Refusals lifted (2) + +Both removed from `crates/ec-av1/src/refusal_inventory.rs` and from their +`stream.rs` guard sites, each with a real-aomenc 10-bit gate in the same commit: + +- `"a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)"` +- `"a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)"` + +## What changed + +- `crates/ec-av1/src/film_grain.rs:180` -- `GRAIN_MIN`/`GRAIN_MAX` consts replaced by + `GRAIN_BIT_DEPTH` (thread-local, set once per `apply_grain`) + `grain_range()`: + `grain_center = 128 << (bit_depth - 8)`, mirroring libaom's file statics + (`grain_synthesis.c:1043-1045`). All 10 clamp sites (luma/chroma AR filter, + ver/hor overlap blending) now read the runtime range. +- `crates/ec-av1/src/film_grain.rs:230,265` -- `gauss_sec_shift` was hardcoded + `4 + grain_scale_shift` (i.e. `12 - 8 + ...`); now `12 - bit_depth + grain_scale_shift` + (`grain_synthesis.c:468,503`). +- `crates/ec-av1/src/film_grain.rs:~296` -- new `scale_lut()`, a verbatim port of + `scale_LUT` (`grain_synthesis.c:616-626`): the scaling LUT stays 256 entries at + every bit depth, so the index is `>> (bit_depth-8)` and the two neighbouring + entries are interpolated with the dropped low bits (`x == 255` short-circuits). + Used at all three blend sites (Y, Cb, Cr) in `add_noise_to_block`. +- `crates/ec-av1/src/film_grain.rs` `add_noise_to_block` -- `cb_offset`/`cr_offset` + now `(offset << (bd-8)) - (1 << bit_depth)` (was `- 256`); the scaling-index clamp + is `(256 << (bd-8)) - 1` (was `255`); `clip_to_restricted_range` legal ranges and + the unrestricted max are `<< (bd-8)` (`grain_synthesis.c:752-795`). +- `crates/ec-av1/src/film_grain.rs:551` -- new `GRAIN_HITS` counter + `grain_hits()` + (class `gate-blind-to-feature`), incremented once per grained picture. +- `crates/ec-av1/src/superres.rs` -- `upscale_row`/`upscale_plane`/`upscale_picture` + take `&[u16]`/`bit_depth` instead of narrowing the (already `u16`) `Picture` planes + to `u8` and back; the only bit-depth-dependent step in spec 7.16 is the output + clamp, now `clamp(0, (1 << bit_depth) - 1)` (`clip_pixel_highbd`). Filter table, + `Round2`, step/x0 and the real-margin edge padding are unchanged. The three + libaom-pinned unit tests were retyped to `u16` and pass `bit_depth = 8`, so the + 8-bit pins still hold byte-for-byte. +- `crates/ec-av1/src/stream.rs` -- both `bit_depth != 8` refusal blocks deleted; + `apply_grain` (2 call sites) and `upscale_picture` (2 call sites) now receive the + sequence header's real `bit_depth`. +- `crates/ec-av1/src/gate_coverage.rs` -- unchanged, deliberately: it derives its set + from `--enable-*` flags only, and neither new gate enables or disables a tool that + was not already covered. `every_gate_disabling_a_tool_is_a_listed_coverage_hole` + stays green with the two new gates in the derived gate set. + +## Gates added (both hard-asserting, neither can SKIP on a mismatch) + +`crates/ec-av1/src/stream.rs`: + +1. `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact` -- + `aomenc --bit-depth=10 --input-bit-depth=10 --film-grain-test=1` over a + `yuv420p10le` lavfi gradients source, pixel-exact vs `ffmpeg_decode_sequence_10bit` + (ffmpeg synthesizes grain by default; no grain-disable flag exists anywhere in + this file). Hard-asserts the parsed `bit_depth == 10`, `apply_grain == true`, + `num_y_points > 0` (an empty scaling LUT would blend a zero delta and make the + gate vacuous), and `grain_hits()` moved. +2. `a_real_aomenc_10bit_superres_stream_decodes_pixel_exact` -- + `aomenc --bit-depth=10 --superres-mode=1 --superres-denominator=12 + --superres-kf-denominator=12`, same tool-disable envelope as the existing 8-bit + superres gate. Hard-asserts `bit_depth == 10` and `superres_hits()` moved. + +Shared helpers `encode_10bit_gradients` / `parsed_bit_depth` factored out next to them. + +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 + +### Sensitivity check (the gates are not vacuous) + +Temporarily passed a literal `8u32` instead of the real `bit_depth` at both call +sites (mutation reverted before commit): +- film-grain gate: panics in `film_grain.rs` `scale_lut` (a 10-bit sample indexes + past the 256-entry LUT) -- proves the grain path really runs over 10-bit samples. +- superres gate: `assertion left == right failed: luma vs ffmpeg`, ours saturated at + `255` where ffmpeg has 10-bit values -- proves the clamp is the thing under test. + +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 + +## His films: does either actually use grain or superres? + +Extracted 2s (`-t 2 -c:v copy -an -f obu`, bounded) of each and counted header +flags with a throwaway `examples/hbd10_headers.rs` (deleted after the run; the +0.4s extract the charter names is only 1.8 KB / a handful of OBUs at 2160p, too +short to be representative, so the window was widened to 2s). + +| film | seq bit_depth | film_grain_params_present | enable_superres | frames | apply_grain | num_y_points>0 | use_superres | +|---|---|---|---|---|---|---|---| +| ReelB (Ballad, 2160p HDR10) | 10 | true | **false** | 50 | **25** | 25 | 0 | +| ReelC (Director's Cut, 1080p) | 10 | true | false | 49 | 0 | 0 | 0 | + +**ReelB really does carry film grain**: half its frames in the first 2s set +`apply_grain` with a non-empty luma scaling LUT, at 10 bit. That refusal was a real +blocker-in-waiting for his library, and it is gone. **Neither film uses superres** +(`enable_superres = false` in both sequence headers, `use_superres = 0` on every +frame) -- the superres refusal is lifted and gated, but it is not on his films' path. + +`decode_probe` on those extracts (this branch): both films still stop earlier than +grain/superres, at partition coverage -- unchanged by this lane, as expected: +- ReelB: `REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes no leaf smaller than 8x8))` +- ReelC: `REFUSED: unsupported: AV1 tile (a 32x32 partition type this decoder does not code (value=4))` + +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 + +## Test totals + +`EC_AV1_REQUIRE_AOMENC=1 nice -n 10 cargo test -j3 -p ec-av1 --lib` +-> **269 passed, 0 failed, 23 ignored, 0 filtered out, 334.60s.** + +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 + +## Residue + +- accepted: 12-bit is code-generic (every formula is `bit_depth`-parameterised, not + `10`-specialised) but ungated -- no 12-bit gate was written and none of his files + is 12-bit. A 12-bit stream would decode, not refuse; that is a claim no test backs. +- accepted: grain at 4:2:2/4:4:4 stays out of scope -- `film_grain.rs` is 4:2:0 by + construction (documented at the top of the module), unchanged by this lane. +- deferred: chroma-only grain params (`num_y_points == 0`, `chroma_scaling_from_luma`) + at 10 bit are exercised by neither gate -- `--film-grain-test=1` sets luma points -- + what unblocks it: a `--film-grain-table` fixture that pins a chroma-only parameter + set. diff --git a/lanes/intrabc-r1.report.md b/lanes/intrabc-r1.report.md new file mode 100644 index 00000000..953744b3 --- /dev/null +++ b/lanes/intrabc-r1.report.md @@ -0,0 +1,114 @@ +# lane-intrabc r1 — the block vector decodes; the transform tree does not + +## Verdict + +The headline refusal `a block that actually uses intrabc (this decoder never +reconstructs one)` is **replaced, not lifted**. Its successor names the real +remaining wall: + +``` +an intrabc block under TxMode::Select (its transform size is coded by the +inter var-tx partition tree, which this decoder never reads) +``` + +Everything the charter listed *before* the residual is implemented and runs on +real aomenc streams: `use_intrabc`, the DV's own mv stack, the `ndvc` full-pel +`read_mv`, `av1_find_ref_dv`'s fallback, and the block-copy prediction. No +pixel-exact gate exists yet, because no aomenc recipe found this round produces +an intrabc block that does *not* also need `read_var_tx_size`. + +## What changed (worktree `edith_codecs-intrabc`, branch `lane-intrabc`) + +- `crates/ec-av1/src/cdf_state.rs:422` — `dv_joint`/`dv_comp`: libaom's `ndvc` + (`av1_init_mv_probs` gives it the same spec-8.4 defaults as `nmvc`, separate + adaptation), added to the per-frame counter-reset list at `:684`. +- `crates/ec-av1/src/decode.rs:590` — `INTRABC_MI_GRID` / `INTRABC_DV` / + `INTRABC_HITS` thread-locals + `intrabc_hits()`, `reset_intrabc_hits()`, + `record_intrabc_mi()`. The mi grid exists only while a frame header set + `allow_intrabc`. +- `crates/ec-av1/src/decode.rs:4046` (`read_intra_mode`) — `use_intrabc == 1` + now reads the DV instead of refusing, and returns immediately with + `YMode`/`UVMode` forced `DC_PRED` (libaom `read_intra_frame_mode_info` + returns at `decodemv.c:895`, so no mode/angle/palette/CFL/filter-intra + syntax follows). +- `crates/ec-av1/src/decode.rs:7681` — `read_intrabc_dv`: MV stack against + `INTRA_FRAME`, `nearest` else `near`, else `av1_find_ref_dv` + (`(0, -(64+256)*8)` in the first SB row, else `(-64*8, 0)`), predictor + floored to full pel, then `read_mv` on `dv_comp`/`dv_joint` with + `MV_SUBPEL_NONE` semantics (`force_integer_mv=true`, + `allow_high_precision_mv=false`). No DRL symbol is coded for a DV, so a + wrong predictor can only move pixels, never the bitstream position. +- `crates/ec-av1/src/decode.rs` (`decode_block`) — takes the DV, refuses + var-tx by name, switches the luma `TxbSet` to the **inter** ext-tx sets + (`txbset_for_inter`, since libaom's `is_inter_block` is true for intrabc, + `blockd.h:373`), builds the Y/U/V block-copy prediction with + `mc::predict_with_filter(.., Bilinear, ..)` off the *current* planes and + ships it through the existing `PALETTE_PRED` per-block prediction override, + and records the block into the mi grid. +- `crates/ec-av1/src/mvstack.rs:330,368` — **two real index bugs**: + `sign_bias()` and `gm_mv()` both indexed `table[ref_frame - LAST_FRAME]` + with no lower guard, so any query with `ref_frame == INTRA_FRAME` (0), which + is exactly what an intrabc block does, panicked with + `index out of bounds: the len is 7 but the index is 18446744073709551615`. + Both now return the neutral value below `LAST_FRAME`. Same-shape sweep: those + are the only two `- LAST_FRAME` table indexes in the crate. +- `crates/ec-av1/src/refusal_inventory.rs:55`, `gate_coverage.rs:36` — refusal + string replaced; `enable-intrabc` stays in `NEVER_EXERCISED` with its reason + rewritten to the true state. + +## Fixture recipe (the round's most reusable finding) + +Intra block copy is **impossible in a 64x64 frame**: a valid DV must clear +`INTRABC_DELAY_PIXELS` (256) plus one superblock, so a single-SB frame can +never contain one. Every 64x64 sweep this lane ran (3 sources x 6 cq) produced +zero intrabc blocks. A 512-wide frame with horizontally repeated content does: + +``` +ffmpeg -f lavfi -i "testsrc2=size=64x64:rate=1" -t 0.04 \ + -vf "tile=8x1,scale=512:64" -pix_fmt yuv420p -f rawvideo wide512.yuv +~/.cache/aom-oracle/build/aomenc --codec=av1 -w 512 -h 64 --i420 --limit=1 \ + --kf-max-dist=1 --cpu-used=1 --passes=1 --end-usage=q --cq-level=20 \ + --enable-intrabc=1 --tune-content=screen --enable-palette=0 \ + --enable-rect-partitions=0 --enable-ab-partitions=0 \ + --enable-1to4-partitions=0 --min-partition-size=16 --max-partition-size=32 \ + --obu -o w.obu wide512.yuv +cargo run -p ec-av1 --release --example decode_probe -- w.obu +``` + +`--enable-palette=0` and the partition switches are a **deviation from the +charter's gate recipe** (`--enable-palette=1`): with palette on, or with rect/AB +partitions available, the stream refuses on palette or on a sub-16x16 AB +partition *before* the first intrabc block, so it cannot isolate this lane's +capability at all. `cpu-used` must be <= 2 — at 3 and above aomenc's speed +features stop searching intrabc entirely (sweep: cpu 3/5/6/8 x cq 20/40, all 8 +decode clean, i.e. no intrabc block at all). + +## EVIDENCE + +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 +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 + +## Residue + +- fix-now (next round, needs its own charter): `read_var_tx_size` — the + `txfm_partition` CDF (21 contexts) does not exist anywhere in the crate, nor + do the above/left txfm-context arrays it needs, nor does the residual loop + handle a non-uniform TU tree. This is the single blocker between here and a + pixel-exact intrabc gate. +- deferred(var-tx): the pixel-exact 8-bit/10-bit gate the charter asks for, and + the `gate_coverage.rs` entry retirement — no stream can reach reconstruction + until var-tx reads. +- accepted, documented as corner-cuts in source: only `decode_block` (square + path) records into the intrabc mi grid; a frame mixing intrabc with rect or + sub-8x8 leaves would predict off an incomplete grid (DV value only, never the + parse). Chroma of an inter/intrabc block should inherit the co-located luma + `tx_type` (libaom `av1_get_tx_type`), while `read_plane` still derives + `DCT_DCT` for chroma — no symbol difference, but a suspected pixel difference + the moment luma picks a non-DCT type. Both are prime suspects for the first + pixel mismatch once var-tx lands. + +## Test totals + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (worktree, commit 09d6ff9): +**267 passed, 0 failed, 23 ignored**, 1125 s. `refusal_inventory` and +`gate_coverage` are green with the rewritten entries. diff --git a/lanes/rectsplit-r1.report.md b/lanes/rectsplit-r1.report.md new file mode 100644 index 00000000..c0fbb444 --- /dev/null +++ b/lanes/rectsplit-r1.report.md @@ -0,0 +1,93 @@ +# lane-rectsplit r1 — HORZ/VERT strips with a split transform, and filter intra on a strip + +Branch `lane-rectsplit` off main `3808cf8`; continues the orchestrator's WIP snapshot +`c5de1b6` (previous builder's uncommitted state), commit `16baa0f` is this round. + +## What changed + +- `crates/ec-av1/src/decode.rs:3159` `decode_rect_split` (from the WIP snapshot, kept): + a HORZ/VERT strip with `tx_depth != 0` predicts and reconstructs PER TRANSFORM UNIT in + raster order (spec 5.11.36), each unit taking its edges from the units already + reconstructed inside the same strip, with per-unit `has_top_right`/`has_bottom_left` + (libaom `reconintra.c`) instead of the standalone-block table; chroma stays one un-split + rect transform. `sub_tx_size_map[TX_32X16] == TX_16X16`, so every unit is square and reads + through the ordinary square `read_plane`. +- `crates/ec-av1/src/decode.rs:3453` — refusal "filter intra on a HORZ/VERT strip (this + decoder predicts square-only)" REMOVED from `decode_block_rect`, replaced by the + `FILTER_INTRA_RECT_HITS` counter. +- `crates/ec-av1/src/intra.rs:733` `predict_filter_intra` now takes `bw`x`bh` instead of one + square `side` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a rectangle just + as happily; `av1_filter_intra_allowed_bsize` genuinely allows every strip with both sides + <= 32). Two call sites updated (`reconstruct_rect` passes `bw, bh`, `reconstruct` passes + `side, side`). +- `crates/ec-av1/src/decode.rs:3833` — the below-16x16 leaf arm (`decode_leaf_rect`) keeps + BOTH refusals; its split-transform one is renamed to name the size ("a HORZ/VERT intra + strip below 16x16 with a split transform ...") because the 32x32-level string it shared is + now lifted, and it is added to `refusal_inventory.rs:41`. +- `crates/ec-av1/src/stream.rs:9337` gate (a), `:9503` gate (c), `:9700` gate (b, `#[ignore]`d + RED, from the WIP snapshot). + +## Refusals lifted (each with its gate) + +| refusal | gate | result | +| --- | --- | --- | +| "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 | +| "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 | + +Not lifted: +- "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not + ported)" — the port itself is wired at that level too, but gate (b) + `a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact` is + MEASURED RED: seed 50 decodes one sample off, luma (171, 56) ours 147 vs ffmpeg 148, inside + the 64x32 strip at mi=(8,32) whose transform resolved to depth 2 (TX_16X16). Seeds 42-49 + (depth 1 / TX_32X32 units) are pixel-exact. `#[ignore]`d with that number. + disposition: deferred(a range-ladder/prefilt-dump bisection of that one TU's top-right edge + availability) — the refusal stays, so no wrong pixels ship. +- "filter intra on a HORZ/VERT strip" / "a HORZ/VERT intra strip below 16x16 with a split + transform" at `decode_leaf_rect` (below 16x16): that arm only ports the skip case and has no + gate of its own. disposition: deferred(a below-16x16 strip gate, lane-sub8's territory). + +## Gate-recipe search (the part that cost the round) + +`--enable-filter-intra=1` alone never fires filter intra on a strip. Measured, 192x128 +`gradients` + `hue=s=0`, `--min/max-partition-size=16/32`, `--threads=1 --row-mt=0`: + +| recipe | rect strips | filter-intra blocks (any shape) | filter intra ON a strip | +| --- | --- | --- | --- | +| cq 45, smooth/paeth/directional/angle-delta all OFF (the square filter-intra gate's recipe), 20 seeds | 0 | 23 | 0 | +| cq 45, every intra mode ON, 100 seeds | 18 | 136 | 0 | +| cq 25, every intra mode ON, 100 seeds | 130 | 61 | 5 | +| cq 25, every intra mode ON, 40 seeds (PINNED) | 56 | 16 | 3 | + +Disabling the directional/smooth/paeth competitors — the trick the square filter-intra gate +uses — makes aomenc stop choosing rect partitions altogether (class `gate-recipe-confound`). +The knob that actually works is the quantiser: at cq 25 strips are ~7x more common. `smptebars` +and `testsrc2` sources were tried and are unusable here (every attempt refused, 0 decodes). +`EC_RECTSPLIT_CQ` / `EC_RECTSPLIT_OFF` / `EC_RECTSPLIT_GATE_ATTEMPTS` stay as diagnosis knobs +with the pinned recipe as default. + +## Evidence + +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 +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 + +## Film check (ReelB) + +``` +ffmpeg -v error -t 0.4 -i ".../reelb.mkv" -c:v copy -f obu hg.obu # 1817 bytes +cargo run -p ec-av1 --example decode_probe -- hg.obu +REFUSED: unsupported: AV1 tile (a partition below 8x8 (this decoder codes no leaf smaller than 8x8)) +``` + +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 + +The charter's premise that this extract stops at a rect-split refusal is stale for the film's +first 0.4s: the blocker there is the below-8x8 partition refusal (lane-sub8's, still open per +`memory/`). "Before" was not re-measured on main — the refusal reached is upstream of every +line this lane touched, so the branch cannot have moved it. +disposition: deferred(lane-sub8's below-8x8 leaf) — nothing this lane can do about it. + +## Suite + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3` (crate lib only, never the workspace): +**269 passed, 0 failed, 24 ignored**, 1062s. `refusal_inventory` and `gate_coverage` green. diff --git a/lanes/seg-r1.report.md b/lanes/seg-r1.report.md new file mode 100644 index 00000000..c0a2991c --- /dev/null +++ b/lanes/seg-r1.report.md @@ -0,0 +1,67 @@ +# lane-seg r1 — per-block `segment_id` and its consumers + +Branch `lane-seg`, off main `3808cf8` (WIP snapshot `51581d3` continued, not restarted). + +## What changed + +- `crates/ec-av1/src/cdf.rs:564` — `SEGMENT_ID` (`default_spatial_pred_seg_tree_cdf`, 3 ctx x 8 symbols) + and `SEGMENT_PRED` (`seg_id_predicted`, 3 ctx) default CDFs. +- `crates/ec-av1/src/cdf_state.rs:467` — both tables in `Cdfs`, in `reset_counters` (class + `cdf-counter-not-reset`) and in the default-table constructor, so they adapt and reset like every + other per-tile table. +- `crates/ec-av1/src/decode.rs:319-655` — the reader: `set_segmentation` (per-frame install + + `load_previous_segment_ids`), `CurrentSegmentIds`/`PrevSegmentIds` maps, `AboveSegPredContext`/ + `LeftSegPredContext`, `av1_neg_deinterleave`, `av1_get_spatial_seg_pred` (ctx + prediction), + `read_segment_id`, `intra_segment_id` (spec 5.11.7) and `inter_segment_id` (5.11.9, both + pre-skip and post-skip positions, `seg_id_predicted` under `temporal_update`, inherited map when + `update_map == 0`), `set_segment_id` stamping the block's whole mi footprint. +- Call sites: `read_intra_mode` (decode.rs:4375) and `read_intra_mode_rect` (3332) read + `intra_segment_id` before `skip` when `SegIdPreSkip`, after it otherwise; + `decode_inter_block` (9250/9268) and `decode_inter_block8` (11106/11116) read both spec positions. +- Consumers: `block_q_idx()` (decode.rs:400, spec 7.12.2 `get_qindex` with `SEG_LVL_ALT_Q`) replaces + the raw `CURRENT_Q_IDX` read at all 10 dequant sites; `lf_level` (decode.rs:6168) takes the block's + segment id and applies `SEG_LVL_ALT_LF_Y_V/H`/`_U`/`_V` (spec 7.14.4) between the `DeltaLF` term and + the ref/mode deltas; `edge_params` passes the per-side segment ids. +- `crates/ec-av1/src/stream.rs:266-291` — frame-level: narrowed refusal (below), spec + `load_previous_segment_ids` from the primary reference's slot, `set_segmentation` per frame; + `stream.rs:736` stores the decoded map into every slot `refresh_frame_flags` names. +- `crates/ec-av1/src/refusal_inventory.rs:59` — refusal replaced. + +## Refusal + +LIFTED: `"a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)"`. +REPLACED BY (narrower): `"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)"` — +those three features rewrite mode/reference decisions and suppress symbols `decode_inter_block` reads +unconditionally; aomenc's `--aq-mode` only ever sets `SEG_LVL_ALT_Q`, so no gate here can exercise +them. `gate_coverage.rs` needed no edit: it derives coverage from `--enable-*` flags and segmentation +is driven by `--aq-mode`, not an `--enable-*` flag; its two tests stay green. + +## Gates (both hard-assert; no decode error or mismatch becomes SKIP) + +`stream.rs:8698 run_segmentation_gate` — mandelbrot fixture (varying local contrast so AQ has +something to segment), `--aq-mode=1 --deltaq-mode=0`, 10 attempts, pixel-exact vs ffmpeg over every +decoded frame including hidden alt-refs (`--auto-alt-ref=1 --lag-in-frames=16`), asserting +`segment_id_hits > 0`, `segment_ids_seen >= 2`, and — for multi-frame runs — `segment_pred_hits > 0` +(the `temporal_update` path). + +Command: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib aq_segmentation -- --nocapture` + +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 +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 +EVIDENCE: cargo test -p ec-av1 --lib (EC_AV1_REQUIRE_AOMENC=1) | full ec-av1 lib suite | 269 passed, 0 failed, 23 ignored, 494s +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 + +## Residue + +- deferred(sub-16x16 rect/AB partition lanes): an `--aq-mode=2` (complexity AQ) twin. libaom only + enables segmentation for complexity AQ under `--end-usage=vbr` (`aq_complexity.c:is_sb_aq_enabled`, + `sb64_target_rate >= 256`), and every VBR recipe tried makes aomenc pick partition shapes other + lanes still refuse (AB below 16x16, SB-level HORZ/VERT, part32 value 4/6) — 10/10 attempts refuse + before a pixel is compared. Coverage, not capability: complexity AQ sets exactly the same + `SEG_LVL_ALT_Q`/`update_map` syntax variance AQ does. Comment at stream.rs:8919. +- deferred(a 10-bit inter-frame decode defect unrelated to this lane): the 10-bit gate is key-frame + only. Measured: the same recipe with `--aq-mode=0` (segmentation entirely off) also mismatches at + frame 2, so a 16-frame 10-bit variant would gate a pre-existing gap. Comment at stream.rs:8933. +- accepted: `SEG_LVL_REF_FRAME`/`SKIP`/`GLOBALMV` stay refused by name (see above) — no aomenc + `--aq-mode` path writes them, so a gate cannot be built from this oracle today. diff --git a/lanes/tiny-r4.report.md b/lanes/tiny-r4.report.md new file mode 100644 index 00000000..8ee196e4 --- /dev/null +++ b/lanes/tiny-r4.report.md @@ -0,0 +1,106 @@ +# lane-tiny r4 report + +Rebased onto main `3808cf8` first (r3 was already merged there); branch head `9b1297a`. + +## Residue closed: 32x16 seeds 42 and 47, chroma-only + +### Fixture determinism (charter step 1) +The sweep's "seed" is not an encoder seed -- it is `attempt`, which shifts +`mandelbrot` start_x/start_y. Regenerated both failing 32x16 fixtures twice +each and hashed: + + attempt 0 (seed 42): c72a6a1b...5659 both runs, 152 bytes + attempt 5 (seed 47): fcbf0894...c388 both runs, 151 bytes + +So the sweep is genuinely reproducible and no binary fixture needed pinning +(per `seeded-fixture-not-reproducible.md`, checked rather than assumed). + +### Bisection (charter step 2) +Not an entropy defect -- the range ladder was never needed. Stage dumps +settled it in one step: + +| stage | Y | U | V | +|---|---|---|---| +| pre-filter recon (`EC_AV1_PREFILT_DUMP`, ours vs aomdec) | 0 diff | **0 diff** | 0 diff | +| post-deblock (`EC_AV1_POSTDEBLOCK_DUMP`, ours vs aomdec) | 0 diff | **5 diff** | 0 diff | + +Reconstruction (and therefore the whole entropy/prediction path) is exact; +the deblocker introduces the mismatch. Printing the U plane rows 0..7 shows +the oracle leaves the horizontal edge at chroma row 4 **completely +unfiltered**, while we filter it and move rows 3/4 at columns 1, 2, 15. + +## Root cause + +`av1_get_max_uv_txsize`: a block's chroma transform is the largest transform +covering the **subsampled BLOCK**, capped at 32x32. It does **not** follow +luma's `tx_depth` split. `tx_px_at`/`tx_h_px_at` (decode.rs) computed it as +`tx_grid[...] / 2` -- half the *resolved luma* transform. A 16x16 block whose +luma transform split to 8x8 therefore read a 4-pixel chroma transform, and the +deblocker filtered a chroma transform edge that does not exist in the stream. + +Reconstruction was never wrong because it derives chroma from the block side +(`chroma_side = side / 2`, decode.rs 4313/4850/8881) -- which is exactly why +the symptom was luma-bit-exact, chroma-only, +-1, and seed-dependent (the +phantom edge only changes pixels on the seeds where the filter masks pass). +V was clean on both seeds for the same reason: its masks did not pass. + +**Fix** (decode.rs): `Neighbours::uv_tx_grid` / `uv_tx_h_grid`, written per-mi +from the block's own mi span inside `fill_lf_grid_rect` -- the single writer +every `fill_lf_grid*` caller routes through -- as +`((span_mi * MI / 2).max(4).min(32))`; `tx_px_at`/`tx_h_px_at` read those +grids for chroma instead of halving luma's. + +**Class sweep**: grepped every other chroma-from-luma derivation. +`tx_px_at`/`tx_h_px_at` were the only sites deriving chroma tx from the luma +*transform*; 4313/4850/8881 derive from the block *side* and are correct. +No sibling instances. + +## Gate (charter step 4) + +`probe_tiny_frame_size_boundary` -> `stream.rs` +`a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact`, no `#[ignore]`: +- wrong pixels at any size/seed = panic (was: an eprintln) +- a decode error that is not a NAMED `unsupported:` refusal = panic +- floor assert `total_exact >= 70` so refusals can never make it vacuous + (per `gate-skips-on-its-own-failure.md` / `refusal-lifted-without-a-gate.md`) +- `EC_AV1_REQUIRE_AOMENC=1` makes an absent oracle fail, not skip. + +`gate_coverage.rs` needed no change: it derives the tool set from `stream.rs` +source and this gate's `--enable-*` flags are unchanged (it was already in the +derived gate set while `#[ignore]`d). `gate_coverage` + `refusal_inventory` +are green. + +| size | r3 | r4 | +|---|---|---| +| 8x8 | refused 10/10 | refused 10/10 (named: 16x16 block whose true edge cuts both axes needs a rect transform) | +| 16x16, 32x32, 16x32, 48x48, 64x64, 24x24 | 10/10 | 10/10 | +| **32x16** | **8/10** | **10/10** | + +No refusal string was lifted this round (the 8x8 rect-transform refusal stays; +it is a genuine missing capability, now pinned by the gate). + +## Instruments added +- `EC_AV1_POSTDEBLOCK_DUMP` / `EC_AV1_POSTCDEF_DUMP` (decode.rs `dump_stage`), + mirroring aomdec's own `EC_AV1_POSTDEBLOCK_DUMP` (decodeframe.c ~5404) -- with + the existing pre-filter dump these bisect which filter stage broke a frame. +- `decode_probe [out.yuv]` now writes the decoded planes as raw + yuv420p, so a pixel diff against `ffmpeg -f rawvideo` needs no test harness. + +## Verification + +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib`: **268 passed, 0 failed, + 22 ignored** (362s). +- New gate alone: 9.5s. + +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 +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) +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 + +## Open + +- 8x8 frames: `deferred(a real rectangular TX_4X8/TX_8X4 coefficient path)` -- + refused by name, now pinned by the gate; the same square-only-transform + ceiling `square-only-transform-ceiling.md` already tracks. +- Repo-wide `cargo fmt --check` drift exists in `cdf.rs` and elsewhere and + predates this lane: `accepted`, not touched (formatting the crate would bury + this diff).