forge
Explore
Log in

Don't you dare go Hollow

Implement the intra edge filter/upsample (spec 7.11.2.7-2.9)

Browse files at this commit

645882d9cc4cf56a22886cc9fd8c47d6e6b817cbAhmet Kaan GümüşParent: 637d48a
  • feat
    • implement the intra edge filter/upsample (spec 7.11.2.7-2.9)
Show full message
feat(av1): implement the intra edge filter/upsample (spec 7.11.2.7-2.9)

r5 left directional()'s edge filter/upsample as an unimplemented corner-cut
and left the two new predict() bool params half-plumbed (encode.rs call
sites done, stream.rs/decode.rs test-module sites missing). This round:

- finished the plumbing: decode.rs threads the sequence header's
  enable_intra_edge_filter through a thread-local (ENABLE_EDGE_FILTER,
  set once per decode_key_frame_tile_with_cdfs call, not per-block --
  documented why a thread-local beats touching two dozen call sites)
  down to PlaneBuf::reconstruct's predict() call; stream.rs sets it from
  the parsed seq header; encode.rs sites already passed false (our
  encoder never turns it on, so round-trips stay bit-green regardless).
- filter_intra_edge (5-tap kernel, 3 strength buckets via
  intra_edge_filter_strength's two smooth/non-smooth threshold tables),
  the filter_corner blend, and upsample_intra_edge (av1_upsample_intra_edge_c)
  were transcribed against libaom's reconintra.c and wired into
  directional()'s z1/z2/z3 walk (base/shift math doubled for the
  upsampled-density case). All present, none stubbed.
- flipped the gate's --enable-intra-edge-filter=0 to =1 so
  a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact
  actually exercises the new path instead of the disabled one.

