forge
Explore
Log in

Don't you dare go Hollow

Finish CDEF in-loop filter (spec 7.15), close r1's borrow error

Browse files at this commit

8425e467359088a6784698fe7c26ab3376ff4544Ahmet Kaan GümüşParent: 588c3e4
  • feat
    • finish CDEF in-loop filter (spec 7.15), close r1's borrow error
Show full message
feat(av1): finish CDEF in-loop filter (spec 7.15), close r1's borrow error

r1 left decode.rs with a full CDEF port (direction search, primary/
secondary taps, damping, chroma) but an E0502 borrow (closures captured
`y.width`/`y.true_*` while `y` was mutably borrowed by the filter call) and
several test call sites at the old decode_key_frame_tile/decode_inter_frame_tile
arity. Fixed the borrow by copying the plane's stride/extent into locals
before the closures, and threaded &CdefParams::default() through every
in-crate test caller.

Verified two real correctness bugs against libaom's cdef_block.c/cdef.c
while porting:
- is_skip_txfm only read one of the four 4x4 mi cells an 8x8 CDEF unit
  covers; libaom's is_8x8_block_skip requires all four skip (a sub-8x8
  partition can straddle the unit with mixed skip flags).
- av1_cdef_filter_fb zeroes the shared `dir` per plane when *that plane's
  own* frame-level primary strength is 0 (`pri_strength ? dir : 0`),
  independent of the per-block adjusted strength and of the other plane;
  the port was passing the same nonzero dir to both.

