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+289 -56
@@ -83,6 +83,37 @@ pub(crate) fn tx_depth_hits() -> usize {
83 /// landing on `DCT_DCT`.83 /// landing on `DCT_DCT`.
84 static TX_CLASS1_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);84 static TX_CLASS1_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
85 85
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+
86 /// Current value of [`TX_CLASS1_HITS`].117 /// Current value of [`TX_CLASS1_HITS`].
87 pub(crate) fn tx_class1_hits() -> usize {118 pub(crate) fn tx_class1_hits() -> usize {
88 TX_CLASS1_HITS.load(std::sync::atomic::Ordering::Relaxed)119 TX_CLASS1_HITS.load(std::sync::atomic::Ordering::Relaxed)
@@ -368,12 +399,41 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) ->
368 /// CDF's own set (a corrupt or unsupported bitstream) — every value the399 /// CDF's own set (a corrupt or unsupported bitstream) — every value the
369 /// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can400 /// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
370 /// produce dispatches to a real inverse transform.401 /// 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+
371 fn read_coeffs(425 fn read_coeffs(
372 dec: &mut SymbolDecoder,426 dec: &mut SymbolDecoder,
373 coding: &mut TxbTables,427 coding: &mut TxbTables,
374 scan: &[u16],428 scan: &[u16],
375 skip_ctx: usize,429 skip_ctx: usize,
376 sign_ctx: usize,430 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,
377 ) -> Result<(Vec<i32>, TxType)> {437 ) -> Result<(Vec<i32>, TxType)> {
378 let trace = std::env::var_os("EC_AV1_TRACE").is_some();438 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
379 let side = coding.side;439 let side = coding.side;
@@ -385,7 +445,7 @@ fn read_coeffs(
385 if all_zero {445 if all_zero {
386 return Ok((grid, TxType::DctDct));446 return Ok((grid, TxType::DctDct));
387 }447 }
388- let mut tx_type = TxType::DctDct;448+ let mut tx_type = default_tx_type;
389 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {449 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
390 // The CDF row's own width names its set: 7 symbols (8 slots) is450 // The CDF row's own width names its set: 7 symbols (8 slots) is
391 // `TX_SET_INTRA_1`, 5 (6 slots) the reduced `TX_SET_INTRA_2` (the451 // `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> {
940 }1000 }
941 }1001 }
942 1002
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+
943 fn read_intra_mode(1015 fn read_intra_mode(
944 dec: &mut SymbolDecoder,1016 dec: &mut SymbolDecoder,
945 cdfs: &mut Cdfs,1017 cdfs: &mut Cdfs,
@@ -948,7 +1020,15 @@ fn read_intra_mode(
948 cfl: bool,1020 cfl: bool,
949 side: usize,1021 side: usize,
950 enable_filter_intra: bool,1022 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+)> {
952 let trace = std::env::var_os("EC_AV1_TRACE").is_some();1032 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
953 let skip = dec.symbol(&mut cdfs.skip[0]) != 0;1033 let skip = dec.symbol(&mut cdfs.skip[0]) != 0;
954 if trace {1034 if trace {
@@ -960,17 +1040,18 @@ fn read_intra_mode(
960 if trace {1040 if trace {
961 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");1041 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
962 }1042 }
963- if (V_PRED..=D67_PRED).contains(&mode) {1043+ let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
964- let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);1044+ let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
965 if trace {1045 if trace {
966- eprintln!("TRACE angle_delta value={angle}");1046+ eprintln!(
967- }1047+ "TRACE angle_delta value={}",
968- if angle != ANGLE_DELTA_ZERO {1048+ delta + ANGLE_DELTA_ZERO as i32
969- return Err(unsupported(1049+ );
970- "a nonzero angle delta (this encoder never writes one)",
971- ));
972- }
973 }1050 }
1051+ delta
1052+ } else {
1053+ 0
1054+ };
974 let uv_mode = if cfl {1055 let uv_mode = if cfl {
975 dec.symbol(&mut cdfs.uv_mode_cfl[mode])1056 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
976 } else {1057 } else {
@@ -979,12 +1060,31 @@ fn read_intra_mode(
979 if trace {1060 if trace {
980 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");1061 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
981 }1062 }
982- let alpha = if uv_mode == DC_PRED {1063+ let alpha = if cfl && uv_mode == UV_CFL_PRED {
983- None
984- } else if cfl && uv_mode == UV_CFL_PRED {
985 Some(read_cfl_alphas(dec, cdfs))1064 Some(read_cfl_alphas(dec, cdfs))
986 } else {1065 } 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
988 };1088 };
989 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a1089 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
990 // `use_filter_intra` symbol this decoder never read at all until1090 // `use_filter_intra` symbol this decoder never read at all until
@@ -1014,7 +1114,15 @@ fn read_intra_mode(
1014 filter_intra = Some(fi_mode);1114 filter_intra = Some(fi_mode);
1015 }1115 }
1016 }1116 }
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+ ))
1018 }1126 }
1019 1127
1020 /// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth1128 /// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
@@ -1149,6 +1257,7 @@ impl PlaneBuf {
1149 y: usize,1257 y: usize,
1150 side: usize,1258 side: usize,
1151 mode: usize,1259 mode: usize,
1260+ angle_delta: i32,
1152 reach: Reach,1261 reach: Reach,
1153 residual: &[i32],1262 residual: &[i32],
1154 cfl: Option<(i32, &[i32])>,1263 cfl: Option<(i32, &[i32])>,
@@ -1166,12 +1275,29 @@ impl PlaneBuf {
1166 &mut prediction,1275 &mut prediction,
1167 );1276 );
1168 } else {1277 } 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);
1169 predict(1292 predict(
1170 mode as u8,1293 mode as u8,
1294+ angle_delta,
1171 above.as_deref(),1295 above.as_deref(),
1172 left.as_deref(),1296 left.as_deref(),
1173 corner,1297 corner,
1174 side,1298 side,
1299+ enable_edge_filter,
1300+ false,
1175 &mut prediction,1301 &mut prediction,
1176 );1302 );
1177 }1303 }
@@ -1204,6 +1330,7 @@ fn read_plane(
1204 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.1330 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
1205 tx_mode: usize,1331 tx_mode: usize,
1206 predict_mode: usize,1332 predict_mode: usize,
1333+ angle_delta: i32,
1207 reach: Reach,1334 reach: Reach,
1208 plane: &mut PlaneBuf,1335 plane: &mut PlaneBuf,
1209 x: usize,1336 x: usize,
@@ -1227,7 +1354,31 @@ fn read_plane(
1227 usize::from(around.0) + usize::from(around.1)1354 usize::from(around.0) + usize::from(around.1)
1228 };1355 };
1229 let mut coding = cdfs.txb(set, tx_mode);1356 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+ )?;
1231 // A 64x64 luma block's transform covers the whole 64x64 area, but only its1382 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
1232 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the1383 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
1233 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`1384 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
@@ -1248,9 +1399,7 @@ fn read_plane(
1248 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);1399 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
1249 if std::env::var_os("EC_AV1_TRACE").is_some() {1400 if std::env::var_os("EC_AV1_TRACE").is_some() {
1250 eprintln!(1401 eprintln!(
1251- "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} levels[0..4]={:?} residual[0..4]={:?}",1402+ "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
1252- &levels[..4.min(levels.len())],
1253- &residual[..4.min(residual.len())]
1254 );1403 );
1255 }1404 }
1256 plane.reconstruct(1405 plane.reconstruct(
@@ -1258,6 +1407,7 @@ fn read_plane(
1258 y,1407 y,
1259 side,1408 side,
1260 predict_mode,1409 predict_mode,
1410+ angle_delta,
1261 reach,1411 reach,
1262 &residual,1412 &residual,
1263 cfl,1413 cfl,
@@ -1308,7 +1458,8 @@ fn decode_block(
1308 ) -> Result<()> {1458 ) -> Result<()> {
1309 let (r, c) = at;1459 let (r, c) = at;
1310 let (px, py) = (c * SUB, r * SUB);1460 let (px, py) = (c * SUB, r * SUB);
1311- let (skip, mode, alpha, filter_intra) = read_intra_mode(1461+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
1462+ read_intra_mode(
1312 dec,1463 dec,
1313 cdfs,1464 cdfs,
1314 neighbours.above_mode[c],1465 neighbours.above_mode[c],
@@ -1317,6 +1468,20 @@ fn decode_block(
1317 side,1468 side,
1318 enable_filter_intra,1469 enable_filter_intra,
1319 )?;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+ }
1320 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));1485 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
1321 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra1486 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
1322 // block, skipped or not. `logical_tx` is what the loop filter's edge1487 // block, skipped or not. `logical_tx` is what the loop filter's edge
@@ -1347,6 +1512,7 @@ fn decode_block(
1347 py,1512 py,
1348 side,1513 side,
1349 mode,1514 mode,
1515+ angle_delta_y,
1350 reach,1516 reach,
1351 &vec![0i32; side * side],1517 &vec![0i32; side * side],
1352 None,1518 None,
@@ -1357,8 +1523,9 @@ fn decode_block(
1357 cpx,1523 cpx,
1358 cpy,1524 cpy,
1359 chroma_side,1525 chroma_side,
1360- DC_PRED,1526+ uv_predict_mode,
1361- Reach::none(),1527+ angle_delta_uv,
1528+ reach,
1362 &vec![0i32; chroma_side * chroma_side],1529 &vec![0i32; chroma_side * chroma_side],
1363 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),1530 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1364 None,1531 None,
@@ -1367,8 +1534,9 @@ fn decode_block(
1367 cpx,1534 cpx,
1368 cpy,1535 cpy,
1369 chroma_side,1536 chroma_side,
1370- DC_PRED,1537+ uv_predict_mode,
1371- Reach::none(),1538+ angle_delta_uv,
1539+ reach,
1372 &vec![0i32; chroma_side * chroma_side],1540 &vec![0i32; chroma_side * chroma_side],
1373 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),1541 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1374 None,1542 None,
@@ -1391,6 +1559,7 @@ fn decode_block(
1391 around[0],1559 around[0],
1392 mode,1560 mode,
1393 mode,1561 mode,
1562+ angle_delta_y,
1394 reach,1563 reach,
1395 y,1564 y,
1396 px,1565 px,
@@ -1411,8 +1580,9 @@ fn decode_block(
1411 1,1580 1,
1412 around[1],1581 around[1],
1413 mode,1582 mode,
1414- DC_PRED,1583+ uv_predict_mode,
1415- Reach::none(),1584+ angle_delta_uv,
1585+ reach,
1416 u,1586 u,
1417 cpx,1587 cpx,
1418 cpy,1588 cpy,
@@ -1423,6 +1593,12 @@ fn decode_block(
1423 None,1593 None,
1424 None,1594 None,
1425 )?;1595 )?;
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+ }
1426 let v_grid = read_plane(1602 let v_grid = read_plane(
1427 dec,1603 dec,
1428 cdfs,1604 cdfs,
@@ -1431,8 +1607,9 @@ fn decode_block(
1431 2,1607 2,
1432 around[2],1608 around[2],
1433 mode,1609 mode,
1434- DC_PRED,1610+ uv_predict_mode,
1435- Reach::none(),1611+ angle_delta_uv,
1612+ reach,
1436 v,1613 v,
1437 cpx,1614 cpx,
1438 cpy,1615 cpy,
@@ -1476,6 +1653,7 @@ fn decode_block(
1476 tu_around,1653 tu_around,
1477 mode,1654 mode,
1478 mode,1655 mode,
1656+ angle_delta_y,
1479 tu_reach,1657 tu_reach,
1480 y,1658 y,
1481 tu_px,1659 tu_px,
@@ -1508,8 +1686,9 @@ fn decode_block(
1508 1,1686 1,
1509 chroma_around[1],1687 chroma_around[1],
1510 mode,1688 mode,
1511- DC_PRED,1689+ uv_predict_mode,
1512- Reach::none(),1690+ angle_delta_uv,
1691+ reach,
1513 u,1692 u,
1514 cpx,1693 cpx,
1515 cpy,1694 cpy,
@@ -1528,8 +1707,9 @@ fn decode_block(
1528 2,1707 2,
1529 chroma_around[2],1708 chroma_around[2],
1530 mode,1709 mode,
1531- DC_PRED,1710+ uv_predict_mode,
1532- Reach::none(),1711+ angle_delta_uv,
1712+ reach,
1533 v,1713 v,
1534 cpx,1714 cpx,
1535 cpy,1715 cpy,
@@ -1591,7 +1771,8 @@ fn decode_leaf8(
1591 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec1771 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
1592 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other1772 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
1593 // `decode_block` caller at 16x16 and up.1773 // `decode_block` caller at 16x16 and up.
1594- let (skip, mode, alpha, filter_intra) = read_intra_mode(1774+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
1775+ read_intra_mode(
1595 dec,1776 dec,
1596 cdfs,1777 cdfs,
1597 above_mode,1778 above_mode,
@@ -1600,6 +1781,11 @@ fn decode_leaf8(
1600 8,1781 8,
1601 enable_filter_intra,1782 enable_filter_intra,
1602 )?;1783 )?;
1784+ let uv_predict_mode = if uv_mode == UV_CFL_PRED {
1785+ DC_PRED
1786+ } else {
1787+ uv_mode
1788+ };
1603 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only1789 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
1604 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,1790 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
1605 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x41791 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
@@ -1615,14 +1801,25 @@ fn decode_leaf8(
1615 let (cpx, cpy) = (px / 2, py / 2);1801 let (cpx, cpy) = (px / 2, py / 2);
1616 let (luma_grid, u_grid, v_grid);1802 let (luma_grid, u_grid, v_grid);
1617 if skip {1803 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+ );
1619 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));1815 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
1620 u.reconstruct(1816 u.reconstruct(
1621 cpx,1817 cpx,
1622 cpy,1818 cpy,
1623 4,1819 4,
1624- DC_PRED,1820+ uv_predict_mode,
1625- Reach::none(),1821+ angle_delta_uv,
1822+ reach,
1626 &vec![0i32; 16],1823 &vec![0i32; 16],
1627 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),1824 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1628 None,1825 None,
@@ -1631,8 +1828,9 @@ fn decode_leaf8(
1631 cpx,1828 cpx,
1632 cpy,1829 cpy,
1633 4,1830 4,
1634- DC_PRED,1831+ uv_predict_mode,
1635- Reach::none(),1832+ angle_delta_uv,
1833+ reach,
1636 &vec![0i32; 16],1834 &vec![0i32; 16],
1637 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),1835 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1638 None,1836 None,
@@ -1655,6 +1853,7 @@ fn decode_leaf8(
1655 around[0],1853 around[0],
1656 mode,1854 mode,
1657 mode,1855 mode,
1856+ angle_delta_y,
1658 reach,1857 reach,
1659 y,1858 y,
1660 px,1859 px,
@@ -1675,8 +1874,9 @@ fn decode_leaf8(
1675 1,1874 1,
1676 around[1],1875 around[1],
1677 mode,1876 mode,
1678- DC_PRED,1877+ uv_predict_mode,
1679- Reach::none(),1878+ angle_delta_uv,
1879+ reach,
1680 u,1880 u,
1681 cpx,1881 cpx,
1682 cpy,1882 cpy,
@@ -1695,8 +1895,9 @@ fn decode_leaf8(
1695 2,1895 2,
1696 around[2],1896 around[2],
1697 mode,1897 mode,
1698- DC_PRED,1898+ uv_predict_mode,
1699- Reach::none(),1899+ angle_delta_uv,
1900+ reach,
1700 v,1901 v,
1701 cpx,1902 cpx,
1702 cpy,1903 cpy,
@@ -1735,6 +1936,7 @@ fn decode_leaf8(
1735 tu_around,1936 tu_around,
1736 mode,1937 mode,
1737 mode,1938 mode,
1939+ angle_delta_y,
1738 tu_reach,1940 tu_reach,
1739 y,1941 y,
1740 tu_px,1942 tu_px,
@@ -1767,8 +1969,9 @@ fn decode_leaf8(
1767 1,1969 1,
1768 chroma_around[1],1970 chroma_around[1],
1769 mode,1971 mode,
1770- DC_PRED,1972+ uv_predict_mode,
1771- Reach::none(),1973+ angle_delta_uv,
1974+ reach,
1772 u,1975 u,
1773 cpx,1976 cpx,
1774 cpy,1977 cpy,
@@ -1787,8 +1990,9 @@ fn decode_leaf8(
1787 2,1990 2,
1788 chroma_around[2],1991 chroma_around[2],
1789 mode,1992 mode,
1790- DC_PRED,1993+ uv_predict_mode,
1791- Reach::none(),1994+ angle_delta_uv,
1995+ reach,
1792 v,1996 v,
1793 cpx,1997 cpx,
1794 cpy,1998 cpy,
@@ -2701,6 +2905,7 @@ pub fn decode_key_frame_tile(
2701 frame_width,2905 frame_width,
2702 frame_height,2906 frame_height,
2703 enable_filter_intra,2907 enable_filter_intra,
2908+ false,
2704 cdef,2909 cdef,
2705 loop_filter,2910 loop_filter,
2706 None,2911 None,
@@ -2726,6 +2931,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2726 frame_width: u32,2931 frame_width: u32,
2727 frame_height: u32,2932 frame_height: u32,
2728 enable_filter_intra: bool,2933 enable_filter_intra: bool,
2934+ enable_edge_filter: bool,
2729 cdef: &CdefParams,2935 cdef: &CdefParams,
2730 loop_filter: &LoopFilterParams,2936 loop_filter: &LoopFilterParams,
2731 initial_cdfs: Option<Cdfs>,2937 initial_cdfs: Option<Cdfs>,
@@ -2735,6 +2941,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2735 if mi_cols == 0 || mi_rows == 0 {2941 if mi_cols == 0 || mi_rows == 0 {
2736 return Err(unsupported("a frame with no mode-info grid"));2942 return Err(unsupported("a frame with no mode-info grid"));
2737 }2943 }
2944+ ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
2738 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));2945 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
2739 let (cols32, rows32) = block_grid(mi_cols, mi_rows);2946 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
2740 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);2947 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
@@ -3353,7 +3560,21 @@ fn read_inter_plane(
3353 usize::from(around.0) + usize::from(around.1)3560 usize::from(around.0) + usize::from(around.1)
3354 };3561 };
3355 let mut coding = cdfs.txb(set, tx_mode);3562 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+ )?;
3357 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);3578 let residual = dequant_and_inverse_typed(&grid, side, 8, i32::from(base_q_idx), tx_type);
3358 plane.reconstruct_mc(x, y, side, prediction, &residual);3579 plane.reconstruct_mc(x, y, side, prediction, &residual);
3359 Ok(grid)3580 Ok(grid)
@@ -3685,6 +3906,7 @@ fn decode_inter_block(
3685 py,3906 py,
3686 side,3907 side,
3687 mode,3908 mode,
3909+ 0,
3688 reach,3910 reach,
3689 &vec![0i32; side * side],3911 &vec![0i32; side * side],
3690 None,3912 None,
@@ -3696,7 +3918,8 @@ fn decode_inter_block(
3696 cpy,3918 cpy,
3697 chroma_side,3919 chroma_side,
3698 DC_PRED,3920 DC_PRED,
3699- Reach::none(),3921+ 0,
3922+ reach,
3700 &vec![0i32; chroma_side * chroma_side],3923 &vec![0i32; chroma_side * chroma_side],
3701 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),3924 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3702 None,3925 None,
@@ -3706,7 +3929,8 @@ fn decode_inter_block(
3706 cpy,3929 cpy,
3707 chroma_side,3930 chroma_side,
3708 DC_PRED,3931 DC_PRED,
3709- Reach::none(),3932+ 0,
3933+ reach,
3710 &vec![0i32; chroma_side * chroma_side],3934 &vec![0i32; chroma_side * chroma_side],
3711 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),3935 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3712 None,3936 None,
@@ -3725,6 +3949,7 @@ fn decode_inter_block(
3725 around[0],3949 around[0],
3726 mode,3950 mode,
3727 mode,3951 mode,
3952+ 0,
3728 reach,3953 reach,
3729 y,3954 y,
3730 px,3955 px,
@@ -3746,7 +3971,8 @@ fn decode_inter_block(
3746 around[1],3971 around[1],
3747 mode,3972 mode,
3748 DC_PRED,3973 DC_PRED,
3749- Reach::none(),3974+ 0,
3975+ reach,
3750 u,3976 u,
3751 cpx,3977 cpx,
3752 cpy,3978 cpy,
@@ -3766,7 +3992,8 @@ fn decode_inter_block(
3766 around[2],3992 around[2],
3767 mode,3993 mode,
3768 DC_PRED,3994 DC_PRED,
3769- Reach::none(),3995+ 0,
3996+ reach,
3770 v,3997 v,
3771 cpx,3998 cpx,
3772 cpy,3999 cpy,
@@ -4084,6 +4311,7 @@ fn decode_inter_block8(
4084 py,4311 py,
4085 SIDE,4312 SIDE,
4086 mode,4313 mode,
4314+ 0,
4087 reach,4315 reach,
4088 &vec![0i32; SIDE * SIDE],4316 &vec![0i32; SIDE * SIDE],
4089 None,4317 None,
@@ -4094,7 +4322,8 @@ fn decode_inter_block8(
4094 cpy,4322 cpy,
4095 CHROMA_SIDE,4323 CHROMA_SIDE,
4096 DC_PRED,4324 DC_PRED,
4097- Reach::none(),4325+ 0,
4326+ reach,
4098 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],4327 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
4099 None,4328 None,
4100 None,4329 None,
@@ -4104,7 +4333,8 @@ fn decode_inter_block8(
4104 cpy,4333 cpy,
4105 CHROMA_SIDE,4334 CHROMA_SIDE,
4106 DC_PRED,4335 DC_PRED,
4107- Reach::none(),4336+ 0,
4337+ reach,
4108 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],4338 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
4109 None,4339 None,
4110 None,4340 None,
@@ -4123,6 +4353,7 @@ fn decode_inter_block8(
4123 around[0],4353 around[0],
4124 mode,4354 mode,
4125 mode,4355 mode,
4356+ 0,
4126 reach,4357 reach,
4127 y,4358 y,
4128 px,4359 px,
@@ -4143,7 +4374,8 @@ fn decode_inter_block8(
4143 around[1],4374 around[1],
4144 mode,4375 mode,
4145 DC_PRED,4376 DC_PRED,
4146- Reach::none(),4377+ 0,
4378+ reach,
4147 u,4379 u,
4148 cpx,4380 cpx,
4149 cpy,4381 cpy,
@@ -4163,7 +4395,8 @@ fn decode_inter_block8(
4163 around[2],4395 around[2],
4164 mode,4396 mode,
4165 DC_PRED,4397 DC_PRED,
4166- Reach::none(),4398+ 0,
4399+ reach,
4167 v,4400 v,
4168 cpx,4401 cpx,
4169 cpy,4402 cpy,
crates/ec-av1/src/encode.rsmodified+12 -0
@@ -599,10 +599,13 @@ impl Plane<'_> {
599 let mut prediction = vec![0u8; side * side];599 let mut prediction = vec![0u8; side * side];
600 crate::intra::predict(600 crate::intra::predict(
601 mode,601 mode,
602+ 0,
602 above.as_deref(),603 above.as_deref(),
603 left.as_deref(),604 left.as_deref(),
604 corner,605 corner,
605 side,606 side,
607+ false,
608+ false,
606 &mut prediction,609 &mut prediction,
607 );610 );
608 611
@@ -815,10 +818,13 @@ impl Plane<'_> {
815 let mut prediction = vec![0u8; side * side];818 let mut prediction = vec![0u8; side * side];
816 crate::intra::predict(819 crate::intra::predict(
817 mode,820 mode,
821+ 0,
818 above.as_deref(),822 above.as_deref(),
819 left.as_deref(),823 left.as_deref(),
820 corner,824 corner,
821 side,825 side,
826+ false,
827+ false,
822 &mut prediction,828 &mut prediction,
823 );829 );
824 let sad: f64 = (0..side * side)830 let sad: f64 = (0..side * side)
@@ -863,10 +869,13 @@ impl Plane<'_> {
863 let mut prediction = vec![0u8; side * side];869 let mut prediction = vec![0u8; side * side];
864 crate::intra::predict(870 crate::intra::predict(
865 mode,871 mode,
872+ 0,
866 above.as_deref(),873 above.as_deref(),
867 left.as_deref(),874 left.as_deref(),
868 corner,875 corner,
869 side,876 side,
877+ false,
878+ false,
870 &mut prediction,879 &mut prediction,
871 );880 );
872 let sad: f64 = (0..side * side)881 let sad: f64 = (0..side * side)
@@ -4418,10 +4427,13 @@ mod tests {
4418 for _ in 0..N {4427 for _ in 0..N {
4419 crate::intra::predict(4428 crate::intra::predict(
4420 D45_PRED,4429 D45_PRED,
4430+ 0,
4421 Some(&above),4431 Some(&above),
4422 Some(&left),4432 Some(&left),
4423 Some(128),4433 Some(128),
4424 side,4434 side,
4435+ false,
4436+ false,
4425 &mut prediction,4437 &mut prediction,
4426 );4438 );
4427 }4439 }
crates/ec-av1/src/intra.rsmodified+261 -28
@@ -124,6 +124,10 @@ fn dr_intra_derivative(angle: u16) -> i32 {
124 /// `Mode_To_Angle` (spec 9.3), zero for the modes that have no angle.124 /// `Mode_To_Angle` (spec 9.3), zero for the modes that have no angle.
125 const MODE_TO_ANGLE: [u16; 13] = [0, 90, 180, 45, 135, 113, 157, 203, 67, 0, 0, 0, 0];125 const MODE_TO_ANGLE: [u16; 13] = [0, 90, 180, 45, 135, 113, 157, 203, 67, 0, 0, 0, 0];
126 126
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+
127 /// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2):131 /// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2):
128 /// a side that does not exist is filled from the side that does, a side that132 /// a side that does not exist is filled from the side that does, a side that
129 /// runs out is extended by repeating its last sample, and the corner falls back133 /// runs out is extended by repeating its last sample, and the corner falls back
@@ -195,27 +199,63 @@ impl Edges {
195 /// the edge is extended by repetition where it does not, which is what the199 /// the edge is extended by repetition where it does not, which is what the
196 /// decoder's own clamp to `aboveLimit` and `leftLimit` comes to.200 /// decoder's own clamp to `aboveLimit` and `leftLimit` comes to.
197 ///201 ///
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+///
198 /// # Panics215 /// # Panics
199 /// Panics on a mode this module does not predict, or when `dst` is not216 /// Panics on a mode this module does not predict, or when `dst` is not
200 /// `side * side` long.217 /// `side * side` long.
218+#[allow(clippy::too_many_arguments)]
201 pub fn predict(219 pub fn predict(
202 mode: u8,220 mode: u8,
221+ angle_delta: i32,
203 above: Option<&[u8]>,222 above: Option<&[u8]>,
204 left: Option<&[u8]>,223 left: Option<&[u8]>,
205 corner: Option<u8>,224 corner: Option<u8>,
206 side: usize,225 side: usize,
226+ enable_edge_filter: bool,
227+ smooth_neighbor: bool,
207 dst: &mut [u8],228 dst: &mut [u8],
208 ) {229 ) {
209 assert_eq!(dst.len(), side * side, "the destination is the block");230 assert_eq!(dst.len(), side * side, "the destination is the block");
210 let edges = Edges::build(above, left, corner, side);231 let edges = Edges::build(above, left, corner, side);
211- let angle = MODE_TO_ANGLE[usize::from(mode)];232+ let is_directional = matches!(
212- if matches!(
213 mode,233 mode,
214- D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED234+ V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
215- ) {235+ );
216- directional(angle, &edges, side, dst);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+ );
217 return;256 return;
218 }257 }
258+ }
219 let weights = &SM_WEIGHTS[side..side * 2];259 let weights = &SM_WEIGHTS[side..side * 2];
220 for row in 0..side {260 for row in 0..side {
221 for col in 0..side {261 for col in 0..side {
@@ -250,52 +290,245 @@ pub fn predict(
250 }290 }
251 }291 }
252 292
253-/// Directional intra prediction (spec 7.11.2.4), with the intra edge filter off293+/// `intra_edge_filter_strength` (spec 7.11.2.9, libaom `reconintra.c`): the
254-/// -- which is what our sequence header says -- so nothing here upsamples.294+/// filter kernel index (`0`..=`3`) for a gap of `delta` degrees against a
255-fn directional(angle: u16, edges: &Edges, side: usize, dst: &mut [u8]) {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+) {
256 let n = side as i32;430 let n = side as i32;
257- // The furthest sample the walk can reach, past which the edge is flat.431+ let need_above = angle < 180;
258- let max_base = n + n - 1;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);
259 let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| {484 let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| {
260 round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5)485 round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5)
261 };486 };
262- let above = |i: i32| edges.above(i);487+
263- let left = |i: i32| edges.left(i);
264 for row in 0..n {488 for row in 0..n {
265 for col in 0..n {489 for col in 0..n {
266 let value = if angle < 90 {490 let value = if angle < 90 {
267 let dx = dr_intra_derivative(angle);491 let dx = dr_intra_derivative(angle);
268- let idx = (row + 1) * dx;492+ let max_base = (2 * n - 1) << up_a;
269- let base = (idx >> 6) + col;493+ let frac_bits = 6 - up_a;
270- let shift = (idx >> 1) & 0x1F;494+ let x = dx * (row + 1);
495+ let base = (x >> frac_bits) + (col << up_a);
496+ let shift = ((x << up_a) & 0x3F) >> 1;
271 if base < max_base {497 if base < max_base {
272- blend(&above, base, shift)498+ blend(&above_at, base, shift)
273 } else {499 } else {
274- above(max_base)500+ above_at(max_base)
275 }501 }
276 } else if angle > 180 {502 } else if angle > 180 {
277 let dy = dr_intra_derivative(270 - angle);503 let dy = dr_intra_derivative(270 - angle);
278- let idx = (col + 1) * dy;504+ let max_base = (2 * n - 1) << up_l;
279- let base = (idx >> 6) + row;505+ let frac_bits = 6 - up_l;
280- let shift = (idx >> 1) & 0x1F;506+ let y = dy * (col + 1);
507+ let base = (y >> frac_bits) + (row << up_l);
508+ let shift = ((y << up_l) & 0x3F) >> 1;
281 if base < max_base {509 if base < max_base {
282- blend(&left, base, shift)510+ blend(&left_at, base, shift)
283 } else {511 } else {
284- left(max_base)512+ left_at(max_base)
285 }513 }
286 } else {514 } else {
287 // The two zones meet here: a ray that leaves through the row515 // The two zones meet here: a ray that leaves through the row
288 // above is read there, and one that leaves through the column516 // above is read there, and one that leaves through the column
289 // to the left is read there instead.517 // to the left is read there instead.
290 let dx = dr_intra_derivative(180 - angle);518 let dx = dr_intra_derivative(180 - angle);
291- let idx = (col << 6) - (row + 1) * dx;519+ let min_base = -(1 << up_a);
292- let base = idx >> 6;520+ let frac_bits_x = 6 - up_a;
293- if base >= -1 {521+ let y = row + 1;
294- blend(&above, base, (idx >> 1) & 0x1F)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)
295 } else {526 } else {
296 let dy = dr_intra_derivative(angle - 90);527 let dy = dr_intra_derivative(angle - 90);
297- let idx = (row << 6) - (col + 1) * dy;528+ let frac_bits_y = 6 - up_l;
298- blend(&left, idx >> 6, (idx >> 1) & 0x1F)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)
299 }532 }
300 };533 };
301 dst[(row * n + col) as usize] = value.clamp(0, 255) as u8;534 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>> {
187 let enable_dual_filter = parser187 let enable_dual_filter = parser
188 .sequence_header()188 .sequence_header()
189 .is_some_and(|seq| seq.enable_dual_filter);189 .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);
190 let interp_fixed = match header.interpolation_filter {193 let interp_fixed = match header.interpolation_filter {
191 ec_av1_syntax::InterpolationFilter::Switchable => None,194 ec_av1_syntax::InterpolationFilter::Switchable => None,
192 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),195 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
@@ -218,6 +221,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
218 header.frame_width,221 header.frame_width,
219 header.frame_height,222 header.frame_height,
220 enable_filter_intra,223 enable_filter_intra,
224+ enable_edge_filter,
221 &header.cdef,225 &header.cdef,
222 &header.loop_filter,226 &header.loop_filter,
223 initial_cdfs,227 initial_cdfs,
@@ -1175,6 +1179,158 @@ mod tests {
1175 );1179 );
1176 }1180 }
1177 1181
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+
1178 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=01334 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
1179 /// --auto-alt-ref=0` keep every non-key frame a simple forward1335 /// --auto-alt-ref=0` keep every non-key frame a simple forward
1180 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this1336 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this