The gate still fails, but NOT from this filter: patched-aomdec
cross-checks (EC_UDUMP dqcoeff/pred/recon dumps, /tmp/libaom-src's
decodeframe.c, not committed) prove the failing TU (chroma cpx=0/cpy=0,
DC_PRED, tx_type DctDct, skip=1 both sides) reconstructs bit-identically
pre-loop-filter in both decoders -- flat 128 either way, edge filter
inapplicable there (no real neighbours, corner-filter's 2n>=24 gate
doesn't fire at n=8). A PREDEBLOCK/POSTDEBLOCK trace (also not committed)
localizes the actual divergence to apply_deblock: our decoder introduces
a value our own pre-filter data does not justify at the row6-9/col6-9
TU-corner intersection, where both a horizontal and a vertical deblock
edge are filtered back to back. r4/r5's "intra edge filter gap" and
"tx_type path" suspects are both now falsified for this failure; the
next round's target is deblock_plane's edge-intersection order/read-back
(vertical-then-horizontal at a corner where an already-filtered vertical
sample feeds the horizontal filter's taps).

Suite: 174 passed, 1 failed (the known gate above) -- no regression from
r5's own checkpoint of the same numbers; the cdffwd flake did not fire
this run.
crates/ec-av1/src/decode.rsmodified+28 -0
@@ -100,6 +100,15 @@ pub(crate) fn directional_uv_hits() -> usize {
100100 /// proving a stream actually exercised a nonzero angle delta.
101101 static ANGLE_DELTA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
102102
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+
103112 /// Current value of [`ANGLE_DELTA_HITS`].
104113 pub(crate) fn angle_delta_hits() -> usize {
105114 ANGLE_DELTA_HITS.load(std::sync::atomic::Ordering::Relaxed)
@@ -1266,6 +1275,20 @@ impl PlaneBuf {
12661275 &mut prediction,
12671276 );
12681277 } 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);
12691292 predict(
12701293 mode as u8,
12711294 angle_delta,
@@ -1273,6 +1296,8 @@ impl PlaneBuf {
12731296 left.as_deref(),
12741297 corner,
12751298 side,
1299+ enable_edge_filter,
1300+ false,
12761301 &mut prediction,
12771302 );
12781303 }
@@ -2880,6 +2905,7 @@ pub fn decode_key_frame_tile(
28802905 frame_width,
28812906 frame_height,
28822907 enable_filter_intra,
2908+ false,
28832909 cdef,
28842910 loop_filter,
28852911 None,
@@ -2905,6 +2931,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
29052931 frame_width: u32,
29062932 frame_height: u32,
29072933 enable_filter_intra: bool,
2934+ enable_edge_filter: bool,
29082935 cdef: &CdefParams,
29092936 loop_filter: &LoopFilterParams,
29102937 initial_cdfs: Option<Cdfs>,
@@ -2914,6 +2941,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
29142941 if mi_cols == 0 || mi_rows == 0 {
29152942 return Err(unsupported("a frame with no mode-info grid"));
29162943 }
2944+ ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
29172945 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
29182946 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
29192947 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
crates/ec-av1/src/encode.rsmodified+8 -0
@@ -604,6 +604,8 @@ impl Plane<'_> {
604604 left.as_deref(),
605605 corner,
606606 side,
607+ false,
608+ false,
607609 &mut prediction,
608610 );
609611
@@ -821,6 +823,8 @@ impl Plane<'_> {
821823 left.as_deref(),
822824 corner,
823825 side,
826+ false,
827+ false,
824828 &mut prediction,
825829 );
826830 let sad: f64 = (0..side * side)
@@ -870,6 +874,8 @@ impl Plane<'_> {
870874 left.as_deref(),
871875 corner,
872876 side,
877+ false,
878+ false,
873879 &mut prediction,
874880 );
875881 let sad: f64 = (0..side * side)
@@ -4426,6 +4432,8 @@ mod tests {
44264432 Some(&left),
44274433 Some(128),
44284434 side,
4435+ false,
4436+ false,
44294437 &mut prediction,
44304438 );
44314439 }
crates/ec-av1/src/intra.rsmodified+238 -24
@@ -205,9 +205,17 @@ impl Edges {
205205 /// 7.11.2.1's `pAngle = Mode_To_Angle[mode] + angleDelta * ANGLE_STEP`);
206206 /// ignored (must be `0`) for the seven modes that carry no angle at all.
207207 ///
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+///
208215 /// # Panics
209216 /// Panics on a mode this module does not predict, or when `dst` is not
210217 /// `side * side` long.
218+#[allow(clippy::too_many_arguments)]
211219 pub fn predict(
212220 mode: u8,
213221 angle_delta: i32,
@@ -215,6 +223,8 @@ pub fn predict(
215223 left: Option<&[u8]>,
216224 corner: Option<u8>,
217225 side: usize,
226+ enable_edge_filter: bool,
227+ smooth_neighbor: bool,
218228 dst: &mut [u8],
219229 ) {
220230 assert_eq!(dst.len(), side * side, "the destination is the block");
@@ -231,7 +241,18 @@ pub fn predict(
231241 // way (`av1_is_directional_mode`'s callers never call the z1/z2/z3
232242 // walk there either).
233243 if angle != 90 && angle != 180 {
234- directional(angle as u16, &edges, side, dst);
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+ );
235256 return;
236257 }
237258 }
@@ -269,52 +290,245 @@ pub fn predict(
269290 }
270291 }
271292
272-/// Directional intra prediction (spec 7.11.2.4), with the intra edge filter off
273-/// -- which is what our sequence header says -- so nothing here upsamples.
274-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+) {
275430 let n = side as i32;
276- // The furthest sample the walk can reach, past which the edge is flat.
277- 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);
278484 let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| {
279485 round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5)
280486 };
281- let above = |i: i32| edges.above(i);
282- let left = |i: i32| edges.left(i);
487+
283488 for row in 0..n {
284489 for col in 0..n {
285490 let value = if angle < 90 {
286491 let dx = dr_intra_derivative(angle);
287- let idx = (row + 1) * dx;
288- let base = (idx >> 6) + col;
289- 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;
290497 if base < max_base {
291- blend(&above, base, shift)
498+ blend(&above_at, base, shift)
292499 } else {
293- above(max_base)
500+ above_at(max_base)
294501 }
295502 } else if angle > 180 {
296503 let dy = dr_intra_derivative(270 - angle);
297- let idx = (col + 1) * dy;
298- let base = (idx >> 6) + row;
299- 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;
300509 if base < max_base {
301- blend(&left, base, shift)
510+ blend(&left_at, base, shift)
302511 } else {
303- left(max_base)
512+ left_at(max_base)
304513 }
305514 } else {
306515 // The two zones meet here: a ray that leaves through the row
307516 // above is read there, and one that leaves through the column
308517 // to the left is read there instead.
309518 let dx = dr_intra_derivative(180 - angle);
310- let idx = (col << 6) - (row + 1) * dx;
311- let base = idx >> 6;
312- if base >= -1 {
313- 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)
314526 } else {
315527 let dy = dr_intra_derivative(angle - 90);
316- let idx = (row << 6) - (col + 1) * dy;
317- 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)
318532 }
319533 };
320534 dst[(row * n + col) as usize] = value.clamp(0, 255) as u8;
crates/ec-av1/src/stream.rsmodified+10 -6
@@ -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,
@@ -1254,12 +1258,12 @@ mod tests {
12541258 "--enable-tx-size-search=0",
12551259 "--enable-cdef=0",
12561260 "--enable-restoration=0",
1257- // The intra edge filter/upsample (spec 7.11.2.7-2.10) is
1258- // its own unimplemented corner-cut (`directional()`'s own
1259- // doc comment) -- off so a nonzero angle delta does not
1260- // also need it, same convention as every other
1261- // not-yet-supported tool disabled above.
1262- "--enable-intra-edge-filter=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",
12631267 "--max-partition-size=32",
12641268 // Same reason as the tx-select gate above: 8x8 and other
12651269 // sub-16x16 splits are a separate, already-named refusal.