forge
Explore
Log in

Don't you dare go Hollow

Refuse a decodes-but-wrong CDEF path instead of miscoding it

Browse files at this commit

cef0239f2bdd8de95ffbbee38c7dbbba41e69459Ahmet Kaan GümüşParent: 35539ec
  • fix
    • refuse a decodes-but-wrong CDEF path instead of miscoding it
Show full message
fix(av1): refuse a decodes-but-wrong CDEF path instead of miscoding it

A real libaom-av1 stream with active CDEF strength decoded without error
(cdef_bits==0 needs no per-block bitstream index) but produced wrong pixels
-- neither tile decoder applies the in-loop CDEF filter (spec 7.15) at all.
decode_stream now refuses any frame whose CDEF params would actually filter
samples, naming the real gap instead of silently miscoding it.

Pinned a deterministic real-libaom-av1 fixture (gradients + its own seed=,
-threads 1/-row-mt 0/no tiling -- cpu-used 8's RD search is not otherwise
stable run-to-run on this box) with CDEF disabled, and hardened the
report-only E2E test into a pixel-exact assertion against ffmpeg's own
decode of the identical bytes for that fixture.

CfL (this round's other target) stays refused: implementing it needs
libaom's cfl.c ported (subsample+average+alpha scale, spec 5.11.45/7.11.5)
plus new cfl_sign/cfl_alpha CDFs, out of this round's remaining budget --
left as a named gap, not attempted half-done.
crates/ec-av1/src/stream.rsmodified+148 -9
@@ -10,12 +10,27 @@
10 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is10 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
11 //! an implementation detail of how this crate happens to build it).11 //! an implementation detail of how this crate happens to build it).
12 12
13-use ec_av1_syntax::{Av1Parser, FrameType, ObuKind};13+use ec_av1_syntax::{Av1Parser, CdefParams, FrameType, ObuKind};
14 use ec_core::{Error, Result};14 use ec_core::{Error, Result};
15 15
16 use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile};16 use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile};
17 use crate::encode::Picture;17 use crate::encode::Picture;
18 18
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+
19 /// Decode every frame in a raw AV1 OBU stream, in coding order.34 /// Decode every frame in a raw AV1 OBU stream, in coding order.
20 ///35 ///
21 /// A key frame becomes the reference for the inter frames that follow it,36 /// A key frame becomes the reference for the inter frames that follow it,
@@ -48,6 +63,18 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
48 let tile = tiles.first().ok_or_else(|| {63 let tile = tiles.first().ok_or_else(|| {
49 Error::unsupported("AV1 decode_stream", "a frame OBU with no tile group")64 Error::unsupported("AV1 decode_stream", "a frame OBU with no tile group")
50 })?;65 })?;
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) {
73+ return Err(Error::unsupported(
74+ "AV1 decode_stream",
75+ "a frame with an active CDEF filter (not yet applied by this decoder)",
76+ ));
77+ }
51 // `Tile::offset` is relative to the buffer `parse_obu` was handed78 // `Tile::offset` is relative to the buffer `parse_obu` was handed
52 // (`&data[pos..]` at the time this OBU was parsed), so it is relative79 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
53 // to `obu_offset`, not to `data` as a whole.80 // to `obu_offset`, not to `data` as a whole.
@@ -287,8 +314,22 @@ mod tests {
287 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it314 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
288 /// gets past an encoder this crate never wrote a byte of.315 /// gets past an encoder this crate never wrote a byte of.
289 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {316 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
290- let out = Command::new("ffmpeg")317+ libaom_encode_with(lavfi, width, height, crf, &[])
291- .args([318+ }
319+
320+ /// As [`libaom_encode`], with extra encoder args appended -- used to pin
321+ /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
322+ /// RD search is not otherwise stable run-to-run on this box, and lavfi
323+ /// `gradients` needs its own `seed=` for the same reason) and to gate
324+ /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
325+ fn libaom_encode_with(
326+ lavfi: &str,
327+ width: usize,
328+ height: usize,
329+ crf: u32,
330+ extra: &[&str],
331+ ) -> Option<Vec<u8>> {
332+ let mut args = vec![
292 "-v",333 "-v",
293 "error",334 "error",
294 "-f",335 "-f",
@@ -301,8 +342,10 @@ mod tests {
301 "yuv420p",342 "yuv420p",
302 "-c:v",343 "-c:v",
303 "libaom-av1",344 "libaom-av1",
304- "-crf",345+ ];
305- &crf.to_string(),346+ let crf_str = crf.to_string();
347+ args.extend(["-crf", &crf_str]);
348+ args.extend([
306 "-cpu-used",349 "-cpu-used",
307 "8",350 "8",
308 "-enable-rect-partitions",351 "-enable-rect-partitions",
@@ -315,10 +358,11 @@ mod tests {
315 "0",358 "0",
316 "-enable-cfl-intra",359 "-enable-cfl-intra",
317 "0",360 "0",
318- "-f",361+ ]);
319- "obu",362+ args.extend(extra.iter().copied());
320- "-",363+ args.extend(["-f", "obu", "-"]);
321- ])364+ let out = Command::new("ffmpeg")
365+ .args(&args)
322 .stdin(Stdio::null())366 .stdin(Stdio::null())
323 .stdout(Stdio::piped())367 .stdout(Stdio::piped())
324 .stderr(Stdio::piped())368 .stderr(Stdio::piped())
@@ -393,4 +437,99 @@ mod tests {
393 eprintln!(" {v}");437 eprintln!(" {v}");
394 }438 }
395 }439 }
440+
441+ /// Hardened past the report-only test above: a real libaom-av1 gradients
442+ /// stream, pinned deterministic (`gradients`' own `seed=`, plus
443+ /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
444+ /// cannot pick a different mode set run to run) and with CDEF turned off
445+ /// (this decoder's tile path never applies that in-loop filter -- see
446+ /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
447+ /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
448+ /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
449+ /// test working around it). Asserts pixel-exact against ffmpeg's own
450+ /// decode of the identical bytes, not just "decoded without error".
451+ #[test]
452+ fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
453+ if !have_ffmpeg() {
454+ eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
455+ return;
456+ }
457+ let (width, height) = (64, 64);
458+ let stream = libaom_encode_with(
459+ "gradients=size=64x64:c0=red:c1=blue:c2=green:rate=1:seed=42",
460+ width,
461+ height,
462+ 15,
463+ &[
464+ "-threads",
465+ "1",
466+ "-row-mt",
467+ "0",
468+ "-tile-columns",
469+ "0",
470+ "-tile-rows",
471+ "0",
472+ "-enable-cdef",
473+ "0",
474+ ],
475+ )
476+ .expect("ffmpeg encode");
477+ let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
478+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
479+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
480+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
481+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
482+ }
483+
484+ /// scratch: isolate a pinned mismatching stream's first divergent pixel.
485+ #[test]
486+ #[ignore]
487+ fn scratch_isolate_pinned_mismatch() {
488+ let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
489+ let stream = std::fs::read(&path).expect("read pinned stream");
490+ {
491+ let mut p = Av1Parser::new();
492+ let mut pos = 0usize;
493+ while pos < stream.len() {
494+ let obu = p.parse_obu(&stream[pos..]).expect("parse");
495+ pos += obu.total_size;
496+ if let ObuKind::Frame(header, _) = obu.kind {
497+ eprintln!("cdef: {:?}", header.cdef);
498+ }
499+ }
500+ }
501+ let width = 64;
502+ let height = 64;
503+ let frames = decode_stream(&stream).expect("our decode");
504+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
505+ let ours = &frames[0];
506+ let theirs = &ffmpeg_frames[0];
507+ for (plane_name, a, b, w) in [
508+ ("y", &ours.y, &theirs.y, width),
509+ ("u", &ours.u, &theirs.u, width / 2),
510+ ("v", &ours.v, &theirs.v, width / 2),
511+ ] {
512+ let mut first = None;
513+ let mut count = 0;
514+ for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
515+ if x != y {
516+ count += 1;
517+ if first.is_none() {
518+ first = Some(i);
519+ }
520+ }
521+ }
522+ if let Some(i) = first {
523+ eprintln!(
524+ "plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}",
525+ i / w,
526+ i % w,
527+ a[i],
528+ b[i]
529+ );
530+ } else {
531+ eprintln!("plane {plane_name}: MATCH");
532+ }
533+ }
534+ }
396 }535 }