New hard test (a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact)
encodes a real libaom-av1 stream with CDEF left on (no -enable-cdef 0) and
asserts pixel-exact against ffmpeg's own decode -- passed first run after
the two fixes above. Full cargo test -p ec-av1 --release: 166 passed, 0
failed, 12 ignored.
crates/ec-av1/src/decode.rsmodified+365 -3
@@ -21,6 +21,7 @@
2121 //! too). Anything outside that refuses with [`Error::unsupported`] rather than
2222 //! silently miscoding.
2323
24+use ec_av1_syntax::CdefParams;
2425 use ec_core::{Error, Result};
2526
2627 use crate::cdf;
@@ -393,6 +394,15 @@ struct Neighbours {
393394 left_inter: Vec<bool>,
394395 mi_cols: usize,
395396 mi_rows: usize,
397+ /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
398+ /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
399+ /// 7.15) never filters an 8x8 luma block whose covering coded block read
400+ /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
401+ /// grain [`Self::record_mi`] already writes at), read back at 8x8
402+ /// granularity by [`apply_cdef`] since `skip` is constant across every
403+ /// mi cell one coded block covers.
404+ skip_grid: Vec<bool>,
405+ skip_grid_cols_mi: usize,
396406 }
397407
398408 impl Neighbours {
@@ -414,9 +424,45 @@ impl Neighbours {
414424 left_inter: vec![false; rows],
415425 mi_cols,
416426 mi_rows,
427+ skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
428+ skip_grid_cols_mi: cols * (SUB / MI),
417429 }
418430 }
419431
432+ /// Marks every 4x4 mi cell a just-decoded coded block covers with its
433+ /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
434+ /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
435+ /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
436+ fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
437+ let (mi_r, mi_c) = at_mi;
438+ for rr in 0..side_mi {
439+ for cc in 0..side_mi {
440+ if let Some(cell) = self
441+ .skip_grid
442+ .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
443+ {
444+ *cell = skip;
445+ }
446+ }
447+ }
448+ }
449+
450+ /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
451+ /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
452+ /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
453+ /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
454+ /// straddle the region with a mix of skip/non-skip blocks).
455+ fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
456+ (0..2).all(|rr| {
457+ (0..2).all(|cc| {
458+ self.skip_grid
459+ .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
460+ .copied()
461+ .unwrap_or(false)
462+ })
463+ })
464+ }
465+
420466 fn start_row(&mut self) {
421467 self.left.iter_mut().for_each(|l| *l = Default::default());
422468 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
@@ -989,6 +1035,7 @@ fn decode_block(
9891035 )?;
9901036 }
9911037 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
1038+ neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
9921039 Ok(())
9931040 }
9941041
@@ -1125,9 +1172,300 @@ fn decode_leaf8(
11251172 )?;
11261173 }
11271174 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
1175+ neighbours.fill_skip_grid(leaf_mi, 2, skip);
11281176 Ok(mode)
11291177 }
11301178
1179+/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
1180+/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
1181+/// (mod 8) reuse the same table.
1182+const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
1183+ [(-1, 1), (-2, 2)],
1184+ [(0, 1), (-1, 2)],
1185+ [(0, 1), (0, 2)],
1186+ [(0, 1), (1, 2)],
1187+ [(1, 1), (2, 2)],
1188+ [(1, 0), (2, 1)],
1189+ [(1, 0), (2, 0)],
1190+ [(1, 0), (2, -1)],
1191+];
1192+/// A neighbour tap outside the frame's true extent -- `constrain` reads this
1193+/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
1194+const CDEF_VERY_LARGE: i32 = 0x4000;
1195+const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
1196+const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
1197+
1198+fn cdef_msb(x: i32) -> i32 {
1199+ 31 - x.leading_zeros() as i32
1200+}
1201+
1202+/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
1203+/// centre sample a filter tap is allowed to contribute.
1204+fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
1205+ if threshold == 0 {
1206+ return 0;
1207+ }
1208+ let shift = (damping - cdef_msb(threshold)).max(0);
1209+ diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
1210+}
1211+
1212+/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
1213+/// direction of an 8x8 luma window and the variance gap between it and its
1214+/// orthogonal, `sample(row, col)` reading that window's own pixels.
1215+fn cdef_find_dir(sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
1216+ const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
1217+ let mut partial = [[0i64; 15]; 8];
1218+ for i in 0..8i64 {
1219+ for j in 0..8i64 {
1220+ let x = i64::from(sample(i as usize, j as usize)) - 128;
1221+ partial[0][(i + j) as usize] += x;
1222+ partial[1][(i + j / 2) as usize] += x;
1223+ partial[2][i as usize] += x;
1224+ partial[3][(3 + i - j / 2) as usize] += x;
1225+ partial[4][(7 + i - j) as usize] += x;
1226+ partial[5][(3 - i / 2 + j) as usize] += x;
1227+ partial[6][j as usize] += x;
1228+ partial[7][(i / 2 + j) as usize] += x;
1229+ }
1230+ }
1231+ let mut cost = [0i64; 8];
1232+ for i in 0..8usize {
1233+ cost[2] += partial[2][i] * partial[2][i];
1234+ cost[6] += partial[6][i] * partial[6][i];
1235+ }
1236+ cost[2] *= DIV_TABLE[8];
1237+ cost[6] *= DIV_TABLE[8];
1238+ for i in 0..7usize {
1239+ cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
1240+ * DIV_TABLE[i + 1];
1241+ cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
1242+ * DIV_TABLE[i + 1];
1243+ }
1244+ cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
1245+ cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
1246+ for i in (1..8).step_by(2) {
1247+ for j in 0..5usize {
1248+ cost[i] += partial[i][3 + j] * partial[i][3 + j];
1249+ }
1250+ cost[i] *= DIV_TABLE[8];
1251+ for j in 0..3usize {
1252+ cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
1253+ * DIV_TABLE[2 * j + 2];
1254+ }
1255+ }
1256+ let mut best_cost = 0i64;
1257+ let mut best_dir = 0usize;
1258+ for (i, &c) in cost.iter().enumerate() {
1259+ if c > best_cost {
1260+ best_cost = c;
1261+ best_dir = i;
1262+ }
1263+ }
1264+ let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
1265+ (best_dir, var as i32)
1266+}
1267+
1268+/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
1269+/// (high variance gap) gets more deringing than a flat or non-directional
1270+/// one, only ever applied to the luma primary strength.
1271+fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
1272+ if var == 0 {
1273+ return 0;
1274+ }
1275+ let i = if var >> 6 != 0 {
1276+ cdef_msb(var >> 6).min(12)
1277+ } else {
1278+ 0
1279+ };
1280+ (strength * (4 + i) + 8) >> 4
1281+}
1282+
1283+/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
1284+/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
1285+/// previously-filtered neighbour must never feed this block's own sum).
1286+#[allow(clippy::too_many_arguments)]
1287+fn cdef_filter_block(
1288+ sample: impl Fn(i32, i32) -> i32,
1289+ dst: &mut PlaneBuf,
1290+ ox: usize,
1291+ oy: usize,
1292+ bw: usize,
1293+ bh: usize,
1294+ pri_strength: i32,
1295+ sec_strength: i32,
1296+ dir: usize,
1297+ pri_damping: i32,
1298+ sec_damping: i32,
1299+ enable_primary: bool,
1300+ enable_secondary: bool,
1301+) {
1302+ let clipping_required = enable_primary && enable_secondary;
1303+ let pri_taps = CDEF_PRI_TAPS[(pri_strength & 1) as usize];
1304+ for i in 0..bh {
1305+ for j in 0..bw {
1306+ let x = sample(i as i32, j as i32);
1307+ let mut sum = 0i32;
1308+ let mut max = x;
1309+ let mut min = x;
1310+ for k in 0..2usize {
1311+ if enable_primary {
1312+ let (tr, tc) = CDEF_DIRECTIONS[dir][k];
1313+ let p0 = sample(i as i32 + tr, j as i32 + tc);
1314+ let p1 = sample(i as i32 - tr, j as i32 - tc);
1315+ sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
1316+ sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
1317+ if clipping_required {
1318+ if p0 != CDEF_VERY_LARGE {
1319+ max = max.max(p0);
1320+ }
1321+ if p1 != CDEF_VERY_LARGE {
1322+ max = max.max(p1);
1323+ }
1324+ min = min.min(p0).min(p1);
1325+ }
1326+ }
1327+ if enable_secondary {
1328+ let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
1329+ let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
1330+ let s0 = sample(i as i32 + tr0, j as i32 + tc0);
1331+ let s1 = sample(i as i32 - tr0, j as i32 - tc0);
1332+ let s2 = sample(i as i32 + tr1, j as i32 + tc1);
1333+ let s3 = sample(i as i32 - tr1, j as i32 - tc1);
1334+ if clipping_required {
1335+ for s in [s0, s1, s2, s3] {
1336+ if s != CDEF_VERY_LARGE {
1337+ max = max.max(s);
1338+ }
1339+ }
1340+ min = min.min(s0).min(s1).min(s2).min(s3);
1341+ }
1342+ sum += CDEF_SEC_TAPS[k]
1343+ * (cdef_constrain(s0 - x, sec_strength, sec_damping)
1344+ + cdef_constrain(s1 - x, sec_strength, sec_damping)
1345+ + cdef_constrain(s2 - x, sec_strength, sec_damping)
1346+ + cdef_constrain(s3 - x, sec_strength, sec_damping));
1347+ }
1348+ }
1349+ let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
1350+ if clipping_required {
1351+ y = y.clamp(min, max);
1352+ }
1353+ dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, 255) as u8;
1354+ }
1355+ }
1356+}
1357+
1358+/// Applies CDEF (spec 7.15) to the whole reconstructed frame, over its true
1359+/// (unpadded) `mi_cols`/`mi_rows` extent, before it is cropped to its display
1360+/// size. `cdef_bits == 0` is this crate's only supported case so far (see the
1361+/// refusal in `stream.rs`), so every 64x64 filter block always uses index 0's
1362+/// strengths -- no per-block `cdef_idx` selection is implemented yet.
1363+fn apply_cdef(
1364+ y: &mut PlaneBuf,
1365+ u: &mut PlaneBuf,
1366+ v: &mut PlaneBuf,
1367+ cdef: &CdefParams,
1368+ skip_grid: &Neighbours,
1369+) {
1370+ if cdef.y_pri_strength[0] == 0
1371+ && cdef.y_sec_strength[0] == 0
1372+ && cdef.uv_pri_strength[0] == 0
1373+ && cdef.uv_sec_strength[0] == 0
1374+ {
1375+ return;
1376+ }
1377+ let src_y = y.data.clone();
1378+ let src_u = u.data.clone();
1379+ let src_v = v.data.clone();
1380+ let damping = i32::from(cdef.damping);
1381+ let damping_uv = (damping - 1).max(0);
1382+ let mut mi_r = 0usize;
1383+ while mi_r < skip_grid.mi_rows {
1384+ let mut mi_c = 0usize;
1385+ while mi_c < skip_grid.mi_cols {
1386+ if !skip_grid.is_skip_txfm(mi_r, mi_c) {
1387+ let (ox, oy) = (mi_c * 4, mi_r * 4);
1388+ let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
1389+ let sample_y = |r: i32, c: i32| -> i32 {
1390+ let (ny, nx) = (oy as i32 + r, ox as i32 + c);
1391+ if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
1392+ CDEF_VERY_LARGE
1393+ } else {
1394+ i32::from(src_y[ny as usize * y_stride + nx as usize])
1395+ }
1396+ };
1397+ let (dir, var) = cdef_find_dir(|r, c| {
1398+ let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
1399+ i32::from(src_y[ny * y_stride + nx])
1400+ });
1401+
1402+ // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
1403+ // -- each plane zeroes the shared direction when *its own*
1404+ // frame-level primary strength is 0, independent of the
1405+ // per-block adjusted `t` and of the other plane's strength.
1406+ let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 };
1407+ let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var);
1408+ let enable_primary = t != 0;
1409+ let enable_secondary = cdef.y_sec_strength[0] != 0;
1410+ if enable_primary || enable_secondary {
1411+ cdef_filter_block(
1412+ sample_y,
1413+ y,
1414+ ox,
1415+ oy,
1416+ 8,
1417+ 8,
1418+ t,
1419+ i32::from(cdef.y_sec_strength[0]),
1420+ y_dir,
1421+ damping,
1422+ damping,
1423+ enable_primary,
1424+ enable_secondary,
1425+ );
1426+ }
1427+
1428+ let t_uv = i32::from(cdef.uv_pri_strength[0]);
1429+ let uv_dir = if t_uv != 0 { dir } else { 0 };
1430+ let enable_primary_uv = t_uv != 0;
1431+ let enable_secondary_uv = cdef.uv_sec_strength[0] != 0;
1432+ if enable_primary_uv || enable_secondary_uv {
1433+ let (cox, coy) = (ox / 2, oy / 2);
1434+ for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
1435+ let (tw, th) = (plane.true_width, plane.true_height);
1436+ let stride = plane.width;
1437+ let sample_uv = |r: i32, c: i32| -> i32 {
1438+ let (ny, nx) = (coy as i32 + r, cox as i32 + c);
1439+ if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
1440+ CDEF_VERY_LARGE
1441+ } else {
1442+ i32::from(src_p[ny as usize * stride + nx as usize])
1443+ }
1444+ };
1445+ cdef_filter_block(
1446+ sample_uv,
1447+ plane,
1448+ cox,
1449+ coy,
1450+ 4,
1451+ 4,
1452+ t_uv,
1453+ i32::from(cdef.uv_sec_strength[0]),
1454+ uv_dir,
1455+ damping_uv,
1456+ damping_uv,
1457+ enable_primary_uv,
1458+ enable_secondary_uv,
1459+ );
1460+ }
1461+ }
1462+ }
1463+ mi_c += 2;
1464+ }
1465+ mi_r += 2;
1466+ }
1467+}
1468+
11311469 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
11321470 /// returning the picture it reconstructs to.
11331471 ///
@@ -1154,6 +1492,7 @@ pub fn decode_key_frame_tile(
11541492 frame_width: u32,
11551493 frame_height: u32,
11561494 enable_filter_intra: bool,
1495+ cdef: &CdefParams,
11571496 ) -> Result<Picture> {
11581497 if mi_cols == 0 || mi_rows == 0 {
11591498 return Err(unsupported("a frame with no mode-info grid"));
@@ -1488,6 +1827,8 @@ pub fn decode_key_frame_tile(
14881827 }
14891828 }
14901829
1830+ apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
1831+
14911832 let (fw, fh) = (frame_width as usize, frame_height as usize);
14921833 if fw == width && fh == height {
14931834 return Ok(Picture {
@@ -2008,6 +2349,7 @@ fn decode_inter_block(
20082349 }
20092350 neighbours.record(at, side, mode_for_tx, &[luma_grid, u_grid, v_grid]);
20102351 neighbours.record_inter(at, side, skip, is_inter);
2352+ neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
20112353 Ok(())
20122354 }
20132355
@@ -2032,6 +2374,7 @@ pub fn decode_inter_frame_tile(
20322374 frame_width: u32,
20332375 frame_height: u32,
20342376 reference: &Picture,
2377+ cdef: &CdefParams,
20352378 ) -> Result<Picture> {
20362379 if mi_cols == 0 || mi_rows == 0 {
20372380 return Err(unsupported("a frame with no mode-info grid"));
@@ -2237,6 +2580,8 @@ pub fn decode_inter_frame_tile(
22372580 }
22382581 }
22392582
2583+ apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
2584+
22402585 let (fw, fh) = (frame_width as usize, frame_height as usize);
22412586 if fw == width && fh == height {
22422587 return Ok(Picture {
@@ -2279,7 +2624,10 @@ mod tests {
22792624
22802625 #[test]
22812626 fn a_frame_with_no_mode_info_grid_is_refused() {
2282- assert!(decode_key_frame_tile(&[0u8; 4], 0, 32, 32, 0, 128, false).is_err());
2627+ assert!(
2628+ decode_key_frame_tile(&[0u8; 4], 0, 32, 32, 0, 128, false, &CdefParams::default())
2629+ .is_err()
2630+ );
22832631 }
22842632
22852633 /// Encodes and decodes one picture with `modes`, asserting the decoder's
@@ -2308,7 +2656,14 @@ mod tests {
23082656 ..
23092657 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
23102658 let decoded = decode_key_frame_tile(
2311- &tile, mi_cols, mi_rows, base_q_idx, w as u32, h as u32, false,
2659+ &tile,
2660+ mi_cols,
2661+ mi_rows,
2662+ base_q_idx,
2663+ w as u32,
2664+ h as u32,
2665+ false,
2666+ &CdefParams::default(),
23122667 )
23132668 .unwrap();
23142669 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
@@ -2380,7 +2735,9 @@ mod tests {
23802735 );
23812736 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
23822737 let data = enc.finish();
2383- let decoded = decode_key_frame_tile(&data, 16, 16, 40, 64, 64, false).unwrap();
2738+ let decoded =
2739+ decode_key_frame_tile(&data, 16, 16, 40, 64, 64, false, &CdefParams::default())
2740+ .unwrap();
23842741 assert!(
23852742 decoded.y.iter().all(|&s| s == 128),
23862743 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
@@ -2560,6 +2917,7 @@ mod tests {
25602917 coded_w,
25612918 coded_h,
25622919 false,
2920+ &CdefParams::default(),
25632921 )
25642922 .unwrap();
25652923 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
@@ -2628,6 +2986,7 @@ mod tests {
26282986 width as u32,
26292987 height as u32,
26302988 false,
2989+ &CdefParams::default(),
26312990 )
26322991 .unwrap();
26332992 assert_eq!(
@@ -2652,6 +3011,7 @@ mod tests {
26523011 width as u32,
26533012 height as u32,
26543013 &reference,
3014+ &CdefParams::default(),
26553015 )
26563016 .unwrap();
26573017 assert_eq!(
@@ -2895,6 +3255,7 @@ mod tests {
28953255 coded_w,
28963256 coded_h,
28973257 false,
3258+ &CdefParams::default(),
28983259 )
28993260 .unwrap();
29003261 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
@@ -2908,6 +3269,7 @@ mod tests {
29083269 coded_w,
29093270 coded_h,
29103271 &reference,
3272+ &CdefParams::default(),
29113273 )
29123274 .unwrap();
29133275 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
crates/ec-av1/src/stream.rsmodified+63 -24
@@ -10,27 +10,12 @@
1010 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
1111 //! an implementation detail of how this crate happens to build it).
1212
13-use ec_av1_syntax::{Av1Parser, CdefParams, FrameType, ObuKind, TxMode};
13+use ec_av1_syntax::{Av1Parser, FrameType, ObuKind, TxMode};
1414 use ec_core::{Error, Result};
1515
1616 use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile};
1717 use crate::encode::Picture;
1818
19-/// Whether a frame's CDEF parameters would actually filter any samples —
20-/// `1 << bits` strength pairs are declared, but only the used ones (any
21-/// non-zero primary/secondary strength) matter; `read_cdef_params` already
22-/// zeroes every field when CDEF is off for the frame (lossless, intrabc, or
23-/// the sequence header disabling it), so a plain field check is enough.
24-fn cdef_is_active(cdef: &CdefParams) -> bool {
25- let n = 1usize << cdef.bits;
26- (0..n).any(|i| {
27- cdef.y_pri_strength[i] != 0
28- || cdef.y_sec_strength[i] != 0
29- || cdef.uv_pri_strength[i] != 0
30- || cdef.uv_sec_strength[i] != 0
31- })
32-}
33-
3419 /// Decode every frame in a raw AV1 OBU stream, in coding order.
3520 ///
3621 /// A key frame becomes the reference for the inter frames that follow it,
@@ -63,16 +48,19 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
6348 let tile = tiles.first().ok_or_else(|| {
6449 Error::unsupported("AV1 decode_stream", "a frame OBU with no tile group")
6550 })?;
66- // Neither tile decoder applies the in-loop CDEF filter (spec 7.15):
67- // its `cdef_idx` syntax needs no bits when `cdef_bits == 0` (this
68- // crate's own writer's only case), so a real libaom stream with an
69- // active strength decodes with the bitstream in sync but the wrong
70- // pixels — decodes-but-wrong, worse than a refusal. Refuse before
71- // that happens rather than let it through silently.
72- if cdef_is_active(&header.cdef) {
51+ // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
52+ // block of each 64x64) only reads a literal `cdef_idx` when
53+ // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (this
54+ // crate's own writer's only case, and both `lane-av1cdef` gate
55+ // streams'), so the per-block symbol this crate's tile readers never
56+ // consume is a true no-op there. A `cdef_bits > 0` stream would
57+ // desync the moment it hit a real strength selector this decoder
58+ // never reads — refuse that by name rather than silently miscode,
59+ // the same pattern as the other round-2 refusals below.
60+ if header.cdef.bits != 0 {
7361 return Err(Error::unsupported(
7462 "AV1 decode_stream",
75- "a frame with an active CDEF filter (not yet applied by this decoder)",
63+ "a frame with cdef_bits > 0 (this decoder never reads the per-64x64 cdef_idx symbol)",
7664 ));
7765 }
7866 // Every `decode_block` call below assumes the block's transform is
@@ -139,6 +127,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
139127 header.frame_width,
140128 header.frame_height,
141129 enable_filter_intra,
130+ &header.cdef,
142131 )?
143132 } else {
144133 let reference = reference.as_ref().ok_or_else(|| {
@@ -155,6 +144,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
155144 header.frame_width,
156145 header.frame_height,
157146 reference,
147+ &header.cdef,
158148 )?
159149 };
160150 reference = Some(picture.clone());
@@ -221,6 +211,7 @@ mod tests {
221211 width as u32,
222212 height as u32,
223213 false,
214+ &ec_av1_syntax::CdefParams::default(),
224215 )
225216 .unwrap();
226217 let via_stream = decode_stream(&encoded.stream).unwrap();
@@ -578,6 +569,54 @@ mod tests {
578569 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
579570 }
580571
572+ /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
573+ /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
574+ /// proves `apply_cdef` itself, not just that this decoder still works
575+ /// when the filter never fires. Gradient content at a low crf reliably
576+ /// gives libaom something to dering. If a run happens to land on
577+ /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
578+ /// refusal in `decode_stream`) the stream is skipped rather than failed:
579+ /// that gap is named by the refusal's own error text, not silently
580+ /// swallowed here.
581+ #[test]
582+ fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
583+ if !have_ffmpeg() {
584+ eprintln!(
585+ "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
586+ );
587+ return;
588+ }
589+ let (width, height) = (64, 64);
590+ let stream = libaom_encode_with(
591+ "gradients=size=64x64:c0=red:c1=blue:c2=green:rate=1:seed=42",
592+ width,
593+ height,
594+ 30,
595+ &[
596+ "-threads",
597+ "1",
598+ "-row-mt",
599+ "0",
600+ "-tile-columns",
601+ "0",
602+ "-tile-rows",
603+ "0",
604+ ],
605+ )
606+ .expect("ffmpeg encode");
607+ match decode_stream(&stream) {
608+ Ok(frames) => {
609+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
610+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
611+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
612+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
613+ }
614+ Err(e) => {
615+ eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
616+ }
617+ }
618+ }
619+
581620 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
582621 #[test]
583622 #[ignore]