FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Harden AV1 and MPEG-2 decoders against hostile input; add mutation-fuzz tests for the video codecs
Logan Jenningscb2ac66c3b68
diff --git a/Cargo.lock b/Cargo.lockindex b32d5d259..fb963bf1f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2357,6 +2357,7 @@ dependencies = [name = "filmcraft-vp8"version = "0.7.2"dependencies = [+ "filmcraft-testkit","thiserror 2.0.21",]@@ -2365,6 +2366,7 @@ name = "filmcraft-vp9"version = "0.7.2"dependencies = ["filmcraft-bitstream",+ "filmcraft-testkit","rayon","thiserror 2.0.21",]diff --git a/crates/apv/tests/fuzz_hostile.rs b/crates/apv/tests/fuzz_hostile.rsnew file mode 100644index 000000000..b04a8f1c1--- /dev/null+++ b/crates/apv/tests/fuzz_hostile.rs@@ -0,0 +1,103 @@+//! Hostile-input robustness: every header byte set to extreme values, every bit flipped,+//! truncation at (nearly) every length must never panic or run away (errors are fine).++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::time::{Duration, Instant};++use filmcraft_apv::*;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++fn seeds() -> Vec<Vec<u8>> {+ let mut v = Vec::new();+ for (p, w, h) in [(Profile::P422_10, 64u32, 48u32), (Profile::P444_10, 48, 32), (Profile::P4444_10, 32, 32), (Profile::P400_10, 32, 32)] {+ let chroma = p.default_chroma();+ let depth = p.default_bit_depth();+ let mut f = Frame::new(w, h, chroma, depth, chroma == ChromaFormat::Yuv4444);+ for (i, s) in f.y.iter_mut().enumerate() {+ *s = (64 + (i * 37) % 800) as u16;+ }+ let mut cfg = EncoderConfig::new(p, w, h);+ cfg.qp = Some(16);+ let Ok(mut enc) = Encoder::with_config(cfg) else { continue };+ if let Ok(d) = enc.encode(&f) {+ v.push(d);+ }+ if let Ok(d) = enc.encode_raw_au(&f) {+ v.push(d);+ }+ }+ v+}++fn run(d: &[u8], label: &str) {+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for depth in [None, Some(8), Some(16)] {+ let _ = decode_frame_with(d, &DecodeOptions { bit_depth: depth, threads: depth.is_none() });+ }+ let _ = probe(d);+ let _ = split_raw_bitstream(d);+ }));+ assert!(res.is_ok(), "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(10), "too slow ({:?}): {label}", t.elapsed());+}++#[test]+fn hostile_frames_never_panic() {+ let seeds = seeds();+ assert!(!seeds.is_empty());+ for (si, seed) in seeds.iter().enumerate() {+ let stride = (seed.len() / 400).max(1);+ for n in (0..seed.len()).step_by(stride) {+ run(&seed[..n], &format!("seed {si} truncate {n}"));+ }+ for p in 0..seed.len().min(256) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[p] = v;+ run(&d, &format!("seed {si} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[p] ^= 1 << b;+ run(&d, &format!("seed {si} flip {p}.{b}"));+ }+ }+ // Whole big-endian 32-bit words of the header set to 0 / huge values (sizes, counts, dimensions).+ for p in 0..seed.len().min(128) {+ for v in [0u32, 0xffff_ffff, 0x0001_0000, 0x7fff_ffff] {+ let mut d = seed.clone();+ if let Some(s) = d.get_mut(p..p + 4) {+ s.copy_from_slice(&v.to_be_bytes());+ }+ run(&d, &format!("seed {si} u32 {p}={v:#x}"));+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ si as u64);+ let iters = std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(1000);+ for i in 0..iters {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(8) {+ let p = rng.below(d.len());+ if rng.below(2) == 0 {+ d[p] ^= 1 << rng.below(8);+ } else {+ d[p] = rng.next() as u8;+ }+ }+ run(&d, &format!("seed {si} random {i}"));+ }+ }+}diff --git a/crates/av1/src/decoder.rs b/crates/av1/src/decoder.rsindex 66c966986..d10068fcc 100644--- a/crates/av1/src/decoder.rs+++ b/crates/av1/src/decoder.rs@@ -23,6 +23,9 @@ use crate::stats::{DecodeStats, Stage, Timer};use crate::tile::TileDecoder;use crate::{Error, Picture, Result};+/// Largest accepted frame side and area: AV1 level 6.3 stops at 16384 x 8704; the sequence header allows 65536 x 65536 (gigabytes of buffers).+const MAX_FRAME_DIM: u32 = 16384;+const MAX_FRAME_AREA: u64 = 1 << 27;const OBU_SEQUENCE_HEADER_T: u32 = 1;const OBU_TEMPORAL_DELIMITER_T: u32 = 2;const OBU_FRAME_HEADER_T: u32 = 3;@@ -505,7 +508,7 @@ impl Decoder {}// Encoders exist that code frames slightly larger than the sequence maximum (e.g. a// 270-line stream coded as 272 lines); like other decoders we accept them.- if fh.upscaled_width > 65536 || fh.frame_height > 65536 {+ if fh.upscaled_width > MAX_FRAME_DIM || fh.frame_height > MAX_FRAME_DIM || u64::from(fh.upscaled_width) * u64::from(fh.frame_height) > MAX_FRAME_AREA {return Err(Error::Invalid("frame size"));}if !fh.frame_is_intra {diff --git a/crates/av1/src/tile.rs b/crates/av1/src/tile.rsindex 9d5344652..6776f201f 100644--- a/crates/av1/src/tile.rs+++ b/crates/av1/src/tile.rs@@ -394,6 +394,10 @@ impl<'a, 'f> TileDecoder<'a, 'f> {fn decode_block(&mut self, r: usize, c: usize, sub_size: usize) -> Result<()> {let (ssx, ssy) = (self.fs.ssx, self.fs.ssy);let num_planes = self.fs.num_planes;+ // Conformance requirement (4:2:2 has no chroma size for 4x16 and similar blocks); indexing the size tables with BLOCK_INVALID would panic.+ if num_planes > 1 && self.fs.plane_residual_size(sub_size, 1) == BLOCK_INVALID {+ return Err(crate::Error::Invalid("block size has no chroma size at this subsampling"));+ }let mut b = Block { mi_row: r, mi_col: c, mi_size: sub_size, ..Default::default() };b.bw4 = NUM_4X4_BLOCKS_WIDE[sub_size] as usize;b.bh4 = NUM_4X4_BLOCKS_HIGH[sub_size] as usize;diff --git a/crates/av1/tests/fuzz_hostile.rs b/crates/av1/tests/fuzz_hostile.rsnew file mode 100644index 000000000..482bb844c--- /dev/null+++ b/crates/av1/tests/fuzz_hostile.rs@@ -0,0 +1,144 @@+//! Hostile-input robustness: truncation, header-region sweeps and random mutation of small+//! ffmpeg-generated AV1 streams (frame by frame) must never panic or run away. Skips without ffmpeg.++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::process::{Command, Stdio};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::{Duration, Instant};++use filmcraft_av1::Decoder;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++/// (name, encoder args, pix_fmt)+const SEEDS: &[(&str, &str, &str)] = &[("av1_fz_default", "-c:v libsvtav1 -g 4", "yuv420p"), ("av1_fz_10bit", "-c:v libsvtav1 -g 6", "yuv420p10le")];++fn ivf_frames(data: &[u8]) -> Vec<Vec<u8>> {+ let mut out = Vec::new();+ let Some(h) = data.get(6..8) else { return out };+ let mut pos = usize::from(u16::from_le_bytes([h[0], h[1]]));+ while let Some(hd) = data.get(pos..pos + 12) {+ let size = u32::from_le_bytes([hd[0], hd[1], hd[2], hd[3]]) as usize;+ pos += 12;+ let end = pos.saturating_add(size).min(data.len());+ out.push(data[pos..end].to_vec());+ pos = end;+ }+ out+}++fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str) -> Option<Vec<Vec<u8>>> {+ let out = filmcraft_testkit::fixtures_dir("av1").join(format!("{name}.ivf"));+ let p = filmcraft_testkit::fixtures::generate(&out, |tmp| {+ let a: Vec<&str> = args.split_whitespace().collect();+ matches!(+ Command::new(ff)+ .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "6", "-pix_fmt", pix])+ .args(a)+ .args(["-f", "ivf"])+ .arg(tmp)+ .stdin(Stdio::null())+ .status(),+ Ok(s) if s.success()+ )+ })?;+ Some(ivf_frames(&std::fs::read(p).ok()?))+}++static PANICS: AtomicUsize = AtomicUsize::new(0);++/// Decoder worker threads may catch panics and turn them into errors; count them so they still fail the test.+fn count_panics() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ std::panic::set_hook(Box::new(|info| {+ PANICS.fetch_add(1, Ordering::SeqCst);+ eprintln!("PANIC: {info}");+ }));+ });+}++fn run_all(frames: &[Vec<u8>], label: &str) {+ count_panics();+ let before = PANICS.load(Ordering::SeqCst);+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for threads in [1, 3] {+ let mut dec = Decoder::with_threads(threads);+ for (i, f) in frames.iter().enumerate() {+ let _ = dec.decode_pts(f, i as i64);+ }+ let _ = dec.flush_result();+ }+ }));+ assert!(res.is_ok() && PANICS.load(Ordering::SeqCst) == before, "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(20), "too slow ({:?}): {label}", t.elapsed());+}++/// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt).+fn iters() -> usize {+ std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(300)+}++#[test]+fn hostile_streams_never_panic() {+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("AV1 fuzz") else { return };+ for &(name, args, pix) in SEEDS {+ let Some(seed) = make(&ff, name, args, pix) else { continue };+ if seed.is_empty() {+ continue;+ }+ // truncate each of the first frames at every length+ for fi in 0..seed.len().min(3) {+ let len = seed[fi].len();+ for n in (0..len).step_by((len / 200).max(1)) {+ let mut d = seed.clone();+ d[fi].truncate(n);+ run_all(&d, &format!("{name} frame {fi} truncate {n}"));+ }+ }+ // header region of every frame: every byte to a few values, every bit+ for fi in 0..seed.len() {+ for p in 0..seed[fi].len().min(96) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[fi][p] = v;+ run_all(&d, &format!("{name} frame {fi} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[fi][p] ^= 1 << b;+ run_all(&d, &format!("{name} frame {fi} flip {p}.{b}"));+ }+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ name.len() as u64);+ for i in 0..iters() {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(6) {+ let fi = rng.below(d.len());+ if d[fi].is_empty() {+ continue;+ }+ let p = rng.below(d[fi].len());+ if rng.below(2) == 0 {+ d[fi][p] ^= 1 << rng.below(8);+ } else {+ d[fi][p] = rng.next() as u8;+ }+ }+ run_all(&d, &format!("{name} random {i}"));+ }+ }+}diff --git a/crates/av1/tests/hostile_dims.rs b/crates/av1/tests/hostile_dims.rsnew file mode 100644index 000000000..166b69d5e--- /dev/null+++ b/crates/av1/tests/hostile_dims.rs@@ -0,0 +1,151 @@+//! A few bytes must not make the decoder allocate gigabytes: oversized sequences are refused.+//! Hand-built (no ffmpeg): a reduced still-picture sequence header plus a lossless key frame whose+//! tiles are one zero byte each.++use filmcraft_av1::{Decoder, Error};++#[derive(Default)]+struct Bits {+ bytes: Vec<u8>,+ n: usize,+}++impl Bits {+ fn put(&mut self, value: u32, bits: usize) {+ for i in (0..bits).rev() {+ if self.n.is_multiple_of(8) {+ self.bytes.push(0);+ }+ if (value >> i) & 1 == 1+ && let Some(b) = self.bytes.last_mut()+ {+ *b |= 0x80 >> (self.n % 8);+ }+ self.n += 1;+ }+ }+}++fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {+ let mut v = vec![kind << 3 | 0b10];+ let mut n = payload.len();+ loop {+ let b = (n & 0x7f) as u8;+ n >>= 7;+ v.push(if n > 0 { b | 0x80 } else { b });+ if n == 0 {+ break;+ }+ }+ v.extend_from_slice(payload);+ v+}++fn tile_log2(blk: u32, target: u32) -> u32 {+ let mut k = 0;+ while (blk << k) < target {+ k += 1;+ }+ k+}++/// Temporal delimiter, reduced still-picture sequence header of `w` x `h` (64x64 superblocks) and a+/// lossless key frame whose uniformly spaced tiles are one zero byte each.+fn stream(w: u32, h: u32) -> Vec<u8> {+ let mut s = Bits::default();+ s.put(0, 3); // seq_profile+ s.put(1, 1); // still_picture+ s.put(1, 1); // reduced_still_picture_header+ s.put(0, 5); // seq_level_idx+ s.put(15, 4); // frame_width_bits_minus_1+ s.put(15, 4); // frame_height_bits_minus_1+ s.put(w - 1, 16);+ s.put(h - 1, 16);+ s.put(0, 3 + 3 + 7 + 1); // sb size, filter intra, edge; superres, cdef, restoration; color config; film grain+ s.put(1, 1); // trailing bit++ let (sb_cols, sb_rows) = (w.div_ceil(64), h.div_ceil(64));+ let cols_log2 = tile_log2(64, sb_cols); // MAX_TILE_WIDTH / 64 superblocks+ let min_log2_tiles = cols_log2.max(tile_log2(2304, sb_rows * sb_cols));+ let rows_log2 = min_log2_tiles.saturating_sub(cols_log2);+ let tiles = (sb_cols.div_ceil(sb_cols.div_ceil(1 << cols_log2))) * (sb_rows.div_ceil(sb_rows.div_ceil(1 << rows_log2)));+ let mut f = Bits::default();+ f.put(0b0001, 4); // disable_cdf_update, allow_screen_content_tools, render_and_frame_size_different, uniform_tile_spacing_flag+ f.put(0, 2); // no increment of the tile column / row counts+ if tiles > 1 {+ f.put(0, (cols_log2 + rows_log2) as usize + 2); // context_update_tile_id, tile_size_bytes_minus_1+ }+ f.put(0, 8 + 4 + 1 + 1); // base_q_idx 0 (lossless), delta flags, using_qmatrix, segmentation_enabled, reduced_tx_set+ let mut frame = f.bytes;+ frame.push(0); // tile_start_and_end_present_flag+ for _ in 1..tiles {+ frame.extend([0, 0]); // tile_size_minus_1 = 0, one data byte+ }+ frame.extend([0, 0]);++ let mut out = obu(2, &[]);+ out.extend(obu(1, &s.bytes));+ out.extend(obu(6, &frame));+ out+}++fn refused(w: u32, h: u32) {+ let mut dec = Decoder::new();+ let r = dec.decode(&stream(w, h)).and_then(|_| dec.flush_result());+ assert!(matches!(r, Err(Error::Invalid(m)) if m.contains("frame size")), "{w}x{h} must be refused as too large, got {:?}", r.as_ref().map(|p| p.len()));+}++#[test]+fn very_wide_frame_is_refused() {+ refused(65536, 16);+}++#[test]+fn very_tall_frame_is_refused() {+ refused(16, 65536);+}++#[test]+fn huge_frames_are_refused_without_allocating() {+ refused(65536, 65536);+ refused(65535, 65535);+ refused(30000, 30000);+}++/// A 64x48 4:2:0 key frame whose sequence profile bit was flipped to 2 (4:2:2): blocks such as 4x16 then have no+/// chroma size (BLOCK_INVALID) and used to index the size tables out of bounds.+const PROFILE_FLIPPED: &[u8] = &[+ 0x12, 0x00, 0x0a, 0x0b, 0x42, 0x00, 0x00, 0x05, 0x55, 0x7f, 0xbc, 0x6a, 0xf9, 0x00, 0x40, 0x32, 0x81, 0x05, 0x14, 0x00, 0xa5, 0xa0, 0x40, 0xd9, 0x52, 0xb9,+ 0xe7, 0x3c, 0xa6, 0xc1, 0xe4, 0xe9, 0xff, 0x6d, 0x12, 0xc3, 0xce, 0xac, 0x00, 0x92, 0x6f, 0x29, 0x6a, 0xee, 0x7e, 0x1a, 0x31, 0xfe, 0xe6, 0xb8, 0x2e, 0xe2,+ 0xcf, 0x3d, 0xce, 0x24, 0xe6, 0x30, 0x03, 0xcd, 0x89, 0x49, 0x1f, 0xa7, 0x8a, 0x75, 0xb3, 0x93, 0x27, 0x7b, 0x2f, 0x39, 0xc7, 0x60, 0xb7, 0xf8, 0x69, 0xbc,+ 0x53, 0x71, 0x30, 0x64, 0x20, 0x7e, 0xc1, 0x10, 0x17, 0xe4, 0xca, 0x34, 0xe9, 0xae, 0x47, 0x39, 0x68, 0x68, 0xef, 0x33, 0x9f, 0x26, 0xe2, 0x3f, 0xf1, 0xef,+ 0x02, 0xb7, 0xfd, 0xb1, 0x78, 0x4c, 0x35, 0x31, 0x17, 0x27, 0x11, 0x2f, 0xd7, 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is_an_error_not_a_panic() {+ let mut dec = Decoder::new();+ let r = dec.decode(PROFILE_FLIPPED).and_then(|_| dec.flush_result());+ assert!(matches!(r, Err(Error::Invalid(m)) if m.contains("chroma size")), "got {:?}", r.as_ref().map(|p| p.len()));+}diff --git a/crates/dnx/tests/fuzz_hostile.rs b/crates/dnx/tests/fuzz_hostile.rsnew file mode 100644index 000000000..2c3381ffa--- /dev/null+++ b/crates/dnx/tests/fuzz_hostile.rs@@ -0,0 +1,105 @@+//! Hostile-input robustness: every header byte set to extreme values, every bit flipped,+//! truncation at (nearly) every length and random mutation of encoder-made frames must never+//! panic or run away (errors are fine). No ffmpeg needed.++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::time::{Duration, Instant};++use filmcraft_dnx::{ChromaFormat, DecodeOptions, Encoder, EncoderConfig, Frame, Profile, decode_frame_with, probe};++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++fn seeds() -> Vec<Vec<u8>> {+ let mut v = Vec::new();+ for (profile, depth, w, h) in+ [(Profile::Lb, 8, 64u32, 48u32), (Profile::Hq, 8, 48, 32), (Profile::Hqx, 10, 64, 32), (Profile::Hqx, 12, 48, 32), (Profile::R444, 10, 48, 32)]+ {+ let mut cfg = EncoderConfig::new(profile, w, h);+ cfg.bit_depth = depth;+ let chroma = cfg.chroma();+ let mut f = Frame::new(w, h, chroma, depth, false);+ for (i, s) in f.y.iter_mut().enumerate() {+ *s = ((16 + (i * 37) % 200) as u16) << (depth - 8);+ }+ if chroma != ChromaFormat::Yuv444 {+ f.cb.fill(128 << (depth - 8));+ f.cr.fill(100 << (depth - 8));+ }+ if let Ok(mut enc) = Encoder::with_config(cfg)+ && let Ok(d) = enc.encode(&f)+ {+ v.push(d);+ }+ }+ v+}++fn run(d: &[u8], label: &str) {+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ let _ = probe(d);+ for opts in [DecodeOptions::default(), DecodeOptions { threads: true, spec_dequant: true }] {+ let _ = decode_frame_with(d, &opts);+ }+ }));+ assert!(res.is_ok(), "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(10), "too slow ({:?}): {label}", t.elapsed());+}++#[test]+fn hostile_frames_never_panic() {+ let seeds = seeds();+ assert!(!seeds.is_empty());+ for (si, seed) in seeds.iter().enumerate() {+ let stride = (seed.len() / 400).max(1);+ for n in (0..seed.len()).step_by(stride) {+ run(&seed[..n], &format!("seed {si} truncate {n}"));+ }+ // The header (and the start of the scan-line index): every byte to extreme values, every bit.+ for p in 0..seed.len().min(0x300) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[p] = v;+ run(&d, &format!("seed {si} byte {p:#x}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[p] ^= 1 << b;+ run(&d, &format!("seed {si} flip {p:#x}.{b}"));+ }+ }+ // Big dimension fields with the rest intact (lines 0x18, width 0x1A, macroblock rows 0x16C).+ for (off, v) in [(0x18usize, 0xffffu16), (0x1a, 0xffff), (0x18, 0x4000), (0x1a, 0x4000), (0x16c, 0xffff)] {+ let mut d = seed.clone();+ if let Some(s) = d.get_mut(off..off + 2) {+ s.copy_from_slice(&v.to_be_bytes());+ }+ run(&d, &format!("seed {si} u16 {off:#x}={v:#x}"));+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ si as u64);+ let iters = std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(1500);+ for i in 0..iters {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(8) {+ let p = rng.below(d.len());+ if rng.below(2) == 0 {+ d[p] ^= 1 << rng.below(8);+ } else {+ d[p] = rng.next() as u8;+ }+ }+ run(&d, &format!("seed {si} random {i}"));+ }+ }+}diff --git a/crates/h264/tests/fuzz_hostile.rs b/crates/h264/tests/fuzz_hostile.rsnew file mode 100644index 000000000..b85dcc458--- /dev/null+++ b/crates/h264/tests/fuzz_hostile.rs@@ -0,0 +1,125 @@+//! Hostile-input robustness: header-region sweeps (SPS/PPS/first slice headers), truncation and+//! random mutation of small libx264 streams must never panic or run away. Skips without ffmpeg.++mod common;++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++use filmcraft_h264::Decoder;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++/// (name, extra x264 args, pix_fmt)+const SEEDS: &[(&str, &str, &str)] = &[+ ("h264_fz_cabac_b", "-profile:v high -bf 2 -g 8 -x264-params cabac=1:weightp=2:8x8dct=1", "yuv420p"),+ ("h264_fz_cavlc", "-profile:v baseline -g 6 -x264-params cabac=0", "yuv420p"),+ ("h264_fz_interlaced", "-profile:v high -flags +ildct+ilme -bf 1 -g 6 -x264-params tff=1:interlaced=1", "yuv420p"),+ ("h264_fz_10bit_422", "-profile:v high422 -bf 1 -g 6", "yuv422p10le"),+ ("h264_fz_multislice", "-profile:v main -g 6 -x264-params slices=3:cabac=1", "yuv420p"),+];++fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str) -> Option<Vec<u8>> {+ let out = filmcraft_testkit::fixtures_dir("h264").join(format!("{name}.h264"));+ let p = filmcraft_testkit::fixtures::generate(&out, |tmp| {+ let a: Vec<&str> = args.split_whitespace().collect();+ matches!(+ Command::new(ff)+ .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "7", "-pix_fmt", pix, "-c:v", "libx264"])+ .args(a)+ .args(["-f", "h264"])+ .arg(tmp)+ .stdin(Stdio::null())+ .status(),+ Ok(s) if s.success()+ )+ })?;+ std::fs::read(p).ok()+}++static PANICS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);++/// Decoder worker threads catch panics and turn them into errors; count them so they still fail the test.+fn count_panics() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ std::panic::set_hook(Box::new(|info| {+ PANICS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ eprintln!("PANIC: {info}");+ }));+ });+}++fn run_all(d: &[u8], label: &str) {+ count_panics();+ let before = PANICS.load(std::sync::atomic::Ordering::SeqCst);+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for threads in [1, 3] {+ let mut dec = Decoder::with_threads(threads);+ for au in common::split_access_units(d) {+ let _ = dec.decode(au, 0);+ }+ let _ = dec.decode(d, 1);+ let _ = dec.flush();+ let _ = dec.take_error();+ }+ }));+ assert!(res.is_ok() && PANICS.load(std::sync::atomic::Ordering::SeqCst) == before, "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(20), "too slow ({:?}): {label}", t.elapsed());+}++#[test]+fn hostile_streams_never_panic() {+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("h264 fuzz") else { return };+ for &(name, args, pix) in SEEDS {+ let Some(seed) = make(&ff, name, args, pix) else { continue };+ let stride = (seed.len() / 300).max(1);+ for n in (0..seed.len()).step_by(stride) {+ run_all(&seed[..n], &format!("{name} truncate {n}"));+ }+ // SPS/PPS/first slice header region: every byte to a few values, every bit+ for p in 0..seed.len().min(120) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[p] = v;+ run_all(&d, &format!("{name} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[p] ^= 1 << b;+ run_all(&d, &format!("{name} flip {p}.{b}"));+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ name.len() as u64);+ for i in 0..iters() {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(6) {+ let p = rng.below(d.len());+ if rng.below(2) == 0 {+ d[p] ^= 1 << rng.below(8);+ } else {+ d[p] = rng.next() as u8;+ }+ }+ run_all(&d, &format!("{name} random {i}"));+ }+ }+}++/// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt).+fn iters() -> usize {+ std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(400)+}diff --git a/crates/hevc/tests/fuzz_hostile.rs b/crates/hevc/tests/fuzz_hostile.rsnew file mode 100644index 000000000..7eac8128b--- /dev/null+++ b/crates/hevc/tests/fuzz_hostile.rs@@ -0,0 +1,125 @@+//! Hostile-input robustness: header-region sweeps (SPS/PPS/first slice headers), truncation and+//! random mutation of small libx265 streams must never panic or run away. Skips without ffmpeg.++mod common;++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++use filmcraft_hevc::Decoder;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++/// (name, extra x264 args, pix_fmt)+const SEEDS: &[(&str, &str, &str)] = &[+ ("hevc_fz_main_b", "-x265-params log-level=error:bframes=2:keyint=8:min-keyint=8:sao=1:amp=1", "yuv420p"),+ ("hevc_fz_main10", "-x265-params log-level=error:bframes=1:keyint=6:min-keyint=6", "yuv420p10le"),+ ("hevc_fz_wpp_slices", "-x265-params log-level=error:keyint=6:min-keyint=6:wpp=1:slices=3", "yuv420p"),+ ("hevc_fz_tiles", "-x265-params log-level=error:keyint=6:min-keyint=6:tiles=2x2", "yuv420p"),+ ("hevc_fz_422_10", "-x265-params log-level=error:keyint=6:min-keyint=6", "yuv422p10le"),+];++fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str) -> Option<Vec<u8>> {+ let out = filmcraft_testkit::fixtures_dir("hevc").join(format!("{name}.hevc"));+ let p = filmcraft_testkit::fixtures::generate(&out, |tmp| {+ let a: Vec<&str> = args.split_whitespace().collect();+ matches!(+ Command::new(ff)+ .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "7", "-pix_fmt", pix, "-c:v", "libx265"])+ .args(a)+ .args(["-f", "hevc"])+ .arg(tmp)+ .stdin(Stdio::null())+ .status(),+ Ok(s) if s.success()+ )+ })?;+ std::fs::read(p).ok()+}++static PANICS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);++/// Decoder worker threads catch panics and turn them into errors; count them so they still fail the test.+fn count_panics() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ std::panic::set_hook(Box::new(|info| {+ PANICS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ eprintln!("PANIC: {info}");+ }));+ });+}++fn run_all(d: &[u8], label: &str) {+ count_panics();+ let before = PANICS.load(std::sync::atomic::Ordering::SeqCst);+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for threads in [1, 3] {+ let mut dec = Decoder::with_threads(threads);+ for au in common::split_access_units(d) {+ let _ = dec.decode(au, 0);+ }+ let _ = dec.decode(d, 1);+ let _ = dec.flush();+ let _ = dec.take_error();+ }+ }));+ assert!(res.is_ok() && PANICS.load(std::sync::atomic::Ordering::SeqCst) == before, "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(20), "too slow ({:?}): {label}", t.elapsed());+}++#[test]+fn hostile_streams_never_panic() {+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("hevc fuzz") else { return };+ for &(name, args, pix) in SEEDS {+ let Some(seed) = make(&ff, name, args, pix) else { continue };+ let stride = (seed.len() / 300).max(1);+ for n in (0..seed.len()).step_by(stride) {+ run_all(&seed[..n], &format!("{name} truncate {n}"));+ }+ // SPS/PPS/first slice header region: every byte to a few values, every bit+ for p in 0..seed.len().min(120) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[p] = v;+ run_all(&d, &format!("{name} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[p] ^= 1 << b;+ run_all(&d, &format!("{name} flip {p}.{b}"));+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ name.len() as u64);+ for i in 0..iters() {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(6) {+ let p = rng.below(d.len());+ if rng.below(2) == 0 {+ d[p] ^= 1 << rng.below(8);+ } else {+ d[p] = rng.next() as u8;+ }+ }+ run_all(&d, &format!("{name} random {i}"));+ }+ }+}++/// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt).+fn iters() -> usize {+ std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(400)+}diff --git a/crates/mpeg2v/src/lib.rs b/crates/mpeg2v/src/lib.rsindex 261742c25..6d8cb0497 100644--- a/crates/mpeg2v/src/lib.rs+++ b/crates/mpeg2v/src/lib.rs@@ -163,6 +163,9 @@ struct Seq {/// MPEG-1 pel_aspect_ratio (height/width of a sample) ×10000, Table 2-D.2.const MPEG1_PEL_ASPECT: [u32; 15] = [0, 10000, 6735, 7031, 7615, 8055, 8437, 8935, 9157, 9815, 10255, 10695, 10950, 11575, 12015];+/// Largest accepted luma area (8192 x 4096; 8K UHD is 7680 x 4320).+const MAX_PICTURE_AREA: u64 = 1 << 25;+impl Seq {fn new(hdr: SequenceHeader, ext: Option<SequenceExtension>, display: Option<DisplayExtension>) -> Result<Seq> {let (w, h) = match &ext {@@ -175,7 +178,9 @@ impl Seq {3 => ChromaFormat::Yuv444,_ => return Err(Error::Invalid("reserved chroma_format".into())),};- if w > 16383 || h > 16383 {+ // The 14-bit sizes allow 16383 x 16383 (gigabytes per frame, several frames and a gray reference+ // held); no real stream exceeds 8K, so cap the area there.+ if w > 16383 || h > 16383 || u64::from(w) * u64::from(h) > MAX_PICTURE_AREA {return Err(Error::Unsupported(format!("{w}x{h}")));}let progressive_sequence = ext.is_none_or(|e| e.progressive_sequence);diff --git a/crates/mpeg2v/tests/fuzz_hostile.rs b/crates/mpeg2v/tests/fuzz_hostile.rsnew file mode 100644index 000000000..93710a980--- /dev/null+++ b/crates/mpeg2v/tests/fuzz_hostile.rs@@ -0,0 +1,131 @@+//! Hostile-input robustness: truncation at every length, byte/bit mutation and header-field+//! sweeps over a small ffmpeg-generated stream must never panic or run away (errors are fine).+//! Skips when ffmpeg is missing.++mod common;++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::time::{Duration, Instant};++use filmcraft_mpeg2v::{Decoder, access_units, probe, scan_access_unit};++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++const SPECS: [common::Spec; 3] = [+ common::Spec {+ name: "m2v_fuzz_seed",+ lavfi: "testsrc2=size=64x48:rate=25",+ frames: 8,+ enc: &["-c:v", "mpeg2video", "-bf", "2", "-g", "6", "-b:v", "500k"],+ pix_fmt: "yuv420p",+ },+ common::Spec {+ name: "m2v_fuzz_seed_interlaced",+ lavfi: "testsrc2=size=96x64:rate=25,tinterlace=mode=interleave_top,setfield=tff",+ frames: 6,+ enc: &["-c:v", "mpeg2video", "-flags", "+ilme+ildct", "-bf", "1", "-g", "6", "-b:v", "800k"],+ pix_fmt: "yuv420p",+ },+ common::Spec {+ name: "m2v_fuzz_seed_422",+ lavfi: "testsrc2=size=64x48:rate=25",+ frames: 4,+ enc: &["-c:v", "mpeg2video", "-pix_fmt", "yuv422p", "-profile:v", "0", "-b:v", "1M"],+ pix_fmt: "yuv422p",+ },+];++static PANICS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);++/// Decoder worker threads catch panics and turn them into errors; count them so they still fail the test.+fn count_panics() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ std::panic::set_hook(Box::new(|info| {+ PANICS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ eprintln!("PANIC: {info}");+ }));+ });+}++fn run_all(d: &[u8], label: &str) {+ count_panics();+ let before = PANICS.load(std::sync::atomic::Ordering::SeqCst);+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ let _ = probe(d);+ let _ = scan_access_unit(d);+ for threads in [false, true] {+ let mut dec = Decoder::new();+ dec.set_threads(threads);+ for (i, r) in access_units(d).into_iter().enumerate() {+ let _ = dec.decode(&d[r], i as i64);+ }+ // also the whole buffer as one unit+ let _ = dec.decode(d, 99);+ let _ = dec.flush();+ }+ }));+ assert!(res.is_ok() && PANICS.load(std::sync::atomic::Ordering::SeqCst) == before, "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(20), "too slow ({:?}): {label}", t.elapsed());+}++#[test]+fn hostile_streams_never_panic() {+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("mpeg2v fuzz") else { return };+ for spec in &SPECS {+ let Some(path) = common::make(&ff, spec) else { continue };+ fuzz(&std::fs::read(path).unwrap());+ }+}++fn fuzz(seed: &[u8]) {+ // every truncation length (stride keeps it quick on larger seeds)+ let stride = (seed.len() / 600).max(1);+ for n in (0..seed.len()).step_by(stride) {+ run_all(&seed[..n], &format!("truncate {n}"));+ }+ // header region: every byte to 0 / 0xff / 0x80 / each single bit+ for p in 0..seed.len().min(96) {+ for v in [0u8, 0xff, 0x80, 0x01] {+ let mut d = seed.to_vec();+ d[p] = v;+ run_all(&d, &format!("byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.to_vec();+ d[p] ^= 1 << b;+ run_all(&d, &format!("flip {p}.{b}"));+ }+ }+ // random multi-mutations+ let mut rng = Rng(0x9e3779b97f4a7c15);+ for i in 0..iters() {+ let mut d = seed.to_vec();+ for _ in 0..1 + rng.below(6) {+ let p = rng.below(d.len());+ if rng.below(2) == 0 {+ d[p] ^= 1 << rng.below(8);+ } else {+ d[p] = rng.next() as u8;+ }+ }+ run_all(&d, &format!("random {i}"));+ }+}++/// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt).+fn iters() -> usize {+ std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(2500)+}diff --git a/crates/mpeg2v/tests/hostile_dims.rs b/crates/mpeg2v/tests/hostile_dims.rsnew file mode 100644index 000000000..01dcf25f8--- /dev/null+++ b/crates/mpeg2v/tests/hostile_dims.rs@@ -0,0 +1,73 @@+//! A 14-byte sequence header must not make the decoder size its frame buffers at 16383 x 16383+//! (gigabytes per picture). Hand-built, no ffmpeg.++use filmcraft_mpeg2v::Decoder;++#[derive(Default)]+struct Bits {+ bytes: Vec<u8>,+ n: usize,+}++impl Bits {+ fn put(&mut self, value: u32, bits: usize) {+ for i in (0..bits).rev() {+ if self.n.is_multiple_of(8) {+ self.bytes.push(0);+ }+ if (value >> i) & 1 == 1+ && let Some(b) = self.bytes.last_mut()+ {+ *b |= 0x80 >> (self.n % 8);+ }+ self.n += 1;+ }+ }+}++/// Sequence header plus sequence extension for a `w` x `h` 4:4:4 stream.+fn sequence(w: u32, h: u32, chroma_format: u32) -> Vec<u8> {+ let mut s = Bits::default();+ s.put(w & 0xfff, 12);+ s.put(h & 0xfff, 12);+ s.put(1, 4); // aspect_ratio_information+ s.put(4, 4); // frame_rate_code+ s.put(1000, 18); // bit_rate_value+ s.put(1, 1); // marker+ s.put(100, 10); // vbv_buffer_size_value+ s.put(0, 3); // constrained_parameters_flag, load_intra, load_non_intra+ let mut e = Bits::default();+ e.put(1, 4); // sequence_extension+ e.put(0x48, 8); // profile_and_level_indication+ e.put(1, 1); // progressive_sequence+ e.put(chroma_format, 2);+ e.put(w >> 12, 2);+ e.put(h >> 12, 2);+ e.put(0, 12); // bit_rate_extension+ e.put(1, 1); // marker+ e.put(0, 8 + 1 + 2 + 5); // vbv_buffer_size_extension, low_delay, frame_rate_extension_n/d+ let mut out = vec![0, 0, 1, 0xb3];+ out.extend(s.bytes);+ out.extend([0, 0, 1, 0xb5]);+ out.extend(e.bytes);+ out+}++fn accepted(w: u32, h: u32, chroma_format: u32) -> bool {+ let mut dec = Decoder::new();+ let _ = dec.decode(&sequence(w, h, chroma_format), 0);+ dec.sequence().is_some()+}++#[test]+fn ordinary_sequences_are_accepted() {+ assert!(accepted(1920, 1080, 1));+ assert!(accepted(7680, 4320, 3));+}++#[test]+fn gigantic_sequences_are_refused() {+ assert!(!accepted(16383, 16383, 3));+ assert!(!accepted(16383, 16383, 1));+ assert!(!accepted(8192, 8192, 1));+}diff --git a/crates/prores/tests/fuzz_hostile.rs b/crates/prores/tests/fuzz_hostile.rsnew file mode 100644index 000000000..4e374e186--- /dev/null+++ b/crates/prores/tests/fuzz_hostile.rs@@ -0,0 +1,102 @@+//! Hostile-input robustness: every header byte set to extreme values, every bit flipped,+//! truncation at (nearly) every length must never panic or run away (errors are fine).++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::time::{Duration, Instant};++use filmcraft_prores::*;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++fn seeds() -> Vec<Vec<u8>> {+ let mut v = Vec::new();+ for (p, w, h) in [(Profile::Proxy, 96u32, 48u32), (Profile::Hq, 70, 38), (Profile::P4444, 64, 32), (Profile::P4444Xq, 48, 20)] {+ let chroma = p.chroma();+ let mut f = Frame::new(w, h, chroma, 10, chroma == ChromaFormat::Yuv444);+ for (i, s) in f.y.iter_mut().enumerate() {+ *s = (64 + (i * 37) % 800) as u16;+ }+ if let Some(a) = f.alpha.as_mut() {+ for (i, s) in a.iter_mut().enumerate() {+ *s = if i % 5 == 0 { 1023 } else { (i % 1024) as u16 };+ }+ }+ let mut cfg = EncoderConfig::new(p, w, h);+ cfg.log2_slice_mbs = (w % 4) as u8;+ if let Ok(d) = Encoder::with_config(cfg).encode(&f) {+ v.push(d);+ }+ }+ v+}++fn run(d: &[u8], label: &str) {+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for depth in [None, Some(8), Some(16)] {+ let _ = decode_frame_with(d, &DecodeOptions { bit_depth: depth, threads: depth.is_none() });+ }+ let _ = probe(d);+ }));+ assert!(res.is_ok(), "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(10), "too slow ({:?}): {label}", t.elapsed());+}++#[test]+fn hostile_frames_never_panic() {+ let seeds = seeds();+ assert!(!seeds.is_empty());+ for (si, seed) in seeds.iter().enumerate() {+ let stride = (seed.len() / 400).max(1);+ for n in (0..seed.len()).step_by(stride) {+ run(&seed[..n], &format!("seed {si} truncate {n}"));+ }+ for p in 0..seed.len().min(256) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[p] = v;+ run(&d, &format!("seed {si} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[p] ^= 1 << b;+ run(&d, &format!("seed {si} flip {p}.{b}"));+ }+ }+ // Whole big-endian 32-bit words of the header set to 0 / huge values (sizes, counts, dimensions).+ for p in 0..seed.len().min(128) {+ for v in [0u32, 0xffff_ffff, 0x0001_0000, 0x7fff_ffff] {+ let mut d = seed.clone();+ if let Some(s) = d.get_mut(p..p + 4) {+ s.copy_from_slice(&v.to_be_bytes());+ }+ run(&d, &format!("seed {si} u32 {p}={v:#x}"));+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ si as u64);+ let iters = std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(1000);+ for i in 0..iters {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(8) {+ let p = rng.below(d.len());+ if rng.below(2) == 0 {+ d[p] ^= 1 << rng.below(8);+ } else {+ d[p] = rng.next() as u8;+ }+ }+ run(&d, &format!("seed {si} random {i}"));+ }+ }+}diff --git a/crates/vp8/Cargo.toml b/crates/vp8/Cargo.tomlindex 52f274907..8089708d3 100644--- a/crates/vp8/Cargo.toml+++ b/crates/vp8/Cargo.toml@@ -11,3 +11,6 @@ workspace = true[dependencies]thiserror = { workspace = true }++[dev-dependencies]+filmcraft-testkit = { workspace = true }diff --git a/crates/vp8/tests/fuzz_hostile.rs b/crates/vp8/tests/fuzz_hostile.rsnew file mode 100644index 000000000..52f418e50--- /dev/null+++ b/crates/vp8/tests/fuzz_hostile.rs@@ -0,0 +1,146 @@+//! Hostile-input robustness: truncation, header-region sweeps and random mutation of small+//! ffmpeg-generated VP8 streams (frame by frame) must never panic or run away. Skips without ffmpeg.++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::process::{Command, Stdio};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::{Duration, Instant};++use filmcraft_vp8::Decoder;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++/// (name, encoder args, pix_fmt)+const SEEDS: &[(&str, &str, &str)] = &[+ ("vp8_fz_default", "-c:v libvpx -g 4 -b:v 300k", "yuv420p"),+ ("vp8_fz_partitions", "-c:v libvpx -g 6 -b:v 300k -token-parts 3 -auto-alt-ref 0 -lag-in-frames 0 -error-resilient 1", "yuv420p"),+];++fn ivf_frames(data: &[u8]) -> Vec<Vec<u8>> {+ let mut out = Vec::new();+ let Some(h) = data.get(6..8) else { return out };+ let mut pos = usize::from(u16::from_le_bytes([h[0], h[1]]));+ while let Some(hd) = data.get(pos..pos + 12) {+ let size = u32::from_le_bytes([hd[0], hd[1], hd[2], hd[3]]) as usize;+ pos += 12;+ let end = pos.saturating_add(size).min(data.len());+ out.push(data[pos..end].to_vec());+ pos = end;+ }+ out+}++fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str) -> Option<Vec<Vec<u8>>> {+ let out = filmcraft_testkit::fixtures_dir("vp8").join(format!("{name}.ivf"));+ let p = filmcraft_testkit::fixtures::generate(&out, |tmp| {+ let a: Vec<&str> = args.split_whitespace().collect();+ matches!(+ Command::new(ff)+ .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "6", "-pix_fmt", pix])+ .args(a)+ .args(["-f", "ivf"])+ .arg(tmp)+ .stdin(Stdio::null())+ .status(),+ Ok(s) if s.success()+ )+ })?;+ Some(ivf_frames(&std::fs::read(p).ok()?))+}++static PANICS: AtomicUsize = AtomicUsize::new(0);++/// Decoder worker threads may catch panics and turn them into errors; count them so they still fail the test.+fn count_panics() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ std::panic::set_hook(Box::new(|info| {+ PANICS.fetch_add(1, Ordering::SeqCst);+ eprintln!("PANIC: {info}");+ }));+ });+}++fn run_all(frames: &[Vec<u8>], label: &str) {+ count_panics();+ let before = PANICS.load(Ordering::SeqCst);+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for _ in 0..1 {+ let mut dec = Decoder::new();+ for (i, f) in frames.iter().enumerate() {+ let _ = dec.decode(f, i as i64);+ }+ }+ }));+ assert!(res.is_ok() && PANICS.load(Ordering::SeqCst) == before, "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(20), "too slow ({:?}): {label}", t.elapsed());+}++/// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt).+fn iters() -> usize {+ std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(300)+}++#[test]+fn hostile_streams_never_panic() {+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("VP8 fuzz") else { return };+ for &(name, args, pix) in SEEDS {+ let Some(seed) = make(&ff, name, args, pix) else { continue };+ if seed.is_empty() {+ continue;+ }+ // truncate each of the first frames at every length+ for fi in 0..seed.len().min(3) {+ let len = seed[fi].len();+ for n in (0..len).step_by((len / 200).max(1)) {+ let mut d = seed.clone();+ d[fi].truncate(n);+ run_all(&d, &format!("{name} frame {fi} truncate {n}"));+ }+ }+ // header region of every frame: every byte to a few values, every bit+ for fi in 0..seed.len() {+ for p in 0..seed[fi].len().min(96) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[fi][p] = v;+ run_all(&d, &format!("{name} frame {fi} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[fi][p] ^= 1 << b;+ run_all(&d, &format!("{name} frame {fi} flip {p}.{b}"));+ }+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ name.len() as u64);+ for i in 0..iters() {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(6) {+ let fi = rng.below(d.len());+ if d[fi].is_empty() {+ continue;+ }+ let p = rng.below(d[fi].len());+ if rng.below(2) == 0 {+ d[fi][p] ^= 1 << rng.below(8);+ } else {+ d[fi][p] = rng.next() as u8;+ }+ }+ run_all(&d, &format!("{name} random {i}"));+ }+ }+}diff --git a/crates/vp9/Cargo.toml b/crates/vp9/Cargo.tomlindex 5e9fd06e3..c8aef8ca3 100644--- a/crates/vp9/Cargo.toml+++ b/crates/vp9/Cargo.toml@@ -19,3 +19,4 @@ thiserror = { workspace = true }rayon = { workspace = true, optional = true }[dev-dependencies]+filmcraft-testkit = { workspace = true }diff --git a/crates/vp9/tests/fuzz_hostile.rs b/crates/vp9/tests/fuzz_hostile.rsnew file mode 100644index 000000000..1a383b542--- /dev/null+++ b/crates/vp9/tests/fuzz_hostile.rs@@ -0,0 +1,149 @@+//! Hostile-input robustness: truncation, header-region sweeps and random mutation of small+//! ffmpeg-generated VP9 streams (frame by frame) must never panic or run away. Skips without ffmpeg.++use std::panic::{AssertUnwindSafe, catch_unwind};+use std::process::{Command, Stdio};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::{Duration, Instant};++use filmcraft_vp9::Decoder;++struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: usize) -> usize {+ (self.next() % n.max(1) as u64) as usize+ }+}++/// (name, encoder args, pix_fmt)+const SEEDS: &[(&str, &str, &str)] = &[+ ("vp9_fz_default", "-c:v libvpx-vp9 -g 4 -b:v 300k -lag-in-frames 0", "yuv420p"),+ ("vp9_fz_tiles_10bit", "-c:v libvpx-vp9 -g 6 -b:v 300k -lag-in-frames 0 -tile-columns 1 -profile:v 2", "yuv420p10le"),+ ("vp9_fz_444", "-c:v libvpx-vp9 -g 6 -b:v 300k -lag-in-frames 0 -profile:v 1", "yuv444p"),+ ("vp9_fz_altref", "-c:v libvpx-vp9 -g 6 -b:v 300k -auto-alt-ref 1 -lag-in-frames 5", "yuv420p"),+];++fn ivf_frames(data: &[u8]) -> Vec<Vec<u8>> {+ let mut out = Vec::new();+ let Some(h) = data.get(6..8) else { return out };+ let mut pos = usize::from(u16::from_le_bytes([h[0], h[1]]));+ while let Some(hd) = data.get(pos..pos + 12) {+ let size = u32::from_le_bytes([hd[0], hd[1], hd[2], hd[3]]) as usize;+ pos += 12;+ let end = pos.saturating_add(size).min(data.len());+ out.push(data[pos..end].to_vec());+ pos = end;+ }+ out+}++fn make(ff: &std::path::Path, name: &str, args: &str, pix: &str) -> Option<Vec<Vec<u8>>> {+ let out = filmcraft_testkit::fixtures_dir("vp9").join(format!("{name}.ivf"));+ let p = filmcraft_testkit::fixtures::generate(&out, |tmp| {+ let a: Vec<&str> = args.split_whitespace().collect();+ matches!(+ Command::new(ff)+ .args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "6", "-pix_fmt", pix])+ .args(a)+ .args(["-f", "ivf"])+ .arg(tmp)+ .stdin(Stdio::null())+ .status(),+ Ok(s) if s.success()+ )+ })?;+ Some(ivf_frames(&std::fs::read(p).ok()?))+}++static PANICS: AtomicUsize = AtomicUsize::new(0);++/// Decoder worker threads may catch panics and turn them into errors; count them so they still fail the test.+fn count_panics() {+ static ONCE: std::sync::Once = std::sync::Once::new();+ ONCE.call_once(|| {+ std::panic::set_hook(Box::new(|info| {+ PANICS.fetch_add(1, Ordering::SeqCst);+ eprintln!("PANIC: {info}");+ }));+ });+}++fn run_all(frames: &[Vec<u8>], label: &str) {+ count_panics();+ let before = PANICS.load(Ordering::SeqCst);+ let t = Instant::now();+ let res = catch_unwind(AssertUnwindSafe(|| {+ for threads in [1, 3] {+ let mut dec = Decoder::with_threads(threads);+ for (i, f) in frames.iter().enumerate() {+ let _ = dec.decode(f, i as i64);+ }+ let _ = dec.flush();+ }+ }));+ assert!(res.is_ok() && PANICS.load(Ordering::SeqCst) == before, "panic: {label}");+ assert!(t.elapsed() < Duration::from_secs(20), "too slow ({:?}): {label}", t.elapsed());+}++/// Random-mutation rounds per seed (raise with FILMCRAFT_FUZZ_ITERS for a long hunt).+fn iters() -> usize {+ std::env::var("FILMCRAFT_FUZZ_ITERS").ok().and_then(|s| s.parse().ok()).unwrap_or(300)+}++#[test]+fn hostile_streams_never_panic() {+ let Some(ff) = filmcraft_testkit::ffmpeg_or_skip("VP9 fuzz") else { return };+ for &(name, args, pix) in SEEDS {+ let Some(seed) = make(&ff, name, args, pix) else { continue };+ if seed.is_empty() {+ continue;+ }+ // truncate each of the first frames at every length+ for fi in 0..seed.len().min(3) {+ let len = seed[fi].len();+ for n in (0..len).step_by((len / 200).max(1)) {+ let mut d = seed.clone();+ d[fi].truncate(n);+ run_all(&d, &format!("{name} frame {fi} truncate {n}"));+ }+ }+ // header region of every frame: every byte to a few values, every bit+ for fi in 0..seed.len() {+ for p in 0..seed[fi].len().min(96) {+ for v in [0u8, 0xff, 0x80, 0x01, 0x7f] {+ let mut d = seed.clone();+ d[fi][p] = v;+ run_all(&d, &format!("{name} frame {fi} byte {p}={v:#x}"));+ }+ for b in 0..8 {+ let mut d = seed.clone();+ d[fi][p] ^= 1 << b;+ run_all(&d, &format!("{name} frame {fi} flip {p}.{b}"));+ }+ }+ }+ let mut rng = Rng(0x9e3779b97f4a7c15 ^ name.len() as u64);+ for i in 0..iters() {+ let mut d = seed.clone();+ for _ in 0..1 + rng.below(6) {+ let fi = rng.below(d.len());+ if d[fi].is_empty() {+ continue;+ }+ let p = rng.below(d[fi].len());+ if rng.below(2) == 0 {+ d[fi][p] ^= 1 << rng.below(8);+ } else {+ d[fi][p] = rng.next() as u8;+ }+ }+ run_all(&d, &format!("{name} random {i}"));+ }+ }+}