Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#598: filmcraft-avi, a clean-room AVI / OpenDML demuxer

JordyUSA2f4b59329e53
diff --git a/Cargo.lock b/Cargo.lock
index d94a44573..ed05e601d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1755,6 +1755,13 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "filmcraft-avi"
+version = "0.5.0"
+dependencies = [
+ "filmcraft-testkit",
+]
+
[[package]]
name = "filmcraft-bitstream"
version = "0.5.0"
@@ -1808,6 +1815,7 @@ dependencies = [
"filmcraft-ac3",
"filmcraft-apv",
"filmcraft-av1",
+ "filmcraft-avi",
"filmcraft-bitstream",
"filmcraft-color",
"filmcraft-dnx",
diff --git a/Cargo.toml b/Cargo.toml
index 1d306cffa..d69ecd83b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,6 +17,7 @@ filmcraft-geom = { path = "crates/geom" }
filmcraft-color = { path = "crates/color" }
filmcraft-bitstream = { path = "crates/bitstream" }
filmcraft-isobmff = { path = "crates/isobmff" }
+filmcraft-avi = { path = "crates/avi" }
filmcraft-matroska = { path = "crates/matroska" }
filmcraft-mxf = { path = "crates/mxf" }
filmcraft-cfb = { path = "crates/cfb" }
diff --git a/crates/avi/Cargo.toml b/crates/avi/Cargo.toml
new file mode 100644
index 000000000..519c098dc
--- /dev/null
+++ b/crates/avi/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "filmcraft-avi"
+description = "Clean-room AVI (RIFF) and OpenDML demuxer"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+
+[dev-dependencies]
+filmcraft-testkit = { workspace = true }
diff --git a/crates/avi/README.md b/crates/avi/README.md
new file mode 100644
index 000000000..d10ba02f2
--- /dev/null
+++ b/crates/avi/README.md
@@ -0,0 +1,43 @@
+# filmcraft-avi
+
+A clean-room AVI demuxer, written from Microsoft's published AVI RIFF file reference and the
+OpenDML AVI File Format Extensions 1.02. Layer L0: no dependencies beyond `std`, no `unsafe`, builds
+for `wasm32-unknown-unknown`. No FFmpeg, libavformat or other AVI implementation was read; ffmpeg
+and ffprobe are used only as external **test oracles**.
+
+## API
+
+```rust
+use filmcraft_avi::{open, StreamKind};
+
+let file = open(&bytes)?; // any ByteSource: a slice, a file, a web Blob…
+for (i, s) in file.streams.iter().enumerate() {
+ match s.kind {
+ StreamKind::Video => println!("{:?} {} fps", s.video.as_ref().map(|b| b.compression), s.rate as f64 / s.scale as f64),
+ StreamKind::Audio => println!("format 0x{:04x}", s.audio.as_ref().map_or(0, |w| w.format_tag)),
+ _ => {}
+ }
+ let first = file.read_chunk(&bytes, i, 0)?; // frame data, on demand
+}
+```
+
+## What it reads
+
+| Part | |
+|---|---|
+| Headers | `avih`; per stream `strh`, `strf` (`BITMAPINFOHEADER`, `WAVEFORMATEX` / `WAVEFORMATEXTENSIBLE`), `strn` |
+| Index | OpenDML `indx` super index → `ix##` standard indexes (field indexes too), else `idx1` (offsets relative to `movi` or absolute), else a scan of the `movi` lists |
+| Large files | `RIFF AVIX` extensions: through the OpenDML index, or scanned after `idx1`, which only covers the first RIFF |
+| Key frames | from the index; a scan marks every chunk and says so (`keyframes_known`) |
+| Damage | sizes clamped to the file (a cut-off recording opens with what is there), `rec ` lists nested at most 3 deep, tables bounded by what the file could hold |
+
+`filmcraft-codecs` maps the streams onto decoders (`AviSource`): Motion JPEG, H.264, HEVC and
+uncompressed RGB / YUV video; PCM, MP3, MP2 and AC-3 audio.
+
+## Tests
+
+`cargo test -p filmcraft-avi`: hand-built files for every index path (`idx1` relative and absolute,
+`rec ` lists, OpenDML standard indexes, a scan), truncation, and every single-byte mutation and
+truncation of them (never a panic). `tests/ffmpeg_oracle.rs` checks ffmpeg-made files (Motion JPEG,
+H.264 with B-frames, BGR24, YUY2; PCM and MP3) against ffprobe; the ignored `opendml_file_past_1_gb`
+checks a 1.16 GB OpenDML file with `AVIX` extensions.
diff --git a/crates/avi/src/lib.rs b/crates/avi/src/lib.rs
new file mode 100644
index 000000000..0294fdfea
--- /dev/null
+++ b/crates/avi/src/lib.rs
@@ -0,0 +1,542 @@
+//! Clean-room AVI demuxer, written from Microsoft's published AVI RIFF file reference and the
+//! OpenDML AVI File Format Extensions 1.02.
+//!
+//! [`open`] reads the `hdrl` header list (`avih`, and per stream `strh` / `strf` / `strn` /
+//! `indx`) of the first `RIFF AVI ` and builds a per-stream table of [`Chunk`]s from the best index
+//! the file has: the OpenDML super index (`indx` → `ix##` standard indexes, which also cover the
+//! `RIFF AVIX` extensions of files past 1 GB), else the AVI 1.0 `idx1` (plus a scan of any `AVIX`
+//! extension it cannot see), else a scan of the `movi` lists. Frame data is read on demand with
+//! [`AviFile::read_chunk`]. Truncated files (a recording cut off) open with what is there.
+//!
+//! Every size and count comes from the file and is treated as hostile: reads are bounded by the
+//! file length, tables by the number of chunks the file could hold, and nesting by a fixed depth.
+//!
+//! Layer L0: no dependencies beyond `std`, no `unsafe`, builds for `wasm32-unknown-unknown`.
+
+#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
+
+mod source;
+#[cfg(test)]
+mod tests;
+
+pub use source::ByteSource;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Error {
+ /// Not an AVI file (no `RIFF` … `AVI ` header).
+ NotAvi,
+ /// A read failed.
+ Io(String),
+ /// Structurally invalid data.
+ Invalid(String),
+}
+
+impl std::fmt::Display for Error {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Error::NotAvi => f.write_str("not an AVI file"),
+ Error::Io(e) => write!(f, "I/O error: {e}"),
+ Error::Invalid(e) => write!(f, "invalid AVI: {e}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Whether `head` starts like an AVI file: `RIFF` <size> `AVI `.
+pub fn sniff(head: &[u8]) -> bool {
+ head.get(..4) == Some(b"RIFF") && head.get(8..12) == Some(b"AVI ")
+}
+
+/// `avih`: the main header (frame period, flags, frame count, size).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct MainHeader {
+ pub micro_sec_per_frame: u32,
+ pub flags: u32,
+ pub total_frames: u32,
+ pub streams: u32,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StreamKind {
+ Video,
+ Audio,
+ /// Text, MIDI or anything else (`fccType`).
+ Other([u8; 4]),
+}
+
+/// `strf` of a video stream: a `BITMAPINFOHEADER`.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct BitmapInfo {
+ pub width: i32,
+ /// Positive: rows stored bottom-up (uncompressed RGB); negative: top-down.
+ pub height: i32,
+ pub bit_count: u16,
+ /// `biCompression` as four bytes: a FourCC (`MJPG`, `H264`, `YUY2`…) or 0 / 3 (`BI_RGB`,
+ /// `BI_BITFIELDS`) in little-endian.
+ pub compression: [u8; 4],
+ pub size_image: u32,
+ /// Bytes after the 40-byte header (codec setup, palette).
+ pub extra: Vec<u8>,
+}
+
+impl BitmapInfo {
+ /// Uncompressed RGB (`BI_RGB` / `BI_BITFIELDS`).
+ pub fn is_rgb(&self) -> bool {
+ matches!(u32::from_le_bytes(self.compression), 0 | 3)
+ }
+}
+
+/// `strf` of an audio stream: a `WAVEFORMATEX` (`WAVEFORMATEXTENSIBLE` is resolved to its sub-format).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct WaveFormat {
+ /// 1 PCM, 3 IEEE float, 0x50 MPEG audio, 0x55 MP3, 0x2000 AC-3, 0xFF AAC…
+ pub format_tag: u16,
+ pub channels: u16,
+ pub sample_rate: u32,
+ pub avg_bytes_per_sec: u32,
+ pub block_align: u16,
+ pub bits_per_sample: u16,
+ /// `cbSize` bytes after the 18-byte header.
+ pub extra: Vec<u8>,
+}
+
+/// One stored frame or audio chunk.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct Chunk {
+ /// Offset of the data (after the 8-byte chunk header).
+ pub offset: u64,
+ pub size: u32,
+ /// A key frame (always true for audio and when the index does not say).
+ pub key: bool,
+}
+
+/// Where the chunk tables came from.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum IndexSource {
+ /// OpenDML `indx` super index and `ix##` standard indexes.
+ OpenDml,
+ /// The AVI 1.0 `idx1` (plus a scan of the `AVIX` extensions).
+ Idx1,
+ /// No usable index: the `movi` lists were scanned (key frames unknown).
+ Scan,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Stream {
+ pub kind: StreamKind,
+ /// `fccHandler`.
+ pub handler: [u8; 4],
+ /// Time base: `rate / scale` units per second (frames per second for video).
+ pub scale: u32,
+ pub rate: u32,
+ /// Start time in `scale / rate` units.
+ pub start: u32,
+ /// Length in `scale / rate` units.
+ pub length: u32,
+ /// Bytes per sample for fixed-size samples (PCM block align), 0 when samples vary.
+ pub sample_size: u32,
+ pub video: Option<BitmapInfo>,
+ pub audio: Option<WaveFormat>,
+ /// `strn`.
+ pub name: Option<String>,
+ pub chunks: Vec<Chunk>,
+ /// Whether [`Chunk::key`] comes from an index (a scan cannot tell).
+ pub keyframes_known: bool,
+ /// The OpenDML super index entries (offsets of the `ix##` chunks).
+ super_index: Vec<u64>,
+}
+
+impl Stream {
+ /// Stream index of a `movi` chunk id (`00dc`, `01wb`…): its first two characters.
+ fn number(id: &[u8; 4]) -> Option<usize> {
+ let d = |b: u8| (b as char).to_digit(16).map(|v| v as usize);
+ Some(d(id[0])? * 16 + d(id[1])?)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct AviFile {
+ pub header: MainHeader,
+ pub streams: Vec<Stream>,
+ pub index: IndexSource,
+}
+
+/// Options for [`open_with`] (tests reach the fallback indexes with them).
+#[derive(Clone, Copy, Debug, Default)]
+pub struct OpenOptions {
+ pub ignore_odml: bool,
+ pub ignore_idx1: bool,
+}
+
+/// Headers larger than this are refused (a real `hdrl` is a few kilobytes).
+const MAX_HEADER: u64 = 16 << 20;
+/// Streams beyond this are ignored.
+const MAX_STREAMS: usize = 64;
+/// `LIST rec ` inside `movi` nests once; deeper is refused.
+const MAX_DEPTH: u32 = 3;
+
+fn io(e: std::io::Error) -> Error {
+ Error::Io(e.to_string())
+}
+
+fn read<S: ByteSource + ?Sized>(src: &S, at: u64, n: u64) -> Result<Vec<u8>> {
+ let end = at.checked_add(n).filter(|e| *e <= src.len()).ok_or_else(|| Error::Invalid(format!("{n} bytes at {at} run past the end")))?;
+ let len = usize::try_from(end - at).map_err(|_| Error::Invalid("chunk too large".into()))?;
+ let mut buf = vec![0; len];
+ src.read_at(at, &mut buf).map_err(io)?;
+ Ok(buf)
+}
+
+fn fourcc(b: &[u8], at: usize) -> [u8; 4] {
+ let mut f = [0; 4];
+ if let Some(s) = b.get(at..at + 4) {
+ f.copy_from_slice(s);
+ }
+ f
+}
+
+fn le16(b: &[u8], at: usize) -> u16 {
+ b.get(at..at + 2).map_or(0, |s| u16::from_le_bytes([s[0], s[1]]))
+}
+
+fn le32(b: &[u8], at: usize) -> u32 {
+ b.get(at..at + 4).map_or(0, |s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
+}
+
+fn le64(b: &[u8], at: usize) -> u64 {
+ u64::from(le32(b, at)) | (u64::from(le32(b, at + 4)) << 32)
+}
+
+/// A chunk header at `at`: (id, size, data offset). The size is clamped to the file (a truncated
+/// recording keeps what is there).
+fn header_at<S: ByteSource + ?Sized>(src: &S, at: u64) -> Result<([u8; 4], u64, u64)> {
+ let h = read(src, at, 8)?;
+ let data = at + 8;
+ let size = u64::from(le32(&h, 4)).min(src.len().saturating_sub(data));
+ Ok((fourcc(&h, 0), size, data))
+}
+
+/// Iterate the chunks of `[from, to)`: (id, size, data offset). Stops at the first unreadable
+/// header; every step moves forward, so it ends.
+fn children<S: ByteSource + ?Sized>(src: &S, from: u64, to: u64) -> Vec<([u8; 4], u64, u64)> {
+ let mut out = Vec::new();
+ let mut at = from;
+ while at.checked_add(8).is_some_and(|e| e <= to) {
+ let Ok((id, size, data)) = header_at(src, at) else { break };
+ out.push((id, size, data));
+ // chunks are padded to an even size
+ let Some(next) = data.checked_add(size).and_then(|e| e.checked_add(size & 1)) else { break };
+ if next <= at {
+ break;
+ }
+ at = next;
+ }
+ out
+}
+
+/// Open an AVI file.
+pub fn open<S: ByteSource + ?Sized>(src: &S) -> Result<AviFile> {
+ open_with(src, OpenOptions::default())
+}
+
+pub fn open_with<S: ByteSource + ?Sized>(src: &S, opts: OpenOptions) -> Result<AviFile> {
+ let head = read(src, 0, 12.min(src.len())).map_err(|_| Error::NotAvi)?;
+ if !sniff(&head) {
+ return Err(Error::NotAvi);
+ }
+ // the RIFF forms: the first `AVI `, then any `AVIX` extensions (OpenDML)
+ let mut hdrl = None;
+ let mut movis: Vec<(u64, u64, u64)> = Vec::new(); // (position of the `movi` id, data start, data end)
+ let mut idx1 = None;
+ for (id, size, data) in children(src, 0, src.len()) {
+ if id != *b"RIFF" || size < 4 {
+ continue;
+ }
+ let end = data + size;
+ let form = fourcc(&read(src, data, 4)?, 0);
+ if form != *b"AVI " && form != *b"AVIX" {
+ continue;
+ }
+ for (cid, csize, cdata) in children(src, data + 4, end) {
+ match &cid {
+ b"LIST" if csize >= 4 => {
+ let ltype = fourcc(&read(src, cdata, 4)?, 0);
+ if ltype == *b"hdrl" && hdrl.is_none() && form == *b"AVI " {
+ hdrl = Some((cdata + 4, cdata + csize));
+ } else if ltype == *b"movi" {
+ movis.push((cdata, cdata + 4, cdata + csize));
+ }
+ }
+ b"idx1" if form == *b"AVI " => idx1 = Some((cdata, csize)),
+ _ => {}
+ }
+ }
+ }
+ let (hfrom, hto) = hdrl.ok_or_else(|| Error::Invalid("no hdrl header list".into()))?;
+ if hto - hfrom > MAX_HEADER {
+ return Err(Error::Invalid("header list too large".into()));
+ }
+ let (header, mut streams) = parse_hdrl(src, hfrom, hto)?;
+ if streams.is_empty() {
+ return Err(Error::Invalid("no streams".into()));
+ }
+ // chunk tables from the best index
+ let odml = !opts.ignore_odml && streams.iter().any(|s| !s.super_index.is_empty());
+ let index = if odml && read_odml(src, &mut streams) {
+ IndexSource::OpenDml
+ } else if let (false, Some((at, size)), Some(first)) = (opts.ignore_idx1, idx1, movis.first()) {
+ clear(&mut streams);
+ read_idx1(src, &mut streams, at, size, first.0);
+ // idx1 only covers the first RIFF: the AVIX extensions are scanned
+ for &(_, from, to) in movis.iter().skip(1) {
+ scan(src, &mut streams, from, to, 0);
+ }
+ if streams.iter().all(|s| s.chunks.is_empty()) { scan_all(src, &mut streams, &movis) } else { IndexSource::Idx1 }
+ } else {
+ scan_all(src, &mut streams, &movis)
+ };
+ Ok(AviFile { header, streams, index })
+}
+
+fn clear(streams: &mut [Stream]) {
+ for s in streams.iter_mut() {
+ s.chunks.clear();
+ s.keyframes_known = true;
+ }
+}
+
+fn scan_all<S: ByteSource + ?Sized>(src: &S, streams: &mut [Stream], movis: &[(u64, u64, u64)]) -> IndexSource {
+ clear(streams);
+ for &(_, from, to) in movis {
+ scan(src, streams, from, to, 0);
+ }
+ for s in streams.iter_mut() {
+ s.keyframes_known = false;
+ }
+ IndexSource::Scan
+}
+
+fn parse_hdrl<S: ByteSource + ?Sized>(src: &S, from: u64, to: u64) -> Result<(MainHeader, Vec<Stream>)> {
+ let mut header = MainHeader::default();
+ let mut streams = Vec::new();
+ for (id, size, data) in children(src, from, to) {
+ match &id {
+ b"avih" => {
+ let b = read(src, data, size.min(64))?;
+ header = MainHeader {
+ micro_sec_per_frame: le32(&b, 0),
+ flags: le32(&b, 12),
+ total_frames: le32(&b, 16),
+ streams: le32(&b, 24),
+ width: le32(&b, 32),
+ height: le32(&b, 36),
+ };
+ }
+ b"LIST" if size >= 4 && streams.len() < MAX_STREAMS && fourcc(&read(src, data, 4)?, 0) == *b"strl" => {
+ streams.push(parse_strl(src, data + 4, data + size)?);
+ }
+ _ => {}
+ }
+ }
+ Ok((header, streams))
+}
+
+fn parse_strl<S: ByteSource + ?Sized>(src: &S, from: u64, to: u64) -> Result<Stream> {
+ let mut s = Stream {
+ kind: StreamKind::Other([0; 4]),
+ handler: [0; 4],
+ scale: 1,
+ rate: 1,
+ start: 0,
+ length: 0,
+ sample_size: 0,
+ video: None,
+ audio: None,
+ name: None,
+ chunks: Vec::new(),
+ keyframes_known: true,
+ super_index: Vec::new(),
+ };
+ let mut strf = None;
+ for (id, size, data) in children(src, from, to) {
+ match &id {
+ b"strh" => {
+ let b = read(src, data, size.min(64))?;
+ s.kind = match &fourcc(&b, 0) {
+ b"vids" => StreamKind::Video,
+ b"auds" => StreamKind::Audio,
+ other => StreamKind::Other(*other),
+ };
+ s.handler = fourcc(&b, 4);
+ s.scale = le32(&b, 20);
+ s.rate = le32(&b, 24);
+ s.start = le32(&b, 28);
+ s.length = le32(&b, 32);
+ s.sample_size = le32(&b, 44);
+ }
+ b"strf" => strf = Some(read(src, data, size.min(1 << 20))?),
+ b"strn" => {
+ let b = read(src, data, size.min(4096))?;
+ let name = String::from_utf8_lossy(b.split(|&c| c == 0).next().unwrap_or_default()).trim().to_string();
+ s.name = (!name.is_empty()).then_some(name);
+ }
+ b"indx" => s.super_index = super_index(&read(src, data, size.min(MAX_HEADER))?),
+ _ => {}
+ }
+ }
+ if let Some(b) = strf {
+ match s.kind {
+ StreamKind::Video => {
+ s.video = Some(BitmapInfo {
+ width: le32(&b, 4) as i32,
+ height: le32(&b, 8) as i32,
+ bit_count: le16(&b, 14),
+ compression: fourcc(&b, 16),
+ size_image: le32(&b, 20),
+ extra: b.get(40.min(b.len())..).unwrap_or_default().to_vec(),
+ });
+ }
+ StreamKind::Audio => {
+ let cb = usize::from(le16(&b, 16));
+ let extra = b.get(18.min(b.len())..(18 + cb).min(b.len())).unwrap_or_default().to_vec();
+ let mut tag = le16(&b, 0);
+ // WAVE_FORMAT_EXTENSIBLE: the sub-format GUID starts with the real tag
+ if tag == 0xFFFE && extra.len() >= 22 {
+ tag = le16(&extra, 6);
+ }
+ s.audio = Some(WaveFormat {
+ format_tag: tag,
+ channels: le16(&b, 2),
+ sample_rate: le32(&b, 4),
+ avg_bytes_per_sec: le32(&b, 8),
+ block_align: le16(&b, 12),
+ bits_per_sample: le16(&b, 14),
+ extra,
+ });
+ }
+ StreamKind::Other(_) => {}
+ }
+ }
+ if s.scale == 0 || s.rate == 0 {
+ (s.scale, s.rate) = (1, 1);
+ }
+ Ok(s)
+}
+
+/// The `ix##` chunk offsets of an `indx` super index (`AVI_INDEX_OF_INDEXES`, 4 longs per entry).
+fn super_index(b: &[u8]) -> Vec<u64> {
+ let longs = usize::from(le16(b, 0));
+ let (subtype, itype, n) = (b.get(2).copied().unwrap_or(0), b.get(3).copied().unwrap_or(0xFF), le32(b, 4) as usize);
+ if itype != 0 || subtype != 0 || longs != 4 {
+ return Vec::new();
+ }
+ // header 24 bytes, entries of 16: qwOffset, dwSize, dwDuration
+ let n = n.min(b.len().saturating_sub(24) / 16);
+ (0..n).map(|k| le64(b, 24 + k * 16)).filter(|&o| o > 0).collect()
+}
+
+/// Fill the chunk tables from the OpenDML standard indexes; false (tables cleared) when a stream
+/// that has data lacks one or none could be read.
+fn read_odml<S: ByteSource + ?Sized>(src: &S, streams: &mut [Stream]) -> bool {
+ let limit = src.len() / 8;
+ let mut total = 0u64;
+ for s in streams.iter_mut() {
+ s.chunks.clear();
+ s.keyframes_known = true;
+ for &at in &s.super_index {
+ let Ok((id, size, data)) = header_at(src, at) else { continue };
+ if &id[..2] != b"ix" {
+ continue;
+ }
+ let Ok(b) = read(src, data, size.min(MAX_HEADER * 8)) else { continue };
+ let (longs, subtype, itype) = (usize::from(le16(&b, 0)), b.get(2).copied().unwrap_or(0), b.get(3).copied().unwrap_or(0));
+ // AVI_INDEX_OF_CHUNKS; 2 longs per entry, or 3 for the field index (AVI_INDEX_2FIELD)
+ if itype != 1 || !(longs == 2 && subtype == 0 || longs == 3 && subtype == 1) {
+ continue;
+ }
+ let base = le64(&b, 12);
+ let step = longs * 4;
+ let n = (le32(&b, 4) as usize).min(b.len().saturating_sub(24) / step);
+ for k in 0..n {
+ let e = 24 + k * step;
+ let (off, raw) = (u64::from(le32(&b, e)), le32(&b, e + 4));
+ let size = raw & 0x7FFF_FFFF;
+ let Some(offset) = base.checked_add(off).filter(|o| o.checked_add(u64::from(size)).is_some_and(|end| end <= src.len())) else { continue };
+ total += 1;
+ if total > limit {
+ return false;
+ }
+ s.chunks.push(Chunk { offset, size, key: raw & 0x8000_0000 == 0 });
+ }
+ }
+ }
+ let ok = streams.iter().any(|s| !s.chunks.is_empty()) && streams.iter().all(|s| !s.super_index.is_empty() || matches!(s.kind, StreamKind::Other(_)));
+ if !ok {
+ clear(streams);
+ }
+ ok
+}
+
+/// Fill the chunk tables from `idx1` (16-byte entries: id, flags, offset, size). Offsets are
+/// relative to the `movi` list's type id, or (some writers) absolute: the first entry decides.
+fn read_idx1<S: ByteSource + ?Sized>(src: &S, streams: &mut [Stream], at: u64, size: u64, movi: u64) {
+ let Ok(b) = read(src, at, size.min(src.len() / 2)) else { return };
+ let entries: Vec<&[u8]> = b.as_chunks::<16>().0.iter().map(|e| e.as_slice()).collect();
+ let id_at = |pos: u64| read(src, pos, 4).ok().map(|v| fourcc(&v, 0));
+ let first = entries.iter().find(|e| le32(e, 4) & 1 == 0);
+ let relative = match first {
+ Some(e) => {
+ let (id, off) = (fourcc(e, 0), u64::from(le32(e, 8)));
+ id_at(movi + off) == Some(id) || id_at(off) != Some(id)
+ }
+ None => true,
+ };
+ let base = if relative { movi } else { 0 };
+ for e in entries {
+ let (id, flags, off, len) = (fourcc(e, 0), le32(e, 4), u64::from(le32(e, 8)), le32(e, 12));
+ // AVIIF_LIST entries (`rec ` lists) and palette changes carry no samples
+ if flags & 1 != 0 || &id[2..] == b"pc" {
+ continue;
+ }
+ let Some(s) = Stream::number(&id).and_then(|n| streams.get_mut(n)) else { continue };
+ let Some(offset) = base.checked_add(off).and_then(|o| o.checked_add(8)).filter(|o| o.checked_add(u64::from(len)).is_some_and(|end| end <= src.len()))
+ else {
+ continue;
+ };
+ s.chunks.push(Chunk { offset, size: len, key: flags & 0x10 != 0 || s.kind != StreamKind::Video });
+ }
+}
+
+/// Append the data chunks of a `movi` list (`[from, to)`) to the streams' tables, in file order.
+fn scan<S: ByteSource + ?Sized>(src: &S, streams: &mut [Stream], from: u64, to: u64, depth: u32) {
+ if depth >= MAX_DEPTH {
+ return;
+ }
+ for (id, size, data) in children(src, from, to) {
+ if id == *b"LIST" {
+ if size >= 4 {
+ scan(src, streams, data + 4, data + size, depth + 1);
+ }
+ continue;
+ }
+ if &id[..2] == b"ix" || &id[2..] == b"pc" {
+ continue;
+ }
+ if let Some(s) = Stream::number(&id).and_then(|n| streams.get_mut(n)) {
+ s.chunks.push(Chunk { offset: data, size: u32::try_from(size).unwrap_or(u32::MAX), key: true });
+ }
+ }
+}
+
+impl AviFile {
+ /// The bytes of chunk `i` of stream `stream`.
+ pub fn read_chunk<S: ByteSource + ?Sized>(&self, src: &S, stream: usize, i: usize) -> Result<Vec<u8>> {
+ let c = self.streams.get(stream).and_then(|s| s.chunks.get(i)).ok_or_else(|| Error::Invalid(format!("no chunk {i} in stream {stream}")))?;
+ read(src, c.offset, u64::from(c.size))
+ }
+}
diff --git a/crates/avi/src/source.rs b/crates/avi/src/source.rs
new file mode 100644
index 000000000..783cc1905
--- /dev/null
+++ b/crates/avi/src/source.rs
@@ -0,0 +1,59 @@
+//! Random-access byte sources for the demuxer (same shape as the other container crates', so one
+//! adapter serves them all).
+
+use std::io;
+
+/// Random-access, read-only byte source (file, in-memory buffer, web Blob…).
+pub trait ByteSource {
+ /// Total length in bytes.
+ fn len(&self) -> u64;
+ /// Fill `buf` entirely with bytes starting at `offset`; fail with `UnexpectedEof` if past the end.
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>;
+ /// True if the source holds no bytes.
+ fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+}
+
+fn eof() -> io::Error {
+ io::Error::new(io::ErrorKind::UnexpectedEof, "read past end of byte source")
+}
+
+impl ByteSource for [u8] {
+ fn len(&self) -> u64 {
+ <[u8]>::len(self) as u64
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ let start = usize::try_from(offset).map_err(|_| eof())?;
+ let end = start.checked_add(buf.len()).ok_or_else(eof)?;
+ buf.copy_from_slice(self.get(start..end).ok_or_else(eof)?);
+ Ok(())
+ }
+}
+
+impl ByteSource for Vec<u8> {
+ fn len(&self) -> u64 {
+ self.as_slice().len() as u64
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ self.as_slice().read_at(offset, buf)
+ }
+}
+
+impl<T: ByteSource + ?Sized> ByteSource for &T {
+ fn len(&self) -> u64 {
+ (**self).len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ (**self).read_at(offset, buf)
+ }
+}
+
+impl<T: ByteSource + ?Sized> ByteSource for std::sync::Arc<T> {
+ fn len(&self) -> u64 {
+ (**self).len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ (**self).read_at(offset, buf)
+ }
+}
diff --git a/crates/avi/src/tests.rs b/crates/avi/src/tests.rs
new file mode 100644
index 000000000..248364d6f
--- /dev/null
+++ b/crates/avi/src/tests.rs
@@ -0,0 +1,269 @@
+use super::*;
+
+fn chunk(id: &[u8; 4], data: &[u8]) -> Vec<u8> {
+ let mut v = id.to_vec();
+ v.extend_from_slice(&(data.len() as u32).to_le_bytes());
+ v.extend_from_slice(data);
+ if data.len() % 2 == 1 {
+ v.push(0);
+ }
+ v
+}
+
+fn list(ltype: &[u8; 4], body: &[u8]) -> Vec<u8> {
+ let mut d = ltype.to_vec();
+ d.extend_from_slice(body);
+ chunk(b"LIST", &d)
+}
+
+fn strl(video: bool) -> Vec<u8> {
+ let mut strh = vec![0u8; 56];
+ strh[..4].copy_from_slice(if video { b"vids" } else { b"auds" });
+ strh[4..8].copy_from_slice(if video { b"MJPG" } else { &[0; 4] });
+ let (scale, rate, ss) = if video { (1u32, 25u32, 0u32) } else { (4, 192_000, 4) };
+ strh[20..24].copy_from_slice(&scale.to_le_bytes());
+ strh[24..28].copy_from_slice(&rate.to_le_bytes());
+ strh[44..48].copy_from_slice(&ss.to_le_bytes());
+ let strf = if video {
+ let mut b = vec![0u8; 40];
+ b[..4].copy_from_slice(&40u32.to_le_bytes());
+ b[4..8].copy_from_slice(&64i32.to_le_bytes());
+ b[8..12].copy_from_slice(&48i32.to_le_bytes());
+ b[14..16].copy_from_slice(&24u16.to_le_bytes());
+ b[16..20].copy_from_slice(b"MJPG");
+ b
+ } else {
+ let mut b = vec![0u8; 18];
+ b[..2].copy_from_slice(&1u16.to_le_bytes());
+ b[2..4].copy_from_slice(&2u16.to_le_bytes());
+ b[4..8].copy_from_slice(&48_000u32.to_le_bytes());
+ b[8..12].copy_from_slice(&192_000u32.to_le_bytes());
+ b[12..14].copy_from_slice(&4u16.to_le_bytes());
+ b[14..16].copy_from_slice(&16u16.to_le_bytes());
+ b
+ };
+ let mut body = chunk(b"strh", &strh);
+ body.extend(chunk(b"strf", &strf));
+ body.extend(chunk(b"strn", if video { b"Camera\0" } else { b"Mic\0" }));
+ list(b"strl", &body)
+}
+
+/// A small AVI: 3 video frames (the second a delta, the third odd-sized) and 2 audio chunks,
+/// optionally inside a `rec ` list, with an `idx1` whose offsets are relative to `movi` or absolute.
+fn avi(idx1: bool, absolute: bool, rec: bool) -> Vec<u8> {
+ let mut avih = vec![0u8; 56];
+ avih[0..4].copy_from_slice(&40_000u32.to_le_bytes());
+ avih[12..16].copy_from_slice(&0x10u32.to_le_bytes());
+ avih[16..20].copy_from_slice(&3u32.to_le_bytes());
+ avih[24..28].copy_from_slice(&2u32.to_le_bytes());
+ avih[32..36].copy_from_slice(&64u32.to_le_bytes());
+ avih[36..40].copy_from_slice(&48u32.to_le_bytes());
+ let mut hdrl = chunk(b"avih", &avih);
+ hdrl.extend(strl(true));
+ hdrl.extend(strl(false));
+ let hdrl = list(b"hdrl", &hdrl);
+ let samples: [(&[u8; 4], Vec<u8>, bool); 5] =
+ [(b"00dc", vec![1; 10], true), (b"01wb", vec![2; 16], true), (b"00dc", vec![3; 6], false), (b"01wb", vec![4; 8], true), (b"00dc", vec![5; 7], true)];
+ let mut body = Vec::new();
+ let mut entries = Vec::new();
+ for (id, data, key) in &samples {
+ entries.push((**id, body.len() as u32 + 4, data.len() as u32, *key));
+ body.extend(chunk(id, data));
+ }
+ let movi_body = if rec {
+ let r = list(b"rec ", &body);
+ // the samples moved 12 bytes in (the rec list's header and type)
+ for e in &mut entries {
+ e.1 += 12;
+ }
+ r
+ } else {
+ body
+ };
+ let movi = list(b"movi", &movi_body);
+ let mut riff = b"AVI ".to_vec();
+ riff.extend(hdrl);
+ // position of the `movi` type id: after `RIFF` <size>, what `riff` holds so far, `LIST` <size>
+ let movi_at = (8 + riff.len() + 8) as u32;
+ riff.extend(movi);
+ if idx1 {
+ let mut ix = Vec::new();
+ for (id, off, len, key) in entries {
+ ix.extend_from_slice(&id);
+ ix.extend_from_slice(&(if key { 0x10u32 } else { 0 }).to_le_bytes());
+ ix.extend_from_slice(&(if absolute { off + movi_at } else { off }).to_le_bytes());
+ ix.extend_from_slice(&len.to_le_bytes());
+ }
+ riff.extend(chunk(b"idx1", &ix));
+ }
+ chunk(b"RIFF", &riff)
+}
+
+fn table(f: &AviFile, s: usize) -> Vec<(u32, bool)> {
+ f.streams[s].chunks.iter().map(|c| (c.size, c.key)).collect()
+}
+
+#[test]
+fn headers_and_every_index_path_agree() {
+ for (idx1, absolute, rec, want) in [
+ (true, false, false, IndexSource::Idx1),
+ (true, true, false, IndexSource::Idx1),
+ (true, false, true, IndexSource::Idx1),
+ (false, false, false, IndexSource::Scan),
+ (false, false, true, IndexSource::Scan),
+ ] {
+ let file = avi(idx1, absolute, rec);
+ let f = open(&file).unwrap();
+ let what = format!("idx1 {idx1} absolute {absolute} rec {rec}");
+ assert_eq!(f.index, want, "{what}");
+ assert_eq!((f.header.width, f.header.height, f.header.total_frames, f.header.micro_sec_per_frame), (64, 48, 3, 40_000));
+ let (v, a) = (&f.streams[0], &f.streams[1]);
+ assert_eq!((v.kind, v.handler, v.scale, v.rate, v.name.as_deref()), (StreamKind::Video, *b"MJPG", 1, 25, Some("Camera")));
+ assert_eq!(v.video.as_ref().map(|b| (b.width, b.height, b.bit_count, b.compression)), Some((64, 48, 24, *b"MJPG")));
+ let w = a.audio.as_ref().unwrap();
+ assert_eq!((w.format_tag, w.channels, w.sample_rate, w.block_align, w.bits_per_sample, a.sample_size), (1, 2, 48_000, 4, 16, 4));
+ // the index knows the delta frame; a scan cannot
+ let keys = if idx1 { [true, false, true] } else { [true; 3] };
+ assert_eq!(table(&f, 0), vec![(10, keys[0]), (6, keys[1]), (7, keys[2])], "{what}");
+ assert_eq!(f.streams[0].keyframes_known, idx1);
+ assert_eq!(table(&f, 1), vec![(16, true), (8, true)], "{what}");
+ assert_eq!(f.read_chunk(&file, 0, 1).unwrap(), vec![3; 6], "{what}");
+ assert_eq!(f.read_chunk(&file, 0, 2).unwrap(), vec![5; 7], "{what}");
+ assert_eq!(f.read_chunk(&file, 1, 1).unwrap(), vec![4; 8], "{what}");
+ assert!(f.read_chunk(&file, 0, 3).is_err() && f.read_chunk(&file, 5, 0).is_err());
+ }
+ // the idx1 path can be skipped
+ let f = open_with(&avi(true, false, false), OpenOptions { ignore_idx1: true, ..Default::default() }).unwrap();
+ assert_eq!(f.index, IndexSource::Scan);
+}
+
+#[test]
+fn not_avi_and_truncated_recordings() {
+ assert_eq!(open(&b"RIFF\0\0\0\0WAVEfmt ".to_vec()), Err(Error::NotAvi));
+ assert_eq!(open(&Vec::new()), Err(Error::NotAvi));
+ assert!(sniff(&avi(true, false, false)) && !sniff(b"RIFF"));
+ // a recording cut off in its last frame: the headers and the whole frames are there
+ let full = avi(false, false, false);
+ let cut = full[..full.len() - 4].to_vec();
+ let f = open(&cut).unwrap();
+ assert_eq!(f.streams[0].chunks.len(), 3);
+ assert!(f.read_chunk(&cut, 0, 0).is_ok());
+}
+
+/// Every single-byte change and every truncation of a valid file opens or fails, never panics, and
+/// whatever opens reads its chunks without panicking.
+#[test]
+fn mutations_never_panic() {
+ for base in [avi(true, false, true), avi(false, false, false), avi(true, true, false)] {
+ for cut in 0..base.len() {
+ let b = base[..cut].to_vec();
+ if let Ok(f) = open(&b) {
+ for (s, st) in f.streams.iter().enumerate() {
+ for i in 0..st.chunks.len() {
+ let _ = f.read_chunk(&b, s, i);
+ }
+ }
+ }
+ }
+ for at in 0..base.len() {
+ for v in [0x00u8, 0xFF, 0x7F, 0x80] {
+ let mut b = base.clone();
+ b[at] = v;
+ if let Ok(f) = open(&b) {
+ for (s, st) in f.streams.iter().enumerate() {
+ for i in 0..st.chunks.len() {
+ let _ = f.read_chunk(&b, s, i);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/// An OpenDML file: each stream's `indx` super index points at an `ix##` standard index (base
+/// offset + offsets to the data, bit 31 of the size marking delta frames). Built twice: the second
+/// pass knows where the `ix##` chunks landed.
+fn avi_odml(ix_at: [u64; 2]) -> (Vec<u8>, [u64; 2]) {
+ let indx = |stream: u8, at: u64| {
+ let mut b = Vec::new();
+ b.extend_from_slice(&4u16.to_le_bytes()); // wLongsPerEntry
+ b.extend_from_slice(&[0, 0]); // subtype, AVI_INDEX_OF_INDEXES
+ b.extend_from_slice(&1u32.to_le_bytes());
+ b.extend_from_slice(&[b'0', b'0' + stream, if stream == 0 { b'd' } else { b'w' }, if stream == 0 { b'c' } else { b'b' }]);
+ b.extend_from_slice(&[0; 12]);
+ b.extend_from_slice(&at.to_le_bytes());
+ b.extend_from_slice(&0u32.to_le_bytes());
+ b.extend_from_slice(&0u32.to_le_bytes());
+ chunk(b"indx", &b)
+ };
+ let mut hdrl = chunk(b"avih", &[0; 56]);
+ for (s, at) in ix_at.iter().enumerate() {
+ let l = strl(s == 0);
+ // strl = LIST <size> strl …: append indx inside it
+ let mut body = l[12..].to_vec();
+ body.extend(indx(s as u8, *at));
+ hdrl.extend(list(b"strl", &body));
+ }
+ let mut riff = b"AVI ".to_vec();
+ riff.extend(list(b"hdrl", &hdrl));
+ // movi: video 10 (key) 6 (delta) 7 (key), audio 16 8; then ix00, ix01
+ let movi_data_at = 8 + riff.len() as u64 + 12; // RIFF hdr, so far, LIST hdr + `movi`
+ let mut body = Vec::new();
+ let mut at: [Vec<(u64, u32, bool)>; 2] = [Vec::new(), Vec::new()];
+ for (s, data, key) in [(0usize, vec![1u8; 10], true), (1, vec![2; 16], true), (0, vec![3; 6], false), (1, vec![4; 8], true), (0, vec![5; 7], true)] {
+ let id = if s == 0 { b"00dc" } else { b"01wb" };
+ at[s].push((movi_data_at + body.len() as u64 + 8, data.len() as u32, key));
+ body.extend(chunk(id, &data));
+ }
+ let mut where_ix = [0u64; 2];
+ for (s, entries) in at.iter().enumerate() {
+ let base = 100u64; // offsets are relative to qwBaseOffset
+ let mut b = Vec::new();
+ b.extend_from_slice(&2u16.to_le_bytes());
+ b.extend_from_slice(&[0, 1]); // subtype 0, AVI_INDEX_OF_CHUNKS
+ b.extend_from_slice(&(entries.len() as u32).to_le_bytes());
+ b.extend_from_slice(if s == 0 { b"00dc" } else { b"01wb" });
+ b.extend_from_slice(&base.to_le_bytes());
+ b.extend_from_slice(&0u32.to_le_bytes());
+ for &(off, size, key) in entries {
+ b.extend_from_slice(&((off - base) as u32).to_le_bytes());
+ b.extend_from_slice(&(size | if key { 0 } else { 0x8000_0000 }).to_le_bytes());
+ }
+ where_ix[s] = movi_data_at + body.len() as u64;
+ body.extend(chunk(if s == 0 { b"ix00" } else { b"ix01" }, &b));
+ }
+ riff.extend(list(b"movi", &body));
+ (chunk(b"RIFF", &riff), where_ix)
+}
+
+#[test]
+fn opendml_standard_indexes() {
+ let (_, at) = avi_odml([0, 0]);
+ let (file, again) = avi_odml(at);
+ assert_eq!(at, again, "the layout does not depend on the offsets");
+ let f = open(&file).unwrap();
+ assert_eq!(f.index, IndexSource::OpenDml);
+ assert_eq!(table(&f, 0), vec![(10, true), (6, false), (7, true)]);
+ assert_eq!(table(&f, 1), vec![(16, true), (8, true)]);
+ assert_eq!(f.read_chunk(&file, 0, 2).unwrap(), vec![5; 7]);
+ // ignoring the OpenDML index, the scan finds the same chunks (and skips the ix## chunks)
+ let s = open_with(&file, OpenOptions { ignore_odml: true, ..Default::default() }).unwrap();
+ assert_eq!(s.index, IndexSource::Scan);
+ assert_eq!(s.streams[0].chunks.iter().map(|c| c.offset).collect::<Vec<_>>(), f.streams[0].chunks.iter().map(|c| c.offset).collect::<Vec<_>>());
+ // a broken super index (pointing nowhere) falls back to a scan
+ let (bad, _) = avi_odml([3, 5]);
+ assert_eq!(open(&bad).unwrap().index, IndexSource::Scan);
+ // and mutations of the OpenDML file never panic
+ for i in 0..file.len() {
+ let mut b = file.clone();
+ b[i] ^= 0xFF;
+ if let Ok(f) = open(&b) {
+ for (s, st) in f.streams.iter().enumerate() {
+ for k in 0..st.chunks.len() {
+ let _ = f.read_chunk(&b, s, k);
+ }
+ }
+ }
+ }
+}
diff --git a/crates/avi/tests/ffmpeg_oracle.rs b/crates/avi/tests/ffmpeg_oracle.rs
new file mode 100644
index 000000000..7f1b1662f
--- /dev/null
+++ b/crates/avi/tests/ffmpeg_oracle.rs
@@ -0,0 +1,151 @@
+//! ffmpeg-made AVI files (skipped without ffmpeg): the chunk tables match ffprobe's packet counts,
+//! and every index the file has (`idx1`; OpenDML once a file passes 1 GB) and a `movi` scan describe
+//! the same chunks.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use filmcraft_avi::{IndexSource, OpenOptions, StreamKind, open, open_with};
+
+fn fixture(name: &str, args: &[&str]) -> Option<PathBuf> {
+ let ffmpeg = filmcraft_testkit::ffmpeg_or_skip("avi oracle")?;
+ let out = filmcraft_testkit::fixtures_dir("avi").join(name);
+ filmcraft_testkit::fixtures::generate(&out, |tmp: &Path| {
+ let mut c = Command::new(&ffmpeg);
+ c.args(["-v", "error", "-y"]).args(args).args(["-f", "avi"]).arg(tmp);
+ c.status().is_ok_and(|s| s.success())
+ })
+}
+
+fn packets(path: &Path, stream: usize) -> usize {
+ let ffprobe = filmcraft_testkit::ffprobe().expect("ffprobe next to ffmpeg");
+ let out = Command::new(ffprobe)
+ .args(["-v", "error", "-select_streams", &stream.to_string(), "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0"])
+ .arg(path)
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&out.stdout).trim().parse().unwrap_or(0)
+}
+
+fn packet_bytes(path: &Path, stream: usize) -> u64 {
+ let ffprobe = filmcraft_testkit::ffprobe().expect("ffprobe next to ffmpeg");
+ let out = Command::new(ffprobe)
+ .args(["-v", "error", "-select_streams", &stream.to_string(), "-show_entries", "packet=size", "-of", "csv=p=0"])
+ .arg(path)
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| l.trim().parse::<u64>().ok()).sum()
+}
+
+const TONE: [&str; 4] = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:d=2"];
+
+fn cases() -> Vec<(&'static str, Vec<&'static str>, [u8; 4])> {
+ let pic = vec!["-f", "lavfi", "-i", "testsrc2=s=160x120:r=25:d=2"];
+ let with = |v: &[&'static str], a: &[&'static str]| -> Vec<&'static str> {
+ let mut x = pic.clone();
+ x.extend_from_slice(&TONE);
+ x.extend_from_slice(v);
+ x.extend_from_slice(a);
+ x
+ };
+ vec![
+ ("mjpeg_pcm.avi", with(&["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p"], &["-c:a", "pcm_s16le"]), *b"MJPG"),
+ ("h264_mp3.avi", with(&["-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"], &["-c:a", "libmp3lame", "-b:a", "128k"]), *b"H264"),
+ ("bgr24_pcm.avi", with(&["-c:v", "rawvideo", "-pix_fmt", "bgr24"], &["-c:a", "pcm_s16le"]), [0; 4]),
+ ("yuyv_pcm.avi", with(&["-c:v", "rawvideo", "-pix_fmt", "yuyv422"], &["-c:a", "pcm_s16le"]), *b"YUY2"),
+ ]
+}
+
+#[test]
+fn ffmpeg_files_match_ffprobe_on_every_index_path() {
+ for (name, args, fourcc) in cases() {
+ let Some(path) = fixture(name, &args) else { return };
+ let bytes = std::fs::read(&path).unwrap();
+ let f = open(&bytes).unwrap();
+ // ffmpeg reserves room for the OpenDML index but writes only idx1 under 1 GB
+ assert_eq!(f.index, IndexSource::Idx1, "{name}");
+ assert_eq!(f.streams.len(), 2, "{name}");
+ let (v, a) = (&f.streams[0], &f.streams[1]);
+ assert_eq!((v.kind, a.kind), (StreamKind::Video, StreamKind::Audio), "{name}");
+ let bmp = v.video.as_ref().unwrap();
+ assert_eq!((bmp.width, bmp.height.abs(), bmp.compression), (160, 120, fourcc), "{name}");
+ assert_eq!((v.rate as f64 / v.scale as f64).round(), 25.0, "{name}");
+ assert_eq!(a.audio.as_ref().map(|w| (w.sample_rate, w.channels)), Some((48_000, 1)), "{name}");
+ // the tables hold what ffprobe reads
+ assert_eq!(v.chunks.len(), packets(&path, 0), "{name}: video");
+ // PCM chunks are packets; ffprobe re-splits MP3 into its frames, which AVI chunks need not
+ // follow, so compressed audio compares by bytes
+ if a.audio.as_ref().is_some_and(|w| w.format_tag == 1) {
+ assert_eq!(a.chunks.len(), packets(&path, 1), "{name}: audio");
+ } else {
+ let ours: u64 = a.chunks.iter().map(|c| u64::from(c.size)).sum();
+ assert_eq!(ours, packet_bytes(&path, 1), "{name}: audio bytes");
+ }
+ assert!(v.chunks[0].key, "{name}: the first frame is a key frame");
+ if fourcc == *b"H264" {
+ assert!(v.chunks.iter().any(|c| !c.key), "{name}: the index marks the delta frames");
+ }
+ // a scan finds the same chunks (it cannot know key frames)
+ let scanned = open_with(&bytes, OpenOptions { ignore_odml: true, ignore_idx1: true }).unwrap();
+ assert_eq!(scanned.index, IndexSource::Scan, "{name}");
+ for s in 0..2 {
+ assert_eq!(sizes(&scanned, s), sizes(&f, s), "{name}: scan stream {s}");
+ }
+ }
+}
+
+fn sizes(f: &filmcraft_avi::AviFile, s: usize) -> Vec<(u64, u32)> {
+ f.streams[s].chunks.iter().map(|c| (c.offset, c.size)).collect()
+}
+
+/// A file past 1 GB, as long recordings are: ffmpeg writes `RIFF AVIX` extensions and the
+/// OpenDML index. Needs ffmpeg and 1.2 GB of disk: `cargo test -p filmcraft-avi --test
+/// ffmpeg_oracle -- --ignored`.
+#[test]
+#[ignore]
+fn opendml_file_past_1_gb() {
+ let args = [
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=s=640x480:r=25:d=50",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=440:sample_rate=48000:d=50",
+ "-c:v",
+ "rawvideo",
+ "-pix_fmt",
+ "bgr24",
+ "-c:a",
+ "pcm_s16le",
+ ];
+ let Some(path) = fixture("large_opendml.avi", &args) else { return };
+ let file = std::fs::File::open(&path).unwrap();
+ let src = FileSource(file);
+ let f = open(&src).unwrap();
+ assert_eq!(f.index, IndexSource::OpenDml);
+ assert_eq!(f.streams[0].chunks.len(), packets(&path, 0));
+ assert_eq!(f.streams[1].chunks.len(), packets(&path, 1));
+ assert_eq!(f.streams[0].chunks.len(), 1250);
+ assert!(f.streams[0].chunks.last().unwrap().offset > 1 << 30, "the last frames are in an AVIX extension");
+ // idx1 covers the first RIFF only; the AVIX extensions are scanned: the same chunks
+ let idx1 = open_with(&src, OpenOptions { ignore_odml: true, ..Default::default() }).unwrap();
+ assert_eq!(idx1.index, IndexSource::Idx1);
+ for s in 0..2 {
+ assert_eq!(sizes(&idx1, s), sizes(&f, s), "stream {s}");
+ }
+ assert_eq!(f.read_chunk(&src, 0, 1249).unwrap().len(), 640 * 480 * 3);
+}
+
+/// A file on disk as a byte source, read where asked.
+struct FileSource(std::fs::File);
+
+impl filmcraft_avi::ByteSource for FileSource {
+ fn len(&self) -> u64 {
+ self.0.metadata().map(|m| m.len()).unwrap_or(0)
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
+ std::os::unix::fs::FileExt::read_exact_at(&self.0, buf, offset)
+ }
+}
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 631678d84..e44a843e5 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -29,6 +29,7 @@ const LAYERS: &[(&str, u8)] = &[
("color", 0),
("bitstream", 0),
("isobmff", 0),
+ ("avi", 0),
("matroska", 0),
("mxf", 0),
("cfb", 0),