forge
Explore
Log in

Don't you dare go Hollow

QP and geometry sweeps with motion, real library, SP refusal

Browse files at this commit

7c078b58c4bc5aa970c3ab262b67be6d9c0b5bb3Ahmet Kaan GümüşParent: 09040eb
  • test
    • QP and geometry sweeps with motion, real library, SP refusal
Show full message
test(h264): QP and geometry sweeps with motion, real library, SP refusal

- every_quantiser_with_motion_matches_ffmpeg: all 51 quantisers over a
  P/B GOP under both entropy coders. Boundary strengths 1 and 2 only
  exist between inter macroblocks, so their tC0 columns had no oracle
  before this and both were wrong; every row of both is now covered.
- geometry_with_motion_matches_ffmpeg: 1080p, odd sizes, four slices per
  picture, loop filter off, a single-macroblock picture and five
  reference frames with B-pyramid — all over GOPs, both coders.
- real_library_streams_match_ffmpeg: the H.264 files actually on this
  machine, 500 frames each, streamed against ffmpeg one frame at a time
  so a 1080p sweep costs two frames of memory. Three files bit-exact at
  500 frames; eight refused by name, every one of them for the 8x8
  transform, which is what stands between this decoder and most real
  H.264 content.
- switching_slices_are_refused_by_name: no encoder here emits SP slices,
  so the stream is hand built, because an unproven refusal string is
  indistinguishable from a hidden bug.
- The corrupt sweep now includes a B-slice, multi-reference stream and
  exercises the whole-sequence path, where a mangled slice meets the
  decoded picture buffer.
