forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1dirchroma': directional chroma, angle deltas, the intra edge filter

Browse files at this commit

821ba2ffc5cc05bef039eca5323476fdfd29d169Ahmet Kaan GümüşParent: 843a5a80c4687e
Eight rounds: the uv_mode/angle_delta reads, chroma directional
prediction, the chroma tx_type derivation from Intra_Mode_To_Tx_Type,
the spec-7.11.2.7-2.9 intra edge filter and upsampling, and the real
fix under the final mismatch -- twenty call sites passing an empty
neighbour reach into prediction. Directional-chroma gate fires and
passes 4/4 pixel-exact on real aomenc bytes.
crates/ec-av1/src/decode.rsmodified+305 -72
@@ -83,6 +83,37 @@ pub(crate) fn tx_depth_hits() -> usize {
8383 /// landing on `DCT_DCT`.
8484 static TX_CLASS1_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
8585
86+/// How many `uv_mode` reads resolved to a directional chroma mode (neither
87+/// `DC_PRED` nor `UV_CFL_PRED`), across every call in the process -- the same
88+/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
89+/// actually exercised chroma's own directional predictor.
90+static DIRECTIONAL_UV_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
91+
92+/// Current value of [`DIRECTIONAL_UV_HITS`].
93+pub(crate) fn directional_uv_hits() -> usize {
94+ DIRECTIONAL_UV_HITS.load(std::sync::atomic::Ordering::Relaxed)
95+}
96+
97+/// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
98+/// something other than [`ANGLE_DELTA_ZERO`], across every call in the
99+/// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
100+/// proving a stream actually exercised a nonzero angle delta.
101+static ANGLE_DELTA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
102+
103+thread_local! {
104+ /// The sequence header's `enable_intra_edge_filter`, set once per
105+ /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
106+ /// own read of it, kept off the call stack (see that function's own doc
107+ /// comment for why) rather than threaded through every `read_plane`/
108+ /// `decode_block`/`decode_leaf8` call between here and there.
109+ static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
110+}
111+
112+/// Current value of [`ANGLE_DELTA_HITS`].
113+pub(crate) fn angle_delta_hits() -> usize {
114+ ANGLE_DELTA_HITS.load(std::sync::atomic::Ordering::Relaxed)
115+}
116+
86117 /// Current value of [`TX_CLASS1_HITS`].
87118 pub(crate) fn tx_class1_hits() -> usize {
88119 TX_CLASS1_HITS.load(std::sync::atomic::Ordering::Relaxed)
@@ -368,12 +399,41 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) ->
368399 /// CDF's own set (a corrupt or unsupported bitstream) — every value the
369400 /// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
370401 /// produce dispatches to a real inverse transform.
402+/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
403+/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
404+/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
405+/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
406+/// the plane's own predicted mode instead. Every entry this table can
407+/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
408+/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
409+/// table ever names), so unlike the CDF-coded luma path there is no
410+/// ext-tx-set membership check to fall back from here.
411+fn default_intra_tx_type(mode: u8) -> TxType {
412+ use crate::intra::{
413+ D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
414+ PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
415+ };
416+ match mode {
417+ DC_PRED | D45_PRED => TxType::DctDct,
418+ V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
419+ H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
420+ D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
421+ other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
422+ }
423+}
424+
371425 fn read_coeffs(
372426 dec: &mut SymbolDecoder,
373427 coding: &mut TxbTables,
374428 scan: &[u16],
375429 skip_ctx: usize,
376430 sign_ctx: usize,
431+ // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
432+ // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
433+ // nothing at all; `DctDct` for every luma call and every chroma call at
434+ // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
435+ // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
436+ default_tx_type: TxType,
377437 ) -> Result<(Vec<i32>, TxType)> {
378438 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
379439 let side = coding.side;
@@ -385,7 +445,7 @@ fn read_coeffs(
385445 if all_zero {
386446 return Ok((grid, TxType::DctDct));
387447 }
388- let mut tx_type = TxType::DctDct;
448+ let mut tx_type = default_tx_type;
389449 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
390450 // The CDF row's own width names its set: 7 symbols (8 slots) is
391451 // `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<usize> {
9401000 }
9411001 }
9421002
1003+/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
1004+/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
1005+/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
1006+/// it lands away from zero, for gate tests to prove a real stream fired one.
1007+fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
1008+ let symbol = dec.symbol(cdf);
1009+ if symbol != ANGLE_DELTA_ZERO {
1010+ ANGLE_DELTA_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1011+ }
1012+ symbol as i32 - ANGLE_DELTA_ZERO as i32
1013+}
1014+
9431015 fn read_intra_mode(
9441016 dec: &mut SymbolDecoder,
9451017 cdfs: &mut Cdfs,
@@ -948,7 +1020,15 @@ fn read_intra_mode(
9481020 cfl: bool,
9491021 side: usize,
9501022 enable_filter_intra: bool,
951-) -> Result<(bool, usize, Option<(i32, i32)>, Option<usize>)> {
1023+) -> Result<(
1024+ bool,
1025+ usize,
1026+ i32,
1027+ usize,
1028+ i32,
1029+ Option<(i32, i32)>,
1030+ Option<usize>,
1031+)> {
9521032 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
9531033 let skip = dec.symbol(&mut cdfs.skip[0]) != 0;
9541034 if trace {
@@ -960,17 +1040,18 @@ fn read_intra_mode(
9601040 if trace {
9611041 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
9621042 }
963- if (V_PRED..=D67_PRED).contains(&mode) {
964- let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
1043+ let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
1044+ let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
9651045 if trace {
966- eprintln!("TRACE angle_delta value={angle}");
967- }
968- if angle != ANGLE_DELTA_ZERO {
969- return Err(unsupported(
970- "a nonzero angle delta (this encoder never writes one)",
971- ));
1046+ eprintln!(
1047+ "TRACE angle_delta value={}",
1048+ delta + ANGLE_DELTA_ZERO as i32
1049+ );
9721050 }
973- }
1051+ delta
1052+ } else {
1053+ 0
1054+ };
9741055 let uv_mode = if cfl {
9751056 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9761057 } else {
@@ -979,12 +1060,31 @@ fn read_intra_mode(
9791060 if trace {
9801061 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
9811062 }
982- let alpha = if uv_mode == DC_PRED {
983- None
984- } else if cfl && uv_mode == UV_CFL_PRED {
1063+ let alpha = if cfl && uv_mode == UV_CFL_PRED {
9851064 Some(read_cfl_alphas(dec, cdfs))
9861065 } else {
987- return Err(unsupported("a directional chroma mode (round 2)"));
1066+ None
1067+ };
1068+ // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
1069+ // from this lane's directional chroma: a corner block with neither
1070+ // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
1071+ // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
1072+ // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
1073+ // bug in that fallback this lane's own scope does not cover. Keep it
1074+ // refused here rather than ship a silently-wrong decode.
1075+ if (9..=12).contains(&uv_mode) {
1076+ return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
1077+ }
1078+ // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
1079+ // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
1080+ // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
1081+ // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
1082+ // the `else` branch below and never reads one either way.
1083+ let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
1084+ DIRECTIONAL_UV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1085+ read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
1086+ } else {
1087+ 0
9881088 };
9891089 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
9901090 // `use_filter_intra` symbol this decoder never read at all until
@@ -1014,7 +1114,15 @@ fn read_intra_mode(
10141114 filter_intra = Some(fi_mode);
10151115 }
10161116 }
1017- Ok((skip, mode, alpha, filter_intra))
1117+ Ok((
1118+ skip,
1119+ mode,
1120+ angle_delta_y,
1121+ uv_mode,
1122+ angle_delta_uv,
1123+ alpha,
1124+ filter_intra,
1125+ ))
10181126 }
10191127
10201128 /// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
@@ -1149,6 +1257,7 @@ impl PlaneBuf {
11491257 y: usize,
11501258 side: usize,
11511259 mode: usize,
1260+ angle_delta: i32,
11521261 reach: Reach,
11531262 residual: &[i32],
11541263 cfl: Option<(i32, &[i32])>,
@@ -1166,12 +1275,29 @@ impl PlaneBuf {
11661275 &mut prediction,
11671276 );
11681277 } else {
1278+ // `enable_intra_edge_filter` is the sequence header's own flag
1279+ // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
1280+ // call, never per-block) -- threading it through every
1281+ // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
1282+ // dozen sites for a value that never changes mid-decode, so it
1283+ // rides a thread-local instead (this decoder is single-threaded
1284+ // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)
1285+ // is left `false`: exact for chroma here (a smooth `uv_mode` is
1286+ // refused before decode reaches this call) and a corner-cut for
1287+ // luma -- ceiling is one wrong filter-strength bucket on a block
1288+ // whose real neighbour predicted smooth; upgrade path is
1289+ // threading `Neighbours::above_mode`/`left_mode`'s
1290+ // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.
1291+ let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
11691292 predict(
11701293 mode as u8,
1294+ angle_delta,
11711295 above.as_deref(),
11721296 left.as_deref(),
11731297 corner,
11741298 side,
1299+ enable_edge_filter,
1300+ false,
11751301 &mut prediction,
11761302 );
11771303 }
@@ -1204,6 +1330,7 @@ fn read_plane(
12041330 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
12051331 tx_mode: usize,
12061332 predict_mode: usize,
1333+ angle_delta: i32,
12071334 reach: Reach,
12081335 plane: &mut PlaneBuf,
12091336 x: usize,
@@ -1227,7 +1354,31 @@ fn read_plane(
12271354 usize::from(around.0) + usize::from(around.1)
12281355 };
12291356 let mut coding = cdfs.txb(set, tx_mode);
1230- let (grid, tx_type) = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;
1357+ // Luma's `default_tx_type` is only a fallback for the sizes whose
1358+ // `TxbSet` carries no symbol at all (32-point and up), which the spec
1359+ // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
1360+ // *never* its own coded symbol (`coding.tx_type` is always `None` for
1361+ // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
1362+ // the plane's own predicted mode (`default_intra_tx_type`) -- except
1363+ // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
1364+ // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
1365+ // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
1366+ // and `Chroma16` never hit this — every value `default_intra_tx_type` can
1367+ // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
1368+ // narrows there — only `Chroma32` and up do).
1369+ let default_tx_type = if plane_idx == 0 || side >= 32 {
1370+ TxType::DctDct
1371+ } else {
1372+ default_intra_tx_type(predict_mode as u8)
1373+ };
1374+ let (grid, tx_type) = read_coeffs(
1375+ dec,
1376+ &mut coding,
1377+ scan,
1378+ skip_ctx,
1379+ dc_sign_ctx(around.2),
1380+ default_tx_type,
1381+ )?;
12311382 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
12321383 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
12331384 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
@@ -1248,9 +1399,7 @@ fn read_plane(
12481399 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
12491400 if std::env::var_os("EC_AV1_TRACE").is_some() {
12501401 eprintln!(
1251- "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} levels[0..4]={:?} residual[0..4]={:?}",
1252- &levels[..4.min(levels.len())],
1253- &residual[..4.min(residual.len())]
1402+ "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
12541403 );
12551404 }
12561405 plane.reconstruct(
@@ -1258,6 +1407,7 @@ fn read_plane(
12581407 y,
12591408 side,
12601409 predict_mode,
1410+ angle_delta,
12611411 reach,
12621412 &residual,
12631413 cfl,
@@ -1308,15 +1458,30 @@ fn decode_block(
13081458 ) -> Result<()> {
13091459 let (r, c) = at;
13101460 let (px, py) = (c * SUB, r * SUB);
1311- let (skip, mode, alpha, filter_intra) = read_intra_mode(
1312- dec,
1313- cdfs,
1314- neighbours.above_mode[c],
1315- neighbours.left_mode[r],
1316- cfl,
1317- side,
1318- enable_filter_intra,
1319- )?;
1461+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
1462+ read_intra_mode(
1463+ dec,
1464+ cdfs,
1465+ neighbours.above_mode[c],
1466+ neighbours.left_mode[r],
1467+ cfl,
1468+ side,
1469+ enable_filter_intra,
1470+ )?;
1471+ // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
1472+ // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
1473+ // actual chroma-from-luma correlation, same as this decoder always did.
1474+ let uv_predict_mode = if uv_mode == UV_CFL_PRED {
1475+ DC_PRED
1476+ } else {
1477+ uv_mode
1478+ };
1479+ if std::env::var_os("EC_AV1_TRACE").is_some() {
1480+ eprintln!(
1481+ "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
1482+ angle_delta_uv={angle_delta_uv}"
1483+ );
1484+ }
13201485 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
13211486 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
13221487 // block, skipped or not. `logical_tx` is what the loop filter's edge
@@ -1347,6 +1512,7 @@ fn decode_block(
13471512 py,
13481513 side,
13491514 mode,
1515+ angle_delta_y,
13501516 reach,
13511517 &vec![0i32; side * side],
13521518 None,
@@ -1357,8 +1523,9 @@ fn decode_block(
13571523 cpx,
13581524 cpy,
13591525 chroma_side,
1360- DC_PRED,
1361- Reach::none(),
1526+ uv_predict_mode,
1527+ angle_delta_uv,
1528+ reach,
13621529 &vec![0i32; chroma_side * chroma_side],
13631530 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
13641531 None,
@@ -1367,8 +1534,9 @@ fn decode_block(
13671534 cpx,
13681535 cpy,
13691536 chroma_side,
1370- DC_PRED,
1371- Reach::none(),
1537+ uv_predict_mode,
1538+ angle_delta_uv,
1539+ reach,
13721540 &vec![0i32; chroma_side * chroma_side],
13731541 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
13741542 None,
@@ -1391,6 +1559,7 @@ fn decode_block(
13911559 around[0],
13921560 mode,
13931561 mode,
1562+ angle_delta_y,
13941563 reach,
13951564 y,
13961565 px,
@@ -1411,8 +1580,9 @@ fn decode_block(
14111580 1,
14121581 around[1],
14131582 mode,
1414- DC_PRED,
1415- Reach::none(),
1583+ uv_predict_mode,
1584+ angle_delta_uv,
1585+ reach,
14161586 u,
14171587 cpx,
14181588 cpy,
@@ -1423,6 +1593,12 @@ fn decode_block(
14231593 None,
14241594 None,
14251595 )?;
1596+ if std::env::var_os("EC_AV1_TRACE").is_some() {
1597+ eprintln!(
1598+ "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
1599+ &u.data[cpy * u.width + cpx..][..chroma_side]
1600+ );
1601+ }
14261602 let v_grid = read_plane(
14271603 dec,
14281604 cdfs,
@@ -1431,8 +1607,9 @@ fn decode_block(
14311607 2,
14321608 around[2],
14331609 mode,
1434- DC_PRED,
1435- Reach::none(),
1610+ uv_predict_mode,
1611+ angle_delta_uv,
1612+ reach,
14361613 v,
14371614 cpx,
14381615 cpy,
@@ -1476,6 +1653,7 @@ fn decode_block(
14761653 tu_around,
14771654 mode,
14781655 mode,
1656+ angle_delta_y,
14791657 tu_reach,
14801658 y,
14811659 tu_px,
@@ -1508,8 +1686,9 @@ fn decode_block(
15081686 1,
15091687 chroma_around[1],
15101688 mode,
1511- DC_PRED,
1512- Reach::none(),
1689+ uv_predict_mode,
1690+ angle_delta_uv,
1691+ reach,
15131692 u,
15141693 cpx,
15151694 cpy,
@@ -1528,8 +1707,9 @@ fn decode_block(
15281707 2,
15291708 chroma_around[2],
15301709 mode,
1531- DC_PRED,
1532- Reach::none(),
1710+ uv_predict_mode,
1711+ angle_delta_uv,
1712+ reach,
15331713 v,
15341714 cpx,
15351715 cpy,
@@ -1591,15 +1771,21 @@ fn decode_leaf8(
15911771 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
15921772 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
15931773 // `decode_block` caller at 16x16 and up.
1594- let (skip, mode, alpha, filter_intra) = read_intra_mode(
1595- dec,
1596- cdfs,
1597- above_mode,
1598- left_mode,
1599- true,
1600- 8,
1601- enable_filter_intra,
1602- )?;
1774+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
1775+ read_intra_mode(
1776+ dec,
1777+ cdfs,
1778+ above_mode,
1779+ left_mode,
1780+ true,
1781+ 8,
1782+ enable_filter_intra,
1783+ )?;
1784+ let uv_predict_mode = if uv_mode == UV_CFL_PRED {
1785+ DC_PRED
1786+ } else {
1787+ uv_mode
1788+ };
16031789 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
16041790 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
16051791 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
@@ -1615,14 +1801,25 @@ fn decode_leaf8(
16151801 let (cpx, cpy) = (px / 2, py / 2);
16161802 let (luma_grid, u_grid, v_grid);
16171803 if skip {
1618- y.reconstruct(px, py, 8, mode, reach, &vec![0i32; 64], None, filter_intra);
1804+ y.reconstruct(
1805+ px,
1806+ py,
1807+ 8,
1808+ mode,
1809+ angle_delta_y,
1810+ reach,
1811+ &vec![0i32; 64],
1812+ None,
1813+ filter_intra,
1814+ );
16191815 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
16201816 u.reconstruct(
16211817 cpx,
16221818 cpy,
16231819 4,
1624- DC_PRED,
1625- Reach::none(),
1820+ uv_predict_mode,
1821+ angle_delta_uv,
1822+ reach,
16261823 &vec![0i32; 16],
16271824 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
16281825 None,
@@ -1631,8 +1828,9 @@ fn decode_leaf8(
16311828 cpx,
16321829 cpy,
16331830 4,
1634- DC_PRED,
1635- Reach::none(),
1831+ uv_predict_mode,
1832+ angle_delta_uv,
1833+ reach,
16361834 &vec![0i32; 16],
16371835 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16381836 None,
@@ -1655,6 +1853,7 @@ fn decode_leaf8(
16551853 around[0],
16561854 mode,
16571855 mode,
1856+ angle_delta_y,
16581857 reach,
16591858 y,
16601859 px,
@@ -1675,8 +1874,9 @@ fn decode_leaf8(
16751874 1,
16761875 around[1],
16771876 mode,
1678- DC_PRED,
1679- Reach::none(),
1877+ uv_predict_mode,
1878+ angle_delta_uv,
1879+ reach,
16801880 u,
16811881 cpx,
16821882 cpy,
@@ -1695,8 +1895,9 @@ fn decode_leaf8(
16951895 2,
16961896 around[2],
16971897 mode,
1698- DC_PRED,
1699- Reach::none(),
1898+ uv_predict_mode,
1899+ angle_delta_uv,
1900+ reach,
17001901 v,
17011902 cpx,
17021903 cpy,
@@ -1735,6 +1936,7 @@ fn decode_leaf8(
17351936 tu_around,
17361937 mode,
17371938 mode,
1939+ angle_delta_y,
17381940 tu_reach,
17391941 y,
17401942 tu_px,
@@ -1767,8 +1969,9 @@ fn decode_leaf8(
17671969 1,
17681970 chroma_around[1],
17691971 mode,
1770- DC_PRED,
1771- Reach::none(),
1972+ uv_predict_mode,
1973+ angle_delta_uv,
1974+ reach,
17721975 u,
17731976 cpx,
17741977 cpy,
@@ -1787,8 +1990,9 @@ fn decode_leaf8(
17871990 2,
17881991 chroma_around[2],
17891992 mode,
1790- DC_PRED,
1791- Reach::none(),
1993+ uv_predict_mode,
1994+ angle_delta_uv,
1995+ reach,
17921996 v,
17931997 cpx,
17941998 cpy,
@@ -2701,6 +2905,7 @@ pub fn decode_key_frame_tile(
27012905 frame_width,
27022906 frame_height,
27032907 enable_filter_intra,
2908+ false,
27042909 cdef,
27052910 loop_filter,
27062911 None,
@@ -2726,6 +2931,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
27262931 frame_width: u32,
27272932 frame_height: u32,
27282933 enable_filter_intra: bool,
2934+ enable_edge_filter: bool,
27292935 cdef: &CdefParams,
27302936 loop_filter: &LoopFilterParams,
27312937 initial_cdfs: Option<Cdfs>,
@@ -2735,6 +2941,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
27352941 if mi_cols == 0 || mi_rows == 0 {
27362942 return Err(unsupported("a frame with no mode-info grid"));
27372943 }
2944+ ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
27382945 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
27392946 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
27402947 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
@@ -3353,7 +3560,21 @@ fn read_inter_plane(
33533560 usize::from(around.0) + usize::from(around.1)
33543561 };
33553562 let mut coding = cdfs.txb(set, tx_mode);
3356- let (grid, tx_type) = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;
3563+ // `av1_get_tx_type` (libaom `blockd.h`): `Intra_Mode_To_Tx_Type` only
3564+ // ever applies to an intra block's chroma plane -- an `is_inter` block
3565+ // (this function, [`read_inter_plane`], reads only those) has no
3566+ // predicted intra mode to index it with, and its `tx_type` (luma or
3567+ // chroma alike) is `DCT_DCT` whenever the `TxbSet` itself codes no
3568+ // symbol for it.
3569+ let default_tx_type = TxType::DctDct;
3570+ let (grid, tx_type) = read_coeffs(
3571+ dec,
3572+ &mut coding,
3573+ scan,
3574+ skip_ctx,
3575+ dc_sign_ctx(around.2),
3576+ default_tx_type,
3577+ )?;
33573578 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
33583579 plane.reconstruct_mc(x, y, side, prediction, &residual);
33593580 Ok(grid)
@@ -3685,6 +3906,7 @@ fn decode_inter_block(
36853906 py,
36863907 side,
36873908 mode,
3909+ 0,
36883910 reach,
36893911 &vec![0i32; side * side],
36903912 None,
@@ -3696,7 +3918,8 @@ fn decode_inter_block(
36963918 cpy,
36973919 chroma_side,
36983920 DC_PRED,
3699- Reach::none(),
3921+ 0,
3922+ reach,
37003923 &vec![0i32; chroma_side * chroma_side],
37013924 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
37023925 None,
@@ -3706,7 +3929,8 @@ fn decode_inter_block(
37063929 cpy,
37073930 chroma_side,
37083931 DC_PRED,
3709- Reach::none(),
3932+ 0,
3933+ reach,
37103934 &vec![0i32; chroma_side * chroma_side],
37113935 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
37123936 None,
@@ -3725,6 +3949,7 @@ fn decode_inter_block(
37253949 around[0],
37263950 mode,
37273951 mode,
3952+ 0,
37283953 reach,
37293954 y,
37303955 px,
@@ -3746,7 +3971,8 @@ fn decode_inter_block(
37463971 around[1],
37473972 mode,
37483973 DC_PRED,
3749- Reach::none(),
3974+ 0,
3975+ reach,
37503976 u,
37513977 cpx,
37523978 cpy,
@@ -3766,7 +3992,8 @@ fn decode_inter_block(
37663992 around[2],
37673993 mode,
37683994 DC_PRED,
3769- Reach::none(),
3995+ 0,
3996+ reach,
37703997 v,
37713998 cpx,
37723999 cpy,
@@ -4084,6 +4311,7 @@ fn decode_inter_block8(
40844311 py,
40854312 SIDE,
40864313 mode,
4314+ 0,
40874315 reach,
40884316 &vec![0i32; SIDE * SIDE],
40894317 None,
@@ -4094,7 +4322,8 @@ fn decode_inter_block8(
40944322 cpy,
40954323 CHROMA_SIDE,
40964324 DC_PRED,
4097- Reach::none(),
4325+ 0,
4326+ reach,
40984327 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
40994328 None,
41004329 None,
@@ -4104,7 +4333,8 @@ fn decode_inter_block8(
41044333 cpy,
41054334 CHROMA_SIDE,
41064335 DC_PRED,
4107- Reach::none(),
4336+ 0,
4337+ reach,
41084338 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
41094339 None,
41104340 None,
@@ -4123,6 +4353,7 @@ fn decode_inter_block8(
41234353 around[0],
41244354 mode,
41254355 mode,
4356+ 0,
41264357 reach,
41274358 y,
41284359 px,
@@ -4143,7 +4374,8 @@ fn decode_inter_block8(
41434374 around[1],
41444375 mode,
41454376 DC_PRED,
4146- Reach::none(),
4377+ 0,
4378+ reach,
41474379 u,
41484380 cpx,
41494381 cpy,
@@ -4163,7 +4395,8 @@ fn decode_inter_block8(
41634395 around[2],
41644396 mode,
41654397 DC_PRED,
4166- Reach::none(),
4398+ 0,
4399+ reach,
41674400 v,
41684401 cpx,
41694402 cpy,
crates/ec-av1/src/encode.rsmodified+12 -0
@@ -599,10 +599,13 @@ impl Plane<'_> {
599599 let mut prediction = vec![0u8; side * side];
600600 crate::intra::predict(
601601 mode,
602+ 0,
602603 above.as_deref(),
603604 left.as_deref(),
604605 corner,
605606 side,
607+ false,
608+ false,
606609 &mut prediction,
607610 );
608611
@@ -815,10 +818,13 @@ impl Plane<'_> {
815818 let mut prediction = vec![0u8; side * side];
816819 crate::intra::predict(
817820 mode,
821+ 0,
818822 above.as_deref(),
819823 left.as_deref(),
820824 corner,
821825 side,
826+ false,
827+ false,
822828 &mut prediction,
823829 );
824830 let sad: f64 = (0..side * side)
@@ -863,10 +869,13 @@ impl Plane<'_> {
863869 let mut prediction = vec![0u8; side * side];
864870 crate::intra::predict(
865871 mode,
872+ 0,
866873 above.as_deref(),
867874 left.as_deref(),
868875 corner,
869876 side,
877+ false,
878+ false,
870879 &mut prediction,
871880 );
872881 let sad: f64 = (0..side * side)
@@ -4418,10 +4427,13 @@ mod tests {
44184427 for _ in 0..N {
44194428 crate::intra::predict(
44204429 D45_PRED,
4430+ 0,
44214431 Some(&above),
44224432 Some(&left),
44234433 Some(128),
44244434 side,
4435+ false,
4436+ false,
44254437 &mut prediction,
44264438 );
44274439 }
crates/ec-av1/src/intra.rsmodified+262 -29
@@ -124,6 +124,10 @@ fn dr_intra_derivative(angle: u16) -> i32 {
124124 /// `Mode_To_Angle` (spec 9.3), zero for the modes that have no angle.
125125 const MODE_TO_ANGLE: [u16; 13] = [0, 90, 180, 45, 135, 113, 157, 203, 67, 0, 0, 0, 0];
126126
127+/// `ANGLE_STEP` (spec 9.3): degrees per unit of `angle_delta`, whose own
128+/// range is `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA` (`MAX_ANGLE_DELTA == 3`).
129+const ANGLE_STEP: i32 = 3;
130+
127131 /// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2):
128132 /// a side that does not exist is filled from the side that does, a side that
129133 /// runs out is extended by repeating its last sample, and the corner falls back
@@ -195,26 +199,62 @@ impl Edges {
195199 /// the edge is extended by repetition where it does not, which is what the
196200 /// decoder's own clamp to `aboveLimit` and `leftLimit` comes to.
197201 ///
202+/// `angle_delta` (spec `AngleDeltaY`/`AngleDeltaUV`, `-MAX_ANGLE_DELTA` to
203+/// `MAX_ANGLE_DELTA`) steers every one of `V_PRED`, `H_PRED` and the six
204+/// diagonal modes off their base angle by `ANGLE_STEP` degrees per unit (spec
205+/// 7.11.2.1's `pAngle = Mode_To_Angle[mode] + angleDelta * ANGLE_STEP`);
206+/// ignored (must be `0`) for the seven modes that carry no angle at all.
207+///
208+/// `enable_edge_filter` is the sequence header's `enable_intra_edge_filter`
209+/// (spec 7.11.2.4's own gate on the whole filter/upsample step); `smooth_neighbor`
210+/// is `get_intra_edge_filter_type` (spec 7.11.2.9, libaom `reconintra.c`) --
211+/// whether the block above or to the left predicted with one of the three
212+/// smooth modes, which steers [`intra_edge_filter_strength`]'s threshold
213+/// table. Ignored outside the directional modes.
214+///
198215 /// # Panics
199216 /// Panics on a mode this module does not predict, or when `dst` is not
200217 /// `side * side` long.
218+#[allow(clippy::too_many_arguments)]
201219 pub fn predict(
202220 mode: u8,
221+ angle_delta: i32,
203222 above: Option<&[u8]>,
204223 left: Option<&[u8]>,
205224 corner: Option<u8>,
206225 side: usize,
226+ enable_edge_filter: bool,
227+ smooth_neighbor: bool,
207228 dst: &mut [u8],
208229 ) {
209230 assert_eq!(dst.len(), side * side, "the destination is the block");
210231 let edges = Edges::build(above, left, corner, side);
211- let angle = MODE_TO_ANGLE[usize::from(mode)];
212- if matches!(
232+ let is_directional = matches!(
213233 mode,
214- D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
215- ) {
216- directional(angle, &edges, side, dst);
217- return;
234+ V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
235+ );
236+ if is_directional {
237+ let angle = i32::from(MODE_TO_ANGLE[usize::from(mode)]) + angle_delta * ANGLE_STEP;
238+ // `pAngle == 90`/`180` is `V_PRED`/`H_PRED` at zero delta: a plain
239+ // edge copy, no walk -- and the only two angles `dr_intra_derivative`
240+ // has no table entry for, since libaom special-cases them the same
241+ // way (`av1_is_directional_mode`'s callers never call the z1/z2/z3
242+ // walk there either).
243+ if angle != 90 && angle != 180 {
244+ let n_top = above.map_or(0, |a| a.len().min(side));
245+ let n_left = left.map_or(0, |a| a.len().min(side));
246+ directional(
247+ angle as u16,
248+ &edges,
249+ side,
250+ enable_edge_filter,
251+ smooth_neighbor,
252+ n_top,
253+ n_left,
254+ dst,
255+ );
256+ return;
257+ }
218258 }
219259 let weights = &SM_WEIGHTS[side..side * 2];
220260 for row in 0..side {
@@ -250,52 +290,245 @@ pub fn predict(
250290 }
251291 }
252292
253-/// Directional intra prediction (spec 7.11.2.4), with the intra edge filter off
254-/// -- which is what our sequence header says -- so nothing here upsamples.
255-fn directional(angle: u16, edges: &Edges, side: usize, dst: &mut [u8]) {
293+/// `intra_edge_filter_strength` (spec 7.11.2.9, libaom `reconintra.c`): the
294+/// filter kernel index (`0`..=`3`) for a gap of `delta` degrees against a
295+/// `bs0 + bs1`-wide block, split by `smooth_neighbor`'s two threshold tables.
296+fn intra_edge_filter_strength(bs0: i32, bs1: i32, delta: i32, smooth_neighbor: bool) -> i32 {
297+ let d = delta.abs();
298+ let blk_wh = bs0 + bs1;
299+ let mut strength = 0;
300+ if !smooth_neighbor {
301+ if blk_wh <= 8 {
302+ if d >= 56 {
303+ strength = 1;
304+ }
305+ } else if blk_wh <= 16 {
306+ if d >= 40 {
307+ strength = 1;
308+ }
309+ } else if blk_wh <= 24 {
310+ if d >= 8 {
311+ strength = 1;
312+ }
313+ if d >= 16 {
314+ strength = 2;
315+ }
316+ if d >= 32 {
317+ strength = 3;
318+ }
319+ } else if blk_wh <= 32 {
320+ if d >= 1 {
321+ strength = 1;
322+ }
323+ if d >= 4 {
324+ strength = 2;
325+ }
326+ if d >= 32 {
327+ strength = 3;
328+ }
329+ } else if d >= 1 {
330+ strength = 3;
331+ }
332+ } else if blk_wh <= 8 {
333+ if d >= 40 {
334+ strength = 1;
335+ }
336+ if d >= 64 {
337+ strength = 2;
338+ }
339+ } else if blk_wh <= 16 {
340+ if d >= 20 {
341+ strength = 1;
342+ }
343+ if d >= 48 {
344+ strength = 2;
345+ }
346+ } else if blk_wh <= 24 {
347+ if d >= 4 {
348+ strength = 3;
349+ }
350+ } else if d >= 1 {
351+ strength = 3;
352+ }
353+ strength
354+}
355+
356+/// `av1_use_intra_edge_upsample` (spec 7.11.2.9): whether the edge doubles in
357+/// density before the walk reads it.
358+fn use_intra_edge_upsample(bs0: i32, bs1: i32, delta: i32, smooth_neighbor: bool) -> bool {
359+ let d = delta.abs();
360+ let blk_wh = bs0 + bs1;
361+ if d == 0 || d >= 40 {
362+ return false;
363+ }
364+ if smooth_neighbor {
365+ blk_wh <= 8
366+ } else {
367+ blk_wh <= 16
368+ }
369+}
370+
371+/// `av1_filter_intra_edge_c` (spec 7.11.2.8): a 5-tap smoothing pass over
372+/// `buf` in place, `buf[0]` (the corner) held fixed as every tap's clamp
373+/// floor/ceiling.
374+fn filter_intra_edge(buf: &mut [i32], strength: i32) {
375+ if strength == 0 {
376+ return;
377+ }
378+ const KERNEL: [[i32; 5]; 3] = [[0, 4, 8, 4, 0], [0, 5, 6, 5, 0], [2, 4, 4, 4, 2]];
379+ let filt = usize::try_from(strength - 1).expect("a filter strength is never negative");
380+ let sz = buf.len() as i32;
381+ let edge = buf.to_vec();
382+ for i in 1..buf.len() {
383+ let mut s = 0;
384+ for (j, &tap) in KERNEL[filt].iter().enumerate() {
385+ let k = (i as i32 - 2 + j as i32).clamp(0, sz - 1);
386+ s += edge[k as usize] * tap;
387+ }
388+ buf[i] = (s + 8) >> 4;
389+ }
390+}
391+
392+/// `av1_upsample_intra_edge_c` (spec 7.11.2.8): doubles `buf`'s density.
393+/// `buf[0]` is spec position `-1` and `buf[buf.len() - 1]` is `sz - 1`; the
394+/// result's `[0]` is spec position `-2`, `[2*i + 1]` the half-sample between
395+/// `i - 1` and `i`, `[2*i + 2]` the original sample `i` moved to its doubled
396+/// slot.
397+fn upsample_intra_edge(buf: &[i32]) -> Vec<i32> {
398+ let sz = buf.len() - 1;
399+ let mut inp = vec![0i32; sz + 3];
400+ inp[0] = buf[0];
401+ inp[1] = buf[0];
402+ inp[2..sz + 2].copy_from_slice(&buf[1..]);
403+ inp[sz + 2] = buf[sz];
404+ let mut out = vec![0i32; 2 * sz + 1];
405+ out[0] = inp[0];
406+ for i in 0..sz {
407+ let s = -inp[i] + 9 * inp[i + 1] + 9 * inp[i + 2] - inp[i + 3];
408+ out[2 * i + 1] = ((s + 8) >> 4).clamp(0, 255);
409+ out[2 * i + 2] = inp[i + 2];
410+ }
411+ out
412+}
413+
414+/// Directional intra prediction (spec 7.11.2.4): the edge filter/upsample
415+/// steps (spec 7.11.2.7-2.9) run first when `enable_edge_filter` (the
416+/// sequence header's own gate) says to, then the z1/z2/z3 walk (libaom
417+/// `av1_dr_prediction_z{1,2,3}_c`) reads whichever of the two -- filtered,
418+/// upsampled, or neither -- it ends with.
419+#[allow(clippy::too_many_arguments)]
420+fn directional(
421+ angle: u16,
422+ edges: &Edges,
423+ side: usize,
424+ enable_edge_filter: bool,
425+ smooth_neighbor: bool,
426+ n_top: usize,
427+ n_left: usize,
428+ dst: &mut [u8],
429+) {
256430 let n = side as i32;
257- // The furthest sample the walk can reach, past which the edge is flat.
258- let max_base = n + n - 1;
431+ let need_above = angle < 180;
432+ let need_left = angle > 90;
433+ let need_right = angle < 90;
434+ let need_bottom = angle > 180;
435+
436+ // Spec position `-1..=2n - 1`, `above[0]`/`left[0]` the shared corner.
437+ let mut above: Vec<i32> = (-1..2 * n).map(|p| edges.above(p)).collect();
438+ let mut left: Vec<i32> = (-1..2 * n).map(|p| edges.left(p)).collect();
439+
440+ if enable_edge_filter && angle != 90 && angle != 180 {
441+ if need_above && need_left && 2 * n >= 24 {
442+ let s = round2(left[1] * 5 + above[0] * 6 + above[1] * 5, 4);
443+ above[0] = s;
444+ left[0] = s;
445+ }
446+ if need_above && n_top > 0 {
447+ let strength = intra_edge_filter_strength(n, n, i32::from(angle) - 90, smooth_neighbor);
448+ let n_px = n_top as i32 + 1 + if need_right { n } else { 0 };
449+ filter_intra_edge(&mut above[..n_px as usize], strength);
450+ }
451+ if need_left && n_left > 0 {
452+ let strength =
453+ intra_edge_filter_strength(n, n, i32::from(angle) - 180, smooth_neighbor);
454+ let n_px = n_left as i32 + 1 + if need_bottom { n } else { 0 };
455+ filter_intra_edge(&mut left[..n_px as usize], strength);
456+ }
457+ }
458+
459+ let upsample_above =
460+ enable_edge_filter && use_intra_edge_upsample(n, n, i32::from(angle) - 90, smooth_neighbor);
461+ let upsample_left = enable_edge_filter
462+ && use_intra_edge_upsample(n, n, i32::from(angle) - 180, smooth_neighbor);
463+
464+ let above_up;
465+ let (above_buf, above_off): (&[i32], i32) = if need_above && upsample_above {
466+ let n_px = (n + if need_right { n } else { 0 }) as usize;
467+ above_up = upsample_intra_edge(&above[..=n_px]);
468+ (&above_up, 2)
469+ } else {
470+ (&above, 1)
471+ };
472+ let left_up;
473+ let (left_buf, left_off): (&[i32], i32) = if need_left && upsample_left {
474+ let n_px = (n + if need_bottom { n } else { 0 }) as usize;
475+ left_up = upsample_intra_edge(&left[..=n_px]);
476+ (&left_up, 2)
477+ } else {
478+ (&left, 1)
479+ };
480+ let above_at = |p: i32| above_buf[(p + above_off) as usize];
481+ let left_at = |p: i32| left_buf[(p + left_off) as usize];
482+ let up_a = i32::from(upsample_above);
483+ let up_l = i32::from(upsample_left);
259484 let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| {
260485 round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5)
261486 };
262- let above = |i: i32| edges.above(i);
263- let left = |i: i32| edges.left(i);
487+
264488 for row in 0..n {
265489 for col in 0..n {
266490 let value = if angle < 90 {
267491 let dx = dr_intra_derivative(angle);
268- let idx = (row + 1) * dx;
269- let base = (idx >> 6) + col;
270- let shift = (idx >> 1) & 0x1F;
492+ let max_base = (2 * n - 1) << up_a;
493+ let frac_bits = 6 - up_a;
494+ let x = dx * (row + 1);
495+ let base = (x >> frac_bits) + (col << up_a);
496+ let shift = ((x << up_a) & 0x3F) >> 1;
271497 if base < max_base {
272- blend(&above, base, shift)
498+ blend(&above_at, base, shift)
273499 } else {
274- above(max_base)
500+ above_at(max_base)
275501 }
276502 } else if angle > 180 {
277503 let dy = dr_intra_derivative(270 - angle);
278- let idx = (col + 1) * dy;
279- let base = (idx >> 6) + row;
280- let shift = (idx >> 1) & 0x1F;
504+ let max_base = (2 * n - 1) << up_l;
505+ let frac_bits = 6 - up_l;
506+ let y = dy * (col + 1);
507+ let base = (y >> frac_bits) + (row << up_l);
508+ let shift = ((y << up_l) & 0x3F) >> 1;
281509 if base < max_base {
282- blend(&left, base, shift)
510+ blend(&left_at, base, shift)
283511 } else {
284- left(max_base)
512+ left_at(max_base)
285513 }
286514 } else {
287515 // The two zones meet here: a ray that leaves through the row
288516 // above is read there, and one that leaves through the column
289517 // to the left is read there instead.
290518 let dx = dr_intra_derivative(180 - angle);
291- let idx = (col << 6) - (row + 1) * dx;
292- let base = idx >> 6;
293- if base >= -1 {
294- blend(&above, base, (idx >> 1) & 0x1F)
519+ let min_base = -(1 << up_a);
520+ let frac_bits_x = 6 - up_a;
521+ let y = row + 1;
522+ let x = (col << 6) - y * dx;
523+ let base = x >> frac_bits_x;
524+ if base >= min_base {
525+ blend(&above_at, base, ((x << up_a) & 0x3F) >> 1)
295526 } else {
296527 let dy = dr_intra_derivative(angle - 90);
297- let idx = (row << 6) - (col + 1) * dy;
298- blend(&left, idx >> 6, (idx >> 1) & 0x1F)
528+ let frac_bits_y = 6 - up_l;
529+ let x2 = col + 1;
530+ let y2 = (row << 6) - x2 * dy;
531+ blend(&left_at, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1)
299532 }
300533 };
301534 dst[(row * n + col) as usize] = value.clamp(0, 255) as u8;
crates/ec-av1/src/stream.rsmodified+156 -0
@@ -187,6 +187,9 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
187187 let enable_dual_filter = parser
188188 .sequence_header()
189189 .is_some_and(|seq| seq.enable_dual_filter);
190+ let enable_edge_filter = parser
191+ .sequence_header()
192+ .is_some_and(|seq| seq.enable_intra_edge_filter);
190193 let interp_fixed = match header.interpolation_filter {
191194 ec_av1_syntax::InterpolationFilter::Switchable => None,
192195 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
@@ -218,6 +221,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
218221 header.frame_width,
219222 header.frame_height,
220223 enable_filter_intra,
224+ enable_edge_filter,
221225 &header.cdef,
222226 &header.loop_filter,
223227 initial_cdfs,
@@ -1175,6 +1179,158 @@ mod tests {
11751179 );
11761180 }
11771181
1182+ /// The directional-chroma/angle-delta gate: a real aomenc key frame with
1183+ /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
1184+ /// opposite of every sibling recipe's `=0`, which existed specifically to
1185+ /// keep this round-2 gap from firing while a different surface was under
1186+ /// test). A colourful, sharp-edged source gives the RD search a reason to
1187+ /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
1188+ /// seeds still won't, so retry like every other real-encoder gate here,
1189+ /// but the first attempt that actually fires either counter must decode
1190+ /// pixel-exact.
1191+ #[test]
1192+ fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
1193+ if !have_ffmpeg() {
1194+ eprintln!(
1195+ "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
1196+ );
1197+ return;
1198+ }
1199+ if !have_aomenc() {
1200+ eprintln!(
1201+ "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
1202+ aomenc_path().display()
1203+ );
1204+ return;
1205+ }
1206+ let (width, height) = (64usize, 64usize);
1207+ let mut refusals = Vec::new();
1208+ let mut fired_runs = 0u32;
1209+ for attempt in 0..40u32 {
1210+ let seed = 42 + attempt;
1211+ let source = format!(
1212+ "mandelbrot=size=64x64:start_scale={}:rate=25",
1213+ 5.0 - f64::from(attempt) * 0.06
1214+ );
1215+ let y4m = Command::new("ffmpeg")
1216+ .args([
1217+ "-v",
1218+ "error",
1219+ "-f",
1220+ "lavfi",
1221+ "-i",
1222+ &source,
1223+ "-pix_fmt",
1224+ "yuv420p",
1225+ "-t",
1226+ "0.04",
1227+ "-f",
1228+ "yuv4mpegpipe",
1229+ "-",
1230+ ])
1231+ .stdin(Stdio::null())
1232+ .stdout(Stdio::piped())
1233+ .stderr(Stdio::piped())
1234+ .output()
1235+ .expect("ffmpeg failed to run");
1236+ assert!(
1237+ y4m.status.success(),
1238+ "ffmpeg fixture: {}",
1239+ String::from_utf8_lossy(&y4m.stderr)
1240+ );
1241+ let mut child = Command::new(aomenc_path())
1242+ .args([
1243+ "--codec=av1",
1244+ "--passes=1",
1245+ "--end-usage=q",
1246+ "--cq-level=45",
1247+ "--cpu-used=0",
1248+ "--enable-rect-partitions=0",
1249+ "--enable-ab-partitions=0",
1250+ "--enable-1to4-partitions=0",
1251+ "--enable-filter-intra=0",
1252+ // Smooth/Paeth chroma is a separate, still-refused round-2
1253+ // gap (an unrelated `Edges::build` no-neighbour bug this
1254+ // lane does not cover) -- off so the RD search's only
1255+ // non-DC/CFL chroma choice left is directional.
1256+ "--enable-smooth-intra=0",
1257+ "--enable-paeth-intra=0",
1258+ "--enable-tx-size-search=0",
1259+ "--enable-cdef=0",
1260+ "--enable-restoration=0",
1261+ // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
1262+ // now implemented (`directional()`) -- left ON (aomenc's
1263+ // own default) so this gate actually exercises it instead
1264+ // of the un-filtered fast path a disabled flag would keep
1265+ // testing.
1266+ "--enable-intra-edge-filter=1",
1267+ "--max-partition-size=32",
1268+ // Same reason as the tx-select gate above: 8x8 and other
1269+ // sub-16x16 splits are a separate, already-named refusal.
1270+ "--min-partition-size=16",
1271+ "--enable-palette=0",
1272+ "--enable-intrabc=0",
1273+ "--enable-cfl-intra=0",
1274+ "--obu",
1275+ "-o",
1276+ "-",
1277+ "-",
1278+ ])
1279+ .stdin(Stdio::piped())
1280+ .stdout(Stdio::piped())
1281+ .stderr(Stdio::piped())
1282+ .spawn()
1283+ .expect("aomenc failed to start");
1284+ child
1285+ .stdin
1286+ .take()
1287+ .expect("aomenc stdin")
1288+ .write_all(&y4m.stdout)
1289+ .expect("writing y4m to aomenc");
1290+ let out = child.wait_with_output().expect("aomenc failed to run");
1291+ assert!(
1292+ out.status.success(),
1293+ "aomenc refused the fixture: {}",
1294+ String::from_utf8_lossy(&out.stderr)
1295+ );
1296+ let stream = out.stdout;
1297+ let (uv_before, angle_before) =
1298+ (decode::directional_uv_hits(), decode::angle_delta_hits());
1299+ let frames = match decode_stream(&stream) {
1300+ Ok(frames) => frames,
1301+ Err(e) => {
1302+ refusals.push(format!("seed {seed}: {e}"));
1303+ continue;
1304+ }
1305+ };
1306+ if decode::directional_uv_hits() == uv_before
1307+ && decode::angle_delta_hits() == angle_before
1308+ {
1309+ refusals.push(format!(
1310+ "seed {seed}: decoded, but neither a directional uv_mode nor a \
1311+ nonzero angle delta fired"
1312+ ));
1313+ continue;
1314+ }
1315+ fired_runs += 1;
1316+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1317+ assert_eq!(
1318+ frames[0].y, ffmpeg_frames[0].y,
1319+ "luma vs ffmpeg (seed {seed})"
1320+ );
1321+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
1322+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
1323+ if fired_runs >= 4 {
1324+ return;
1325+ }
1326+ }
1327+ assert!(
1328+ fired_runs > 0,
1329+ "every attempt hit a named refusal or never exercised directional chroma:\n{}",
1330+ refusals.join("\n")
1331+ );
1332+ }
1333+
11781334 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
11791335 /// --auto-alt-ref=0` keep every non-key frame a simple forward
11801336 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this