diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 160627a9..53c04006 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -83,6 +83,37 @@ pub(crate) fn tx_depth_hits() -> usize { /// landing on `DCT_DCT`. static TX_CLASS1_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// How many `uv_mode` reads resolved to a directional chroma mode (neither +/// `DC_PRED` nor `UV_CFL_PRED`), across every call in the process -- the same +/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream +/// actually exercised chroma's own directional predictor. +static DIRECTIONAL_UV_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`DIRECTIONAL_UV_HITS`]. +pub(crate) fn directional_uv_hits() -> usize { + DIRECTIONAL_UV_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as +/// something other than [`ANGLE_DELTA_ZERO`], across every call in the +/// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`], +/// proving a stream actually exercised a nonzero angle delta. +static ANGLE_DELTA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +thread_local! { + /// The sequence header's `enable_intra_edge_filter`, set once per + /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s + /// own read of it, kept off the call stack (see that function's own doc + /// comment for why) rather than threaded through every `read_plane`/ + /// `decode_block`/`decode_leaf8` call between here and there. + static ENABLE_EDGE_FILTER: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Current value of [`ANGLE_DELTA_HITS`]. +pub(crate) fn angle_delta_hits() -> usize { + ANGLE_DELTA_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + /// Current value of [`TX_CLASS1_HITS`]. pub(crate) fn tx_class1_hits() -> usize { TX_CLASS1_HITS.load(std::sync::atomic::Ordering::Relaxed) @@ -368,12 +399,41 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> /// CDF's own set (a corrupt or unsupported bitstream) — every value the /// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can /// produce dispatches to a real inverse transform. +/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its +/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None` +/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so +/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from +/// the plane's own predicted mode instead. Every entry this table can +/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two +/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this +/// table ever names), so unlike the CDF-coded luma path there is no +/// ext-tx-set membership check to fall back from here. +fn default_intra_tx_type(mode: u8) -> TxType { + use crate::intra::{ + D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED, + PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED, + }; + match mode { + DC_PRED | D45_PRED => TxType::DctDct, + V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct, + H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst, + D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst, + other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"), + } +} + fn read_coeffs( dec: &mut SymbolDecoder, coding: &mut TxbTables, scan: &[u16], skip_ctx: usize, sign_ctx: usize, + // The chroma default (spec `Intra_Mode_To_Tx_Type`, see + // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes + // nothing at all; `DctDct` for every luma call and every chroma call at + // a size the spec forces to `DCT_DCT` regardless of mode (32-point and + // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in. + default_tx_type: TxType, ) -> Result<(Vec, TxType)> { let trace = std::env::var_os("EC_AV1_TRACE").is_some(); let side = coding.side; @@ -385,7 +445,7 @@ fn read_coeffs( if all_zero { return Ok((grid, TxType::DctDct)); } - let mut tx_type = TxType::DctDct; + let mut tx_type = default_tx_type; if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { // The CDF row's own width names its set: 7 symbols (8 slots) is // `TX_SET_INTRA_1`, 5 (6 slots) the reduced `TX_SET_INTRA_2` (the @@ -940,6 +1000,18 @@ fn filter_intra_size_class(side: usize) -> Option { } } +/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus +/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA` +/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever +/// it lands away from zero, for gate tests to prove a real stream fired one. +fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 { + let symbol = dec.symbol(cdf); + if symbol != ANGLE_DELTA_ZERO { + ANGLE_DELTA_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + symbol as i32 - ANGLE_DELTA_ZERO as i32 +} + fn read_intra_mode( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, @@ -948,7 +1020,15 @@ fn read_intra_mode( cfl: bool, side: usize, enable_filter_intra: bool, -) -> Result<(bool, usize, Option<(i32, i32)>, Option)> { +) -> Result<( + bool, + usize, + i32, + usize, + i32, + Option<(i32, i32)>, + Option, +)> { let trace = std::env::var_os("EC_AV1_TRACE").is_some(); let skip = dec.symbol(&mut cdfs.skip[0]) != 0; if trace { @@ -960,17 +1040,18 @@ fn read_intra_mode( if trace { eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}"); } - if (V_PRED..=D67_PRED).contains(&mode) { - let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]); + let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { + let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]); if trace { - eprintln!("TRACE angle_delta value={angle}"); - } - if angle != ANGLE_DELTA_ZERO { - return Err(unsupported( - "a nonzero angle delta (this encoder never writes one)", - )); + eprintln!( + "TRACE angle_delta value={}", + delta + ANGLE_DELTA_ZERO as i32 + ); } - } + delta + } else { + 0 + }; let uv_mode = if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { @@ -979,12 +1060,31 @@ fn read_intra_mode( if trace { eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}"); } - let alpha = if uv_mode == DC_PRED { - None - } else if cfl && uv_mode == UV_CFL_PRED { + let alpha = if cfl && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { - return Err(unsupported("a directional chroma mode (round 2)")); + None + }; + // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap + // from this lane's directional chroma: a corner block with neither + // `above` nor `left` (both `Edges::build`'s no-neighbour fallback, + // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta + // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched + // bug in that fallback this lane's own scope does not cover. Keep it + // refused here rather than ship a silently-wrong decode. + if (9..=12).contains(&uv_mode) { + return Err(unsupported("a smooth or paeth chroma mode (round 2)")); + } + // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the + // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads + // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw, + // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes + // the `else` branch below and never reads one either way. + let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) + } else { + 0 }; // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a // `use_filter_intra` symbol this decoder never read at all until @@ -1014,7 +1114,15 @@ fn read_intra_mode( filter_intra = Some(fi_mode); } } - Ok((skip, mode, alpha, filter_intra)) + Ok(( + skip, + mode, + angle_delta_y, + uv_mode, + angle_delta_uv, + alpha, + filter_intra, + )) } /// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth @@ -1149,6 +1257,7 @@ impl PlaneBuf { y: usize, side: usize, mode: usize, + angle_delta: i32, reach: Reach, residual: &[i32], cfl: Option<(i32, &[i32])>, @@ -1166,12 +1275,29 @@ impl PlaneBuf { &mut prediction, ); } else { + // `enable_intra_edge_filter` is the sequence header's own flag + // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs` + // call, never per-block) -- threading it through every + // `read_plane`/`decode_block`/`decode_leaf8` call would touch two + // dozen sites for a value that never changes mid-decode, so it + // rides a thread-local instead (this decoder is single-threaded + // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`) + // is left `false`: exact for chroma here (a smooth `uv_mode` is + // refused before decode reaches this call) and a corner-cut for + // luma -- ceiling is one wrong filter-strength bucket on a block + // whose real neighbour predicted smooth; upgrade path is + // threading `Neighbours::above_mode`/`left_mode`'s + // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`. + let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get); predict( mode as u8, + angle_delta, above.as_deref(), left.as_deref(), corner, side, + enable_edge_filter, + false, &mut prediction, ); } @@ -1204,6 +1330,7 @@ fn read_plane( // CDF is indexed by, spec 9.3), never the plane's own predicted mode. tx_mode: usize, predict_mode: usize, + angle_delta: i32, reach: Reach, plane: &mut PlaneBuf, x: usize, @@ -1227,7 +1354,31 @@ fn read_plane( usize::from(around.0) + usize::from(around.1) }; let mut coding = cdfs.txb(set, tx_mode); - let (grid, tx_type) = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?; + // Luma's `default_tx_type` is only a fallback for the sizes whose + // `TxbSet` carries no symbol at all (32-point and up), which the spec + // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is + // *never* its own coded symbol (`coding.tx_type` is always `None` for + // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of + // the plane's own predicted mode (`default_intra_tx_type`) -- except + // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr + // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to + // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8` + // and `Chroma16` never hit this — every value `default_intra_tx_type` can + // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing + // narrows there — only `Chroma32` and up do). + let default_tx_type = if plane_idx == 0 || side >= 32 { + TxType::DctDct + } else { + default_intra_tx_type(predict_mode as u8) + }; + let (grid, tx_type) = read_coeffs( + dec, + &mut coding, + scan, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + )?; // A 64x64 luma block's transform covers the whole 64x64 area, but only its // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32` @@ -1248,9 +1399,7 @@ fn read_plane( let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( - "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} levels[0..4]={:?} residual[0..4]={:?}", - &levels[..4.min(levels.len())], - &residual[..4.min(residual.len())] + "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}", ); } plane.reconstruct( @@ -1258,6 +1407,7 @@ fn read_plane( y, side, predict_mode, + angle_delta, reach, &residual, cfl, @@ -1308,15 +1458,30 @@ fn decode_block( ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); - let (skip, mode, alpha, filter_intra) = read_intra_mode( - dec, - cdfs, - neighbours.above_mode[c], - neighbours.left_mode[r], - cfl, - side, - enable_filter_intra, - )?; + let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = + read_intra_mode( + dec, + cdfs, + neighbours.above_mode[c], + neighbours.left_mode[r], + cfl, + side, + enable_filter_intra, + )?; + // `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. + let uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \ + angle_delta_uv={angle_delta_uv}" + ); + } let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra // block, skipped or not. `logical_tx` is what the loop filter's edge @@ -1347,6 +1512,7 @@ fn decode_block( py, side, mode, + angle_delta_y, reach, &vec![0i32; side * side], None, @@ -1357,8 +1523,9 @@ fn decode_block( cpx, cpy, chroma_side, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, @@ -1367,8 +1534,9 @@ fn decode_block( cpx, cpy, chroma_side, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, @@ -1391,6 +1559,7 @@ fn decode_block( around[0], mode, mode, + angle_delta_y, reach, y, px, @@ -1411,8 +1580,9 @@ fn decode_block( 1, around[1], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, u, cpx, cpy, @@ -1423,6 +1593,12 @@ fn decode_block( None, None, )?; + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}", + &u.data[cpy * u.width + cpx..][..chroma_side] + ); + } let v_grid = read_plane( dec, cdfs, @@ -1431,8 +1607,9 @@ fn decode_block( 2, around[2], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, v, cpx, cpy, @@ -1476,6 +1653,7 @@ fn decode_block( tu_around, mode, mode, + angle_delta_y, tu_reach, y, tu_px, @@ -1508,8 +1686,9 @@ fn decode_block( 1, chroma_around[1], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, u, cpx, cpy, @@ -1528,8 +1707,9 @@ fn decode_block( 2, chroma_around[2], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, v, cpx, cpy, @@ -1591,15 +1771,21 @@ fn decode_leaf8( // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other // `decode_block` caller at 16x16 and up. - let (skip, mode, alpha, filter_intra) = read_intra_mode( - dec, - cdfs, - above_mode, - left_mode, - true, - 8, - enable_filter_intra, - )?; + let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = + read_intra_mode( + dec, + cdfs, + above_mode, + left_mode, + true, + 8, + enable_filter_intra, + )?; + let uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1, // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4 @@ -1615,14 +1801,25 @@ fn decode_leaf8( let (cpx, cpy) = (px / 2, py / 2); let (luma_grid, u_grid, v_grid); if skip { - y.reconstruct(px, py, 8, mode, reach, &vec![0i32; 64], None, filter_intra); + y.reconstruct( + px, + py, + 8, + mode, + angle_delta_y, + reach, + &vec![0i32; 64], + None, + filter_intra, + ); let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u.reconstruct( cpx, cpy, 4, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, @@ -1631,8 +1828,9 @@ fn decode_leaf8( cpx, cpy, 4, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, @@ -1655,6 +1853,7 @@ fn decode_leaf8( around[0], mode, mode, + angle_delta_y, reach, y, px, @@ -1675,8 +1874,9 @@ fn decode_leaf8( 1, around[1], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, u, cpx, cpy, @@ -1695,8 +1895,9 @@ fn decode_leaf8( 2, around[2], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, v, cpx, cpy, @@ -1735,6 +1936,7 @@ fn decode_leaf8( tu_around, mode, mode, + angle_delta_y, tu_reach, y, tu_px, @@ -1767,8 +1969,9 @@ fn decode_leaf8( 1, chroma_around[1], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, u, cpx, cpy, @@ -1787,8 +1990,9 @@ fn decode_leaf8( 2, chroma_around[2], mode, - DC_PRED, - Reach::none(), + uv_predict_mode, + angle_delta_uv, + reach, v, cpx, cpy, @@ -2701,6 +2905,7 @@ pub fn decode_key_frame_tile( frame_width, frame_height, enable_filter_intra, + false, cdef, loop_filter, None, @@ -2726,6 +2931,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_width: u32, frame_height: u32, enable_filter_intra: bool, + enable_edge_filter: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, initial_cdfs: Option, @@ -2735,6 +2941,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); } + 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)); let (cols32, rows32) = block_grid(mi_cols, mi_rows); let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize); @@ -3353,7 +3560,21 @@ fn read_inter_plane( usize::from(around.0) + usize::from(around.1) }; let mut coding = cdfs.txb(set, tx_mode); - let (grid, tx_type) = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?; + // `av1_get_tx_type` (libaom `blockd.h`): `Intra_Mode_To_Tx_Type` only + // ever applies to an intra block's chroma plane -- an `is_inter` block + // (this function, [`read_inter_plane`], reads only those) has no + // predicted intra mode to index it with, and its `tx_type` (luma or + // chroma alike) is `DCT_DCT` whenever the `TxbSet` itself codes no + // symbol for it. + let default_tx_type = TxType::DctDct; + let (grid, tx_type) = read_coeffs( + dec, + &mut coding, + scan, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + )?; let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type); plane.reconstruct_mc(x, y, side, prediction, &residual); Ok(grid) @@ -3685,6 +3906,7 @@ fn decode_inter_block( py, side, mode, + 0, reach, &vec![0i32; side * side], None, @@ -3696,7 +3918,8 @@ fn decode_inter_block( cpy, chroma_side, DC_PRED, - Reach::none(), + 0, + reach, &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, @@ -3706,7 +3929,8 @@ fn decode_inter_block( cpy, chroma_side, DC_PRED, - Reach::none(), + 0, + reach, &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, @@ -3725,6 +3949,7 @@ fn decode_inter_block( around[0], mode, mode, + 0, reach, y, px, @@ -3746,7 +3971,8 @@ fn decode_inter_block( around[1], mode, DC_PRED, - Reach::none(), + 0, + reach, u, cpx, cpy, @@ -3766,7 +3992,8 @@ fn decode_inter_block( around[2], mode, DC_PRED, - Reach::none(), + 0, + reach, v, cpx, cpy, @@ -4084,6 +4311,7 @@ fn decode_inter_block8( py, SIDE, mode, + 0, reach, &vec![0i32; SIDE * SIDE], None, @@ -4094,7 +4322,8 @@ fn decode_inter_block8( cpy, CHROMA_SIDE, DC_PRED, - Reach::none(), + 0, + reach, &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], None, None, @@ -4104,7 +4333,8 @@ fn decode_inter_block8( cpy, CHROMA_SIDE, DC_PRED, - Reach::none(), + 0, + reach, &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], None, None, @@ -4123,6 +4353,7 @@ fn decode_inter_block8( around[0], mode, mode, + 0, reach, y, px, @@ -4143,7 +4374,8 @@ fn decode_inter_block8( around[1], mode, DC_PRED, - Reach::none(), + 0, + reach, u, cpx, cpy, @@ -4163,7 +4395,8 @@ fn decode_inter_block8( around[2], mode, DC_PRED, - Reach::none(), + 0, + reach, v, cpx, cpy, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0f3f66c5..0c5c66f5 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -599,10 +599,13 @@ impl Plane<'_> { let mut prediction = vec![0u8; side * side]; crate::intra::predict( mode, + 0, above.as_deref(), left.as_deref(), corner, side, + false, + false, &mut prediction, ); @@ -815,10 +818,13 @@ impl Plane<'_> { let mut prediction = vec![0u8; side * side]; crate::intra::predict( mode, + 0, above.as_deref(), left.as_deref(), corner, side, + false, + false, &mut prediction, ); let sad: f64 = (0..side * side) @@ -863,10 +869,13 @@ impl Plane<'_> { let mut prediction = vec![0u8; side * side]; crate::intra::predict( mode, + 0, above.as_deref(), left.as_deref(), corner, side, + false, + false, &mut prediction, ); let sad: f64 = (0..side * side) @@ -4418,10 +4427,13 @@ mod tests { for _ in 0..N { crate::intra::predict( D45_PRED, + 0, Some(&above), Some(&left), Some(128), side, + false, + false, &mut prediction, ); } diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index 1ba1367f..f779818a 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -124,6 +124,10 @@ fn dr_intra_derivative(angle: u16) -> i32 { /// `Mode_To_Angle` (spec 9.3), zero for the modes that have no angle. const MODE_TO_ANGLE: [u16; 13] = [0, 90, 180, 45, 135, 113, 157, 203, 67, 0, 0, 0, 0]; +/// `ANGLE_STEP` (spec 9.3): degrees per unit of `angle_delta`, whose own +/// range is `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA` (`MAX_ANGLE_DELTA == 3`). +const ANGLE_STEP: i32 = 3; + /// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2): /// a side that does not exist is filled from the side that does, a side that /// runs out is extended by repeating its last sample, and the corner falls back @@ -195,26 +199,62 @@ impl Edges { /// the edge is extended by repetition where it does not, which is what the /// decoder's own clamp to `aboveLimit` and `leftLimit` comes to. /// +/// `angle_delta` (spec `AngleDeltaY`/`AngleDeltaUV`, `-MAX_ANGLE_DELTA` to +/// `MAX_ANGLE_DELTA`) steers every one of `V_PRED`, `H_PRED` and the six +/// diagonal modes off their base angle by `ANGLE_STEP` degrees per unit (spec +/// 7.11.2.1's `pAngle = Mode_To_Angle[mode] + angleDelta * ANGLE_STEP`); +/// ignored (must be `0`) for the seven modes that carry no angle at all. +/// +/// `enable_edge_filter` is the sequence header's `enable_intra_edge_filter` +/// (spec 7.11.2.4's own gate on the whole filter/upsample step); `smooth_neighbor` +/// is `get_intra_edge_filter_type` (spec 7.11.2.9, libaom `reconintra.c`) -- +/// whether the block above or to the left predicted with one of the three +/// smooth modes, which steers [`intra_edge_filter_strength`]'s threshold +/// table. Ignored outside the directional modes. +/// /// # Panics /// Panics on a mode this module does not predict, or when `dst` is not /// `side * side` long. +#[allow(clippy::too_many_arguments)] pub fn predict( mode: u8, + angle_delta: i32, above: Option<&[u8]>, left: Option<&[u8]>, corner: Option, side: usize, + enable_edge_filter: bool, + smooth_neighbor: bool, dst: &mut [u8], ) { assert_eq!(dst.len(), side * side, "the destination is the block"); let edges = Edges::build(above, left, corner, side); - let angle = MODE_TO_ANGLE[usize::from(mode)]; - if matches!( + let is_directional = matches!( mode, - D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED - ) { - directional(angle, &edges, side, dst); - return; + V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED + ); + if is_directional { + let angle = i32::from(MODE_TO_ANGLE[usize::from(mode)]) + angle_delta * ANGLE_STEP; + // `pAngle == 90`/`180` is `V_PRED`/`H_PRED` at zero delta: a plain + // edge copy, no walk -- and the only two angles `dr_intra_derivative` + // has no table entry for, since libaom special-cases them the same + // way (`av1_is_directional_mode`'s callers never call the z1/z2/z3 + // walk there either). + if angle != 90 && angle != 180 { + let n_top = above.map_or(0, |a| a.len().min(side)); + let n_left = left.map_or(0, |a| a.len().min(side)); + directional( + angle as u16, + &edges, + side, + enable_edge_filter, + smooth_neighbor, + n_top, + n_left, + dst, + ); + return; + } } let weights = &SM_WEIGHTS[side..side * 2]; for row in 0..side { @@ -250,52 +290,245 @@ pub fn predict( } } -/// Directional intra prediction (spec 7.11.2.4), with the intra edge filter off -/// -- which is what our sequence header says -- so nothing here upsamples. -fn directional(angle: u16, edges: &Edges, side: usize, dst: &mut [u8]) { +/// `intra_edge_filter_strength` (spec 7.11.2.9, libaom `reconintra.c`): the +/// filter kernel index (`0`..=`3`) for a gap of `delta` degrees against a +/// `bs0 + bs1`-wide block, split by `smooth_neighbor`'s two threshold tables. +fn intra_edge_filter_strength(bs0: i32, bs1: i32, delta: i32, smooth_neighbor: bool) -> i32 { + let d = delta.abs(); + let blk_wh = bs0 + bs1; + let mut strength = 0; + if !smooth_neighbor { + if blk_wh <= 8 { + if d >= 56 { + strength = 1; + } + } else if blk_wh <= 16 { + if d >= 40 { + strength = 1; + } + } else if blk_wh <= 24 { + if d >= 8 { + strength = 1; + } + if d >= 16 { + strength = 2; + } + if d >= 32 { + strength = 3; + } + } else if blk_wh <= 32 { + if d >= 1 { + strength = 1; + } + if d >= 4 { + strength = 2; + } + if d >= 32 { + strength = 3; + } + } else if d >= 1 { + strength = 3; + } + } else if blk_wh <= 8 { + if d >= 40 { + strength = 1; + } + if d >= 64 { + strength = 2; + } + } else if blk_wh <= 16 { + if d >= 20 { + strength = 1; + } + if d >= 48 { + strength = 2; + } + } else if blk_wh <= 24 { + if d >= 4 { + strength = 3; + } + } else if d >= 1 { + strength = 3; + } + strength +} + +/// `av1_use_intra_edge_upsample` (spec 7.11.2.9): whether the edge doubles in +/// density before the walk reads it. +fn use_intra_edge_upsample(bs0: i32, bs1: i32, delta: i32, smooth_neighbor: bool) -> bool { + let d = delta.abs(); + let blk_wh = bs0 + bs1; + if d == 0 || d >= 40 { + return false; + } + if smooth_neighbor { + blk_wh <= 8 + } else { + blk_wh <= 16 + } +} + +/// `av1_filter_intra_edge_c` (spec 7.11.2.8): a 5-tap smoothing pass over +/// `buf` in place, `buf[0]` (the corner) held fixed as every tap's clamp +/// floor/ceiling. +fn filter_intra_edge(buf: &mut [i32], strength: i32) { + if strength == 0 { + return; + } + const KERNEL: [[i32; 5]; 3] = [[0, 4, 8, 4, 0], [0, 5, 6, 5, 0], [2, 4, 4, 4, 2]]; + let filt = usize::try_from(strength - 1).expect("a filter strength is never negative"); + let sz = buf.len() as i32; + let edge = buf.to_vec(); + for i in 1..buf.len() { + let mut s = 0; + for (j, &tap) in KERNEL[filt].iter().enumerate() { + let k = (i as i32 - 2 + j as i32).clamp(0, sz - 1); + s += edge[k as usize] * tap; + } + buf[i] = (s + 8) >> 4; + } +} + +/// `av1_upsample_intra_edge_c` (spec 7.11.2.8): doubles `buf`'s density. +/// `buf[0]` is spec position `-1` and `buf[buf.len() - 1]` is `sz - 1`; the +/// result's `[0]` is spec position `-2`, `[2*i + 1]` the half-sample between +/// `i - 1` and `i`, `[2*i + 2]` the original sample `i` moved to its doubled +/// slot. +fn upsample_intra_edge(buf: &[i32]) -> Vec { + let sz = buf.len() - 1; + let mut inp = vec![0i32; sz + 3]; + inp[0] = buf[0]; + inp[1] = buf[0]; + inp[2..sz + 2].copy_from_slice(&buf[1..]); + inp[sz + 2] = buf[sz]; + let mut out = vec![0i32; 2 * sz + 1]; + out[0] = inp[0]; + for i in 0..sz { + let s = -inp[i] + 9 * inp[i + 1] + 9 * inp[i + 2] - inp[i + 3]; + out[2 * i + 1] = ((s + 8) >> 4).clamp(0, 255); + out[2 * i + 2] = inp[i + 2]; + } + out +} + +/// Directional intra prediction (spec 7.11.2.4): the edge filter/upsample +/// steps (spec 7.11.2.7-2.9) run first when `enable_edge_filter` (the +/// sequence header's own gate) says to, then the z1/z2/z3 walk (libaom +/// `av1_dr_prediction_z{1,2,3}_c`) reads whichever of the two -- filtered, +/// upsampled, or neither -- it ends with. +#[allow(clippy::too_many_arguments)] +fn directional( + angle: u16, + edges: &Edges, + side: usize, + enable_edge_filter: bool, + smooth_neighbor: bool, + n_top: usize, + n_left: usize, + dst: &mut [u8], +) { let n = side as i32; - // The furthest sample the walk can reach, past which the edge is flat. - let max_base = n + n - 1; + let need_above = angle < 180; + let need_left = angle > 90; + let need_right = angle < 90; + let need_bottom = angle > 180; + + // Spec position `-1..=2n - 1`, `above[0]`/`left[0]` the shared corner. + let mut above: Vec = (-1..2 * n).map(|p| edges.above(p)).collect(); + let mut left: Vec = (-1..2 * n).map(|p| edges.left(p)).collect(); + + if enable_edge_filter && angle != 90 && angle != 180 { + if need_above && need_left && 2 * n >= 24 { + let s = round2(left[1] * 5 + above[0] * 6 + above[1] * 5, 4); + above[0] = s; + left[0] = s; + } + if need_above && n_top > 0 { + let strength = intra_edge_filter_strength(n, n, i32::from(angle) - 90, smooth_neighbor); + let n_px = n_top as i32 + 1 + if need_right { n } else { 0 }; + filter_intra_edge(&mut above[..n_px as usize], strength); + } + if need_left && n_left > 0 { + let strength = + intra_edge_filter_strength(n, n, i32::from(angle) - 180, smooth_neighbor); + let n_px = n_left as i32 + 1 + if need_bottom { n } else { 0 }; + filter_intra_edge(&mut left[..n_px as usize], strength); + } + } + + let upsample_above = + enable_edge_filter && use_intra_edge_upsample(n, n, i32::from(angle) - 90, smooth_neighbor); + let upsample_left = enable_edge_filter + && use_intra_edge_upsample(n, n, i32::from(angle) - 180, smooth_neighbor); + + let above_up; + let (above_buf, above_off): (&[i32], i32) = if need_above && upsample_above { + let n_px = (n + if need_right { n } else { 0 }) as usize; + above_up = upsample_intra_edge(&above[..=n_px]); + (&above_up, 2) + } else { + (&above, 1) + }; + let left_up; + let (left_buf, left_off): (&[i32], i32) = if need_left && upsample_left { + let n_px = (n + if need_bottom { n } else { 0 }) as usize; + left_up = upsample_intra_edge(&left[..=n_px]); + (&left_up, 2) + } else { + (&left, 1) + }; + let above_at = |p: i32| above_buf[(p + above_off) as usize]; + let left_at = |p: i32| left_buf[(p + left_off) as usize]; + let up_a = i32::from(upsample_above); + let up_l = i32::from(upsample_left); let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| { round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5) }; - let above = |i: i32| edges.above(i); - let left = |i: i32| edges.left(i); + for row in 0..n { for col in 0..n { let value = if angle < 90 { let dx = dr_intra_derivative(angle); - let idx = (row + 1) * dx; - let base = (idx >> 6) + col; - let shift = (idx >> 1) & 0x1F; + let max_base = (2 * n - 1) << up_a; + let frac_bits = 6 - up_a; + let x = dx * (row + 1); + let base = (x >> frac_bits) + (col << up_a); + let shift = ((x << up_a) & 0x3F) >> 1; if base < max_base { - blend(&above, base, shift) + blend(&above_at, base, shift) } else { - above(max_base) + above_at(max_base) } } else if angle > 180 { let dy = dr_intra_derivative(270 - angle); - let idx = (col + 1) * dy; - let base = (idx >> 6) + row; - let shift = (idx >> 1) & 0x1F; + let max_base = (2 * n - 1) << up_l; + let frac_bits = 6 - up_l; + let y = dy * (col + 1); + let base = (y >> frac_bits) + (row << up_l); + let shift = ((y << up_l) & 0x3F) >> 1; if base < max_base { - blend(&left, base, shift) + blend(&left_at, base, shift) } else { - left(max_base) + left_at(max_base) } } else { // The two zones meet here: a ray that leaves through the row // above is read there, and one that leaves through the column // to the left is read there instead. let dx = dr_intra_derivative(180 - angle); - let idx = (col << 6) - (row + 1) * dx; - let base = idx >> 6; - if base >= -1 { - blend(&above, base, (idx >> 1) & 0x1F) + let min_base = -(1 << up_a); + let frac_bits_x = 6 - up_a; + let y = row + 1; + let x = (col << 6) - y * dx; + let base = x >> frac_bits_x; + if base >= min_base { + blend(&above_at, base, ((x << up_a) & 0x3F) >> 1) } else { let dy = dr_intra_derivative(angle - 90); - let idx = (row << 6) - (col + 1) * dy; - blend(&left, idx >> 6, (idx >> 1) & 0x1F) + let frac_bits_y = 6 - up_l; + let x2 = col + 1; + let y2 = (row << 6) - x2 * dy; + blend(&left_at, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1) } }; dst[(row * n + col) as usize] = value.clamp(0, 255) as u8; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 42259bb3..78472d2e 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -187,6 +187,9 @@ pub fn decode_stream(data: &[u8]) -> Result> { let enable_dual_filter = parser .sequence_header() .is_some_and(|seq| seq.enable_dual_filter); + let enable_edge_filter = parser + .sequence_header() + .is_some_and(|seq| seq.enable_intra_edge_filter); let interp_fixed = match header.interpolation_filter { ec_av1_syntax::InterpolationFilter::Switchable => None, fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)), @@ -218,6 +221,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.frame_width, header.frame_height, enable_filter_intra, + enable_edge_filter, &header.cdef, &header.loop_filter, initial_cdfs, @@ -1175,6 +1179,158 @@ mod tests { ); } + /// The directional-chroma/angle-delta gate: a real aomenc key frame with + /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the + /// opposite of every sibling recipe's `=0`, which existed specifically to + /// keep this round-2 gap from firing while a different surface was under + /// test). A colourful, sharp-edged source gives the RD search a reason to + /// pick a directional `uv_mode` and/or a nonzero angle delta -- some + /// seeds still won't, so retry like every other real-encoder gate here, + /// but the first attempt that actually fires either counter must decode + /// pixel-exact. + #[test] + fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height) = (64usize, 64usize); + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + for attempt in 0..40u32 { + let seed = 42 + attempt; + let source = format!( + "mandelbrot=size=64x64:start_scale={}:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-t", + "0.04", + "-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", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + // Smooth/Paeth chroma is a separate, still-refused round-2 + // gap (an unrelated `Edges::build` no-neighbour bug this + // lane does not cover) -- off so the RD search's only + // non-DC/CFL chroma choice left is directional. + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + // The intra edge filter/upsample (spec 7.11.2.7-2.9) is + // now implemented (`directional()`) -- left ON (aomenc's + // own default) so this gate actually exercises it instead + // of the un-filtered fast path a disabled flag would keep + // testing. + "--enable-intra-edge-filter=1", + "--max-partition-size=32", + // Same reason as the tx-select gate above: 8x8 and other + // sub-16x16 splits are a separate, already-named refusal. + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--obu", + "-o", + "-", + "-", + ]) + .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; + let (uv_before, angle_before) = + (decode::directional_uv_hits(), decode::angle_delta_hits()); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + refusals.push(format!("seed {seed}: {e}")); + continue; + } + }; + if decode::directional_uv_hits() == uv_before + && decode::angle_delta_hits() == angle_before + { + refusals.push(format!( + "seed {seed}: decoded, but neither a directional uv_mode nor a \ + nonzero angle delta fired" + )); + continue; + } + fired_runs += 1; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed {seed})" + ); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); + if fired_runs >= 4 { + return; + } + } + assert!( + fired_runs > 0, + "every attempt hit a named refusal or never exercised directional chroma:\n{}", + refusals.join("\n") + ); + } + /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0 /// --auto-alt-ref=0` keep every non-key frame a simple forward /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this