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..9e7bf7e4 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -464,6 +464,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 @@ -701,6 +705,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); @@ -1172,6 +1178,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 86c7cf41..f03ab386 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 @@ -1936,6 +2284,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()); @@ -3010,8 +3361,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 @@ -3366,7 +3725,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, @@ -3407,7 +3766,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, @@ -3447,7 +3806,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, @@ -3806,7 +4165,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)); } @@ -3821,7 +4180,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, @@ -3878,7 +4237,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)); } @@ -3893,7 +4252,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, @@ -3932,7 +4291,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)); } @@ -3947,7 +4306,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, @@ -4045,11 +4404,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); @@ -4721,7 +5089,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:?}", @@ -5835,7 +6203,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 { @@ -5847,6 +6222,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; } @@ -5902,8 +6287,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; } @@ -7814,7 +8206,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)) } @@ -8898,6 +9290,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!( @@ -8911,6 +9308,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); @@ -10748,6 +11146,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)); @@ -10755,6 +11156,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); diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 9c2e1416..747e0547 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -54,7 +54,7 @@ const REFUSALS: &[&str] = &[ "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 palette block with a split luma transform (round 1)", "a reference frame other than LAST_FRAME (round 2)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index f1595d1d..d2195dad 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,6 +131,7 @@ 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]; } } @@ -242,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, @@ -686,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()); @@ -695,6 +733,7 @@ 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; } } @@ -8915,6 +8954,283 @@ mod tests { ); } + /// 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"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); + return; + } + crate::decode::reset_segment_hits(); + let (width, height) = (128usize, 64usize); + let mut named_refusals = 0u32; + 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 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, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-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 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 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.