crates/ec-h264/tests/conformance.rsmodified+425 -5
@@ -514,11 +514,15 @@ fn corrupt_streams_never_panic() {
514 eprintln!("SKIP: fixtures missing");514 eprintln!("SKIP: fixtures missing");
515 return;515 return;
516 }516 }
517- // One stream per entropy coder: CABAC's arithmetic decoder indexes context517+ // One stream per entropy coder, plus one with B slices and multiple
518- // and coefficient arrays from stream-derived values, so it needs the same518+ // references: CABAC's arithmetic decoder indexes context and coefficient
519- // no-panic floor as the CAVLC tables.519+ // arrays from stream-derived values, and inter prediction indexes the
520- for name in ["BA1_Sony_D", "CABA1_SVA_B"] {520+ // decoded picture buffer, the reference lists and the motion arrays from
521- let stream = find_stream(&base.join(name)).expect("fixture");521+ // them too. All of it needs the same no-panic floor as the CAVLC tables.
522+ for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B", "BA_MW_D"] {
523+ let Some(stream) = find_stream(&base.join(name)) else {
524+ continue;
525+ };
522 corrupt_sweep(&std::fs::read(stream).unwrap());526 corrupt_sweep(&std::fs::read(stream).unwrap());
523 }527 }
524 }528 }
@@ -535,6 +539,9 @@ fn corrupt_sweep(bytes: &[u8]) {
535 {539 {
536 let mut dec = Decoder::new();540 let mut dec = Decoder::new();
537 let _ = dec.decode_first_idr(&bytes[..len]);541 let _ = dec.decode_first_idr(&bytes[..len]);
542+ // Truncation must also be survivable on the full-sequence path, where
543+ // a half-decoded picture meets the decoded picture buffer.
544+ let _ = decode_all(&bytes[..len]);
538 }545 }
539 // Single-byte corruptions: xor a walking pattern through the first 6KB546 // Single-byte corruptions: xor a walking pattern through the first 6KB
540 // (covers parameter sets and the first slices), plus scattered hits.547 // (covers parameter sets and the first slices), plus scattered hits.
@@ -556,6 +563,12 @@ fn corrupt_sweep(bytes: &[u8]) {
556 m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1);563 m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1);
557 let mut dec = Decoder::new();564 let mut dec = Decoder::new();
558 let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine565 let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine
566+ if i % 8 == 0 {
567+ // The whole-sequence path costs more, so it gets a thinner sweep;
568+ // it is the one that exercises reference lists and marking with
569+ // stream-derived indices.
570+ let _ = decode_all(&m);
571+ }
559 }572 }
560 }573 }
561 574
@@ -1422,3 +1435,410 @@ fn a_frame_num_gap_keeps_decoding() {
1422 );1435 );
1423 eprintln!("frame_num gap: {frames} frames decoded after dropping one picture");1436 eprintln!("frame_num gap: {frames} frames decoded after dropping one picture");
1424 }1437 }
1438+
1439+/// Every quantisation parameter again, this time over a GOP with motion.
1440+///
1441+/// The intra sweep above walks the alpha, beta and tC0 rows the bS 3 and 4
1442+/// edges use. Boundary strengths 1 and 2 exist only between inter macroblocks,
1443+/// so their tC0 columns (Table 8-17) had no oracle at all until now — and both
1444+/// were wrong when this landed. One P/B GOP per quantiser covers every row of
1445+/// both columns, and under CABAC it also walks the cabac_init_idc columns
1446+/// across all 52 SliceQPY values.
1447+#[test]
1448+fn every_quantiser_with_motion_matches_ffmpeg() {
1449+ if !have_ffmpeg() {
1450+ eprintln!("SKIP: ffmpeg not on PATH");
1451+ return;
1452+ }
1453+ let dir = scratch("qp-motion");
1454+ let mut failures = Vec::new();
1455+ for coder in ["ac", "0"] {
1456+ let mut checked = 0usize;
1457+ for qp in 1..=51u32 {
1458+ let qp_string = qp.to_string();
1459+ let extra = vec![
1460+ "-profile:v",
1461+ "main",
1462+ "-coder",
1463+ coder,
1464+ "-qp",
1465+ &qp_string,
1466+ "-x264-params",
1467+ "bframes=2:b-adapt=0:ref=2",
1468+ ];
1469+ let tag = format!("{coder}-q{qp}");
1470+ match x264_encode_gop(&dir, &tag, "176x144", 8, &extra) {
1471+ Some(stream) => match compare_sequence(&stream) {
1472+ Ok(_) => checked += 1,
1473+ Err(e) => failures.push(format!("{tag}: {e}")),
1474+ },
1475+ None => failures.push(format!("{tag}: ffmpeg cannot encode")),
1476+ }
1477+ }
1478+ assert!(checked >= 40, "too few {coder} quantisers exercised: {checked}");
1479+ eprintln!("{coder}: {checked} quantisers bit-exact over a GOP with motion");
1480+ }
1481+ let _ = std::fs::remove_dir_all(&dir);
1482+ assert!(failures.is_empty(), "{failures:#?}");
1483+}
1484+
1485+/// Geometry and slice structure, over a GOP rather than one picture: cropping,
1486+/// odd sizes, multiple slices per picture and the loop filter off, all with
1487+/// inter prediction and reordering active.
1488+#[test]
1489+fn geometry_with_motion_matches_ffmpeg() {
1490+ if !have_ffmpeg() {
1491+ eprintln!("SKIP: ffmpeg not on PATH");
1492+ return;
1493+ }
1494+ let dir = scratch("geometry-motion");
1495+ let cases: &[(&str, &str, &[&str])] = &[
1496+ ("hd", "1920x1080", &["bframes=2:b-adapt=0"]),
1497+ ("odd", "1916x1078", &["bframes=2:b-adapt=0"]),
1498+ // Neighbour availability stops at every slice boundary, and a motion
1499+ // vector predictor at one sees no partition across it.
1500+ ("slices", "352x288", &["bframes=2:b-adapt=0:slices=4"]),
1501+ ("nodeblock", "352x288", &["bframes=2:b-adapt=0:no-deblock=1"]),
1502+ // One macroblock wide: every spatial neighbour is unavailable, which
1503+ // is where the reference index of a missing partition matters most.
1504+ ("tiny", "16x16", &["bframes=2:b-adapt=0"]),
1505+ // Many references, so the list is long and reordering is real work.
1506+ ("manyref", "352x288", &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"]),
1507+ ];
1508+ let mut table = String::new();
1509+ let mut failures = Vec::new();
1510+ for coder in ["ac", "0"] {
1511+ for (tag, size, params) in cases {
1512+ let extra = vec![
1513+ "-profile:v",
1514+ "main",
1515+ "-coder",
1516+ coder,
1517+ "-qp",
1518+ "26",
1519+ "-x264-params",
1520+ params[0],
1521+ ];
1522+ let name = format!("{coder}-{tag}");
1523+ match x264_encode_gop(&dir, &name, size, 10, &extra) {
1524+ Some(stream) => match compare_sequence(&stream) {
1525+ Ok(n) => table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n")),
1526+ Err(e) => {
1527+ table.push_str(&format!("{name:<14} {size:<10} {e}\n"));
1528+ failures.push(format!("{name}: {e}"));
1529+ }
1530+ },
1531+ None => failures.push(format!("{name}: ffmpeg cannot encode")),
1532+ }
1533+ }
1534+ }
1535+ let _ = std::fs::remove_dir_all(&dir);
1536+ eprintln!("{table}");
1537+ assert!(failures.is_empty(), "{failures:#?}");
1538+}
1539+
1540+/// SP and SI slices are refused by name, proved against a stream that really
1541+/// carries one.
1542+///
1543+/// No encoder here emits switching slices, so the stream is hand built: an SPS
1544+/// and PPS this decoder accepts, then a slice header whose slice_type says SP.
1545+/// Without it the refusal would be an untested string, which is how a refusal
1546+/// becomes a hidden bug.
1547+#[test]
1548+fn switching_slices_are_refused_by_name() {
1549+ use ec_core::BitWriter;
1550+
1551+ let mut annexb: Vec<u8> = Vec::new();
1552+ let mut nal = |kind: u8, ref_idc: u8, payload: &[u8]| {
1553+ annexb.extend_from_slice(&[0, 0, 0, 1]);
1554+ annexb.push((ref_idc << 5) | kind);
1555+ annexb.extend_from_slice(payload);
1556+ };
1557+
1558+ let mut w = BitWriter::new();
1559+ w.write_bits(66, 8); // profile_idc baseline
1560+ w.write_bits(0, 8);
1561+ w.write_bits(30, 8); // level_idc
1562+ w.write_ue(0); // sps id
1563+ w.write_ue(0); // log2_max_frame_num_minus4
1564+ w.write_ue(2); // pic_order_cnt_type 2
1565+ w.write_ue(1); // max_num_ref_frames
1566+ w.write_bit(false); // gaps_in_frame_num_value_allowed
1567+ w.write_ue(10); // pic_width_in_mbs_minus1 -> 176
1568+ w.write_ue(8); // pic_height_in_map_units_minus1 -> 144
1569+ w.write_bit(true); // frame_mbs_only
1570+ w.write_bit(true); // direct_8x8_inference
1571+ w.write_bit(false); // no cropping
1572+ w.write_bit(false); // no vui
1573+ w.write_bit(true); // rbsp stop bit
1574+ w.align_to_byte();
1575+ nal(7, 3, w.as_bytes());
1576+
1577+ let mut w = BitWriter::new();
1578+ w.write_ue(0); // pps id
1579+ w.write_ue(0); // sps id
1580+ w.write_bit(false); // entropy_coding_mode
1581+ w.write_bit(false); // bottom_field_pic_order_in_frame_present
1582+ w.write_ue(0); // num_slice_groups_minus1
1583+ w.write_ue(0); // num_ref_idx_l0_default_active_minus1
1584+ w.write_ue(0); // num_ref_idx_l1_default_active_minus1
1585+ w.write_bit(false); // weighted_pred
1586+ w.write_bits(0, 2); // weighted_bipred_idc
1587+ w.write_se(0); // pic_init_qp_minus26
1588+ w.write_se(0); // pic_init_qs_minus26
1589+ w.write_se(0); // chroma_qp_index_offset
1590+ w.write_bit(false); // deblocking_filter_control_present
1591+ w.write_bit(false); // constrained_intra_pred
1592+ w.write_bit(false); // redundant_pic_cnt_present
1593+ w.write_bit(true); // rbsp stop bit
1594+ w.align_to_byte();
1595+ nal(8, 3, w.as_bytes());
1596+
1597+ // A slice whose slice_type is SP (3), which is what has to be refused.
1598+ let mut w = BitWriter::new();
1599+ w.write_ue(0); // first_mb_in_slice
1600+ w.write_ue(3); // slice_type: SP
1601+ w.write_ue(0); // pps id
1602+ w.write_bits(0, 4); // frame_num
1603+ w.write_bit(false); // num_ref_idx_active_override_flag
1604+ w.write_bit(false); // ref_pic_list_modification_flag_l0
1605+ w.write_bit(false); // adaptive_ref_pic_marking_mode_flag
1606+ w.write_bit(false); // sp_for_switch_flag
1607+ w.write_se(0); // slice_qs_delta
1608+ w.write_se(0); // slice_qp_delta
1609+ w.write_bit(true);
1610+ w.align_to_byte();
1611+ nal(1, 2, w.as_bytes());
1612+
1613+ let mut dec = Decoder::new();
1614+ let mut refusal = None;
1615+ for unit in ec_h264_syntax::AnnexBIter::new(&annexb) {
1616+ if let Err(e) = dec.push_nal(unit) {
1617+ refusal = Some(e);
1618+ break;
1619+ }
1620+ }
1621+ match refusal {
1622+ Some(Error::Unsupported { what, why }) => {
1623+ assert!(
1624+ what.contains("SP and SI"),
1625+ "refused as {what} ({why}), expected the switching-slice refusal"
1626+ );
1627+ }
1628+ other => panic!("expected an SP-slice refusal, got {other:?}"),
1629+ }
1630+}
1631+
1632+// ---------------------------------------------------------------------------
1633+// Real library: the files actually on this machine, not fixtures.
1634+// ---------------------------------------------------------------------------
1635+
1636+/// Compare a long stream against ffmpeg without holding it in memory: ffmpeg's
1637+/// raw output is consumed from a pipe one frame at a time, in step with our
1638+/// own decoding, so a 500-frame 1080p sweep costs two frames of memory rather
1639+/// than three gigabytes.
1640+fn compare_sequence_streamed(
1641+ stream: &Path,
1642+ frames_wanted: usize,
1643+) -> Result<StreamedResult, String> {
1644+ use std::io::Read;
1645+
1646+ let bytes = std::fs::read(stream).map_err(|e| e.to_string())?;
1647+ let mut child = Command::new("ffmpeg")
1648+ .args(["-v", "error", "-i"])
1649+ .arg(stream)
1650+ .args([
1651+ "-frames:v",
1652+ &frames_wanted.to_string(),
1653+ "-f",
1654+ "rawvideo",
1655+ "-pix_fmt",
1656+ "yuv420p",
1657+ "-",
1658+ ])
1659+ .stdout(std::process::Stdio::piped())
1660+ .stderr(std::process::Stdio::null())
1661+ .spawn()
1662+ .map_err(|e| e.to_string())?;
1663+ let mut out = child.stdout.take().expect("piped stdout");
1664+
1665+ let mut dec = Decoder::new();
1666+ let mut reference = Vec::new();
1667+ let mut result = StreamedResult::default();
1668+ let mut oracle_open = true;
1669+ let mut take = |frame: Vec<u8>, result: &mut StreamedResult, reference: &mut Vec<u8>| {
1670+ result.produced += 1;
1671+ if !oracle_open || result.compared >= frames_wanted {
1672+ return;
1673+ }
1674+ reference.resize(frame.len(), 0);
1675+ if out.read_exact(reference).is_err() {
1676+ oracle_open = false;
1677+ return;
1678+ }
1679+ if let Some(pos) = first_diff(&frame, reference) {
1680+ result.diffs.push((result.compared, pos));
1681+ }
1682+ result.compared += 1;
1683+ };
1684+
1685+ for nal in ec_h264_syntax::AnnexBIter::new(&bytes) {
1686+ match dec.push_nal(nal) {
1687+ Ok(NalOutcome::PictureBoundary) => {
1688+ dec.end_picture().map_err(|e| format!("{e}"))?;
1689+ dec.push_nal(nal).map_err(|e| format!("{e}"))?;
1690+ }
1691+ Ok(_) => {}
1692+ Err(e) => return Err(format!("{e}")),
1693+ }
1694+ while let Some(f) = dec.next_frame() {
1695+ take(frame_bytes(&f), &mut result, &mut reference);
1696+ }
1697+ }
1698+ dec.flush().map_err(|e| format!("{e}"))?;
1699+ while let Some(f) = dec.next_frame() {
1700+ take(frame_bytes(&f), &mut result, &mut reference);
1701+ }
1702+ let _ = child.kill();
1703+ let _ = child.wait();
1704+ Ok(result)
1705+}
1706+
1707+/// Outcome of a streamed comparison.
1708+#[derive(Default)]
1709+struct StreamedResult {
1710+ /// Frames this decoder produced.
1711+ produced: usize,
1712+ /// Frames the oracle also produced, and which were therefore compared.
1713+ compared: usize,
1714+ /// `(frame index, byte offset)` of each mismatch.
1715+ diffs: Vec<(usize, usize)>,
1716+}
1717+
1718+/// Extract the video elementary stream of a real file as Annex B.
1719+fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool {
1720+ run(
1721+ "ffmpeg",
1722+ &[
1723+ "-v",
1724+ "error",
1725+ "-y",
1726+ "-i",
1727+ &src.to_string_lossy(),
1728+ "-map",
1729+ "0:v:0",
1730+ "-c",
1731+ "copy",
1732+ "-bsf:v",
1733+ "h264_mp4toannexb",
1734+ "-frames:v",
1735+ &frames.to_string(),
1736+ "-f",
1737+ "h264",
1738+ &dst.to_string_lossy(),
1739+ ],
1740+ )
1741+}
1742+
1743+/// Decode real H.264 files from this machine's library, several hundred frames
1744+/// each, frame for frame against ffmpeg.
1745+///
1746+/// Synthetic clips and conformance vectors are both written by people trying to
1747+/// exercise a decoder. Real files are written by encoders tuned for size, at
1748+/// resolutions and GOP structures the fixtures never use, and they are the ones
1749+/// a user actually opens. Every file either decodes bit-exactly or is refused
1750+/// by name; a file that decodes to different pixels is a failure.
1751+#[test]
1752+fn real_library_streams_match_ffmpeg() {
1753+ if !have_ffmpeg() {
1754+ eprintln!("SKIP: ffmpeg not on PATH");
1755+ return;
1756+ }
1757+ let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
1758+ let Ok(text) = std::fs::read_to_string(&manifest) else {
1759+ eprintln!("SKIP: {} missing", manifest.display());
1760+ return;
1761+ };
1762+ let dir = scratch("real-library");
1763+ const FRAMES: usize = 500;
1764+ /// A file counts as swept only when the oracle stayed with us this long.
1765+ const MIN_FRAMES: usize = 100;
1766+ let mut table = String::new();
1767+ let mut decoded = 0usize;
1768+ let mut refused = 0usize;
1769+ let mut failures = Vec::new();
1770+ let mut seen_containers = std::collections::BTreeSet::new();
1771+
1772+ for line in text.lines().skip(1) {
1773+ let mut f = line.split('\t');
1774+ let (Some(path), Some(container), Some(vcodec)) = (f.next(), f.next(), f.next()) else {
1775+ continue;
1776+ };
1777+ if vcodec != "h264" || !Path::new(path).is_file() {
1778+ continue;
1779+ }
1780+ // One file per container family per resolution class keeps the sweep
1781+ // to a few minutes while still covering both demuxers.
1782+ let width = f.next().unwrap_or("0");
1783+ let key = (container.to_string(), width.to_string());
1784+ if !seen_containers.insert(key) {
1785+ continue;
1786+ }
1787+ let name: String = Path::new(path)
1788+ .file_name()
1789+ .map(|n| n.to_string_lossy().chars().take(38).collect())
1790+ .unwrap_or_default();
1791+ let annexb = dir.join("stream.264");
1792+ if !extract_annexb(Path::new(path), &annexb, FRAMES) {
1793+ table.push_str(&format!("{name:<40} {container:<12} not extractable\n"));
1794+ continue;
1795+ }
1796+ match compare_sequence_streamed(&annexb, FRAMES) {
1797+ Ok(r) if !r.diffs.is_empty() => {
1798+ failures.push(format!(
1799+ "{name}: {} of {} frames differ",
1800+ r.diffs.len(),
1801+ r.compared
1802+ ));
1803+ table.push_str(&format!(
1804+ "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {}\n",
1805+ r.diffs.len(),
1806+ r.compared
1807+ ));
1808+ }
1809+ // The oracle stopped before we did. That is ffmpeg giving up on the
1810+ // elementary stream the bitstream filter produced, not a claim about
1811+ // this decoder, so the file is reported and not counted either way.
1812+ Ok(r) if r.compared < r.produced.min(MIN_FRAMES) => {
1813+ table.push_str(&format!(
1814+ "{name:<40} {container:<12} {width:>5}px oracle short: ffmpeg gave \
1815+ {} frames, we decoded {}\n",
1816+ r.compared, r.produced
1817+ ));
1818+ }
1819+ Ok(r) => {
1820+ decoded += 1;
1821+ table.push_str(&format!(
1822+ "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact\n",
1823+ r.compared
1824+ ));
1825+ }
1826+ Err(e) if e.contains("unsupported") => {
1827+ refused += 1;
1828+ table.push_str(&format!("{name:<40} {container:<12} {width:>5}px refused: {e}\n"));
1829+ }
1830+ Err(e) => {
1831+ failures.push(format!("{name}: {e}"));
1832+ table.push_str(&format!("{name:<40} {container:<12} {width:>5}px ERROR {e}\n"));
1833+ }
1834+ }
1835+ }
1836+ let _ = std::fs::remove_dir_all(&dir);
1837+ eprintln!("{table}");
1838+ eprintln!("real library: {decoded} decoded bit-exact, {refused} refused by name");
1839+ assert!(failures.is_empty(), "{failures:#?}");
1840+ assert!(
1841+ decoded >= 3,
1842+ "only {decoded} real files swept end to end; the sweep is the point"
1843+ );
1844+}