Skip to content

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

M1.2: filmcraft-isobmff MP4/MOV demux + mux

Brandon Thomas527f2aa1e6bd
diff --git a/Cargo.lock b/Cargo.lock
index 4f3edd481..005a3e0fe 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -74,6 +74,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "filmcraft-isobmff"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-bitstream",
+ "proptest",
+ "serde_json",
+ "thiserror",
+]
+
[[package]]
name = "filmcraft-time"
version = "0.1.0"
@@ -361,6 +371,26 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "unarray"
version = "0.1.4"
diff --git a/Cargo.toml b/Cargo.toml
index 2c249a925..cd72c06c7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,6 +16,7 @@ filmcraft-time = { path = "crates/time" }
filmcraft-geom = { path = "crates/geom" }
filmcraft-color = { path = "crates/color" }
filmcraft-bitstream = { path = "crates/bitstream" }
+filmcraft-isobmff = { path = "crates/isobmff" }
filmcraft-frame = { path = "crates/frame" }
filmcraft-media = { path = "crates/media" }
filmcraft-project = { path = "crates/project" }
diff --git a/crates/isobmff/Cargo.toml b/crates/isobmff/Cargo.toml
new file mode 100644
index 000000000..620051ad1
--- /dev/null
+++ b/crates/isobmff/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "filmcraft-isobmff"
+description = "Clean-room ISO BMFF (MP4) and QuickTime (MOV) demuxer and muxer"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+filmcraft-bitstream = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+proptest = { workspace = true }
+serde_json = { workspace = true }
diff --git a/crates/isobmff/README.md b/crates/isobmff/README.md
new file mode 100644
index 000000000..3ada2adee
--- /dev/null
+++ b/crates/isobmff/README.md
@@ -0,0 +1,144 @@
+# filmcraft-isobmff
+
+A clean-room ISO Base Media File Format (MP4, ISO/IEC 14496-12/14/15) and QuickTime (MOV) demuxer and muxer,
+written from the public specifications. Layer L0: it depends only on `filmcraft-bitstream` and `thiserror`,
+has no `unsafe`, and builds for `wasm32-unknown-unknown`.
+
+## Demuxing
+
+```rust
+use filmcraft_isobmff::{open, TrackKind};
+
+let file = std::fs::File::open("clip.mov")?;
+let mp4 = open(&file)?; // any ByteSource: &[u8], Vec<u8>, Arc<[u8]>, File, ...
+let v = mp4.track_of_kind(TrackKind::Video).unwrap();
+let track = &mp4.tracks[v];
+let i = track.sample_at_presentation_time(1000).unwrap(); // track timescale, edit-adjusted
+let key = track.sync_sample_before(i); // decode from here
+let bytes = mp4.read_sample(&file, v, key)?; // raw sample (AVCC/HVCC length-prefixed NALs, ...)
+```
+
+- `ByteSource` (`len`, `read_at(offset, buf)`) is the input abstraction. Implementations exist for `[u8]`,
+ `Vec<u8>`, `&T`, `Arc<T>`, `Box<T>`, and `std::fs::File` on non-wasm targets.
+- `open` reads only top-level box headers, `ftyp`, `moov` and every `moof`. It never reads `mdat`.
+ The one exception is the first sample of a `tmcd` track, which it reads (4 bytes) to get the timecode
+ start frame.
+- `Mp4File`: brands, `is_quicktime`, movie `timescale`/`duration`, `tracks`, `metadata`, `fragmented`,
+ `fragment_count`.
+- `Track`: `id`, `kind` (Video/Audio/Timecode/Subtitle/Other), `handler`, `timescale`, `duration`,
+ `language`, `tkhd` fields (size, matrix, volume, enabled), `entries: Vec<SampleEntry>`, `samples`,
+ `edits`, `edit_offset`, `references` (`tref`), `sdtp`, `sample_groups` (`sbgp`+`sgpd`, raw), `pcm_chunked`.
+ Helpers: `codec()`, `video()`, `audio()`, `presentation_pts(i)`, `sample_at_pts(pts)`,
+ `sample_at_presentation_time(t)`, `sync_sample_before(i)`, `sync_samples()`.
+- `Sample`: `offset`, `size`, `dts`, `pts` (dts + ctts), `duration`, `is_sync` (all samples are sync when
+ `stss` is absent), `description_index`. All times are raw media time in the track timescale.
+- **Edit lists:** `edits` holds the `elst` entries unchanged. `edit_offset` is
+ `leading empty edits (rescaled to media timescale) − first non-empty edit's media_time`, so
+ `presentation time = pts + edit_offset`. This matches ffprobe's timestamps for the common cases
+ (B-frame delay, AAC priming, empty-edit offsets). Multi-segment edits, dwells and rate changes are exposed
+ raw for the caller to interpret.
+- **Uncompressed PCM** (`lpcm`, `sowt`, `twos`, `in24`, `in32`, `fl32`, `fl64`, `raw `, `ipcm`, `fpcm`) is
+ merged to one `Sample` per chunk (`pcm_chunked = true`), with `duration` in frames. This avoids one
+ table entry per audio frame.
+
+### Parsed boxes
+`ftyp`, `moov/mvhd`, `trak/tkhd`, `edts/elst` (v0/v1), `tref`, `mdia/mdhd` (v0/v1, ISO and Mac language
+codes), `hdlr` (ISO and Pascal names), `minf/stbl`: `stsd`, `stts`, `ctts` (v0/v1, read as signed), `stss`,
+`stsc`, `stsz`/`stz2` (4/8/16-bit), `stco`/`co64`, `sdtp`, `sbgp`/`sgpd`. Also `mvex/trex`, `moof/traf/tfhd/tfdt/trun`
+(every `tfhd` base-offset mode and multiple `moof`s), and `udta` metadata (QuickTime `©xxx` atoms,
+`meta/ilst`, and `meta/keys` (mdta)). `uuid`, `free`, `skip`, `wide`, `sidx` and `mfra` are skipped.
+Boxes with 64-bit sizes and with size 0 (runs to the end of the file) are supported.
+
+### Sample entries → `CodecConfig`
+| Format | Config |
+|---|---|
+| `avc1`/`avc3` + `avcC` | `Avc(AvcConfig)`: profile, level, length size, SPS/PPS, extension bytes |
+| `hvc1`/`hev1` + `hvcC` | `Hevc(HevcConfig)`: all header fields plus NAL arrays (`vps()/sps()/pps()`) |
+| `av01` + `av1C` | `Av1(Av1Config)` |
+| `vp09` + `vpcC` | `Vp9(VpcConfig)` |
+| `apch apcn apcs apco ap4h ap4x` | `ProRes { fourcc }` |
+| `jpeg mjpa mjpb` | `Jpeg { fourcc }` |
+| `AVdn AVdh` | `Dnx { fourcc }` |
+| `mp4a` + `esds` (in `wave` too) | `Aac(AacConfig)`: ASC bytes + decoded object type/rate/channels; `Mp3` for OTI 0x69/0x6B |
+| PCM fourccs | `Pcm(PcmConfig)`: bits, float, endianness (`enda`, lpcm flags, `pcmC`), channels, rate |
+| `alac` | `Alac { cookie }` |
+| `Opus` + `dOps` | `Opus(OpusConfig)` |
+| `fLaC` + `dfLa` | `Flac(FlacConfig)` (STREAMINFO decoded) |
+| `ac-3`/`ec-3` | `Ac3 { dac3 }` / `Eac3 { dec3 }` |
+| `tmcd` | `Timecode(TimecodeConfig)`: flags (drop frame), timescale, frame duration, fps, start frame, reel name; `format_frame()` |
+| anything else | `Unknown { fourcc, raw }` |
+
+Video entries also parse `colr` (`nclx`/`nclc`/ICC), `pasp`, `clap`, `fiel`, `gama` and `btrt` into
+`VideoParams`. Audio entries parse QuickTime sound description v0/v1/v2 into `AudioParams`.
+
+### Robustness
+The parser does not panic on malformed input; every error comes back as an `Error`. Table counts are
+checked against the bytes in their box before anything is allocated. A constant-size `stsz` count is
+clamped to what fits in the file. `trun` counts are checked, and each track is capped at 2²⁶ samples.
+`moov`/`moof` are capped at 1 GiB. Compressed movie headers (`cmov`) are rejected with
+`Error::Unsupported`.
+
+## Muxing
+
+```rust
+use filmcraft_isobmff::*;
+let mut w = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4))?;
+let v = w.add_track(TrackConfig::new(SampleEntry::avc(avcc, 1920, 1080), 90_000))?;
+let mut acfg = TrackConfig::new(SampleEntry::aac(asc, 2, 48_000), 48_000);
+acfg.media_start = Some(1024); // AAC encoder delay → edit list
+let a = w.add_track(acfg)?;
+w.write_sample(v, WriteSample { data: &au, duration: 3000, composition_offset: 6000, is_sync: true })?;
+// ... interleave samples in decode order ...
+let bytes = w.finish_faststart()?.into_inner(); // or finish() for moov-at-end
+```
+
+- `Mp4Writer<W: Write + Seek>` streams samples into a single `mdat`. `finish()` appends `moov`.
+ `finish_faststart()` (needs `W: Read + Write + Seek`) moves the media data forward in place and writes
+ `moov` before it. If `mdat` goes past 4 GiB the header becomes a large-size header, and chunk offsets
+ switch to `co64` when needed.
+- Brands: `Brand::Mp4` writes `isom` with `isom iso2 avc1 mp41 mp42`. `Brand::Mov` writes `qt `, uses
+ QuickTime `hdlr`/Pascal names, and sets `wide` as the placeholder box.
+- Tables written: `stts`, `ctts` (v1 when an offset is negative), `stss` (omitted when every sample is
+ sync), `stsc`, `stsz` (constant or table), `stco`/`co64`. Consecutive samples of one track share a chunk.
+- Sample entries come from `SampleEntry` (`avc`, `hevc`, `prores`, `jpeg`, `aac`, `pcm`, or any demuxed
+ entry). Remuxing copies codec config, `colr`, `pasp`, `clap`, `fiel`, `gama` and `btrt`.
+ PCM is written as `sowt`/`twos` (16-bit) or `raw ` (8-bit) or sound description v2 `lpcm` in MOV, and as
+ `ipcm`/`fpcm` + `pcmC` in MP4. A PCM `write_sample` call can hold any whole number of frames, and the
+ track timescale must equal the sample rate.
+- Edit lists: set `TrackConfig::edits` explicitly, or use `media_start` to get a single edit.
+- Timecode: `add_timecode_track(video, TimecodeConfig, start_frame)` adds a `tmcd` track (with `gmhd`)
+ and a `tref/tmcd` link from the video track.
+- `WriterOptions::metadata` writes `©xxx` text atoms to `udta`.
+- `FragmentedWriter<W: Write>` writes fMP4. The init segment is `ftyp` + `moov` with `mvex/trex`. Each
+ `flush_fragment()` then writes `moof` (`mfhd`, `traf` with default-base-is-moof `tfhd`, `tfdt` v1,
+ `trun` with per-sample duration, size, flags and composition offset) followed by `mdat`.
+
+## Tests
+- Unit tests cover the box reader and hand-built `stbl` edge cases (stz2, co64, ctts v1, empty edits,
+ 64-bit and size-0 boxes, uuid/wide/skip), codec config round-trips, and allocation guards.
+- Property tests (`tests/roundtrip.rs`) write random multi-track files, both progressive (MP4/MOV,
+ faststart, PCM, edits) and fragmented, then read them back and compare sample tables and bytes.
+- ffprobe oracle tests (`tests/oracle_demux.rs`) run on ffmpeg-generated fixtures in
+ `target/fixtures/isobmff/`: H.264 with B-frames (MP4 and MOV), HEVC, ProRes 422/4444, MJPEG, DNxHR, PCM
+ s16le/s16be/s24le/f32le, AAC, ALAC, FLAC, Opus, AC-3, VP9, AV1, fragmented (with and without
+ default-base-is-moof), faststart, an edit-list cut, `tmcd` at 29.97 DF and 23.976, and colr/pasp. They
+ compare packet offsets, sizes, pts/dts, durations and key flags, plus stream parameters. Tests skip
+ with a message when ffmpeg or an encoder is missing.
+- Muxer oracle tests (`tests/oracle_mux.rs`) remux fixtures with our writers. They check that
+ `ffmpeg -v error -f null` reports nothing, that ffprobe packets and stream parameters match the source,
+ and that timecode, the AAC priming edit, ipcm and fMP4 output are correct.
+- Mutation fuzzing (`tests/fuzz.rs`) uses a deterministic seed to mutate and truncate synthetic and
+ ffmpeg files, and checks that nothing panics.
+
+## Limitations / not yet supported
+- `presentation time = pts + edit_offset` only applies the leading empty edits and the first media
+ edit. Multi-segment edit lists, dwell edits and non-unity rates are exposed raw. ffmpeg handles an edit
+ that starts mid-frame differently: it snaps to the frame.
+- Other data references (external `alis`/`url ` files), encrypted entries (`encv`/`enca`, `sinf`,
+ `senc`), `cmov`, and QuickTime reference movies are not supported.
+- `sidx`/`mfra` are ignored, because the demuxer scans every top-level box. `stsd` entries with a
+ QuickTime colour table are not decoded.
+- Subtitle and text tracks (`tx3g`, `c608`, `wvtt`) and `mp4v` show up as `Unknown`.
+- Muxer: one `mdat`, no chunk-size or duration limits (the caller controls interleaving), no `sdtp`,
+ `sgpd`/`sbgp` or `cslg` output, ISO-style `meta/ilst` metadata is not written, and the fragmented
+ writer has no PCM, `sidx` or `mfra`.
diff --git a/crates/isobmff/src/bytes.rs b/crates/isobmff/src/bytes.rs
new file mode 100644
index 000000000..97f92690b
--- /dev/null
+++ b/crates/isobmff/src/bytes.rs
@@ -0,0 +1,361 @@
+//! Low-level helpers: four-character codes, a bounds-checked big-endian cursor, box iteration
+//! over in-memory payloads, and a box builder for the muxers.
+
+use crate::error::{Error, Result};
+use std::fmt;
+
+/// A four-character code (box type, sample entry format, brand, handler type…).
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
+pub struct FourCc(pub [u8; 4]);
+
+impl FourCc {
+ pub const fn new(b: &[u8; 4]) -> Self {
+ FourCc(*b)
+ }
+ pub fn as_u32(self) -> u32 {
+ u32::from_be_bytes(self.0)
+ }
+ /// Lossy string form; `©` (0xA9) is mapped to U+00A9, other non-printables to `?`.
+ pub fn to_string_lossy(self) -> String {
+ self.0
+ .iter()
+ .map(|&b| match b {
+ 0xA9 => '©',
+ 0x20..=0x7E => b as char,
+ _ => '?',
+ })
+ .collect()
+ }
+}
+
+impl fmt::Display for FourCc {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.to_string_lossy())
+ }
+}
+impl fmt::Debug for FourCc {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "FourCc({:?})", self.to_string_lossy())
+ }
+}
+impl From<&[u8; 4]> for FourCc {
+ fn from(b: &[u8; 4]) -> Self {
+ FourCc(*b)
+ }
+}
+impl PartialEq<[u8; 4]> for FourCc {
+ fn eq(&self, other: &[u8; 4]) -> bool {
+ &self.0 == other
+ }
+}
+impl PartialEq<&[u8; 4]> for FourCc {
+ fn eq(&self, other: &&[u8; 4]) -> bool {
+ &self.0 == *other
+ }
+}
+impl PartialEq<&&[u8; 4]> for FourCc {
+ fn eq(&self, other: &&&[u8; 4]) -> bool {
+ &self.0 == **other
+ }
+}
+
+/// Bounds-checked big-endian cursor over a byte slice.
+#[derive(Clone)]
+pub(crate) struct Cur<'a> {
+ pub data: &'a [u8],
+ pub pos: usize,
+ what: &'static str,
+}
+
+impl<'a> Cur<'a> {
+ pub fn new(data: &'a [u8], what: &'static str) -> Self {
+ Cur { data, pos: 0, what }
+ }
+ pub fn remaining(&self) -> usize {
+ self.data.len().saturating_sub(self.pos)
+ }
+ pub fn rest(&self) -> &'a [u8] {
+ self.data.get(self.pos..).unwrap_or(&[])
+ }
+ pub fn bytes(&mut self, n: usize) -> Result<&'a [u8]> {
+ let end = self.pos.checked_add(n).ok_or(Error::Truncated(self.what))?;
+ let s = self.data.get(self.pos..end).ok_or(Error::Truncated(self.what))?;
+ self.pos = end;
+ Ok(s)
+ }
+ pub fn skip(&mut self, n: usize) -> Result<()> {
+ self.bytes(n).map(|_| ())
+ }
+ pub fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
+ let s = self.bytes(N)?;
+ let mut a = [0u8; N];
+ a.copy_from_slice(s);
+ Ok(a)
+ }
+ pub fn u8(&mut self) -> Result<u8> {
+ Ok(self.array::<1>()?[0])
+ }
+ pub fn u16(&mut self) -> Result<u16> {
+ Ok(u16::from_be_bytes(self.array()?))
+ }
+ pub fn i16(&mut self) -> Result<i16> {
+ Ok(i16::from_be_bytes(self.array()?))
+ }
+ pub fn u24(&mut self) -> Result<u32> {
+ let a = self.array::<3>()?;
+ Ok(((a[0] as u32) << 16) | ((a[1] as u32) << 8) | a[2] as u32)
+ }
+ pub fn u32(&mut self) -> Result<u32> {
+ Ok(u32::from_be_bytes(self.array()?))
+ }
+ pub fn i32(&mut self) -> Result<i32> {
+ Ok(i32::from_be_bytes(self.array()?))
+ }
+ pub fn u64(&mut self) -> Result<u64> {
+ Ok(u64::from_be_bytes(self.array()?))
+ }
+ pub fn i64(&mut self) -> Result<i64> {
+ Ok(i64::from_be_bytes(self.array()?))
+ }
+ pub fn f64(&mut self) -> Result<f64> {
+ Ok(f64::from_be_bytes(self.array()?))
+ }
+ pub fn fourcc(&mut self) -> Result<FourCc> {
+ Ok(FourCc(self.array()?))
+ }
+ /// Full-box header: (version, flags).
+ pub fn full_header(&mut self) -> Result<(u8, u32)> {
+ let v = self.u32()?;
+ Ok(((v >> 24) as u8, v & 0x00FF_FFFF))
+ }
+ /// Read a count and verify that `count * entry_size` bytes remain (allocation guard).
+ pub fn count(&mut self, entry_size: usize) -> Result<usize> {
+ let n = self.u32()? as usize;
+ self.check_count(n, entry_size)?;
+ Ok(n)
+ }
+ pub fn check_count(&self, n: usize, entry_size: usize) -> Result<()> {
+ match n.checked_mul(entry_size) {
+ Some(b) if b <= self.remaining() => Ok(()),
+ _ => Err(Error::Truncated(self.what)),
+ }
+ }
+}
+
+/// Header of one box as found in a byte stream.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct BoxHeader {
+ pub kind: FourCc,
+ /// Header length including largesize and uuid extended type.
+ pub header_len: u64,
+ /// Total box size including header; `None` means "extends to end of the enclosing container".
+ pub size: Option<u64>,
+ pub uuid: Option<[u8; 16]>,
+}
+
+/// Parse a box header from `buf` (needs up to 32 bytes; fewer if available).
+pub(crate) fn parse_box_header(buf: &[u8]) -> Result<BoxHeader> {
+ let mut c = Cur::new(buf, "box header");
+ let size32 = c.u32()?;
+ let kind = c.fourcc()?;
+ let mut header_len = 8u64;
+ let size = match size32 {
+ 0 => None,
+ 1 => {
+ header_len += 8;
+ let s = c.u64()?;
+ Some(s)
+ }
+ s => Some(s as u64),
+ };
+ let uuid = if kind == b"uuid" {
+ header_len += 16;
+ Some(c.array::<16>()?)
+ } else {
+ None
+ };
+ if let Some(s) = size
+ && s < header_len
+ {
+ return Err(Error::Invalid(format!("box '{kind}' size {s} smaller than its header")));
+ }
+ Ok(BoxHeader { kind, header_len, size, uuid })
+}
+
+/// One child box inside an in-memory payload.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct RawBox<'a> {
+ pub kind: FourCc,
+ pub payload: &'a [u8],
+ #[allow(dead_code)]
+ pub uuid: Option<[u8; 16]>,
+}
+
+/// Iterator over the child boxes of a payload. Yields an error for a malformed box and then stops.
+pub(crate) struct Boxes<'a> {
+ data: &'a [u8],
+ pos: usize,
+ done: bool,
+}
+
+pub(crate) fn boxes(data: &[u8]) -> Boxes<'_> {
+ Boxes { data, pos: 0, done: false }
+}
+
+impl<'a> Iterator for Boxes<'a> {
+ type Item = Result<RawBox<'a>>;
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.done {
+ return None;
+ }
+ let rest = &self.data[self.pos..];
+ if rest.is_empty() {
+ self.done = true;
+ return None;
+ }
+ // QuickTime allows a 32-bit zero terminator at the end of some containers.
+ if rest.len() < 8 {
+ self.done = true;
+ if rest.iter().all(|&b| b == 0) {
+ return None;
+ }
+ return Some(Err(Error::Truncated("box header")));
+ }
+ let h = match parse_box_header(rest) {
+ Ok(h) => h,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ let size = h.size.unwrap_or(rest.len() as u64);
+ if size > rest.len() as u64 {
+ self.done = true;
+ return Some(Err(Error::Invalid(format!("box '{}' size {} exceeds its container ({} bytes left)", h.kind, size, rest.len()))));
+ }
+ let size = size as usize;
+ let payload = &rest[h.header_len as usize..size];
+ self.pos += size;
+ Some(Ok(RawBox { kind: h.kind, payload, uuid: h.uuid }))
+ }
+}
+
+/// Find the first child of the given type (malformed trailing children are ignored).
+pub(crate) fn find<'a>(data: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
+ boxes(data).map_while(|b| b.ok()).find(|b| b.kind == kind).map(|b| b.payload)
+}
+
+/// Growable buffer for building boxes.
+#[derive(Default, Clone, Debug)]
+pub(crate) struct BoxBuf {
+ pub buf: Vec<u8>,
+}
+
+impl BoxBuf {
+ pub fn new() -> Self {
+ Self::default()
+ }
+ /// Begin a box; returns a marker to pass to [`end`](Self::end).
+ pub fn start(&mut self, kind: &[u8; 4]) -> usize {
+ let at = self.buf.len();
+ self.buf.extend_from_slice(&[0, 0, 0, 0]);
+ self.buf.extend_from_slice(kind);
+ at
+ }
+ pub fn start_full(&mut self, kind: &[u8; 4], version: u8, flags: u32) -> usize {
+ let at = self.start(kind);
+ self.u32(((version as u32) << 24) | (flags & 0xFF_FFFF));
+ at
+ }
+ pub fn end(&mut self, at: usize) {
+ let size = (self.buf.len() - at) as u32;
+ self.buf[at..at + 4].copy_from_slice(&size.to_be_bytes());
+ }
+ /// Append a complete box with the given payload.
+ pub fn leaf(&mut self, kind: &[u8; 4], payload: &[u8]) {
+ let at = self.start(kind);
+ self.bytes(payload);
+ self.end(at);
+ }
+ pub fn u8(&mut self, v: u8) {
+ self.buf.push(v);
+ }
+ pub fn u16(&mut self, v: u16) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn i16(&mut self, v: i16) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn u32(&mut self, v: u32) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn i32(&mut self, v: i32) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn u64(&mut self, v: u64) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn i64(&mut self, v: i64) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn f64(&mut self, v: f64) {
+ self.buf.extend_from_slice(&v.to_be_bytes());
+ }
+ pub fn bytes(&mut self, b: &[u8]) {
+ self.buf.extend_from_slice(b);
+ }
+ pub fn zeros(&mut self, n: usize) {
+ self.buf.resize(self.buf.len() + n, 0);
+ }
+ pub fn len(&self) -> usize {
+ self.buf.len()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn header_forms() {
+ let h = parse_box_header(&[0, 0, 0, 16, b'f', b'r', b'e', b'e']).unwrap();
+ assert_eq!((h.kind, h.header_len, h.size), (FourCc(*b"free"), 8, Some(16)));
+ let h = parse_box_header(&[0, 0, 0, 0, b'm', b'd', b'a', b't']).unwrap();
+ assert_eq!(h.size, None);
+ let mut v = vec![0, 0, 0, 1, b'm', b'd', b'a', b't'];
+ v.extend_from_slice(&100u64.to_be_bytes());
+ let h = parse_box_header(&v).unwrap();
+ assert_eq!((h.header_len, h.size), (16, Some(100)));
+ let mut v = vec![0, 0, 0, 30, b'u', b'u', b'i', b'd'];
+ v.extend_from_slice(&[7u8; 16]);
+ let h = parse_box_header(&v).unwrap();
+ assert_eq!((h.header_len, h.uuid), (24, Some([7u8; 16])));
+ assert!(parse_box_header(&[0, 0, 0, 4, b'f', b'r', b'e', b'e']).is_err());
+ assert!(parse_box_header(&[0, 0, 0]).is_err());
+ }
+
+ #[test]
+ fn iterate_children() {
+ let mut b = BoxBuf::new();
+ b.leaf(b"aaaa", &[1, 2]);
+ let m = b.start(b"bbbb");
+ b.leaf(b"cccc", &[]);
+ b.end(m);
+ b.u32(0); // QT terminator
+ let kids: Vec<_> = boxes(&b.buf).collect::<Result<Vec<_>>>().unwrap();
+ assert_eq!(kids.len(), 2);
+ assert_eq!(kids[0].payload, &[1, 2]);
+ assert_eq!(find(&b.buf, b"bbbb").map(|p| p.len()), Some(8));
+ // Oversized child → error, no panic.
+ let bad = [0u8, 0, 0, 99, b'x', b'x', b'x', b'x', 0];
+ assert!(boxes(&bad).next().unwrap().is_err());
+ }
+
+ #[test]
+ fn cursor_bounds() {
+ let mut c = Cur::new(&[0, 0, 0, 5, 1], "t");
+ assert!(c.count(1).is_err());
+ let mut c = Cur::new(&[0xFF, 0xFF, 0xFF, 0xFF], "t");
+ assert!(c.count(usize::MAX).is_err());
+ }
+}
diff --git a/crates/isobmff/src/codec.rs b/crates/isobmff/src/codec.rs
new file mode 100644
index 000000000..f61122fb6
--- /dev/null
+++ b/crates/isobmff/src/codec.rs
@@ -0,0 +1,1479 @@
+//! Sample entries (`stsd` children) and codec configuration records: parsing and serialization.
+
+use crate::bytes::{BoxBuf, Cur, FourCc, boxes};
+use crate::error::{Error, Result};
+use filmcraft_bitstream::BitReader;
+
+/// One sample description (an entry of `stsd`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct SampleEntry {
+ /// Sample entry format (`avc1`, `mp4a`, `apch`, …).
+ pub format: FourCc,
+ pub data_reference_index: u16,
+ pub codec: CodecConfig,
+ /// Present for visual sample entries.
+ pub video: Option<VideoParams>,
+ /// Present for audio sample entries.
+ pub audio: Option<AudioParams>,
+ /// `btrt` box.
+ pub bitrate: Option<BitRate>,
+}
+
+/// Fields common to all visual sample entries plus the optional descriptive boxes.
+#[derive(Clone, Debug, PartialEq, Default)]
+pub struct VideoParams {
+ pub width: u16,
+ pub height: u16,
+ /// Horizontal/vertical resolution in pixels per inch (16.16 fixed point; 72 dpi = 0x0048_0000).
+ pub horiz_resolution: u32,
+ pub vert_resolution: u32,
+ pub frame_count: u16,
+ pub compressor_name: String,
+ pub depth: u16,
+ /// QuickTime `vendor` / version fields (zero in ISO files).
+ pub vendor: FourCc,
+ pub temporal_quality: u32,
+ pub spatial_quality: u32,
+ pub color: Option<ColorInfo>,
+ /// `pasp`: (hSpacing, vSpacing).
+ pub pixel_aspect: Option<(u32, u32)>,
+ pub clean_aperture: Option<CleanAperture>,
+ pub field_info: Option<FieldInfo>,
+ /// QuickTime `gama` (16.16 fixed point).
+ pub gamma: Option<u32>,
+}
+
+/// `colr` box contents.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ColorInfo {
+ /// ISO `nclx` (with full-range flag).
+ Nclx { primaries: u16, transfer: u16, matrix: u16, full_range: bool },
+ /// QuickTime `nclc`.
+ Nclc { primaries: u16, transfer: u16, matrix: u16 },
+ /// Embedded ICC profile (`prof` restricted/unrestricted `rICC`).
+ Icc { kind: FourCc, profile: Vec<u8> },
+}
+
+/// `clap` clean aperture (all rationals num/den; offsets are signed).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct CleanAperture {
+ pub width: (u32, u32),
+ pub height: (u32, u32),
+ pub horiz_offset: (i32, u32),
+ pub vert_offset: (i32, u32),
+}
+
+/// QuickTime `fiel`: field count (1 progressive, 2 interlaced) and ordering detail
+/// (0, 1 = top first, 6 = bottom first, 9 / 14 per the QuickTime spec).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct FieldInfo {
+ pub fields: u8,
+ pub detail: u8,
+}
+
+/// `btrt` box.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct BitRate {
+ pub buffer_size: u32,
+ pub max_bitrate: u32,
+ pub avg_bitrate: u32,
+}
+
+/// Fields of audio sample entries (ISO v0 plus QuickTime sound description v1/v2 extensions).
+#[derive(Clone, Debug, PartialEq, Default)]
+pub struct AudioParams {
+ /// QuickTime sound description version (0, 1, 2). ISO files use 0.
+ pub qt_version: u16,
+ pub channels: u32,
+ /// Bits per sample from the entry (16 for most compressed formats).
+ pub sample_size: u16,
+ pub sample_rate: f64,
+ pub compression_id: i16,
+ /// v1 fields.
+ pub samples_per_packet: u32,
+ pub bytes_per_packet: u32,
+ pub bytes_per_frame: u32,
+ pub bytes_per_sample: u32,
+ /// v2 fields.
+ pub const_bits_per_channel: u32,
+ pub lpcm_flags: u32,
+ pub const_bytes_per_packet: u32,
+ pub const_frames_per_packet: u32,
+ /// `enda` little-endian flag inside a QuickTime `wave` box.
+ pub little_endian: Option<bool>,
+}
+
+/// Codec configuration decoded from the sample entry.
+#[derive(Clone, Debug, PartialEq)]
+pub enum CodecConfig {
+ Avc(AvcConfig),
+ Hevc(HevcConfig),
+ Av1(Av1Config),
+ Vp9(VpcConfig),
+ /// Apple ProRes; fourcc is `apch`/`apcn`/`apcs`/`apco`/`ap4h`/`ap4x`.
+ ProRes {
+ fourcc: FourCc,
+ },
+ /// Motion JPEG (`jpeg`, `mjpa`, `mjpb`).
+ Jpeg {
+ fourcc: FourCc,
+ },
+ /// Avid DNxHD/DNxHR (`AVdn`, `AVdh`).
+ Dnx {
+ fourcc: FourCc,
+ },
+ Aac(AacConfig),
+ /// MPEG-1/2 audio layer III (esds object type 0x69/0x6B, or QuickTime `.mp3`).
+ Mp3,
+ Pcm(PcmConfig),
+ /// ALAC magic cookie (ALACSpecificConfig, 24 bytes, optionally followed by a channel layout).
+ Alac {
+ cookie: Vec<u8>,
+ },
+ Opus(OpusConfig),
+ Flac(FlacConfig),
+ /// `dac3` payload.
+ Ac3 {
+ dac3: Vec<u8>,
+ },
+ /// `dec3` payload.
+ Eac3 {
+ dec3: Vec<u8>,
+ },
+ Timecode(TimecodeConfig),
+ /// Anything else; `raw` is the full sample entry payload (after the 8-byte box header).
+ Unknown {
+ fourcc: FourCc,
+ raw: Vec<u8>,
+ },
+}
+
+impl CodecConfig {
+ /// A short human-readable codec name.
+ pub fn name(&self) -> &'static str {
+ match self {
+ CodecConfig::Avc(_) => "h264",
+ CodecConfig::Hevc(_) => "hevc",
+ CodecConfig::Av1(_) => "av1",
+ CodecConfig::Vp9(_) => "vp9",
+ CodecConfig::ProRes { .. } => "prores",
+ CodecConfig::Jpeg { .. } => "mjpeg",
+ CodecConfig::Dnx { .. } => "dnxhd",
+ CodecConfig::Aac(_) => "aac",
+ CodecConfig::Mp3 => "mp3",
+ CodecConfig::Pcm(_) => "pcm",
+ CodecConfig::Alac { .. } => "alac",
+ CodecConfig::Opus(_) => "opus",
+ CodecConfig::Flac(_) => "flac",
+ CodecConfig::Ac3 { .. } => "ac3",
+ CodecConfig::Eac3 { .. } => "eac3",
+ CodecConfig::Timecode(_) => "timecode",
+ CodecConfig::Unknown { .. } => "unknown",
+ }
+ }
+}
+
+/// `avcC` — AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3).
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct AvcConfig {
+ pub profile: u8,
+ pub compatibility: u8,
+ pub level: u8,
+ /// NAL length field size in bytes (1, 2 or 4).
+ pub length_size: u8,
+ pub sps: Vec<Vec<u8>>,
+ pub pps: Vec<Vec<u8>>,
+ /// Bytes after the PPS list (high-profile extension: chroma format, bit depths, SPS-ext).
+ pub ext: Vec<u8>,
+}
+
+impl AvcConfig {
+ /// Build from parameter sets (NAL units without start codes); profile/level taken from the first SPS.
+ pub fn new(sps: Vec<Vec<u8>>, pps: Vec<Vec<u8>>, length_size: u8) -> Self {
+ let (profile, compatibility, level) = sps.first().filter(|s| s.len() >= 4).map(|s| (s[1], s[2], s[3])).unwrap_or((0, 0, 0));
+ AvcConfig { profile, compatibility, level, length_size, sps, pps, ext: Vec::new() }
+ }
+
+ pub fn parse(data: &[u8]) -> Result<Self> {
+ let mut c = Cur::new(data, "avcC");
+ let _version = c.u8()?;
+ let profile = c.u8()?;
+ let compatibility = c.u8()?;
+ let level = c.u8()?;
+ let length_size = (c.u8()? & 3) + 1;
+ let nsps = (c.u8()? & 0x1F) as usize;
+ let mut sps = Vec::with_capacity(nsps);
+ for _ in 0..nsps {
+ let n = c.u16()? as usize;
+ sps.push(c.bytes(n)?.to_vec());
+ }
+ let npps = c.u8()? as usize;
+ let mut pps = Vec::with_capacity(npps);
+ for _ in 0..npps {
+ let n = c.u16()? as usize;
+ pps.push(c.bytes(n)?.to_vec());
+ }
+ Ok(AvcConfig { profile, compatibility, level, length_size, sps, pps, ext: c.rest().to_vec() })
+ }
+
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ b.u8(1);
+ b.u8(self.profile);
+ b.u8(self.compatibility);
+ b.u8(self.level);
+ b.u8(0xFC | (self.length_size.clamp(1, 4) - 1));
+ b.u8(0xE0 | (self.sps.len().min(31) as u8));
+ for s in self.sps.iter().take(31) {
+ b.u16(s.len() as u16);
+ b.bytes(s);
+ }
+ b.u8(self.pps.len().min(255) as u8);
+ for p in self.pps.iter().take(255) {
+ b.u16(p.len() as u16);
+ b.bytes(p);
+ }
+ b.bytes(&self.ext);
+ b.buf
+ }
+}
+
+/// One NAL array of an `hvcC` record.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct HevcNalArray {
+ pub completeness: bool,
+ pub nal_type: u8,
+ pub nalus: Vec<Vec<u8>>,
+}
+
+/// `hvcC` — HEVCDecoderConfigurationRecord (ISO/IEC 14496-15 §8.3.3).
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct HevcConfig {
+ pub general_profile_space: u8,
+ pub general_tier_flag: bool,
+ pub general_profile_idc: u8,
+ pub general_profile_compatibility_flags: u32,
+ /// 48 bits of general constraint indicator flags.
+ pub general_constraint_indicator_flags: u64,
+ pub general_level_idc: u8,
+ pub min_spatial_segmentation_idc: u16,
+ pub parallelism_type: u8,
+ pub chroma_format_idc: u8,
+ pub bit_depth_luma: u8,
+ pub bit_depth_chroma: u8,
+ pub avg_frame_rate: u16,
+ pub constant_frame_rate: u8,
+ pub num_temporal_layers: u8,
+ pub temporal_id_nested: bool,
+ pub length_size: u8,
+ pub arrays: Vec<HevcNalArray>,
+}
+
+impl HevcConfig {
+ pub fn parse(data: &[u8]) -> Result<Self> {
+ let mut c = Cur::new(data, "hvcC");
+ let _version = c.u8()?;
+ let b = c.u8()?;
+ let compat = c.u32()?;
+ let hi = c.u16()? as u64;
+ let lo = c.u32()? as u64;
+ let level = c.u8()?;
+ let min_seg = c.u16()? & 0x0FFF;
+ let par = c.u8()? & 3;
+ let chroma = c.u8()? & 3;
+ let bdl = (c.u8()? & 7) + 8;
+ let bdc = (c.u8()? & 7) + 8;
+ let afr = c.u16()?;
+ let x = c.u8()?;
+ let narrays = c.u8()? as usize;
+ let mut arrays = Vec::new();
+ for _ in 0..narrays {
+ let t = c.u8()?;
+ let n = c.u16()? as usize;
+ c.check_count(n, 2)?;
+ let mut nalus = Vec::with_capacity(n);
+ for _ in 0..n {
+ let len = c.u16()? as usize;
+ nalus.push(c.bytes(len)?.to_vec());
+ }
+ arrays.push(HevcNalArray { completeness: t & 0x80 != 0, nal_type: t & 0x3F, nalus });
+ }
+ Ok(HevcConfig {
+ general_profile_space: b >> 6,
+ general_tier_flag: b & 0x20 != 0,
+ general_profile_idc: b & 0x1F,
+ general_profile_compatibility_flags: compat,
+ general_constraint_indicator_flags: (hi << 32) | lo,
+ general_level_idc: level,
+ min_spatial_segmentation_idc: min_seg,
+ parallelism_type: par,
+ chroma_format_idc: chroma,
+ bit_depth_luma: bdl,
+ bit_depth_chroma: bdc,
+ avg_frame_rate: afr,
+ constant_frame_rate: x >> 6,
+ num_temporal_layers: (x >> 3) & 7,
+ temporal_id_nested: x & 4 != 0,
+ length_size: (x & 3) + 1,
+ arrays,
+ })
+ }
+
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ b.u8(1);
+ b.u8((self.general_profile_space << 6) | ((self.general_tier_flag as u8) << 5) | (self.general_profile_idc & 0x1F));
+ b.u32(self.general_profile_compatibility_flags);
+ b.u16((self.general_constraint_indicator_flags >> 32) as u16);
+ b.u32(self.general_constraint_indicator_flags as u32);
+ b.u8(self.general_level_idc);
+ b.u16(0xF000 | (self.min_spatial_segmentation_idc & 0x0FFF));
+ b.u8(0xFC | (self.parallelism_type & 3));
+ b.u8(0xFC | (self.chroma_format_idc & 3));
+ b.u8(0xF8 | (self.bit_depth_luma.saturating_sub(8) & 7));
+ b.u8(0xF8 | (self.bit_depth_chroma.saturating_sub(8) & 7));
+ b.u16(self.avg_frame_rate);
+ b.u8((self.constant_frame_rate << 6)
+ | ((self.num_temporal_layers & 7) << 3)
+ | ((self.temporal_id_nested as u8) << 2)
+ | (self.length_size.clamp(1, 4) - 1));
+ b.u8(self.arrays.len() as u8);
+ for a in &self.arrays {
+ b.u8(((a.completeness as u8) << 7) | (a.nal_type & 0x3F));
+ b.u16(a.nalus.len() as u16);
+ for n in &a.nalus {
+ b.u16(n.len() as u16);
+ b.bytes(n);
+ }
+ }
+ b.buf
+ }
+
+ fn nalus_of(&self, t: u8) -> Vec<&[u8]> {
+ self.arrays.iter().filter(|a| a.nal_type == t).flat_map(|a| a.nalus.iter().map(|n| n.as_slice())).collect()
+ }
+ pub fn vps(&self) -> Vec<&[u8]> {
+ self.nalus_of(32)
+ }
+ pub fn sps(&self) -> Vec<&[u8]> {
+ self.nalus_of(33)
+ }
+ pub fn pps(&self) -> Vec<&[u8]> {
+ self.nalus_of(34)
+ }
+}
+
+/// `av1C` — AV1CodecConfigurationRecord.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct Av1Config {
+ pub seq_profile: u8,
+ pub seq_level_idx_0: u8,
+ pub seq_tier_0: bool,
+ pub high_bitdepth: bool,
+ pub twelve_bit: bool,
+ pub monochrome: bool,
+ pub chroma_subsampling_x: bool,
+ pub chroma_subsampling_y: bool,
+ pub chroma_sample_position: u8,
+ pub initial_presentation_delay_minus_one: Option<u8>,
+ pub config_obus: Vec<u8>,
+}
+
+impl Av1Config {
+ pub fn parse(data: &[u8]) -> Result<Self> {
+ let mut c = Cur::new(data, "av1C");
+ let m = c.u8()?;
+ if m & 0x80 == 0 {
+ return Err(Error::Invalid("av1C marker bit not set".into()));
+ }
+ let a = c.u8()?;
+ let b = c.u8()?;
+ let d = c.u8()?;
+ Ok(Av1Config {
+ seq_profile: a >> 5,
+ seq_level_idx_0: a & 0x1F,
+ seq_tier_0: b & 0x80 != 0,
+ high_bitdepth: b & 0x40 != 0,
+ twelve_bit: b & 0x20 != 0,
+ monochrome: b & 0x10 != 0,
+ chroma_subsampling_x: b & 0x08 != 0,
+ chroma_subsampling_y: b & 0x04 != 0,
+ chroma_sample_position: b & 3,
+ initial_presentation_delay_minus_one: if d & 0x10 != 0 { Some(d & 0x0F) } else { None },
+ config_obus: c.rest().to_vec(),
+ })
+ }
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ b.u8(0x81);
+ b.u8((self.seq_profile << 5) | (self.seq_level_idx_0 & 0x1F));
+ b.u8(((self.seq_tier_0 as u8) << 7)
+ | ((self.high_bitdepth as u8) << 6)
+ | ((self.twelve_bit as u8) << 5)
+ | ((self.monochrome as u8) << 4)
+ | ((self.chroma_subsampling_x as u8) << 3)
+ | ((self.chroma_subsampling_y as u8) << 2)
+ | (self.chroma_sample_position & 3));
+ b.u8(match self.initial_presentation_delay_minus_one {
+ Some(d) => 0x10 | (d & 0x0F),
+ None => 0,
+ });
+ b.bytes(&self.config_obus);
+ b.buf
+ }
+}
+
+/// `vpcC` — VP codec configuration (version 1).
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct VpcConfig {
+ pub profile: u8,
+ pub level: u8,
+ pub bit_depth: u8,
+ pub chroma_subsampling: u8,
+ pub full_range: bool,
+ pub colour_primaries: u8,
+ pub transfer_characteristics: u8,
+ pub matrix_coefficients: u8,
+ pub codec_init: Vec<u8>,
+}
+
+impl VpcConfig {
+ pub fn parse(data: &[u8]) -> Result<Self> {
+ let mut c = Cur::new(data, "vpcC");
+ let (version, _) = c.full_header()?;
+ if version == 0 {
+ // Version 0 draft layout: profile, level, bitDepth(4)|colorSpace(4), chroma(4)|transfer(3)|range(1)
+ let profile = c.u8()?;
+ let level = c.u8()?;
+ let a = c.u8()?;
+ let b = c.u8()?;
+ return Ok(VpcConfig { profile, level, bit_depth: a >> 4, chroma_subsampling: b >> 4, full_range: b & 1 != 0, ..Default::default() });
+ }
+ let profile = c.u8()?;
+ let level = c.u8()?;
+ let a = c.u8()?;
+ let colour_primaries = c.u8()?;
+ let transfer_characteristics = c.u8()?;
+ let matrix_coefficients = c.u8()?;
+ let n = c.u16()? as usize;
+ let codec_init = c.bytes(n)?.to_vec();
+ Ok(VpcConfig {
+ profile,
+ level,
+ bit_depth: a >> 4,
+ chroma_subsampling: (a >> 1) & 7,
+ full_range: a & 1 != 0,
+ colour_primaries,
+ transfer_characteristics,
+ matrix_coefficients,
+ codec_init,
+ })
+ }
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ b.u32(1 << 24);
+ b.u8(self.profile);
+ b.u8(self.level);
+ b.u8((self.bit_depth << 4) | ((self.chroma_subsampling & 7) << 1) | self.full_range as u8);
+ b.u8(self.colour_primaries);
+ b.u8(self.transfer_characteristics);
+ b.u8(self.matrix_coefficients);
+ b.u16(self.codec_init.len() as u16);
+ b.bytes(&self.codec_init);
+ b.buf
+ }
+}
+
+/// AAC (MPEG-4 audio) configuration from `esds`.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct AacConfig {
+ /// AudioSpecificConfig bytes (DecoderSpecificInfo).
+ pub asc: Vec<u8>,
+ /// Audio object type (2 = AAC-LC, 5 = SBR/HE-AAC, 29 = PS …) as signalled first in the ASC.
+ pub object_type: u8,
+ /// Sampling rate signalled by the ASC (core rate; 0 if the ASC is missing).
+ pub sample_rate: u32,
+ /// Channel configuration from the ASC (0 = defined elsewhere).
+ pub channel_config: u8,
+ /// DecoderConfigDescriptor fields.
+ pub max_bitrate: u32,
+ pub avg_bitrate: u32,
+ pub buffer_size: u32,
+}
+
+const AAC_RATES: [u32; 13] = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
+
+impl AacConfig {
+ /// Build from an AudioSpecificConfig, decoding its header fields.
+ pub fn from_asc(asc: Vec<u8>) -> Self {
+ let (object_type, sample_rate, channel_config) = parse_asc(&asc).unwrap_or((0, 0, 0));
+ AacConfig { asc, object_type, sample_rate, channel_config, max_bitrate: 0, avg_bitrate: 0, buffer_size: 0 }
+ }
+ /// Channel count implied by the channel configuration (0 if unspecified).
+ pub fn channels(&self) -> u32 {
+ match self.channel_config {
+ 1..=6 => self.channel_config as u32,
+ 7 => 8,
+ _ => 0,
+ }
+ }
+}
+
+/// Decode (audio object type, sampling frequency, channel configuration) from an AudioSpecificConfig.
+pub fn parse_asc(asc: &[u8]) -> Option<(u8, u32, u8)> {
+ let mut r = BitReader::new(asc);
+ let aot = |r: &mut BitReader| -> Option<u8> {
+ let t = r.read_bits(5).ok()? as u8;
+ if t == 31 { Some(32 + r.read_bits(6).ok()? as u8) } else { Some(t) }
+ };
+ let rate = |r: &mut BitReader| -> Option<u32> {
+ let i = r.read_bits(4).ok()? as usize;
+ if i == 15 { r.read_bits(24).ok() } else { AAC_RATES.get(i).copied() }
+ };
+ let t = aot(&mut r)?;
+ let sr = rate(&mut r)?;
+ let ch = r.read_bits(4).ok()? as u8;
+ Some((t, sr, ch))
+}
+
+/// Uncompressed PCM description.
+#[derive(Clone, Copy, Debug, PartialEq, Default)]
+pub struct PcmConfig {
+ pub bits: u16,
+ pub float: bool,
+ pub big_endian: bool,
+ /// Signed integer samples (8-bit `raw ` is unsigned).
+ pub signed: bool,
+ pub channels: u32,
+ pub sample_rate: f64,
+}
+
+impl PcmConfig {
+ /// Bytes per interleaved audio frame (all channels).
+ pub fn bytes_per_frame(&self) -> u32 {
+ (self.bits as u32).div_ceil(8) * self.channels.max(1)
+ }
+}
+
+/// `dOps` — Opus specific box.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct OpusConfig {
+ pub output_channels: u8,
+ pub pre_skip: u16,
+ pub input_sample_rate: u32,
+ pub output_gain: i16,
+ pub channel_mapping_family: u8,
+ /// StreamCount, CoupledCount and ChannelMapping bytes when family != 0.
+ pub channel_mapping: Vec<u8>,
+}
+
+impl OpusConfig {
+ pub fn parse(data: &[u8]) -> Result<Self> {
+ let mut c = Cur::new(data, "dOps");
+ let _version = c.u8()?;
+ Ok(OpusConfig {
+ output_channels: c.u8()?,
+ pre_skip: c.u16()?,
+ input_sample_rate: c.u32()?,
+ output_gain: c.i16()?,
+ channel_mapping_family: c.u8()?,
+ channel_mapping: c.rest().to_vec(),
+ })
+ }
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ b.u8(0);
+ b.u8(self.output_channels);
+ b.u16(self.pre_skip);
+ b.u32(self.input_sample_rate);
+ b.i16(self.output_gain);
+ b.u8(self.channel_mapping_family);
+ b.bytes(&self.channel_mapping);
+ b.buf
+ }
+}
+
+/// `dfLa` — FLAC metadata blocks, with STREAMINFO decoded.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct FlacConfig {
+ /// Raw metadata blocks (each with its 4-byte header) as stored in `dfLa`.
+ pub metadata_blocks: Vec<u8>,
+ pub sample_rate: u32,
+ pub channels: u8,
+ pub bits_per_sample: u8,
+ pub total_samples: u64,
+}
+
+impl FlacConfig {
+ pub fn parse(data: &[u8]) -> Result<Self> {
+ let mut c = Cur::new(data, "dfLa");
+ c.full_header()?;
+ let blocks = c.rest().to_vec();
+ let mut cfg = FlacConfig { metadata_blocks: blocks.clone(), ..Default::default() };
+ let mut b = Cur::new(&blocks, "dfLa");
+ let hdr = b.u32()?;
+ if (hdr >> 24) & 0x7F == 0 {
+ let si = b.bytes(((hdr & 0xFF_FFFF) as usize).min(34))?;
+ if si.len() >= 18 {
+ let mut r = BitReader::new(&si[10..18]);
+ cfg.sample_rate = r.read_bits(20).unwrap_or(0);
+ cfg.channels = r.read_bits(3).unwrap_or(0) as u8 + 1;
+ cfg.bits_per_sample = r.read_bits(5).unwrap_or(0) as u8 + 1;
+ cfg.total_samples = r.read_bits_u64(36).unwrap_or(0);
+ }
+ }
+ Ok(cfg)
+ }
+}
+
+/// QuickTime timecode sample description (`tmcd`) plus the start frame read from its first sample.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct TimecodeConfig {
+ /// Bit 0 drop frame, bit 1 24-hour max, bit 2 negative times OK, bit 3 counter.
+ pub flags: u32,
+ pub timescale: u32,
+ pub frame_duration: u32,
+ /// Nominal frames per second (`numberOfFrames`), e.g. 30 for 29.97.
+ pub frames_per_second: u8,
+ /// Frame number of the first timecode sample (filled in by the demuxer).
+ pub start_frame: Option<u32>,
+ /// Source reel name (`name` box) if present.
+ pub name: Option<String>,
+}
+
+impl TimecodeConfig {
+ pub fn drop_frame(&self) -> bool {
+ self.flags & 1 != 0
+ }
+ /// Format a frame number as `HH:MM:SS:FF` (`;` before the frames when drop-frame).
+ pub fn format_frame(&self, frame: u32) -> String {
+ let fps = self.frames_per_second.max(1) as u64;
+ let mut f = frame as u64;
+ if self.drop_frame() && fps >= 30 {
+ let drop = (fps / 30) * 2; // 2 frames per minute at 30, 4 at 60
+ let per_min = fps * 60 - drop;
+ let per_10 = per_min * 10 + drop;
+ let d = f / per_10;
+ let m = f % per_10;
+ f += drop * 9 * d + if m > drop { drop * ((m - drop) / per_min) } else { 0 };
+ }
+ let ff = f % fps;
+ let s = (f / fps) % 60;
+ let mi = (f / fps / 60) % 60;
+ let h = (f / fps / 3600) % 24;
+ let sep = if self.drop_frame() { ';' } else { ':' };
+ format!("{h:02}:{mi:02}:{s:02}{sep}{ff:02}")
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Parsing
+
+fn is_video_fourcc(f: &[u8; 4]) -> bool {
+ matches!(
+ f,
+ b"avc1"
+ | b"avc3"
+ | b"hvc1"
+ | b"hev1"
+ | b"av01"
+ | b"vp09"
+ | b"vp08"
+ | b"apch"
+ | b"apcn"
+ | b"apcs"
+ | b"apco"
+ | b"ap4h"
+ | b"ap4x"
+ | b"jpeg"
+ | b"mjpa"
+ | b"mjpb"
+ | b"AVdn"
+ | b"AVdh"
+ | b"mp4v"
+ | b"encv"
+ | b"raw "
+ | b"2vuy"
+ | b"v210"
+ )
+}
+
+fn is_audio_fourcc(f: &[u8; 4]) -> bool {
+ matches!(
+ f,
+ b"mp4a"
+ | b"lpcm"
+ | b"sowt"
+ | b"twos"
+ | b"in24"
+ | b"in32"
+ | b"fl32"
+ | b"fl64"
+ | b"ipcm"
+ | b"fpcm"
+ | b"alac"
+ | b"Opus"
+ | b"fLaC"
+ | b"ac-3"
+ | b"ec-3"
+ | b".mp3"
+ | b"enca"
+ | b"ulaw"
+ | b"alaw"
+ | b"NONE"
+ )
+}
+
+/// Parse one `stsd` entry. `handler` is the track handler type; `is_qt` selects QuickTime
+/// interpretation of the sound description version field.
+pub(crate) fn parse_sample_entry(format: FourCc, payload: &[u8], handler: FourCc, is_qt: bool) -> Result<SampleEntry> {
+ let mut c = Cur::new(payload, "sample entry");
+ c.skip(6)?;
+ let data_reference_index = c.u16()?;
+ let f = &format.0;
+ let unknown = || CodecConfig::Unknown { fourcc: format, raw: payload.to_vec() };
+ if f == b"tmcd" || (handler == b"tmcd" && !is_video_fourcc(f)) {
+ let mut tc = TimecodeConfig::default();
+ c.skip(4)?;
+ tc.flags = c.u32()?;
+ tc.timescale = c.u32()?;
+ tc.frame_duration = c.u32()?;
+ tc.frames_per_second = c.u8()?;
+ c.skip(1)?;
+ for b in boxes(c.rest()).map_while(|b| b.ok()) {
+ if b.kind == b"name" && b.payload.len() >= 4 {
+ let n = u16::from_be_bytes([b.payload[0], b.payload[1]]) as usize;
+ let s = b.payload.get(4..4 + n).unwrap_or(&b.payload[4..]);
+ tc.name = Some(String::from_utf8_lossy(s).into_owned());
+ }
+ }
+ return Ok(SampleEntry { format, data_reference_index, codec: CodecConfig::Timecode(tc), video: None, audio: None, bitrate: None });
+ }
+ let video_like = is_video_fourcc(f) || (handler == b"vide" && !is_audio_fourcc(f));
+ let audio_like = is_audio_fourcc(f) || (handler == b"soun" && !video_like);
+ if video_like {
+ let mut v = VideoParams::default();
+ let _version = c.u16()?;
+ let _revision = c.u16()?;
+ v.vendor = c.fourcc()?;
+ v.temporal_quality = c.u32()?;
+ v.spatial_quality = c.u32()?;
+ v.width = c.u16()?;
+ v.height = c.u16()?;
+ v.horiz_resolution = c.u32()?;
+ v.vert_resolution = c.u32()?;
+ c.skip(4)?;
+ v.frame_count = c.u16()?;
+ let name = c.bytes(32)?;
+ let n = (name[0] as usize).min(31);
+ v.compressor_name = String::from_utf8_lossy(&name[1..1 + n]).into_owned();
+ v.depth = c.u16()?;
+ let _ctab = c.i16()?;
+ let mut codec = None;
+ let mut bitrate = None;
+ for b in boxes(c.rest()).map_while(|b| b.ok()) {
+ let p = b.payload;
+ match &b.kind.0 {
+ b"avcC" if matches!(f, b"avc1" | b"avc3") => codec = Some(CodecConfig::Avc(AvcConfig::parse(p)?)),
+ b"hvcC" if matches!(f, b"hvc1" | b"hev1") => codec = Some(CodecConfig::Hevc(HevcConfig::parse(p)?)),
+ b"av1C" if f == b"av01" => codec = Some(CodecConfig::Av1(Av1Config::parse(p)?)),
+ b"vpcC" if f == b"vp09" => codec = Some(CodecConfig::Vp9(VpcConfig::parse(p)?)),
+ b"colr" => v.color = parse_colr(p).ok(),
+ b"pasp" => {
+ let mut c = Cur::new(p, "pasp");
+ v.pixel_aspect = Some((c.u32()?, c.u32()?));
+ }
+ b"clap" => {
+ let mut c = Cur::new(p, "clap");
+ v.clean_aperture = Some(CleanAperture {
+ width: (c.u32()?, c.u32()?),
+ height: (c.u32()?, c.u32()?),
+ horiz_offset: (c.i32()?, c.u32()?),
+ vert_offset: (c.i32()?, c.u32()?),
+ });
+ }
+ b"fiel" => {
+ let mut c = Cur::new(p, "fiel");
+ v.field_info = Some(FieldInfo { fields: c.u8()?, detail: c.u8()? });
+ }
+ b"gama" => v.gamma = Some(Cur::new(p, "gama").u32()?),
+ b"btrt" => bitrate = Some(parse_btrt(p)?),
+ _ => {}
+ }
+ }
+ let codec = match codec {
+ Some(c) => c,
+ None => match f {
+ b"apch" | b"apcn" | b"apcs" | b"apco" | b"ap4h" | b"ap4x" => CodecConfig::ProRes { fourcc: format },
+ b"jpeg" | b"mjpa" | b"mjpb" => CodecConfig::Jpeg { fourcc: format },
+ b"AVdn" | b"AVdh" => CodecConfig::Dnx { fourcc: format },
+ _ => unknown(),
+ },
+ };
+ return Ok(SampleEntry { format, data_reference_index, codec, video: Some(v), audio: None, bitrate });
+ }
+ if audio_like {
+ let mut a = AudioParams { qt_version: c.u16()?, ..Default::default() };
+ let _revision = c.u16()?;
+ let _vendor = c.u32()?;
+ a.channels = c.u16()? as u32;
+ a.sample_size = c.u16()?;
+ a.compression_id = c.i16()?;
+ let _packet_size = c.u16()?;
+ a.sample_rate = c.u32()? as f64 / 65536.0;
+ if is_qt && a.qt_version == 1 {
+ a.samples_per_packet = c.u32()?;
+ a.bytes_per_packet = c.u32()?;
+ a.bytes_per_frame = c.u32()?;
+ a.bytes_per_sample = c.u32()?;
+ } else if is_qt && a.qt_version == 2 {
+ let _size_of_struct = c.u32()?;
+ a.sample_rate = c.f64()?;
+ a.channels = c.u32()?;
+ let _always = c.u32()?;
+ a.const_bits_per_channel = c.u32()?;
+ a.lpcm_flags = c.u32()?;
+ a.const_bytes_per_packet = c.u32()?;
+ a.const_frames_per_packet = c.u32()?;
+ }
+ // Flatten QuickTime `wave` children into the list of extension boxes.
+ let mut ext: Vec<(FourCc, &[u8])> = Vec::new();
+ for b in boxes(c.rest()).map_while(|b| b.ok()) {
+ if b.kind == b"wave" {
+ for w in boxes(b.payload).map_while(|b| b.ok()) {
+ ext.push((w.kind, w.payload));
+ }
+ } else {
+ ext.push((b.kind, b.payload));
+ }
+ }
+ let get = |k: &[u8; 4]| ext.iter().find(|(kk, _)| kk == k).map(|(_, p)| *p);
+ if let Some(p) = get(b"enda") {
+ let v = if p.len() >= 2 { u16::from_be_bytes([p[0], p[1]]) } else { p.first().copied().unwrap_or(0) as u16 };
+ a.little_endian = Some(v != 0);
+ }
+ let bitrate = get(b"btrt").and_then(|p| parse_btrt(p).ok());
+ let codec = match f {
+ b"mp4a" => match get(b"esds") {
+ Some(p) => parse_esds(p)?,
+ None => unknown(),
+ },
+ b".mp3" => CodecConfig::Mp3,
+ b"alac" => match get(b"alac") {
+ Some(p) if p.len() >= 4 => CodecConfig::Alac { cookie: p[4..].to_vec() },
+ _ => unknown(),
+ },
+ b"Opus" => match get(b"dOps") {
+ Some(p) => CodecConfig::Opus(OpusConfig::parse(p)?),
+ None => unknown(),
+ },
+ b"fLaC" => match get(b"dfLa") {
+ Some(p) => CodecConfig::Flac(FlacConfig::parse(p)?),
+ None => unknown(),
+ },
+ b"ac-3" => CodecConfig::Ac3 { dac3: get(b"dac3").unwrap_or(&[]).to_vec() },
+ b"ec-3" => CodecConfig::Eac3 { dec3: get(b"dec3").unwrap_or(&[]).to_vec() },
+ b"lpcm" | b"sowt" | b"twos" | b"in24" | b"in32" | b"fl32" | b"fl64" | b"raw " | b"NONE" => CodecConfig::Pcm(qt_pcm(f, &a)),
+ b"ipcm" | b"fpcm" => {
+ let mut pcm =
+ PcmConfig { bits: a.sample_size, float: f == b"fpcm", big_endian: true, signed: true, channels: a.channels, sample_rate: a.sample_rate };
+ if let Some(p) = get(b"pcmC") {
+ let mut c = Cur::new(p, "pcmC");
+ c.full_header()?;
+ let flags = c.u8()?;
+ pcm.big_endian = flags & 1 == 0;
+ pcm.bits = c.u8()? as u16;
+ }
+ CodecConfig::Pcm(pcm)
+ }
+ _ => unknown(),
+ };
+ return Ok(SampleEntry { format, data_reference_index, codec, video: None, audio: Some(a), bitrate });
+ }
+ Ok(SampleEntry { format, data_reference_index, codec: unknown(), video: None, audio: None, bitrate: None })
+}
+
+fn qt_pcm(f: &[u8; 4], a: &AudioParams) -> PcmConfig {
+ let mut p = PcmConfig { channels: a.channels, sample_rate: a.sample_rate, signed: true, ..Default::default() };
+ match f {
+ b"lpcm" => {
+ p.bits = a.const_bits_per_channel as u16;
+ p.float = a.lpcm_flags & 1 != 0;
+ p.big_endian = a.lpcm_flags & 2 != 0;
+ p.signed = a.lpcm_flags & 4 != 0 || p.float;
+ if p.bits == 0 {
+ p.bits = a.sample_size;
+ }
+ }
+ b"sowt" => {
+ p.bits = if a.sample_size == 0 { 16 } else { a.sample_size };
+ }
+ b"twos" => {
+ p.bits = if a.sample_size == 0 { 16 } else { a.sample_size };
+ p.big_endian = true;
+ }
+ b"raw " | b"NONE" => {
+ p.bits = if a.sample_size == 0 { 8 } else { a.sample_size };
+ p.signed = p.bits != 8;
+ p.big_endian = true;
+ }
+ b"in24" | b"in32" | b"fl32" | b"fl64" => {
+ p.bits = match f {
+ b"in24" => 24,
+ b"in32" | b"fl32" => 32,
+ _ => 64,
+ };
+ p.float = f[0] == b'f';
+ p.big_endian = !a.little_endian.unwrap_or(false);
+ }
+ _ => {}
+ }
+ p
+}
+
+fn parse_btrt(p: &[u8]) -> Result<BitRate> {
+ let mut c = Cur::new(p, "btrt");
+ Ok(BitRate { buffer_size: c.u32()?, max_bitrate: c.u32()?, avg_bitrate: c.u32()? })
+}
+
+fn parse_colr(p: &[u8]) -> Result<ColorInfo> {
+ let mut c = Cur::new(p, "colr");
+ let kind = c.fourcc()?;
+ Ok(match &kind.0 {
+ b"nclx" => ColorInfo::Nclx { primaries: c.u16()?, transfer: c.u16()?, matrix: c.u16()?, full_range: c.u8().map(|v| v & 0x80 != 0).unwrap_or(false) },
+ b"nclc" => ColorInfo::Nclc { primaries: c.u16()?, transfer: c.u16()?, matrix: c.u16()? },
+ _ => ColorInfo::Icc { kind, profile: c.rest().to_vec() },
+ })
+}
+
+fn descriptor(c: &mut Cur) -> Result<(u8, usize)> {
+ let tag = c.u8()?;
+ let mut len = 0usize;
+ for _ in 0..4 {
+ let b = c.u8()?;
+ len = (len << 7) | (b & 0x7F) as usize;
+ if b & 0x80 == 0 {
+ break;
+ }
+ }
+ Ok((tag, len))
+}
+
+fn parse_esds(p: &[u8]) -> Result<CodecConfig> {
+ let mut c = Cur::new(p, "esds");
+ c.full_header()?;
+ let (tag, len) = descriptor(&mut c)?;
+ if tag != 3 {
+ return Err(Error::Invalid(format!("esds: expected ES_Descriptor, got tag {tag}")));
+ }
+ let es = c.bytes(len.min(c.remaining()))?;
+ let mut c = Cur::new(es, "ES_Descriptor");
+ c.u16()?;
+ let fl = c.u8()?;
+ if fl & 0x80 != 0 {
+ c.u16()?;
+ }
+ if fl & 0x40 != 0 {
+ let n = c.u8()? as usize;
+ c.skip(n)?;
+ }
+ if fl & 0x20 != 0 {
+ c.u16()?;
+ }
+ while c.remaining() > 0 {
+ let (tag, len) = descriptor(&mut c)?;
+ let body = c.bytes(len.min(c.remaining()))?;
+ if tag != 4 {
+ continue;
+ }
+ let mut d = Cur::new(body, "DecoderConfigDescriptor");
+ let oti = d.u8()?;
+ let _stream_type = d.u8()?;
+ let buffer_size = d.u24()?;
+ let max_bitrate = d.u32()?;
+ let avg_bitrate = d.u32()?;
+ let mut asc = Vec::new();
+ while d.remaining() > 0 {
+ let (t, l) = descriptor(&mut d)?;
+ let b = d.bytes(l.min(d.remaining()))?;
+ if t == 5 {
+ asc = b.to_vec();
+ break;
+ }
+ }
+ return Ok(match oti {
+ 0x69 | 0x6B => CodecConfig::Mp3,
+ _ => {
+ let mut a = AacConfig::from_asc(asc);
+ a.max_bitrate = max_bitrate;
+ a.avg_bitrate = avg_bitrate;
+ a.buffer_size = buffer_size;
+ CodecConfig::Aac(a)
+ }
+ });
+ }
+ Err(Error::Invalid("esds without DecoderConfigDescriptor".into()))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Serialization (muxer)
+
+fn put_descriptor(b: &mut BoxBuf, tag: u8, body: &[u8]) {
+ b.u8(tag);
+ let n = body.len() as u32;
+ // Always use the 4-byte length form for simplicity (as many encoders do).
+ b.u8(0x80 | ((n >> 21) & 0x7F) as u8);
+ b.u8(0x80 | ((n >> 14) & 0x7F) as u8);
+ b.u8(0x80 | ((n >> 7) & 0x7F) as u8);
+ b.u8((n & 0x7F) as u8);
+ b.bytes(body);
+}
+
+pub(crate) fn esds_payload(oti: u8, asc: &[u8], max_bitrate: u32, avg_bitrate: u32, buffer_size: u32) -> Vec<u8> {
+ let mut dcd = BoxBuf::new();
+ dcd.u8(oti);
+ dcd.u8(0x15); // streamType audio (5) << 2 | upstream 0 | reserved 1
+ dcd.u8((buffer_size >> 16) as u8);
+ dcd.u16(buffer_size as u16);
+ dcd.u32(max_bitrate);
+ dcd.u32(avg_bitrate);
+ if !asc.is_empty() {
+ put_descriptor(&mut dcd, 5, asc);
+ }
+ let mut es = BoxBuf::new();
+ es.u16(1); // ES_ID
+ es.u8(0);
+ put_descriptor(&mut es, 4, &dcd.buf);
+ put_descriptor(&mut es, 6, &[2]); // SLConfigDescriptor, predefined = 2 (MP4)
+ let mut b = BoxBuf::new();
+ b.u32(0);
+ put_descriptor(&mut b, 3, &es.buf);
+ b.buf
+}
+
+impl SampleEntry {
+ /// Convenience constructor for a video entry.
+ pub fn video(format: FourCc, codec: CodecConfig, width: u16, height: u16) -> Self {
+ let compressor_name = match &codec {
+ CodecConfig::ProRes { fourcc } => match &fourcc.0 {
+ b"apch" => "Apple ProRes 422 HQ",
+ b"apcn" => "Apple ProRes 422",
+ b"apcs" => "Apple ProRes 422 LT",
+ b"apco" => "Apple ProRes 422 Proxy",
+ b"ap4h" => "Apple ProRes 4444",
+ _ => "Apple ProRes 4444 XQ",
+ },
+ CodecConfig::Jpeg { .. } => "Photo - JPEG",
+ _ => "",
+ };
+ SampleEntry {
+ format,
+ data_reference_index: 1,
+ codec,
+ video: Some(VideoParams {
+ width,
+ height,
+ horiz_resolution: 0x0048_0000,
+ vert_resolution: 0x0048_0000,
+ frame_count: 1,
+ compressor_name: compressor_name.into(),
+ depth: 24,
+ ..Default::default()
+ }),
+ audio: None,
+ bitrate: None,
+ }
+ }
+
+ /// Convenience constructor for an audio entry (ISO v0 layout; the muxer upgrades PCM in MOV to v2).
+ pub fn audio(format: FourCc, codec: CodecConfig, channels: u32, sample_rate: f64, sample_size: u16) -> Self {
+ SampleEntry {
+ format,
+ data_reference_index: 1,
+ codec,
+ video: None,
+ audio: Some(AudioParams { channels, sample_rate, sample_size, ..Default::default() }),
+ bitrate: None,
+ }
+ }
+
+ /// H.264 entry (`avc1`).
+ pub fn avc(cfg: AvcConfig, width: u16, height: u16) -> Self {
+ Self::video(FourCc(*b"avc1"), CodecConfig::Avc(cfg), width, height)
+ }
+ /// HEVC entry (`hvc1`, parameter sets in the config only).
+ pub fn hevc(cfg: HevcConfig, width: u16, height: u16) -> Self {
+ Self::video(FourCc(*b"hvc1"), CodecConfig::Hevc(cfg), width, height)
+ }
+ /// ProRes entry; `fourcc` one of `apch`/`apcn`/`apcs`/`apco`/`ap4h`/`ap4x`.
+ pub fn prores(fourcc: FourCc, width: u16, height: u16) -> Self {
+ let mut e = Self::video(fourcc, CodecConfig::ProRes { fourcc }, width, height);
+ if let Some(v) = e.video.as_mut()
+ && matches!(&fourcc.0, b"ap4h" | b"ap4x")
+ {
+ v.depth = 32;
+ }
+ e
+ }
+ /// Motion-JPEG entry (`jpeg`).
+ pub fn jpeg(width: u16, height: u16) -> Self {
+ let f = FourCc(*b"jpeg");
+ Self::video(f, CodecConfig::Jpeg { fourcc: f }, width, height)
+ }
+ /// AAC entry (`mp4a` + `esds`) from an AudioSpecificConfig.
+ pub fn aac(asc: Vec<u8>, channels: u32, sample_rate: u32) -> Self {
+ Self::audio(FourCc(*b"mp4a"), CodecConfig::Aac(AacConfig::from_asc(asc)), channels, sample_rate as f64, 16)
+ }
+ /// PCM entry. The muxer picks the on-disk format (`sowt`/`twos`/`lpcm` for MOV, `ipcm`/`fpcm` for MP4).
+ pub fn pcm(cfg: PcmConfig) -> Self {
+ Self::audio(FourCc(*b"lpcm"), CodecConfig::Pcm(cfg), cfg.channels, cfg.sample_rate, cfg.bits)
+ }
+
+ /// Serialize as a complete sample entry box. For PCM the format is chosen from the brand.
+ pub(crate) fn write(&self, b: &mut BoxBuf, qt: bool) -> Result<()> {
+ if let CodecConfig::Unknown { fourcc, raw } = &self.codec {
+ let m = b.start(&fourcc.0);
+ b.bytes(raw);
+ b.end(m);
+ return Ok(());
+ }
+ if let CodecConfig::Timecode(tc) = &self.codec {
+ let m = b.start(b"tmcd");
+ b.zeros(6);
+ b.u16(self.data_reference_index);
+ b.u32(0);
+ b.u32(tc.flags);
+ b.u32(tc.timescale);
+ b.u32(tc.frame_duration);
+ b.u8(tc.frames_per_second);
+ b.u8(0);
+ if let Some(name) = &tc.name {
+ let n = b.start(b"name");
+ b.u16(name.len() as u16);
+ b.u16(0);
+ b.bytes(name.as_bytes());
+ b.end(n);
+ }
+ b.end(m);
+ return Ok(());
+ }
+ if let Some(v) = &self.video {
+ let m = b.start(&self.format.0);
+ b.zeros(6);
+ b.u16(self.data_reference_index);
+ b.u16(0);
+ b.u16(0);
+ b.u32(v.vendor.as_u32());
+ b.u32(v.temporal_quality);
+ b.u32(v.spatial_quality);
+ b.u16(v.width);
+ b.u16(v.height);
+ b.u32(v.horiz_resolution);
+ b.u32(v.vert_resolution);
+ b.u32(0);
+ b.u16(v.frame_count);
+ let name = v.compressor_name.as_bytes();
+ let n = name.len().min(31);
+ let mut nb = [0u8; 32];
+ nb[0] = n as u8;
+ nb[1..1 + n].copy_from_slice(&name[..n]);
+ b.bytes(&nb);
+ b.u16(v.depth);
+ b.i16(-1);
+ match &self.codec {
+ CodecConfig::Avc(c) => b.leaf(b"avcC", &c.to_bytes()),
+ CodecConfig::Hevc(c) => b.leaf(b"hvcC", &c.to_bytes()),
+ CodecConfig::Av1(c) => b.leaf(b"av1C", &c.to_bytes()),
+ CodecConfig::Vp9(c) => b.leaf(b"vpcC", &c.to_bytes()),
+ _ => {}
+ }
+ if let Some(g) = v.gamma {
+ b.leaf(b"gama", &g.to_be_bytes());
+ }
+ if let Some(fi) = v.field_info {
+ b.leaf(b"fiel", &[fi.fields, fi.detail]);
+ }
+ if let Some(ci) = &v.color {
+ let m = b.start(b"colr");
+ match ci {
+ ColorInfo::Nclx { primaries, transfer, matrix, full_range } => {
+ b.bytes(b"nclx");
+ b.u16(*primaries);
+ b.u16(*transfer);
+ b.u16(*matrix);
+ b.u8(if *full_range { 0x80 } else { 0 });
+ }
+ ColorInfo::Nclc { primaries, transfer, matrix } => {
+ b.bytes(b"nclc");
+ b.u16(*primaries);
+ b.u16(*transfer);
+ b.u16(*matrix);
+ }
+ ColorInfo::Icc { kind, profile } => {
+ b.bytes(&kind.0);
+ b.bytes(profile);
+ }
+ }
+ b.end(m);
+ }
+ if let Some((h, vv)) = v.pixel_aspect {
+ let m = b.start(b"pasp");
+ b.u32(h);
+ b.u32(vv);
+ b.end(m);
+ }
+ if let Some(c) = v.clean_aperture {
+ let m = b.start(b"clap");
+ b.u32(c.width.0);
+ b.u32(c.width.1);
+ b.u32(c.height.0);
+ b.u32(c.height.1);
+ b.i32(c.horiz_offset.0);
+ b.u32(c.horiz_offset.1);
+ b.i32(c.vert_offset.0);
+ b.u32(c.vert_offset.1);
+ b.end(m);
+ }
+ if let Some(br) = self.bitrate {
+ write_btrt(b, br);
+ }
+ b.end(m);
+ return Ok(());
+ }
+ let a = self.audio.clone().ok_or_else(|| Error::Mux("sample entry has neither video nor audio params".into()))?;
+ // Choose the on-disk format and sound description version.
+ let (format, version, pcm) = match &self.codec {
+ CodecConfig::Pcm(p) => {
+ if qt {
+ if p.bits == 16 && !p.float {
+ (if p.big_endian { *b"twos" } else { *b"sowt" }, 0u16, Some(*p))
+ } else if p.bits == 8 && !p.float {
+ (*b"raw ", 0, Some(*p))
+ } else {
+ (*b"lpcm", 2, Some(*p))
+ }
+ } else {
+ (if p.float { *b"fpcm" } else { *b"ipcm" }, 0, Some(*p))
+ }
+ }
+ _ => (self.format.0, if qt { a.qt_version.min(2) } else { 0 }, None),
+ };
+ let m = b.start(&format);
+ b.zeros(6);
+ b.u16(self.data_reference_index);
+ if version == 2 {
+ let p = pcm.unwrap_or_default();
+ b.u16(2);
+ b.u16(0);
+ b.u32(0);
+ b.u16(3);
+ b.u16(16);
+ b.i16(-2);
+ b.u16(0);
+ b.u32(65536);
+ b.u32(72);
+ b.f64(p.sample_rate);
+ b.u32(p.channels);
+ b.u32(0x7F00_0000);
+ b.u32(p.bits as u32);
+ let flags = (p.float as u32) | ((p.big_endian as u32) << 1) | (((p.signed && !p.float) as u32) << 2) | 8;
+ b.u32(flags);
+ b.u32(p.bytes_per_frame());
+ b.u32(1);
+ } else {
+ b.u16(version);
+ b.u16(0);
+ b.u32(0);
+ b.u16(a.channels.min(u16::MAX as u32) as u16);
+ b.u16(match pcm {
+ Some(p) => p.bits,
+ None => {
+ if a.sample_size == 0 {
+ 16
+ } else {
+ a.sample_size
+ }
+ }
+ });
+ b.i16(if version == 1 { a.compression_id } else { 0 });
+ b.u16(0);
+ let sr = if a.sample_rate < 65536.0 { (a.sample_rate * 65536.0).round() as u32 } else { 0 };
+ b.u32(sr);
+ if version == 1 {
+ b.u32(a.samples_per_packet);
+ b.u32(a.bytes_per_packet);
+ b.u32(a.bytes_per_frame);
+ b.u32(a.bytes_per_sample);
+ }
+ }
+ match &self.codec {
+ CodecConfig::Aac(c) => {
+ b.leaf(b"esds", &esds_payload(0x40, &c.asc, c.max_bitrate, c.avg_bitrate, c.buffer_size));
+ }
+ CodecConfig::Mp3 => {
+ if format == *b"mp4a" {
+ b.leaf(b"esds", &esds_payload(0x6B, &[], 0, 0, 0));
+ }
+ }
+ CodecConfig::Alac { cookie } => {
+ let m = b.start_full(b"alac", 0, 0);
+ b.bytes(cookie);
+ b.end(m);
+ }
+ CodecConfig::Opus(o) => b.leaf(b"dOps", &o.to_bytes()),
+ CodecConfig::Flac(fl) => {
+ let m = b.start_full(b"dfLa", 0, 0);
+ b.bytes(&fl.metadata_blocks);
+ b.end(m);
+ }
+ CodecConfig::Ac3 { dac3 } => b.leaf(b"dac3", dac3),
+ CodecConfig::Eac3 { dec3 } => b.leaf(b"dec3", dec3),
+ CodecConfig::Pcm(p) if !qt => {
+ let m = b.start_full(b"pcmC", 0, 0);
+ b.u8(if p.big_endian { 0 } else { 1 });
+ b.u8(p.bits as u8);
+ b.end(m);
+ }
+ _ => {}
+ }
+ if let Some(br) = self.bitrate {
+ write_btrt(b, br);
+ }
+ b.end(m);
+ Ok(())
+ }
+}
+
+fn write_btrt(b: &mut BoxBuf, br: BitRate) {
+ let m = b.start(b"btrt");
+ b.u32(br.buffer_size);
+ b.u32(br.max_bitrate);
+ b.u32(br.avg_bitrate);
+ b.end(m);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn roundtrip(e: &SampleEntry, qt: bool, handler: &[u8; 4]) -> SampleEntry {
+ let mut b = BoxBuf::new();
+ e.write(&mut b, qt).unwrap();
+ let bx = crate::bytes::boxes(&b.buf).next().unwrap().unwrap();
+ parse_sample_entry(bx.kind, bx.payload, FourCc(*handler), qt).unwrap()
+ }
+
+ #[test]
+ fn avcc_roundtrip() {
+ let cfg = AvcConfig::new(vec![vec![0x67, 0x64, 0x00, 0x1F, 0xAC]], vec![vec![0x68, 0xEB]], 4);
+ assert_eq!(cfg.profile, 0x64);
+ assert_eq!(AvcConfig::parse(&cfg.to_bytes()).unwrap(), cfg);
+ let mut e = SampleEntry::avc(cfg, 1920, 1080);
+ e.video.as_mut().unwrap().color = Some(ColorInfo::Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false });
+ e.video.as_mut().unwrap().pixel_aspect = Some((4, 3));
+ e.video.as_mut().unwrap().field_info = Some(FieldInfo { fields: 2, detail: 9 });
+ e.video.as_mut().unwrap().clean_aperture = Some(CleanAperture { width: (1920, 1), height: (1080, 1), horiz_offset: (-2, 1), vert_offset: (0, 1) });
+ e.bitrate = Some(BitRate { buffer_size: 1, max_bitrate: 2, avg_bitrate: 3 });
+ assert_eq!(roundtrip(&e, false, b"vide"), e);
+ }
+
+ #[test]
+ fn hvcc_roundtrip() {
+ let cfg = HevcConfig {
+ general_profile_idc: 1,
+ general_profile_compatibility_flags: 0x6000_0000,
+ general_constraint_indicator_flags: 0x9000_0000_0000,
+ general_level_idc: 93,
+ chroma_format_idc: 1,
+ bit_depth_luma: 8,
+ bit_depth_chroma: 8,
+ length_size: 4,
+ num_temporal_layers: 1,
+ temporal_id_nested: true,
+ arrays: vec![
+ HevcNalArray { completeness: true, nal_type: 32, nalus: vec![vec![0x40, 1]] },
+ HevcNalArray { completeness: true, nal_type: 33, nalus: vec![vec![0x42, 1, 2]] },
+ HevcNalArray { completeness: true, nal_type: 34, nalus: vec![vec![0x44, 1]] },
+ ],
+ ..Default::default()
+ };
+ let back = HevcConfig::parse(&cfg.to_bytes()).unwrap();
+ assert_eq!(back, cfg);
+ assert_eq!(back.sps(), vec![&[0x42u8, 1, 2][..]]);
+ }
+
+ #[test]
+ fn av1_vp9_opus_roundtrip() {
+ let a = Av1Config { seq_profile: 1, seq_level_idx_0: 8, high_bitdepth: true, config_obus: vec![1, 2], ..Default::default() };
+ assert_eq!(Av1Config::parse(&a.to_bytes()).unwrap(), a);
+ let v = VpcConfig {
+ profile: 2,
+ level: 31,
+ bit_depth: 10,
+ chroma_subsampling: 1,
+ full_range: true,
+ colour_primaries: 9,
+ transfer_characteristics: 16,
+ matrix_coefficients: 9,
+ codec_init: vec![],
+ };
+ assert_eq!(VpcConfig::parse(&v.to_bytes()).unwrap(), v);
+ let o = OpusConfig { output_channels: 2, pre_skip: 312, input_sample_rate: 48000, output_gain: 0, channel_mapping_family: 0, channel_mapping: vec![] };
+ assert_eq!(OpusConfig::parse(&o.to_bytes()).unwrap(), o);
+ }
+
+ #[test]
+ fn aac_esds_roundtrip() {
+ let e = SampleEntry::aac(vec![0x12, 0x10], 2, 44100);
+ match &e.codec {
+ CodecConfig::Aac(a) => {
+ assert_eq!((a.object_type, a.sample_rate, a.channel_config), (2, 44100, 2));
+ }
+ _ => panic!(),
+ }
+ assert_eq!(roundtrip(&e, false, b"soun"), e);
+ assert_eq!(roundtrip(&e, true, b"soun"), e);
+ }
+
+ #[test]
+ fn pcm_entries() {
+ for (bits, float, be, qt) in [
+ (16, false, false, true),
+ (16, false, true, true),
+ (24, false, false, true),
+ (32, true, false, true),
+ (24, false, true, false),
+ (32, true, false, false),
+ ] {
+ let p = PcmConfig { bits, float, big_endian: be, signed: true, channels: 2, sample_rate: 48000.0 };
+ let e = SampleEntry::pcm(p);
+ let back = roundtrip(&e, qt, b"soun");
+ assert_eq!(back.codec, CodecConfig::Pcm(p), "{bits} {float} {be} {qt}");
+ }
+ }
+
+ #[test]
+ fn timecode_and_prores() {
+ let tc = TimecodeConfig { flags: 1, timescale: 30000, frame_duration: 1001, frames_per_second: 30, start_frame: None, name: Some("reel".into()) };
+ let e = SampleEntry {
+ format: FourCc(*b"tmcd"),
+ data_reference_index: 1,
+ codec: CodecConfig::Timecode(tc.clone()),
+ video: None,
+ audio: None,
+ bitrate: None,
+ };
+ assert_eq!(roundtrip(&e, true, b"tmcd"), e);
+ assert_eq!(tc.format_frame(107892), "01:00:00;00");
+ let nd = TimecodeConfig { flags: 0, frames_per_second: 24, ..Default::default() };
+ assert_eq!(nd.format_frame(86400), "01:00:00:00");
+ let p = SampleEntry::prores(FourCc(*b"apch"), 1920, 1080);
+ assert_eq!(roundtrip(&p, true, b"vide"), p);
+ }
+
+ #[test]
+ fn asc_parse() {
+ assert_eq!(parse_asc(&[0x11, 0x90]), Some((2, 48000, 2)));
+ assert_eq!(parse_asc(&[]), None);
+ }
+}
diff --git a/crates/isobmff/src/demux.rs b/crates/isobmff/src/demux.rs
new file mode 100644
index 000000000..c5f77863c
--- /dev/null
+++ b/crates/isobmff/src/demux.rs
@@ -0,0 +1,1154 @@
+//! Demuxer: parses box structure lazily (headers + `moov`/`moof` only) and builds per-track sample tables.
+
+use crate::bytes::{Cur, FourCc, boxes, find, parse_box_header};
+use crate::codec::{CodecConfig, SampleEntry, parse_sample_entry};
+use crate::error::{Error, Result, invalid};
+use crate::source::ByteSource;
+use std::collections::HashMap;
+
+/// Hard cap on per-track sample count (after PCM chunk merging).
+const MAX_SAMPLES: usize = 1 << 26;
+/// Hard cap on the size of an in-memory `moov`/`moof` box.
+const MAX_HEADER_BOX: u64 = 1 << 30;
+
+/// One sample (access unit) of a track, in the track's media timescale.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub struct Sample {
+ /// Absolute byte offset in the file.
+ pub offset: u64,
+ pub size: u32,
+ /// Decode timestamp (raw media time, edit lists not applied).
+ pub dts: i64,
+ /// Presentation timestamp = dts + composition offset (raw media time).
+ pub pts: i64,
+ pub duration: u32,
+ pub is_sync: bool,
+ /// 1-based index into [`Track::entries`].
+ pub description_index: u32,
+}
+
+/// One edit list entry (`elst`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Edit {
+ /// Duration of this edit in the movie timescale.
+ pub segment_duration: u64,
+ /// Start time within the media (track timescale); `-1` marks an empty edit.
+ pub media_time: i64,
+ /// Media rate as 16.16 fixed point (0x0001_0000 = normal speed, 0 = dwell).
+ pub media_rate: i32,
+}
+
+/// Broad classification of a track by its handler.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TrackKind {
+ Video,
+ Audio,
+ Timecode,
+ Subtitle,
+ Other,
+}
+
+/// A sample-to-group mapping (`sbgp`) with the matching descriptions (`sgpd`) kept raw.
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct SampleGroup {
+ pub grouping_type: FourCc,
+ /// (sample_count, group_description_index) runs.
+ pub runs: Vec<(u32, u32)>,
+ /// Raw description entries from `sgpd`.
+ pub descriptions: Vec<Vec<u8>>,
+}
+
+/// A demuxed track.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Track {
+ pub id: u32,
+ pub kind: TrackKind,
+ pub handler: FourCc,
+ pub handler_name: String,
+ /// Media timescale (`mdhd`).
+ pub timescale: u32,
+ /// Media duration in the media timescale (`mdhd`).
+ pub duration: u64,
+ /// Track duration in the movie timescale (`tkhd`).
+ pub tkhd_duration: u64,
+ /// ISO 639-2/T language code (e.g. `und`, `eng`).
+ pub language: String,
+ /// `tkhd` presentation size (16.16 fixed point converted to integer pixels, rounded down).
+ pub width: u32,
+ pub height: u32,
+ pub enabled: bool,
+ pub alternate_group: u16,
+ /// `tkhd` volume (8.8 fixed point).
+ pub volume: i16,
+ /// `tkhd` transformation matrix.
+ pub matrix: [i32; 9],
+ pub entries: Vec<SampleEntry>,
+ pub samples: Vec<Sample>,
+ pub edits: Vec<Edit>,
+ /// Offset to add to raw pts to get presentation time (track timescale), derived from the
+ /// leading empty edits and the first non-empty edit's `media_time`.
+ pub edit_offset: i64,
+ /// Track references (`tref`): (type, track ids).
+ pub references: Vec<(FourCc, Vec<u32>)>,
+ /// Raw `sdtp` bytes (one per sample) if present.
+ pub sdtp: Vec<u8>,
+ pub sample_groups: Vec<SampleGroup>,
+ /// True if uncompressed audio samples were merged into one [`Sample`] per chunk.
+ pub pcm_chunked: bool,
+ sync_index: Vec<u32>,
+ pts_order: Vec<u32>,
+}
+
+impl Track {
+ /// The first sample entry's codec configuration.
+ pub fn codec(&self) -> Option<&CodecConfig> {
+ self.entries.first().map(|e| &e.codec)
+ }
+ pub fn video(&self) -> Option<&crate::codec::VideoParams> {
+ self.entries.first().and_then(|e| e.video.as_ref())
+ }
+ pub fn audio(&self) -> Option<&crate::codec::AudioParams> {
+ self.entries.first().and_then(|e| e.audio.as_ref())
+ }
+ /// Presentation (edit-adjusted) pts of sample `i`.
+ pub fn presentation_pts(&self, i: usize) -> Option<i64> {
+ self.samples.get(i).map(|s| s.pts.saturating_add(self.edit_offset))
+ }
+ /// Index of the sample being presented at raw media time `pts` (the last sample, in
+ /// presentation order, whose pts is ≤ `pts`; the first sample if `pts` precedes all).
+ pub fn sample_at_pts(&self, pts: i64) -> Option<usize> {
+ if self.pts_order.is_empty() {
+ return None;
+ }
+ let k = self.pts_order.partition_point(|&i| self.samples[i as usize].pts <= pts);
+ Some(self.pts_order[k.saturating_sub(1)] as usize)
+ }
+ /// Like [`sample_at_pts`](Self::sample_at_pts) but for edit-adjusted presentation time.
+ pub fn sample_at_presentation_time(&self, t: i64) -> Option<usize> {
+ self.sample_at_pts(t.saturating_sub(self.edit_offset))
+ }
+ /// The closest sync sample at or before `index` (decode order); 0 if there is none.
+ pub fn sync_sample_before(&self, index: usize) -> usize {
+ let k = self.sync_index.partition_point(|&i| i as usize <= index);
+ if k == 0 { 0 } else { self.sync_index[k - 1] as usize }
+ }
+ /// Indices of all sync samples.
+ pub fn sync_samples(&self) -> &[u32] {
+ &self.sync_index
+ }
+
+ fn finish_indexes(&mut self) {
+ self.sync_index = self.samples.iter().enumerate().filter(|(_, s)| s.is_sync).map(|(i, _)| i as u32).collect();
+ let mut order: Vec<u32> = (0..self.samples.len() as u32).collect();
+ order.sort_by_key(|&i| (self.samples[i as usize].pts, i));
+ self.pts_order = order;
+ }
+}
+
+/// Text metadata from `udta` (QuickTime `©xxx` atoms and iTunes-style `meta/ilst`, incl. `keys`).
+#[derive(Clone, Debug, PartialEq, Eq, Default)]
+pub struct Metadata {
+ pub entries: Vec<(String, String)>,
+}
+
+impl Metadata {
+ pub fn get(&self, key: &str) -> Option<&str> {
+ self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
+ }
+ /// Title from `©nam` or the `com.apple.quicktime.title` key.
+ pub fn title(&self) -> Option<&str> {
+ self.get("©nam").or_else(|| self.get("com.apple.quicktime.title")).or_else(|| self.get("title"))
+ }
+}
+
+/// A parsed MP4/MOV file (headers and sample tables; media data stays in the source).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Mp4File {
+ pub major_brand: FourCc,
+ pub minor_version: u32,
+ pub compatible_brands: Vec<FourCc>,
+ /// QuickTime file (major brand `qt ` or no `ftyp`).
+ pub is_quicktime: bool,
+ /// Movie timescale (`mvhd`).
+ pub timescale: u32,
+ /// Movie duration in the movie timescale (`mvhd`; for fragmented files, the longest track).
+ pub duration: u64,
+ pub tracks: Vec<Track>,
+ pub metadata: Metadata,
+ /// File uses movie fragments (`mvex` present).
+ pub fragmented: bool,
+ /// Byte offset of the `moov` box.
+ pub moov_offset: u64,
+ /// Number of `moof` boxes found.
+ pub fragment_count: usize,
+}
+
+impl Mp4File {
+ /// Read the bytes of sample `index` of track `track` (index into [`tracks`](Self::tracks)).
+ pub fn read_sample<S: ByteSource + ?Sized>(&self, src: &S, track: usize, index: usize) -> Result<Vec<u8>> {
+ let t = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?;
+ let s = t.samples.get(index).ok_or(Error::NoSuchSample(index))?;
+ read_range(src, s.offset, s.size as u64)
+ }
+ pub fn sample_at_pts(&self, track: usize, pts: i64) -> Option<usize> {
+ self.tracks.get(track)?.sample_at_pts(pts)
+ }
+ pub fn sync_sample_before(&self, track: usize, index: usize) -> Option<usize> {
+ Some(self.tracks.get(track)?.sync_sample_before(index))
+ }
+ /// First track of the given kind.
+ pub fn track_of_kind(&self, kind: TrackKind) -> Option<usize> {
+ self.tracks.iter().position(|t| t.kind == kind)
+ }
+}
+
+fn read_range<S: ByteSource + ?Sized>(src: &S, offset: u64, size: u64) -> Result<Vec<u8>> {
+ let end = offset.checked_add(size).ok_or(Error::Truncated("sample"))?;
+ if end > src.len() {
+ return Err(Error::Truncated("sample data"));
+ }
+ let mut v = vec![0u8; size as usize];
+ src.read_at(offset, &mut v)?;
+ Ok(v)
+}
+
+/// Parse an MP4/MOV file. Only box headers, `ftyp`, `moov` and `moof` boxes are read.
+pub fn open<S: ByteSource>(src: S) -> Result<Mp4File> {
+ let len = src.len();
+ let mut offset = 0u64;
+ let mut ftyp: Option<Vec<u8>> = None;
+ let mut moov: Option<(u64, Vec<u8>)> = None;
+ let mut moofs: Vec<(u64, Vec<u8>)> = Vec::new();
+ while offset + 8 <= len {
+ let n = (len - offset).min(32) as usize;
+ let mut hb = [0u8; 32];
+ src.read_at(offset, &mut hb[..n])?;
+ let h = parse_box_header(&hb[..n])?;
+ let size = h.size.unwrap_or(len - offset);
+ let end = offset.saturating_add(size).min(len);
+ let body_len = end.saturating_sub(offset + h.header_len);
+ let read_body = |max: u64| -> Result<Vec<u8>> {
+ if body_len > max {
+ return Err(Error::TooLarge("header box"));
+ }
+ read_range(&src, offset + h.header_len, body_len)
+ };
+ match &h.kind.0 {
+ b"ftyp" if ftyp.is_none() => ftyp = Some(read_body(1 << 16)?),
+ b"moov" if moov.is_none() => moov = Some((offset, read_body(MAX_HEADER_BOX)?)),
+ b"moof" => moofs.push((offset, read_body(MAX_HEADER_BOX)?)),
+ _ => {}
+ }
+ if h.size.is_none() {
+ break;
+ }
+ offset = offset.saturating_add(size);
+ }
+ let (moov_offset, moov) = moov.ok_or(Error::NoMoov)?;
+ let mut file = Mp4File {
+ major_brand: FourCc::default(),
+ minor_version: 0,
+ compatible_brands: Vec::new(),
+ is_quicktime: true,
+ timescale: 0,
+ duration: 0,
+ tracks: Vec::new(),
+ metadata: Metadata::default(),
+ fragmented: false,
+ moov_offset,
+ fragment_count: moofs.len(),
+ };
+ if let Some(f) = &ftyp {
+ let mut c = Cur::new(f, "ftyp");
+ file.major_brand = c.fourcc()?;
+ file.minor_version = c.u32().unwrap_or(0);
+ while c.remaining() >= 4 {
+ file.compatible_brands.push(c.fourcc()?);
+ }
+ file.is_quicktime = file.major_brand == b"qt ";
+ }
+ let mut trex: HashMap<u32, Trex> = HashMap::new();
+ let mut trak_payloads = Vec::new();
+ for b in boxes(&moov) {
+ let b = b?;
+ match &b.kind.0 {
+ b"cmov" => return Err(Error::Unsupported("compressed movie header (cmov)".into())),
+ b"mvhd" => {
+ let mut c = Cur::new(b.payload, "mvhd");
+ let (v, _) = c.full_header()?;
+ if v == 1 {
+ c.skip(16)?;
+ file.timescale = c.u32()?;
+ file.duration = c.u64()?;
+ } else {
+ c.skip(8)?;
+ file.timescale = c.u32()?;
+ file.duration = c.u32()? as u64;
+ }
+ }
+ b"trak" => trak_payloads.push(b.payload),
+ b"mvex" => {
+ file.fragmented = true;
+ for m in boxes(b.payload).map_while(|b| b.ok()) {
+ if m.kind == b"trex" {
+ let mut c = Cur::new(m.payload, "trex");
+ c.full_header()?;
+ let id = c.u32()?;
+ trex.insert(id, Trex { description_index: c.u32()?, duration: c.u32()?, size: c.u32()?, flags: c.u32()? });
+ }
+ }
+ }
+ b"udta" => parse_udta(b.payload, &mut file.metadata),
+ b"meta" => parse_meta(b.payload, &mut file.metadata),
+ _ => {}
+ }
+ }
+ for p in trak_payloads {
+ let t = parse_trak(p, &file, len)?;
+ file.tracks.push(t);
+ }
+ // Movie fragments.
+ let mut next_dts: Vec<i64> = file.tracks.iter().map(|t| t.samples.last().map(|s| s.dts + s.duration as i64).unwrap_or(0)).collect();
+ for (moof_off, moof) in &moofs {
+ parse_moof(*moof_off, moof, &mut file.tracks, &trex, &mut next_dts, len)?;
+ }
+ for t in &mut file.tracks {
+ if file.fragmented && !moofs.is_empty() {
+ let d: u64 = t.samples.iter().map(|s| s.duration as u64).sum();
+ t.duration = t.duration.max(d);
+ if t.timescale > 0 && file.timescale > 0 {
+ let md = (t.duration as u128 * file.timescale as u128 / t.timescale as u128) as u64;
+ file.duration = file.duration.max(md);
+ }
+ }
+ t.finish_indexes();
+ // Timecode start frame from the first sample.
+ if let Some(CodecConfig::Timecode(tc)) = t.entries.first_mut().map(|e| &mut e.codec)
+ && let Some(s) = t.samples.first()
+ && s.size >= 4
+ {
+ let mut b = [0u8; 4];
+ if src.read_at(s.offset, &mut b).is_ok() {
+ tc.start_frame = Some(u32::from_be_bytes(b));
+ }
+ }
+ }
+ Ok(file)
+}
+
+#[derive(Clone, Copy, Debug, Default)]
+struct Trex {
+ description_index: u32,
+ duration: u32,
+ size: u32,
+ flags: u32,
+}
+
+fn parse_language(code: u16) -> String {
+ if code < 0x400 {
+ // QuickTime Macintosh language code.
+ return if code == 0 { "eng".into() } else { "und".into() };
+ }
+ let c = |s: u16| (((code >> s) & 0x1F) as u8 + 0x60) as char;
+ let s: String = [c(10), c(5), c(0)].into_iter().collect();
+ if s.chars().all(|ch| ch.is_ascii_lowercase()) { s } else { "und".into() }
+}
+
+fn rescale(v: i128, from: u32, to: u32) -> i64 {
+ if from == 0 {
+ return 0;
+ }
+ (v * to as i128 / from as i128).clamp(i64::MIN as i128, i64::MAX as i128) as i64
+}
+
+fn parse_trak(p: &[u8], file: &Mp4File, file_len: u64) -> Result<Track> {
+ let mut t = Track {
+ id: 0,
+ kind: TrackKind::Other,
+ handler: FourCc::default(),
+ handler_name: String::new(),
+ timescale: 0,
+ duration: 0,
+ tkhd_duration: 0,
+ language: "und".into(),
+ width: 0,
+ height: 0,
+ enabled: true,
+ alternate_group: 0,
+ volume: 0,
+ matrix: [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000],
+ entries: Vec::new(),
+ samples: Vec::new(),
+ edits: Vec::new(),
+ edit_offset: 0,
+ references: Vec::new(),
+ sdtp: Vec::new(),
+ sample_groups: Vec::new(),
+ pcm_chunked: false,
+ sync_index: Vec::new(),
+ pts_order: Vec::new(),
+ };
+ let mut mdia = None;
+ for b in boxes(p) {
+ let b = b?;
+ match &b.kind.0 {
+ b"tkhd" => {
+ let mut c = Cur::new(b.payload, "tkhd");
+ let (v, flags) = c.full_header()?;
+ t.enabled = flags & 1 != 0;
+ if v == 1 {
+ c.skip(16)?;
+ t.id = c.u32()?;
+ c.skip(4)?;
+ t.tkhd_duration = c.u64()?;
+ } else {
+ c.skip(8)?;
+ t.id = c.u32()?;
+ c.skip(4)?;
+ t.tkhd_duration = c.u32()? as u64;
+ }
+ c.skip(8)?;
+ let _layer = c.i16()?;
+ t.alternate_group = c.u16()?;
+ t.volume = c.i16()?;
+ c.skip(2)?;
+ for m in t.matrix.iter_mut() {
+ *m = c.i32()?;
+ }
+ t.width = c.u32()? >> 16;
+ t.height = c.u32()? >> 16;
+ }
+ b"edts" => {
+ if let Some(e) = find(b.payload, b"elst") {
+ let mut c = Cur::new(e, "elst");
+ let (v, _) = c.full_header()?;
+ let n = c.count(if v == 1 { 20 } else { 12 })?;
+ for _ in 0..n {
+ let (segment_duration, media_time) = if v == 1 { (c.u64()?, c.i64()?) } else { (c.u32()? as u64, c.i32()? as i64) };
+ t.edits.push(Edit { segment_duration, media_time, media_rate: c.i32()? });
+ }
+ }
+ }
+ b"tref" => {
+ for r in boxes(b.payload).map_while(|b| b.ok()) {
+ let ids = r.payload.chunks_exact(4).map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).collect();
+ t.references.push((r.kind, ids));
+ }
+ }
+ b"mdia" => mdia = Some(b.payload),
+ _ => {}
+ }
+ }
+ let mdia = mdia.ok_or_else(|| Error::Invalid("trak without mdia".into()))?;
+ let mut minf = None;
+ for b in boxes(mdia) {
+ let b = b?;
+ match &b.kind.0 {
+ b"mdhd" => {
+ let mut c = Cur::new(b.payload, "mdhd");
+ let (v, _) = c.full_header()?;
+ if v == 1 {
+ c.skip(16)?;
+ t.timescale = c.u32()?;
+ t.duration = c.u64()?;
+ } else {
+ c.skip(8)?;
+ t.timescale = c.u32()?;
+ t.duration = c.u32()? as u64;
+ }
+ t.language = parse_language(c.u16()?);
+ }
+ b"hdlr" => {
+ let mut c = Cur::new(b.payload, "hdlr");
+ c.full_header()?;
+ let _pre = c.u32()?;
+ t.handler = c.fourcc()?;
+ c.skip(12)?;
+ let name = c.rest();
+ // ISO: null-terminated UTF-8; QuickTime: Pascal string.
+ let s = if !name.is_empty() && name[0] as usize == name.len() - 1 && name.len() > 1 {
+ &name[1..]
+ } else {
+ name.split(|&b| b == 0).next().unwrap_or(&[])
+ };
+ t.handler_name = String::from_utf8_lossy(s).into_owned();
+ }
+ b"minf" => minf = Some(b.payload),
+ _ => {}
+ }
+ }
+ t.kind = match &t.handler.0 {
+ b"vide" => TrackKind::Video,
+ b"soun" => TrackKind::Audio,
+ b"tmcd" => TrackKind::Timecode,
+ b"text" | b"sbtl" | b"subt" | b"clcp" => TrackKind::Subtitle,
+ _ => TrackKind::Other,
+ };
+ // Edit offset in media timescale.
+ let mut empty = 0i128;
+ for e in &t.edits {
+ if e.media_time == -1 {
+ empty += e.segment_duration as i128;
+ } else {
+ t.edit_offset = rescale(empty, file.timescale, t.timescale).saturating_sub(e.media_time);
+ break;
+ }
+ }
+ if let Some(stbl) = minf.and_then(|m| find(m, b"stbl")) {
+ parse_stbl(stbl, &mut t, file.is_quicktime, file_len)?;
+ }
+ Ok(t)
+}
+
+struct SttsCursor<'a> {
+ runs: &'a [(u32, u32)],
+ run: usize,
+ used: u32,
+}
+
+impl SttsCursor<'_> {
+ /// Advance by `n` samples, returning the summed duration.
+ fn take(&mut self, mut n: u64) -> u64 {
+ let mut total = 0u64;
+ while n > 0 && self.run < self.runs.len() {
+ let (count, delta) = self.runs[self.run];
+ let avail = (count - self.used) as u64;
+ let k = avail.min(n);
+ total = total.saturating_add(k.saturating_mul(delta as u64));
+ n -= k;
+ self.used += k as u32;
+ if self.used >= count {
+ self.run += 1;
+ self.used = 0;
+ }
+ }
+ total
+ }
+ fn next_value(&mut self) -> u32 {
+ while self.run < self.runs.len() && self.runs[self.run].0 == 0 {
+ self.run += 1;
+ }
+ let Some(&(_, d)) = self.runs.get(self.run) else { return 0 };
+ self.take(1);
+ d
+ }
+}
+
+fn parse_stbl(stbl: &[u8], t: &mut Track, is_qt: bool, file_len: u64) -> Result<()> {
+ let mut stts: Vec<(u32, u32)> = Vec::new();
+ let mut ctts: Vec<(u32, u32)> = Vec::new();
+ let mut stss: Option<Vec<u32>> = None;
+ let mut stsc: Vec<(u32, u32, u32)> = Vec::new();
+ let mut const_size = 0u32;
+ let mut sample_count = 0usize;
+ let mut sizes: Vec<u32> = Vec::new();
+ let mut chunks: Vec<u64> = Vec::new();
+ let mut sbgp: Vec<(FourCc, Vec<(u32, u32)>)> = Vec::new();
+ let mut sgpd: HashMap<FourCc, Vec<Vec<u8>>> = HashMap::new();
+ for b in boxes(stbl) {
+ let b = b?;
+ let mut c = Cur::new(b.payload, "stbl child");
+ match &b.kind.0 {
+ b"stsd" => {
+ c.full_header()?;
+ let n = c.count(8)?;
+ for e in boxes(c.rest()).take(n) {
+ let e = e?;
+ t.entries.push(parse_sample_entry(e.kind, e.payload, t.handler, is_qt)?);
+ }
+ }
+ b"stts" => {
+ c.full_header()?;
+ let n = c.count(8)?;
+ stts = (0..n).map(|_| Ok((c.u32()?, c.u32()?))).collect::<Result<_>>()?;
+ }
+ b"ctts" => {
+ c.full_header()?;
+ let n = c.count(8)?;
+ ctts = (0..n).map(|_| Ok((c.u32()?, c.u32()?))).collect::<Result<_>>()?;
+ }
+ b"stss" => {
+ c.full_header()?;
+ let n = c.count(4)?;
+ let mut v: Vec<u32> = (0..n).map(|_| c.u32()).collect::<Result<_>>()?;
+ v.sort_unstable();
+ stss = Some(v);
+ }
+ b"stsc" => {
+ c.full_header()?;
+ let n = c.count(12)?;
+ stsc = (0..n).map(|_| Ok((c.u32()?, c.u32()?, c.u32()?))).collect::<Result<_>>()?;
+ }
+ b"stsz" => {
+ c.full_header()?;
+ const_size = c.u32()?;
+ let n = c.u32()? as usize;
+ if const_size == 0 {
+ c.check_count(n, 4)?;
+ sizes = (0..n).map(|_| c.u32()).collect::<Result<_>>()?;
+ sample_count = n;
+ } else {
+ // Samples of constant size must fit in the file: clamp absurd counts.
+ sample_count = (n as u64).min(file_len / const_size as u64) as usize;
+ }
+ }
+ b"stz2" => {
+ c.full_header()?;
+ let field = c.u32()? & 0xFF;
+ let n = c.u32()? as usize;
+ let bits = match field {
+ 4 | 8 | 16 => field as usize,
+ _ => return invalid(format!("stz2 field size {field}")),
+ };
+ if n.checked_mul(bits).is_none_or(|b| b.div_ceil(8) > c.remaining()) {
+ return Err(Error::Truncated("stz2"));
+ }
+ let d = c.rest();
+ sizes = (0..n)
+ .map(|i| match bits {
+ 4 => ((d[i / 2] >> if i % 2 == 0 { 4 } else { 0 }) & 0xF) as u32,
+ 8 => d[i] as u32,
+ _ => u16::from_be_bytes([d[2 * i], d[2 * i + 1]]) as u32,
+ })
+ .collect();
+ sample_count = n;
+ }
+ b"stco" => {
+ c.full_header()?;
+ let n = c.count(4)?;
+ chunks = (0..n).map(|_| c.u32().map(|v| v as u64)).collect::<Result<_>>()?;
+ }
+ b"co64" => {
+ c.full_header()?;
+ let n = c.count(8)?;
+ chunks = (0..n).map(|_| c.u64()).collect::<Result<_>>()?;
+ }
+ b"sdtp" => {
+ c.full_header()?;
+ t.sdtp = c.rest().to_vec();
+ }
+ b"sbgp" => {
+ let (v, _) = c.full_header()?;
+ let gt = c.fourcc()?;
+ if v == 1 {
+ c.u32()?;
+ }
+ let n = c.count(8)?;
+ let runs = (0..n).map(|_| Ok((c.u32()?, c.u32()?))).collect::<Result<_>>()?;
+ sbgp.push((gt, runs));
+ }
+ b"sgpd" => {
+ let (v, _) = c.full_header()?;
+ let gt = c.fourcc()?;
+ let default_len = if v >= 1 { c.u32()? } else { 0 };
+ if v >= 2 {
+ c.u32()?;
+ }
+ let n = c.count(0)?;
+ let mut descs = Vec::new();
+ for _ in 0..n {
+ let l = if v >= 1 && default_len == 0 { c.u32()? } else { default_len };
+ if l == 0 {
+ // Version 0 without known length: keep the remainder as a single entry.
+ descs.push(c.rest().to_vec());
+ break;
+ }
+ descs.push(c.bytes(l as usize)?.to_vec());
+ }
+ sgpd.insert(gt, descs);
+ }
+ _ => {}
+ }
+ }
+ t.sample_groups = sbgp.into_iter().map(|(gt, runs)| SampleGroup { grouping_type: gt, runs, descriptions: sgpd.remove(&gt).unwrap_or_default() }).collect();
+ if sample_count == 0 || chunks.is_empty() || stsc.is_empty() {
+ return Ok(());
+ }
+ if stsc[0].0 == 0 || stsc.windows(2).any(|w| w[1].0 <= w[0].0) {
+ return invalid("stsc first_chunk values are not increasing from 1");
+ }
+ let pcm = match t.entries.first().map(|e| &e.codec) {
+ Some(CodecConfig::Pcm(p)) if const_size != 0 => Some(*p),
+ _ => None,
+ };
+ let mut stts_c = SttsCursor { runs: &stts, run: 0, used: 0 };
+ let mut ctts_c = SttsCursor { runs: &ctts, run: 0, used: 0 };
+ let mut samples = Vec::new();
+ let mut sidx = 0usize;
+ let mut dts = 0i64;
+ let mut stsc_i = 0usize;
+ if let Some(p) = pcm {
+ t.pcm_chunked = true;
+ let a = t.audio().cloned().unwrap_or_default();
+ let frame_bytes = |frames: u64| -> u64 {
+ if a.qt_version == 1 && a.bytes_per_frame > 0 && a.samples_per_packet > 0 {
+ frames / a.samples_per_packet as u64 * a.bytes_per_frame as u64
+ } else if const_size > 1 {
+ frames * const_size as u64
+ } else {
+ frames * p.bytes_per_frame() as u64
+ }
+ };
+ if chunks.len() > MAX_SAMPLES {
+ return Err(Error::TooLarge("chunk count"));
+ }
+ samples.reserve(chunks.len());
+ for (ci, &off) in chunks.iter().enumerate() {
+ while stsc_i + 1 < stsc.len() && stsc[stsc_i + 1].0 as usize <= ci + 1 {
+ stsc_i += 1;
+ }
+ let spc = (stsc[stsc_i].1 as usize).min(sample_count - sidx);
+ if spc == 0 {
+ continue;
+ }
+ let dur = stts_c.take(spc as u64);
+ let size = frame_bytes(spc as u64).min(u32::MAX as u64) as u32;
+ samples.push(Sample {
+ offset: off,
+ size,
+ dts,
+ pts: dts,
+ duration: dur.min(u32::MAX as u64) as u32,
+ is_sync: true,
+ description_index: stsc[stsc_i].2,
+ });
+ dts = dts.saturating_add(dur.min(i64::MAX as u64) as i64);
+ sidx += spc;
+ if sidx >= sample_count {
+ break;
+ }
+ }
+ } else {
+ if sample_count > MAX_SAMPLES {
+ return Err(Error::TooLarge("sample count"));
+ }
+ samples.reserve(sample_count);
+ let mut stss_i = 0usize;
+ 'chunks: for (ci, &off) in chunks.iter().enumerate() {
+ while stsc_i + 1 < stsc.len() && stsc[stsc_i + 1].0 as usize <= ci + 1 {
+ stsc_i += 1;
+ }
+ let (_, spc, sdi) = stsc[stsc_i];
+ let mut pos = off;
+ for _ in 0..spc {
+ if sidx >= sample_count {
+ break 'chunks;
+ }
+ let size = if const_size != 0 { const_size } else { sizes[sidx] };
+ let duration = stts_c.next_value();
+ let cts = ctts_c.next_value() as i32 as i64;
+ let is_sync = match &stss {
+ None => true,
+ Some(v) => {
+ while stss_i < v.len() && (v[stss_i] as usize) < sidx + 1 {
+ stss_i += 1;
+ }
+ stss_i < v.len() && v[stss_i] as usize == sidx + 1
+ }
+ };
+ samples.push(Sample { offset: pos, size, dts, pts: dts.saturating_add(cts), duration, is_sync, description_index: sdi });
+ pos = pos.saturating_add(size as u64);
+ dts = dts.saturating_add(duration as i64);
+ sidx += 1;
+ }
+ }
+ }
+ t.samples = samples;
+ Ok(())
+}
+
+fn parse_moof(moof_off: u64, moof: &[u8], tracks: &mut [Track], trex: &HashMap<u32, Trex>, next_dts: &mut [i64], file_len: u64) -> Result<()> {
+ // End of data of the previous traf, for the base-offset default of subsequent trafs.
+ let mut prev_end: Option<u64> = None;
+ for b in boxes(moof) {
+ let b = b?;
+ if b.kind != b"traf" {
+ continue;
+ }
+ let mut tfhd = None;
+ let mut tfdt = None;
+ let mut truns = Vec::new();
+ for c in boxes(b.payload) {
+ let c = c?;
+ match &c.kind.0 {
+ b"tfhd" => tfhd = Some(c.payload),
+ b"tfdt" => tfdt = Some(c.payload),
+ b"trun" => truns.push(c.payload),
+ _ => {}
+ }
+ }
+ let tfhd = tfhd.ok_or_else(|| Error::Invalid("traf without tfhd".into()))?;
+ let mut c = Cur::new(tfhd, "tfhd");
+ let (_, fl) = c.full_header()?;
+ let id = c.u32()?;
+ let Some(ti) = tracks.iter().position(|t| t.id == id) else { continue };
+ let d = trex.get(&id).copied().unwrap_or_default();
+ let base = if fl & 1 != 0 {
+ c.u64()?
+ } else if fl & 0x20000 != 0 {
+ moof_off
+ } else {
+ prev_end.unwrap_or(moof_off)
+ };
+ let sdi = if fl & 2 != 0 { c.u32()? } else { d.description_index };
+ let def_dur = if fl & 8 != 0 { c.u32()? } else { d.duration };
+ let def_size = if fl & 0x10 != 0 { c.u32()? } else { d.size };
+ let def_flags = if fl & 0x20 != 0 { c.u32()? } else { d.flags };
+ if let Some(p) = tfdt {
+ let mut c = Cur::new(p, "tfdt");
+ let (v, _) = c.full_header()?;
+ let t = if v == 1 { c.u64()? } else { c.u32()? as u64 };
+ next_dts[ti] = t.min(i64::MAX as u64) as i64;
+ }
+ let mut data_pos = base;
+ for tr in truns {
+ let mut c = Cur::new(tr, "trun");
+ let (v, tf) = c.full_header()?;
+ let per = [0x100u32, 0x200, 0x400, 0x800].iter().filter(|&&f| tf & f != 0).count() * 4;
+ let n = c.u32()? as usize;
+ if per > 0 {
+ c.check_count(n, per)?;
+ } else if (n as u64).saturating_mul(def_size.max(1) as u64) > file_len {
+ return Err(Error::TooLarge("trun sample count"));
+ }
+ if tracks[ti].samples.len() + n > MAX_SAMPLES {
+ return Err(Error::TooLarge("sample count"));
+ }
+ if tf & 1 != 0 {
+ data_pos = base.wrapping_add_signed(c.i32()? as i64);
+ }
+ let first_flags = if tf & 4 != 0 { Some(c.u32()?) } else { None };
+ let t = &mut tracks[ti];
+ t.samples.reserve(n);
+ for i in 0..n {
+ let dur = if tf & 0x100 != 0 { c.u32()? } else { def_dur };
+ let size = if tf & 0x200 != 0 { c.u32()? } else { def_size };
+ let flags = if tf & 0x400 != 0 { c.u32()? } else { def_flags };
+ // first_sample_flags overrides the flags of the first sample only.
+ let flags = if i == 0 { first_flags.unwrap_or(flags) } else { flags };
+ let cto = if tf & 0x800 != 0 {
+ let raw = c.u32()?;
+ if v == 0 { raw as i64 } else { raw as i32 as i64 }
+ } else {
+ 0
+ };
+ let dts = next_dts[ti];
+ t.samples.push(Sample {
+ offset: data_pos,
+ size,
+ dts,
+ pts: dts.saturating_add(cto),
+ duration: dur,
+ is_sync: flags & 0x1_0000 == 0,
+ description_index: sdi,
+ });
+ data_pos = data_pos.saturating_add(size as u64);
+ next_dts[ti] = dts.saturating_add(dur as i64);
+ }
+ }
+ prev_end = Some(data_pos);
+ }
+ Ok(())
+}
+
+fn parse_udta(p: &[u8], md: &mut Metadata) {
+ for b in boxes(p).map_while(|b| b.ok()) {
+ if b.kind == b"meta" {
+ parse_meta(b.payload, md);
+ } else if b.kind.0[0] == 0xA9 && b.payload.len() >= 4 {
+ let n = u16::from_be_bytes([b.payload[0], b.payload[1]]) as usize;
+ if let Some(s) = b.payload.get(4..4 + n) {
+ md.entries.push((b.kind.to_string_lossy(), String::from_utf8_lossy(s).into_owned()));
+ }
+ }
+ }
+}
+
+fn parse_meta(p: &[u8], md: &mut Metadata) {
+ // QuickTime `meta` is a plain box; ISO `meta` is a full box.
+ let body = if p.len() >= 8 && &p[4..8] == b"hdlr" { p } else { p.get(4..).unwrap_or(&[]) };
+ let mut keys: Vec<String> = Vec::new();
+ if let Some(k) = find(body, b"keys") {
+ let mut c = Cur::new(k, "keys");
+ if c.full_header().is_ok()
+ && let Ok(n) = c.count(8)
+ {
+ for _ in 0..n {
+ let Ok(sz) = c.u32() else { break };
+ let Ok(_ns) = c.u32() else { break };
+ let Ok(name) = c.bytes((sz as usize).saturating_sub(8)) else { break };
+ keys.push(String::from_utf8_lossy(name).into_owned());
+ }
+ }
+ }
+ let Some(ilst) = find(body, b"ilst") else { return };
+ for item in boxes(ilst).map_while(|b| b.ok()) {
+ let idx = item.kind.as_u32() as usize;
+ let key = if !keys.is_empty() && idx >= 1 && idx <= keys.len() { keys[idx - 1].clone() } else { item.kind.to_string_lossy() };
+ if let Some(d) = find(item.payload, b"data")
+ && d.len() >= 8
+ {
+ let ty = u32::from_be_bytes([d[0], d[1], d[2], d[3]]) & 0xFF_FFFF;
+ if ty == 1 || ty == 0 {
+ md.entries.push((key, String::from_utf8_lossy(&d[8..]).into_owned()));
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn language_codes() {
+ // "und" = 0x55C4
+ assert_eq!(parse_language(0x55C4), "und");
+ assert_eq!(parse_language(0), "eng");
+ assert_eq!(parse_language(0x15C7), "eng");
+ }
+
+ #[test]
+ fn stts_cursor() {
+ let runs = [(2, 10), (0, 99), (3, 5)];
+ let mut c = SttsCursor { runs: &runs, run: 0, used: 0 };
+ assert_eq!(c.next_value(), 10);
+ assert_eq!(c.take(3), 10 + 5 + 5);
+ assert_eq!(c.next_value(), 5);
+ assert_eq!(c.next_value(), 0);
+ }
+
+ #[test]
+ fn rejects_no_moov_and_cmov() {
+ let mut b = crate::bytes::BoxBuf::new();
+ b.leaf(b"free", &[0; 4]);
+ assert!(matches!(open(b.buf.clone()), Err(Error::NoMoov)));
+ let m = b.start(b"moov");
+ b.leaf(b"cmov", &[]);
+ b.end(m);
+ assert!(matches!(open(b.buf), Err(Error::Unsupported(_))));
+ }
+
+ #[test]
+ fn metadata_qt_and_ilst() {
+ let mut b = crate::bytes::BoxBuf::new();
+ let m = b.start(&[0xA9, b'n', b'a', b'm']);
+ b.u16(2);
+ b.u16(0);
+ b.bytes(b"hi");
+ b.end(m);
+ let meta = b.start_full(b"meta", 0, 0);
+ b.leaf(b"hdlr", &[0; 24]);
+ let il = b.start(b"ilst");
+ let it = b.start(&[0xA9, b'A', b'R', b'T']);
+ let d = b.start(b"data");
+ b.u32(1);
+ b.u32(0);
+ b.bytes(b"me");
+ b.end(d);
+ b.end(it);
+ b.end(il);
+ b.end(meta);
+ let mut md = Metadata::default();
+ parse_udta(&b.buf, &mut md);
+ assert_eq!(md.title(), Some("hi"));
+ assert_eq!(md.get("©ART"), Some("me"));
+ }
+
+ use crate::bytes::BoxBuf;
+
+ fn full(b: &mut BoxBuf, kind: &[u8; 4], v: u8, f: impl FnOnce(&mut BoxBuf)) {
+ let m = b.start_full(kind, v, 0);
+ f(b);
+ b.end(m);
+ }
+
+ /// Hand-built file: uuid/wide/skip boxes, stz2 sizes, co64, ctts v1 with negative offsets,
+ /// stss, sdtp, sbgp/sgpd, and an edit list with a leading empty edit.
+ fn handmade(stsz_override: Option<(u32, u32)>) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ let m = b.start(b"ftyp");
+ b.bytes(b"isom");
+ b.u32(0);
+ b.bytes(b"isom");
+ b.end(m);
+ let m = b.start(b"uuid");
+ b.bytes(&[0xAB; 16]);
+ b.bytes(b"payload");
+ b.end(m);
+ b.leaf(b"wide", &[]);
+ b.leaf(b"skip", &[1, 2, 3]);
+ // mdat with 64-bit size: 4 samples of 3,1,2,4 bytes.
+ let data_start = b.len() as u64 + 16;
+ b.u32(1);
+ b.bytes(b"mdat");
+ b.u64(16 + 10);
+ b.bytes(&[1, 1, 1, 2, 3, 3, 4, 4, 4, 4]);
+ let moov = b.start(b"moov");
+ full(&mut b, b"mvhd", 0, |b| {
+ b.u32(0);
+ b.u32(0);
+ b.u32(1000);
+ b.u32(500);
+ b.zeros(80);
+ });
+ let trak = b.start(b"trak");
+ full(&mut b, b"tkhd", 0, |b| {
+ b.u32(0);
+ b.u32(0);
+ b.u32(7);
+ b.u32(0);
+ b.u32(500);
+ b.zeros(52);
+ b.u32(320 << 16);
+ b.u32(240 << 16);
+ });
+ let edts = b.start(b"edts");
+ full(&mut b, b"elst", 1, |b| {
+ b.u32(2);
+ b.u64(100);
+ b.i64(-1);
+ b.i32(0x10000);
+ b.u64(400);
+ b.i64(20);
+ b.i32(0x10000);
+ });
+ b.end(edts);
+ let mdia = b.start(b"mdia");
+ full(&mut b, b"mdhd", 0, |b| {
+ b.u32(0);
+ b.u32(0);
+ b.u32(100);
+ b.u32(40);
+ b.u16(0x15C7);
+ b.u16(0);
+ });
+ full(&mut b, b"hdlr", 0, |b| {
+ b.u32(0);
+ b.bytes(b"vide");
+ b.zeros(12);
+ b.bytes(b"Video\0");
+ });
+ let minf = b.start(b"minf");
+ let stbl = b.start(b"stbl");
+ full(&mut b, b"stsd", 0, |b| {
+ b.u32(1);
+ crate::codec::SampleEntry::jpeg(320, 240).write(b, false).unwrap();
+ });
+ full(&mut b, b"stts", 0, |b| {
+ b.u32(1);
+ b.u32(4);
+ b.u32(10);
+ });
+ full(&mut b, b"ctts", 1, |b| {
+ b.u32(2);
+ b.u32(2);
+ b.i32(-5);
+ b.u32(2);
+ b.i32(5);
+ });
+ full(&mut b, b"stss", 0, |b| {
+ b.u32(2);
+ b.u32(3);
+ b.u32(1);
+ });
+ full(&mut b, b"stsc", 0, |b| {
+ b.u32(2);
+ b.u32(1);
+ b.u32(3);
+ b.u32(1);
+ b.u32(2);
+ b.u32(1);
+ b.u32(1);
+ });
+ match stsz_override {
+ Some((size, count)) => full(&mut b, b"stsz", 0, |b| {
+ b.u32(size);
+ b.u32(count);
+ }),
+ None => full(&mut b, b"stz2", 0, |b| {
+ b.u32(4);
+ b.u32(4);
+ b.u8(0x31);
+ b.u8(0x24);
+ }),
+ }
+ full(&mut b, b"co64", 0, |b| {
+ b.u32(2);
+ b.u64(data_start);
+ b.u64(data_start + 6);
+ });
+ full(&mut b, b"sdtp", 0, |b| b.bytes(&[0x20, 0x10, 0x10, 0x10]));
+ full(&mut b, b"sbgp", 0, |b| {
+ b.bytes(b"roll");
+ b.u32(1);
+ b.u32(4);
+ b.u32(1);
+ });
+ full(&mut b, b"sgpd", 1, |b| {
+ b.bytes(b"roll");
+ b.u32(2);
+ b.u32(1);
+ b.i16(-1);
+ });
+ b.end(stbl);
+ b.end(minf);
+ b.end(mdia);
+ b.end(trak);
+ b.end(moov);
+ // Trailing box extending to EOF (size 0).
+ b.u32(0);
+ b.bytes(b"free");
+ b.bytes(&[9; 5]);
+ b.buf
+ }
+
+ #[test]
+ fn handmade_sample_table() {
+ let d = handmade(None);
+ let f = open(d.as_slice()).unwrap();
+ assert_eq!(f.major_brand, *b"isom");
+ let t = &f.tracks[0];
+ assert_eq!((t.id, t.kind, t.timescale, t.language.as_str()), (7, TrackKind::Video, 100, "eng"));
+ assert_eq!((t.width, t.height), (320, 240));
+ assert_eq!(t.handler_name, "Video");
+ let sizes: Vec<u32> = t.samples.iter().map(|s| s.size).collect();
+ assert_eq!(sizes, [3, 1, 2, 4]);
+ let offs: Vec<u64> = t.samples.iter().map(|s| s.offset - t.samples[0].offset).collect();
+ assert_eq!(offs, [0, 3, 4, 6]);
+ let pts: Vec<i64> = t.samples.iter().map(|s| s.pts).collect();
+ assert_eq!(pts, [-5, 5, 25, 35]);
+ let sync: Vec<bool> = t.samples.iter().map(|s| s.is_sync).collect();
+ assert_eq!(sync, [true, false, true, false]);
+ for (i, want) in [vec![1u8, 1, 1], vec![2], vec![3, 3], vec![4; 4]].iter().enumerate() {
+ assert_eq!(&f.read_sample(d.as_slice(), 0, i).unwrap(), want);
+ }
+ // Empty edit of 100 movie ticks = 10 media ticks, then media starts at 20.
+ assert_eq!(t.edits.len(), 2);
+ assert_eq!(t.edit_offset, 10 - 20);
+ assert_eq!(t.presentation_pts(2), Some(15));
+ assert_eq!(t.sdtp.len(), 4);
+ assert_eq!(t.sample_groups[0].grouping_type, *b"roll");
+ assert_eq!(t.sample_groups[0].descriptions, vec![vec![0xFF, 0xFF]]);
+ assert!(f.read_sample(d.as_slice(), 0, 4).is_err());
+ assert!(f.read_sample(d.as_slice(), 1, 0).is_err());
+ }
+
+ #[test]
+ fn absurd_counts_are_bounded() {
+ // Constant-size stsz claiming 4 billion samples is clamped to what fits in the file.
+ let d = handmade(Some((1, u32::MAX)));
+ let f = open(d.as_slice()).unwrap();
+ assert!(f.tracks[0].samples.len() <= d.len());
+ // A table claiming more entries than its box holds fails cleanly.
+ let mut d = handmade(None);
+ let p = d.windows(4).position(|w| w == b"stts").unwrap();
+ d[p + 8..p + 12].copy_from_slice(&u32::MAX.to_be_bytes());
+ assert!(matches!(open(d.as_slice()), Err(Error::Truncated(_))));
+ // Box larger than its parent.
+ let mut d = handmade(None);
+ let p = d.windows(4).position(|w| w == b"stsc").unwrap();
+ d[p - 4..p].copy_from_slice(&0x7FFF_FFFFu32.to_be_bytes());
+ assert!(open(d.as_slice()).is_err());
+ }
+}
diff --git a/crates/isobmff/src/error.rs b/crates/isobmff/src/error.rs
new file mode 100644
index 000000000..b5dfd752f
--- /dev/null
+++ b/crates/isobmff/src/error.rs
@@ -0,0 +1,38 @@
+use std::io;
+
+/// Errors produced by the demuxer and muxer.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error("I/O error: {0}")]
+ Io(#[from] io::Error),
+ /// A box or structure ended before all required fields were read.
+ #[error("truncated data while reading {0}")]
+ Truncated(&'static str),
+ /// Structurally invalid data.
+ #[error("invalid data: {0}")]
+ Invalid(String),
+ /// Valid but unsupported feature (e.g. compressed `cmov` movie header).
+ #[error("unsupported: {0}")]
+ Unsupported(String),
+ /// A count or size exceeds sanity limits relative to the file size.
+ #[error("size limit exceeded: {0}")]
+ TooLarge(&'static str),
+ /// No `moov` box was found.
+ #[error("no moov box found")]
+ NoMoov,
+ /// A track index was out of range.
+ #[error("track index {0} out of range")]
+ NoSuchTrack(usize),
+ /// A sample index was out of range.
+ #[error("sample index {0} out of range")]
+ NoSuchSample(usize),
+ /// Muxer usage error (e.g. invalid track config, bad sample).
+ #[error("muxer: {0}")]
+ Mux(String),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+pub(crate) fn invalid<T>(msg: impl Into<String>) -> Result<T> {
+ Err(Error::Invalid(msg.into()))
+}
diff --git a/crates/isobmff/src/lib.rs b/crates/isobmff/src/lib.rs
new file mode 100644
index 000000000..1b632f1cb
--- /dev/null
+++ b/crates/isobmff/src/lib.rs
@@ -0,0 +1,26 @@
+//! Clean-room ISO Base Media File Format (MP4, ISO/IEC 14496-12/14/15) and QuickTime (MOV) support.
+//!
+//! - **Demux:** [`open`] parses box headers plus `moov` (and `moof` for fragmented files) from a
+//! [`ByteSource`] and builds per-track [`Sample`] tables; media data is read on demand with
+//! [`Mp4File::read_sample`].
+//! - **Mux:** [`Mp4Writer`] writes progressive MP4/MOV (optionally faststart);
+//! [`FragmentedWriter`] writes fragmented MP4.
+//!
+//! See the crate README for supported boxes and limitations.
+
+mod bytes;
+mod codec;
+mod demux;
+mod error;
+mod mux;
+mod source;
+
+pub use bytes::FourCc;
+pub use codec::{
+ AacConfig, AudioParams, Av1Config, AvcConfig, BitRate, CleanAperture, CodecConfig, ColorInfo, FieldInfo, FlacConfig, HevcConfig, HevcNalArray, OpusConfig,
+ PcmConfig, SampleEntry, TimecodeConfig, VideoParams, VpcConfig, parse_asc,
+};
+pub use demux::{Edit, Metadata, Mp4File, Sample, SampleGroup, Track, TrackKind, open};
+pub use error::{Error, Result};
+pub use mux::{Brand, FragmentedWriter, Mp4Writer, TrackConfig, WriteSample, WriterOptions};
+pub use source::ByteSource;
diff --git a/crates/isobmff/src/mux.rs b/crates/isobmff/src/mux.rs
new file mode 100644
index 000000000..83a4dc100
--- /dev/null
+++ b/crates/isobmff/src/mux.rs
@@ -0,0 +1,946 @@
+//! Muxers: progressive MP4/MOV ([`Mp4Writer`], optional faststart) and fragmented MP4 ([`FragmentedWriter`]).
+
+use crate::bytes::BoxBuf;
+use crate::codec::{CodecConfig, SampleEntry, TimecodeConfig};
+use crate::demux::Edit;
+use crate::error::{Error, Result};
+use std::io::{Read, Seek, SeekFrom, Write};
+
+/// Output flavour: determines brands and some sample-entry encodings.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Brand {
+ /// ISO MP4: `isom` major brand, compatible `isom iso2 avc1 mp41 mp42`.
+ Mp4,
+ /// QuickTime MOV: `qt ` major brand.
+ Mov,
+}
+
+/// Movie-level writer options.
+#[derive(Clone, Debug)]
+pub struct WriterOptions {
+ pub brand: Brand,
+ /// Movie timescale (`mvhd`); default 1000.
+ pub movie_timescale: u32,
+ /// Text metadata written to `moov/udta` (keys like `©nam`, `©ART`, `©cmt`, `©too`).
+ pub metadata: Vec<(String, String)>,
+}
+
+impl WriterOptions {
+ pub fn new(brand: Brand) -> Self {
+ WriterOptions { brand, movie_timescale: 1000, metadata: Vec::new() }
+ }
+}
+
+/// Per-track configuration.
+#[derive(Clone, Debug)]
+pub struct TrackConfig {
+ pub entry: SampleEntry,
+ /// Media timescale. For PCM it must equal the sample rate (one tick per audio frame).
+ pub timescale: u32,
+ /// ISO 639-2/T language (`und` by default).
+ pub language: String,
+ /// Explicit edit list (segment durations in the movie timescale). Takes precedence over `media_start`.
+ pub edits: Vec<Edit>,
+ /// Convenience: create one edit starting at this media time (e.g. AAC encoder delay / priming,
+ /// or the first pts of a B-frame stream) spanning the rest of the media.
+ pub media_start: Option<i64>,
+ /// `hdlr` name; a sensible default is used when `None`.
+ pub handler_name: Option<String>,
+}
+
+impl TrackConfig {
+ pub fn new(entry: SampleEntry, timescale: u32) -> Self {
+ TrackConfig { entry, timescale, language: "und".into(), edits: Vec::new(), media_start: None, handler_name: None }
+ }
+}
+
+/// A sample handed to the muxers.
+#[derive(Clone, Copy, Debug)]
+pub struct WriteSample<'a> {
+ pub data: &'a [u8],
+ /// Duration in the media timescale. Ignored for PCM (each frame lasts one tick).
+ pub duration: u32,
+ /// pts − dts in the media timescale.
+ pub composition_offset: i32,
+ pub is_sync: bool,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Handler {
+ Video,
+ Audio,
+ Timecode,
+ Other,
+}
+
+fn handler_of(e: &SampleEntry) -> Handler {
+ if matches!(e.codec, CodecConfig::Timecode(_)) {
+ Handler::Timecode
+ } else if e.video.is_some() {
+ Handler::Video
+ } else if e.audio.is_some() {
+ Handler::Audio
+ } else {
+ Handler::Other
+ }
+}
+
+/// Accumulated sample tables for one track.
+#[derive(Clone, Debug, Default)]
+struct Tables {
+ stts: Vec<(u32, u32)>,
+ ctts: Vec<(u32, i32)>,
+ sizes: Vec<u32>,
+ /// Constant sample size (PCM) — then `sizes` is unused.
+ const_size: Option<u32>,
+ sample_count: u64,
+ /// 1-based sync sample numbers.
+ sync: Vec<u32>,
+ all_sync: bool,
+ /// (offset relative to file start before shifting, sample count)
+ chunks: Vec<(u64, u32)>,
+ media_duration: u64,
+}
+
+impl Tables {
+ fn new() -> Self {
+ Tables { all_sync: true, ..Default::default() }
+ }
+ fn push_run<T: PartialEq + Copy>(runs: &mut Vec<(u32, T)>, count: u32, v: T) {
+ if let Some(last) = runs.last_mut()
+ && last.1 == v
+ && last.0.checked_add(count).is_some()
+ {
+ last.0 += count;
+ return;
+ }
+ runs.push((count, v));
+ }
+}
+
+struct WTrack {
+ cfg: TrackConfig,
+ id: u32,
+ handler: Handler,
+ pcm_frame_bytes: Option<u32>,
+ t: Tables,
+ /// Track id of a linked timecode track (`tref/tmcd`).
+ tmcd_ref: Option<u32>,
+ /// For timecode tracks: (video track index, start frame).
+ tmcd_source: Option<(usize, u32)>,
+}
+
+fn pack_language(lang: &str) -> u16 {
+ let b = lang.as_bytes();
+ if b.len() == 3 && b.iter().all(|c| c.is_ascii_lowercase()) {
+ (((b[0] - 0x60) as u16) << 10) | (((b[1] - 0x60) as u16) << 5) | ((b[2] - 0x60) as u16)
+ } else {
+ 0x55C4 // "und"
+ }
+}
+
+fn rescale(v: u64, from: u32, to: u32) -> u64 {
+ if from == 0 {
+ return 0;
+ }
+ (v as u128 * to as u128 / from as u128).min(u64::MAX as u128) as u64
+}
+
+const MATRIX: [i32; 9] = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000];
+
+fn write_ftyp(b: &mut BoxBuf, brand: Brand) {
+ let m = b.start(b"ftyp");
+ match brand {
+ Brand::Mp4 => {
+ b.bytes(b"isom");
+ b.u32(0x200);
+ for c in [b"isom", b"iso2", b"avc1", b"mp41", b"mp42"] {
+ b.bytes(c);
+ }
+ }
+ Brand::Mov => {
+ b.bytes(b"qt ");
+ b.u32(0x200);
+ b.bytes(b"qt ");
+ }
+ }
+ b.end(m);
+}
+
+fn movie_duration(tracks: &[WTrack], movie_ts: u32) -> u64 {
+ tracks.iter().map(|t| presentation_duration(t, movie_ts)).max().unwrap_or(0)
+}
+
+fn effective_edits(t: &WTrack, movie_ts: u32) -> Vec<Edit> {
+ if !t.cfg.edits.is_empty() {
+ return t.cfg.edits.clone();
+ }
+ if let Some(start) = t.cfg.media_start {
+ let rest = t.t.media_duration.saturating_sub(start.max(0) as u64);
+ return vec![Edit { segment_duration: rescale(rest, t.cfg.timescale, movie_ts), media_time: start, media_rate: 0x10000 }];
+ }
+ Vec::new()
+}
+
+fn presentation_duration(t: &WTrack, movie_ts: u32) -> u64 {
+ let e = effective_edits(t, movie_ts);
+ if e.is_empty() { rescale(t.t.media_duration, t.cfg.timescale, movie_ts) } else { e.iter().map(|e| e.segment_duration).sum() }
+}
+
+fn write_mvhd(b: &mut BoxBuf, timescale: u32, duration: u64, next_id: u32) {
+ let v1 = duration > u32::MAX as u64;
+ let m = b.start_full(b"mvhd", v1 as u8, 0);
+ if v1 {
+ b.u64(0);
+ b.u64(0);
+ b.u32(timescale);
+ b.u64(duration);
+ } else {
+ b.u32(0);
+ b.u32(0);
+ b.u32(timescale);
+ b.u32(duration as u32);
+ }
+ b.u32(0x10000);
+ b.u16(0x100);
+ b.zeros(10);
+ for v in MATRIX {
+ b.i32(v);
+ }
+ b.zeros(24);
+ b.u32(next_id);
+ b.end(m);
+}
+
+fn write_trak(b: &mut BoxBuf, t: &WTrack, movie_ts: u32, qt: bool, shift: u64, force_co64: bool) -> Result<()> {
+ let trak = b.start(b"trak");
+ let dur = presentation_duration(t, movie_ts);
+ let v1 = dur > u32::MAX as u64;
+ let m = b.start_full(b"tkhd", v1 as u8, 3);
+ if v1 {
+ b.u64(0);
+ b.u64(0);
+ b.u32(t.id);
+ b.u32(0);
+ b.u64(dur);
+ } else {
+ b.u32(0);
+ b.u32(0);
+ b.u32(t.id);
+ b.u32(0);
+ b.u32(dur as u32);
+ }
+ b.zeros(8);
+ b.i16(0);
+ b.u16(0);
+ b.i16(if t.handler == Handler::Audio { 0x100 } else { 0 });
+ b.u16(0);
+ for v in MATRIX {
+ b.i32(v);
+ }
+ let (w, h) = match &t.cfg.entry.video {
+ Some(v) => {
+ let w = match v.pixel_aspect {
+ Some((hs, vs)) if hs > 0 && vs > 0 => (v.width as u64 * hs as u64 / vs as u64) as u32,
+ _ => v.width as u32,
+ };
+ (w, v.height as u32)
+ }
+ None => (0, 0),
+ };
+ b.u32(w << 16);
+ b.u32(h << 16);
+ b.end(m);
+ let edits = effective_edits(t, movie_ts);
+ if !edits.is_empty() {
+ let e = b.start(b"edts");
+ let v1 = edits.iter().any(|e| e.segment_duration > u32::MAX as u64 || e.media_time > i32::MAX as i64 || e.media_time < i32::MIN as i64);
+ let l = b.start_full(b"elst", v1 as u8, 0);
+ b.u32(edits.len() as u32);
+ for ed in &edits {
+ if v1 {
+ b.u64(ed.segment_duration);
+ b.i64(ed.media_time);
+ } else {
+ b.u32(ed.segment_duration as u32);
+ b.i32(ed.media_time as i32);
+ }
+ b.i32(ed.media_rate);
+ }
+ b.end(l);
+ b.end(e);
+ }
+ if let Some(id) = t.tmcd_ref {
+ let r = b.start(b"tref");
+ let m = b.start(b"tmcd");
+ b.u32(id);
+ b.end(m);
+ b.end(r);
+ }
+ let mdia = b.start(b"mdia");
+ let mv1 = t.t.media_duration > u32::MAX as u64;
+ let m = b.start_full(b"mdhd", mv1 as u8, 0);
+ if mv1 {
+ b.u64(0);
+ b.u64(0);
+ b.u32(t.cfg.timescale);
+ b.u64(t.t.media_duration);
+ } else {
+ b.u32(0);
+ b.u32(0);
+ b.u32(t.cfg.timescale);
+ b.u32(t.t.media_duration as u32);
+ }
+ b.u16(pack_language(&t.cfg.language));
+ b.u16(0);
+ b.end(m);
+ let (htype, default_name) = match t.handler {
+ Handler::Video => (b"vide", "VideoHandler"),
+ Handler::Audio => (b"soun", "SoundHandler"),
+ Handler::Timecode => (b"tmcd", "TimeCodeHandler"),
+ Handler::Other => (b"meta", "MetaHandler"),
+ };
+ let name = t.cfg.handler_name.clone().unwrap_or_else(|| default_name.into());
+ let m = b.start_full(b"hdlr", 0, 0);
+ b.bytes(if qt { b"mhlr" } else { &[0, 0, 0, 0] });
+ b.bytes(htype);
+ b.zeros(12);
+ if qt {
+ let n = name.len().min(255);
+ b.u8(n as u8);
+ b.bytes(&name.as_bytes()[..n]);
+ } else {
+ b.bytes(name.as_bytes());
+ b.u8(0);
+ }
+ b.end(m);
+ let minf = b.start(b"minf");
+ match t.handler {
+ Handler::Video => {
+ let m = b.start_full(b"vmhd", 0, 1);
+ b.zeros(8);
+ b.end(m);
+ }
+ Handler::Audio => {
+ let m = b.start_full(b"smhd", 0, 0);
+ b.zeros(4);
+ b.end(m);
+ }
+ Handler::Timecode => {
+ let g = b.start(b"gmhd");
+ let m = b.start_full(b"gmin", 0, 0);
+ b.u16(0x40);
+ b.u16(0x8000);
+ b.u16(0x8000);
+ b.u16(0x8000);
+ b.i16(0);
+ b.u16(0);
+ b.end(m);
+ let tm = b.start(b"tmcd");
+ let m = b.start_full(b"tcmi", 0, 0);
+ b.u16(0);
+ b.u16(0);
+ b.u16(12);
+ b.u16(0);
+ b.bytes(&[0xFF; 6]);
+ b.zeros(6);
+ b.u8(0);
+ b.end(m);
+ b.end(tm);
+ b.end(g);
+ }
+ Handler::Other => {
+ let m = b.start_full(b"nmhd", 0, 0);
+ b.end(m);
+ }
+ }
+ if qt {
+ // QuickTime data handler reference.
+ let m = b.start_full(b"hdlr", 0, 0);
+ b.bytes(b"dhlr");
+ b.bytes(b"url ");
+ b.zeros(12);
+ b.u8(0);
+ b.end(m);
+ }
+ let d = b.start(b"dinf");
+ let r = b.start_full(b"dref", 0, 0);
+ b.u32(1);
+ let u = b.start_full(b"url ", 0, 1);
+ b.end(u);
+ b.end(r);
+ b.end(d);
+ let stbl = b.start(b"stbl");
+ let m = b.start_full(b"stsd", 0, 0);
+ b.u32(1);
+ t.cfg.entry.write(b, qt)?;
+ b.end(m);
+ let tb = &t.t;
+ let m = b.start_full(b"stts", 0, 0);
+ b.u32(tb.stts.len() as u32);
+ for &(c, d) in &tb.stts {
+ b.u32(c);
+ b.u32(d);
+ }
+ b.end(m);
+ if tb.ctts.iter().any(|&(_, o)| o != 0) {
+ let neg = tb.ctts.iter().any(|&(_, o)| o < 0);
+ let m = b.start_full(b"ctts", neg as u8, 0);
+ b.u32(tb.ctts.len() as u32);
+ for &(c, o) in &tb.ctts {
+ b.u32(c);
+ b.i32(o);
+ }
+ b.end(m);
+ }
+ if !tb.all_sync {
+ let m = b.start_full(b"stss", 0, 0);
+ b.u32(tb.sync.len() as u32);
+ for &s in &tb.sync {
+ b.u32(s);
+ }
+ b.end(m);
+ }
+ let m = b.start_full(b"stsc", 0, 0);
+ let mut runs: Vec<(u32, u32)> = Vec::new();
+ for (i, &(_, n)) in tb.chunks.iter().enumerate() {
+ if runs.last().is_none_or(|r| r.1 != n) {
+ runs.push((i as u32 + 1, n));
+ }
+ }
+ b.u32(runs.len() as u32);
+ for (first, n) in runs {
+ b.u32(first);
+ b.u32(n);
+ b.u32(1);
+ }
+ b.end(m);
+ let m = b.start_full(b"stsz", 0, 0);
+ match tb.const_size {
+ Some(s) => {
+ b.u32(s);
+ b.u32(tb.sample_count.min(u32::MAX as u64) as u32);
+ }
+ None => {
+ let first = tb.sizes.first().copied().unwrap_or(0);
+ if !tb.sizes.is_empty() && tb.sizes.iter().all(|&s| s == first) {
+ b.u32(first);
+ b.u32(tb.sizes.len() as u32);
+ } else {
+ b.u32(0);
+ b.u32(tb.sizes.len() as u32);
+ for &s in &tb.sizes {
+ b.u32(s);
+ }
+ }
+ }
+ }
+ b.end(m);
+ let co64 = force_co64 || tb.chunks.iter().any(|&(o, _)| o + shift > u32::MAX as u64);
+ let m = b.start_full(if co64 { b"co64" } else { b"stco" }, 0, 0);
+ b.u32(tb.chunks.len() as u32);
+ for &(o, _) in &tb.chunks {
+ if co64 {
+ b.u64(o + shift);
+ } else {
+ b.u32((o + shift) as u32);
+ }
+ }
+ b.end(m);
+ b.end(stbl);
+ b.end(minf);
+ b.end(mdia);
+ b.end(trak);
+ Ok(())
+}
+
+fn write_udta(b: &mut BoxBuf, md: &[(String, String)]) {
+ let items: Vec<([u8; 4], &str)> = md
+ .iter()
+ .filter_map(|(k, v)| {
+ let mut chars = k.chars();
+ if chars.next()? != '©' {
+ return None;
+ }
+ let rest: Vec<u8> = chars.map(|c| c as u32 as u8).collect();
+ (rest.len() == 3).then(|| ([0xA9, rest[0], rest[1], rest[2]], v.as_str()))
+ })
+ .collect();
+ if items.is_empty() {
+ return;
+ }
+ let u = b.start(b"udta");
+ for (k, v) in items {
+ let m = b.start(&k);
+ b.u16(v.len() as u16);
+ b.u16(0x55C4);
+ b.bytes(v.as_bytes());
+ b.end(m);
+ }
+ b.end(u);
+}
+
+fn validate_track(cfg: &TrackConfig) -> Result<Option<u32>> {
+ if cfg.timescale == 0 {
+ return Err(Error::Mux("timescale must be non-zero".into()));
+ }
+ if let CodecConfig::Pcm(p) = &cfg.entry.codec {
+ if p.bits == 0 || p.channels == 0 {
+ return Err(Error::Mux("PCM needs bits and channels".into()));
+ }
+ if (p.sample_rate - cfg.timescale as f64).abs() > 0.5 {
+ return Err(Error::Mux("PCM track timescale must equal the sample rate".into()));
+ }
+ return Ok(Some(p.bytes_per_frame()));
+ }
+ Ok(None)
+}
+
+/// Progressive MP4/MOV writer: `ftyp`, then one `mdat` streamed to `W`, then `moov` at [`finish`](Self::finish)
+/// (or moved in front of `mdat` by [`finish_faststart`](Self::finish_faststart)).
+pub struct Mp4Writer<W: Write + Seek> {
+ w: W,
+ opts: WriterOptions,
+ tracks: Vec<WTrack>,
+ /// Offset of the placeholder box (8 bytes) preceding the mdat header.
+ pad_pos: u64,
+ mdat_pos: u64,
+ pos: u64,
+ last_track: Option<usize>,
+}
+
+impl<W: Write + Seek> Mp4Writer<W> {
+ /// Start a file: writes `ftyp`, a placeholder box and the `mdat` header.
+ pub fn new(mut w: W, opts: WriterOptions) -> Result<Self> {
+ let start = w.stream_position()?;
+ let mut b = BoxBuf::new();
+ write_ftyp(&mut b, opts.brand);
+ let pad_pos = start + b.len() as u64;
+ b.leaf(if opts.brand == Brand::Mov { b"wide" } else { b"free" }, &[]);
+ let mdat_pos = start + b.len() as u64;
+ b.leaf(b"mdat", &[]);
+ w.write_all(&b.buf)?;
+ let pos = start + b.len() as u64;
+ Ok(Mp4Writer { w, opts, tracks: Vec::new(), pad_pos, mdat_pos, pos, last_track: None })
+ }
+
+ /// Add a track; returns its index (track ids are index + 1).
+ pub fn add_track(&mut self, cfg: TrackConfig) -> Result<usize> {
+ let pcm = validate_track(&cfg)?;
+ let handler = handler_of(&cfg.entry);
+ let mut t = Tables::new();
+ t.const_size = pcm;
+ self.tracks.push(WTrack { id: self.tracks.len() as u32 + 1, handler, pcm_frame_bytes: pcm, t, cfg, tmcd_ref: None, tmcd_source: None });
+ Ok(self.tracks.len() - 1)
+ }
+
+ /// Add a QuickTime timecode track referenced by `video_track`. Its single sample (the start
+ /// frame number) is written at finish, spanning the video track's duration.
+ pub fn add_timecode_track(&mut self, video_track: usize, tc: TimecodeConfig, start_frame: u32) -> Result<usize> {
+ if video_track >= self.tracks.len() {
+ return Err(Error::NoSuchTrack(video_track));
+ }
+ if tc.timescale == 0 || tc.frame_duration == 0 || tc.frames_per_second == 0 {
+ return Err(Error::Mux("timecode needs timescale, frame duration and fps".into()));
+ }
+ let entry = SampleEntry {
+ format: crate::bytes::FourCc(*b"tmcd"),
+ data_reference_index: 1,
+ codec: CodecConfig::Timecode(tc.clone()),
+ video: None,
+ audio: None,
+ bitrate: None,
+ };
+ let idx = self.add_track(TrackConfig::new(entry, tc.timescale))?;
+ self.tracks[idx].tmcd_source = Some((video_track, start_frame));
+ let id = self.tracks[idx].id;
+ self.tracks[video_track].tmcd_ref = Some(id);
+ Ok(idx)
+ }
+
+ /// Append one sample to track `track` (decode order). For PCM tracks `data` may hold any whole
+ /// number of audio frames.
+ pub fn write_sample(&mut self, track: usize, s: WriteSample) -> Result<()> {
+ let tr = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?;
+ if tr.tmcd_source.is_some() {
+ return Err(Error::Mux("timecode track samples are written automatically".into()));
+ }
+ let (count, dur) = match tr.pcm_frame_bytes {
+ Some(fb) => {
+ if !s.data.len().is_multiple_of(fb as usize) {
+ return Err(Error::Mux("PCM data is not a whole number of frames".into()));
+ }
+ ((s.data.len() / fb as usize) as u32, 1u32)
+ }
+ None => {
+ if s.data.len() > u32::MAX as usize {
+ return Err(Error::Mux("sample larger than 4 GiB".into()));
+ }
+ (1, s.duration)
+ }
+ };
+ if count == 0 {
+ return Ok(());
+ }
+ self.w.write_all(s.data)?;
+ let offset = self.pos;
+ self.pos += s.data.len() as u64;
+ let contiguous = self.last_track == Some(track);
+ self.last_track = Some(track);
+ let tr = &mut self.tracks[track];
+ let t = &mut tr.t;
+ Tables::push_run(&mut t.stts, count, dur);
+ Tables::push_run(&mut t.ctts, count, if tr.pcm_frame_bytes.is_some() { 0 } else { s.composition_offset });
+ if tr.pcm_frame_bytes.is_none() {
+ t.sizes.push(s.data.len() as u32);
+ if s.is_sync {
+ t.sync.push(t.sample_count as u32 + 1);
+ } else {
+ t.all_sync = false;
+ }
+ }
+ t.sample_count += count as u64;
+ t.media_duration += count as u64 * dur as u64;
+ match t.chunks.last_mut() {
+ Some(c) if contiguous => c.1 += count,
+ _ => t.chunks.push((offset, count)),
+ }
+ Ok(())
+ }
+
+ fn finish_mdat(&mut self) -> Result<()> {
+ // Timecode samples.
+ for i in 0..self.tracks.len() {
+ let Some((vi, start)) = self.tracks[i].tmcd_source else { continue };
+ let v = &self.tracks[vi];
+ let vd = v.t.media_duration;
+ let vts = v.cfg.timescale;
+ let tts = self.tracks[i].cfg.timescale;
+ let tc_dur = match &self.tracks[i].cfg.entry.codec {
+ CodecConfig::Timecode(tc) => tc.frame_duration,
+ _ => 1,
+ };
+ let d = rescale(vd, vts, tts).max(tc_dur as u64).min(u32::MAX as u64) as u32;
+ self.w.write_all(&start.to_be_bytes())?;
+ let off = self.pos;
+ self.pos += 4;
+ self.last_track = None;
+ let t = &mut self.tracks[i].t;
+ t.stts.push((1, d));
+ t.sizes.push(4);
+ t.sync.push(1);
+ t.sample_count = 1;
+ t.media_duration = d as u64;
+ t.chunks.push((off, 1));
+ }
+ let size = self.pos - self.mdat_pos;
+ if size <= u32::MAX as u64 {
+ self.w.seek(SeekFrom::Start(self.mdat_pos))?;
+ self.w.write_all(&(size as u32).to_be_bytes())?;
+ } else {
+ // Merge the placeholder into a 16-byte large-size mdat header.
+ let mut h = [0u8; 16];
+ h[..4].copy_from_slice(&1u32.to_be_bytes());
+ h[4..8].copy_from_slice(b"mdat");
+ h[8..].copy_from_slice(&(self.pos - self.pad_pos).to_be_bytes());
+ self.w.seek(SeekFrom::Start(self.pad_pos))?;
+ self.w.write_all(&h)?;
+ }
+ self.w.seek(SeekFrom::Start(self.pos))?;
+ Ok(())
+ }
+
+ fn build_moov(&self, shift: u64, force_co64: bool) -> Result<Vec<u8>> {
+ let qt = self.opts.brand == Brand::Mov;
+ let ts = self.opts.movie_timescale.max(1);
+ let mut b = BoxBuf::new();
+ let m = b.start(b"moov");
+ write_mvhd(&mut b, ts, movie_duration(&self.tracks, ts), self.tracks.len() as u32 + 1);
+ for t in &self.tracks {
+ write_trak(&mut b, t, ts, qt, shift, force_co64)?;
+ }
+ write_udta(&mut b, &self.opts.metadata);
+ b.end(m);
+ Ok(b.buf)
+ }
+
+ /// Finish the file with `moov` after `mdat`. Returns the underlying writer.
+ pub fn finish(mut self) -> Result<W> {
+ self.finish_mdat()?;
+ let moov = self.build_moov(0, false)?;
+ self.w.write_all(&moov)?;
+ self.w.flush()?;
+ Ok(self.w)
+ }
+}
+
+impl<W: Read + Write + Seek> Mp4Writer<W> {
+ /// Finish with `moov` in front of `mdat` ("fast start"): media data is shifted forward in place.
+ pub fn finish_faststart(mut self) -> Result<W> {
+ self.finish_mdat()?;
+ let mut moov = self.build_moov(0, false)?;
+ let mut force = false;
+ loop {
+ let shift = moov.len() as u64;
+ let next = self.build_moov(shift, force)?;
+ if next.len() == moov.len() {
+ moov = next;
+ break;
+ }
+ // Offsets crossed the 32-bit boundary: switch to co64 (size only grows, so this converges).
+ force = true;
+ moov = next;
+ }
+ let shift = moov.len() as u64;
+ let start = self.pad_pos;
+ let end = self.pos;
+ let mut buf = vec![0u8; 1 << 20];
+ let mut cur = end;
+ while cur > start {
+ let n = (cur - start).min(buf.len() as u64) as usize;
+ cur -= n as u64;
+ self.w.seek(SeekFrom::Start(cur))?;
+ self.w.read_exact(&mut buf[..n])?;
+ self.w.seek(SeekFrom::Start(cur + shift))?;
+ self.w.write_all(&buf[..n])?;
+ }
+ self.w.seek(SeekFrom::Start(start))?;
+ self.w.write_all(&moov)?;
+ self.w.seek(SeekFrom::Start(end + shift))?;
+ self.w.flush()?;
+ Ok(self.w)
+ }
+}
+
+/// Buffered fragment sample: (data, duration, composition offset, sync).
+type PendingSample = (Vec<u8>, u32, i32, bool);
+
+/// Fragmented MP4 writer: an init segment (`ftyp` + `moov` with `mvex`) followed by
+/// `moof`+`mdat` fragments. Samples are buffered until [`flush_fragment`](Self::flush_fragment).
+pub struct FragmentedWriter<W: Write> {
+ w: W,
+ opts: WriterOptions,
+ tracks: Vec<WTrack>,
+ pending: Vec<Vec<PendingSample>>,
+ next_dts: Vec<u64>,
+ seq: u32,
+ init_written: bool,
+}
+
+impl<W: Write> FragmentedWriter<W> {
+ pub fn new(w: W, opts: WriterOptions) -> Self {
+ FragmentedWriter { w, opts, tracks: Vec::new(), pending: Vec::new(), next_dts: Vec::new(), seq: 0, init_written: false }
+ }
+
+ /// Add a track (before the first fragment). PCM is not supported in fragments.
+ pub fn add_track(&mut self, cfg: TrackConfig) -> Result<usize> {
+ if self.init_written {
+ return Err(Error::Mux("tracks must be added before the first fragment".into()));
+ }
+ if validate_track(&cfg)?.is_some() {
+ return Err(Error::Mux("PCM is not supported by the fragmented writer".into()));
+ }
+ let handler = handler_of(&cfg.entry);
+ self.tracks.push(WTrack { id: self.tracks.len() as u32 + 1, handler, pcm_frame_bytes: None, t: Tables::new(), cfg, tmcd_ref: None, tmcd_source: None });
+ self.pending.push(Vec::new());
+ self.next_dts.push(0);
+ Ok(self.tracks.len() - 1)
+ }
+
+ fn write_init(&mut self) -> Result<()> {
+ let qt = self.opts.brand == Brand::Mov;
+ let ts = self.opts.movie_timescale.max(1);
+ let mut b = BoxBuf::new();
+ write_ftyp(&mut b, self.opts.brand);
+ let m = b.start(b"moov");
+ write_mvhd(&mut b, ts, 0, self.tracks.len() as u32 + 1);
+ for t in &self.tracks {
+ write_trak(&mut b, t, ts, qt, 0, false)?;
+ }
+ let mv = b.start(b"mvex");
+ for t in &self.tracks {
+ let x = b.start_full(b"trex", 0, 0);
+ b.u32(t.id);
+ b.u32(1);
+ b.u32(0);
+ b.u32(0);
+ b.u32(0);
+ b.end(x);
+ }
+ b.end(mv);
+ write_udta(&mut b, &self.opts.metadata);
+ b.end(m);
+ self.w.write_all(&b.buf)?;
+ self.init_written = true;
+ Ok(())
+ }
+
+ /// Buffer a sample for the next fragment.
+ pub fn write_sample(&mut self, track: usize, s: WriteSample) -> Result<()> {
+ let p = self.pending.get_mut(track).ok_or(Error::NoSuchTrack(track))?;
+ if s.data.len() > u32::MAX as usize {
+ return Err(Error::Mux("sample larger than 4 GiB".into()));
+ }
+ p.push((s.data.to_vec(), s.duration, s.composition_offset, s.is_sync));
+ Ok(())
+ }
+
+ fn build_moof(&self, data_offsets: &[i32]) -> Vec<u8> {
+ let mut b = BoxBuf::new();
+ let m = b.start(b"moof");
+ let h = b.start_full(b"mfhd", 0, 0);
+ b.u32(self.seq);
+ b.end(h);
+ for (i, t) in self.tracks.iter().enumerate() {
+ let p = &self.pending[i];
+ if p.is_empty() {
+ continue;
+ }
+ let tf = b.start(b"traf");
+ let h = b.start_full(b"tfhd", 0, 0x20000);
+ b.u32(t.id);
+ b.end(h);
+ let h = b.start_full(b"tfdt", 1, 0);
+ b.u64(self.next_dts[i]);
+ b.end(h);
+ let neg = p.iter().any(|s| s.2 < 0);
+ let h = b.start_full(b"trun", neg as u8, 0x1 | 0x100 | 0x200 | 0x400 | 0x800);
+ b.u32(p.len() as u32);
+ b.i32(data_offsets[i]);
+ for (d, dur, cto, sync) in p {
+ b.u32(*dur);
+ b.u32(d.len() as u32);
+ b.u32(if *sync { 0x0200_0000 } else { 0x0101_0000 });
+ b.i32(*cto);
+ }
+ b.end(h);
+ b.end(tf);
+ }
+ b.end(m);
+ b.buf
+ }
+
+ /// Write all buffered samples as one `moof` + `mdat` fragment (no-op if nothing is buffered).
+ pub fn flush_fragment(&mut self) -> Result<()> {
+ if !self.init_written {
+ self.write_init()?;
+ }
+ if self.pending.iter().all(|p| p.is_empty()) {
+ return Ok(());
+ }
+ self.seq += 1;
+ let probe = self.build_moof(&vec![0; self.tracks.len()]);
+ let data_len: u64 = self.pending.iter().flatten().map(|s| s.0.len() as u64).sum();
+ let large = data_len + 8 > u32::MAX as u64;
+ let hdr = if large { 16 } else { 8 };
+ let mut offs = Vec::with_capacity(self.tracks.len());
+ let mut acc = probe.len() as u64 + hdr;
+ for p in &self.pending {
+ offs.push(i32::try_from(acc).map_err(|_| Error::Mux("fragment too large".into()))?);
+ acc += p.iter().map(|s| s.0.len() as u64).sum::<u64>();
+ }
+ let moof = self.build_moof(&offs);
+ self.w.write_all(&moof)?;
+ if large {
+ self.w.write_all(&1u32.to_be_bytes())?;
+ self.w.write_all(b"mdat")?;
+ self.w.write_all(&(data_len + 16).to_be_bytes())?;
+ } else {
+ self.w.write_all(&((data_len + 8) as u32).to_be_bytes())?;
+ self.w.write_all(b"mdat")?;
+ }
+ for (i, p) in self.pending.iter_mut().enumerate() {
+ for (d, dur, _, _) in p.drain(..) {
+ self.w.write_all(&d)?;
+ self.next_dts[i] += dur as u64;
+ }
+ }
+ Ok(())
+ }
+
+ /// Flush remaining samples and return the writer.
+ pub fn finish(mut self) -> Result<W> {
+ self.flush_fragment()?;
+ self.w.flush()?;
+ Ok(self.w)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::codec::{AvcConfig, PcmConfig};
+ use std::io::Cursor;
+
+ fn avc_entry() -> SampleEntry {
+ SampleEntry::avc(AvcConfig::new(vec![vec![0x67, 0x42, 0, 0x1E]], vec![vec![0x68, 0xCE]], 4), 64, 48)
+ }
+
+ #[test]
+ fn language_pack() {
+ assert_eq!(pack_language("und"), 0x55C4);
+ assert_eq!(pack_language("eng"), 0x15C7);
+ assert_eq!(pack_language("EN"), 0x55C4);
+ }
+
+ #[test]
+ fn simple_roundtrip_and_faststart() {
+ for fast in [false, true] {
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
+ let v = w.add_track(TrackConfig::new(avc_entry(), 12800)).unwrap();
+ let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48000.0 };
+ let a = w.add_track(TrackConfig::new(SampleEntry::pcm(pcm), 48000)).unwrap();
+ for i in 0..10u8 {
+ let data = vec![i; 100 + i as usize];
+ w.write_sample(v, WriteSample { data: &data, duration: 512, composition_offset: if i % 2 == 0 { 1024 } else { 0 }, is_sync: i % 5 == 0 })
+ .unwrap();
+ w.write_sample(a, WriteSample { data: &[i; 400], duration: 0, composition_offset: 0, is_sync: true }).unwrap();
+ }
+ let out = if fast { w.finish_faststart() } else { w.finish() }.unwrap().into_inner();
+ let f = crate::open(out.as_slice()).unwrap();
+ assert_eq!(f.tracks.len(), 2);
+ let t = &f.tracks[0];
+ assert_eq!(t.samples.len(), 10);
+ for (i, s) in t.samples.iter().enumerate() {
+ assert_eq!(s.size as usize, 100 + i);
+ assert_eq!(s.dts, 512 * i as i64);
+ assert_eq!(s.is_sync, i % 5 == 0);
+ assert_eq!(f.read_sample(out.as_slice(), 0, i).unwrap(), vec![i as u8; 100 + i]);
+ }
+ let at = &f.tracks[1];
+ assert!(at.pcm_chunked);
+ assert_eq!(at.samples.len(), 10);
+ assert_eq!(at.samples[3].size, 400);
+ assert_eq!(at.samples[3].duration, 100);
+ assert_eq!(f.read_sample(out.as_slice(), 1, 3).unwrap(), vec![3u8; 400]);
+ if fast {
+ assert!(f.moov_offset < t.samples[0].offset);
+ }
+ }
+ }
+
+ #[test]
+ fn fragmented_roundtrip() {
+ let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4));
+ let v = w.add_track(TrackConfig::new(avc_entry(), 1000)).unwrap();
+ for i in 0..6u8 {
+ w.write_sample(v, WriteSample { data: &[i; 10], duration: 40, composition_offset: -(i as i32 % 2), is_sync: i % 3 == 0 }).unwrap();
+ if i % 3 == 2 {
+ w.flush_fragment().unwrap();
+ }
+ }
+ let out = w.finish().unwrap();
+ let f = crate::open(out.as_slice()).unwrap();
+ assert!(f.fragmented);
+ assert_eq!(f.fragment_count, 2);
+ let t = &f.tracks[0];
+ assert_eq!(t.samples.len(), 6);
+ for (i, s) in t.samples.iter().enumerate() {
+ assert_eq!(s.dts, 40 * i as i64);
+ assert_eq!(s.pts, s.dts - (i as i64 % 2));
+ assert_eq!(s.is_sync, i % 3 == 0);
+ assert_eq!(f.read_sample(out.as_slice(), 0, i).unwrap(), vec![i as u8; 10]);
+ }
+ assert_eq!(t.sync_sample_before(5), 3);
+ }
+}
diff --git a/crates/isobmff/src/source.rs b/crates/isobmff/src/source.rs
new file mode 100644
index 000000000..0dad82b20
--- /dev/null
+++ b/crates/isobmff/src/source.rs
@@ -0,0 +1,123 @@
+//! Random-access byte sources for the demuxer.
+
+use std::io;
+use std::sync::Arc;
+
+/// Random-access, read-only byte source (file, in-memory buffer, web Blob…).
+///
+/// Implementations must be able to serve reads at arbitrary offsets through `&self`.
+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)?;
+ let src = self.get(start..end).ok_or_else(eof)?;
+ buf.copy_from_slice(src);
+ 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 Arc<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 Box<T> {
+ fn len(&self) -> u64 {
+ (**self).len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ (**self).read_at(offset, buf)
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl ByteSource for std::fs::File {
+ fn len(&self) -> u64 {
+ self.metadata().map(|m| m.len()).unwrap_or(0)
+ }
+ #[cfg(unix)]
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ std::os::unix::fs::FileExt::read_exact_at(self, buf, offset)
+ }
+ #[cfg(windows)]
+ fn read_at(&self, mut offset: u64, mut buf: &mut [u8]) -> io::Result<()> {
+ use std::os::windows::fs::FileExt;
+ while !buf.is_empty() {
+ let n = self.seek_read(buf, offset)?;
+ if n == 0 {
+ return Err(eof());
+ }
+ offset += n as u64;
+ buf = &mut buf[n..];
+ }
+ Ok(())
+ }
+ #[cfg(not(any(unix, windows)))]
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ use std::io::{Read, Seek, SeekFrom};
+ let mut f = self;
+ f.seek(SeekFrom::Start(offset))?;
+ f.read_exact(buf)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn slice_reads() {
+ let v = vec![1u8, 2, 3, 4];
+ let mut b = [0u8; 2];
+ v.read_at(1, &mut b).unwrap();
+ assert_eq!(b, [2, 3]);
+ assert!(v.read_at(3, &mut b).is_err());
+ assert!(v.read_at(u64::MAX, &mut b).is_err());
+ let a: Arc<[u8]> = Arc::from(v.clone());
+ a.read_at(2, &mut b).unwrap();
+ assert_eq!(b, [3, 4]);
+ assert_eq!(ByteSource::len(&a), 4);
+ let s: &[u8] = &v;
+ assert_eq!(ByteSource::len(&s), 4);
+ }
+}
diff --git a/crates/isobmff/tests/common/mod.rs b/crates/isobmff/tests/common/mod.rs
new file mode 100644
index 000000000..209f148e0
--- /dev/null
+++ b/crates/isobmff/tests/common/mod.rs
@@ -0,0 +1,196 @@
+//! Shared helpers for oracle tests: ffmpeg/ffprobe discovery and fixture generation.
+//! ffmpeg is used only as an external fixture generator and oracle (never linked).
+#![allow(dead_code)]
+
+use serde_json::Value;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+pub fn tool(name: &str) -> Option<PathBuf> {
+ for dir in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"] {
+ let p = Path::new(dir).join(name);
+ if p.exists() {
+ return Some(p);
+ }
+ }
+ let ok = Command::new(name).arg("-version").output().map(|o| o.status.success()).unwrap_or(false);
+ ok.then(|| PathBuf::from(name))
+}
+
+pub fn ffmpeg() -> Option<PathBuf> {
+ let f = tool("ffmpeg");
+ if f.is_none() {
+ eprintln!("ffmpeg not found; skipping oracle test");
+ }
+ f
+}
+
+pub fn ffprobe() -> Option<PathBuf> {
+ let f = tool("ffprobe");
+ if f.is_none() {
+ eprintln!("ffprobe not found; skipping oracle test");
+ }
+ f
+}
+
+pub fn fixture_dir() -> PathBuf {
+ let d = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/isobmff");
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+pub fn out_dir() -> PathBuf {
+ let d = fixture_dir().join("out");
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+const V: &[&str] = &["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"];
+const A: &[&str] = &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000"];
+
+/// (fixture name, ffmpeg arguments after the global options, output file name derived from the name).
+pub fn fixture_specs() -> Vec<(&'static str, Vec<&'static str>)> {
+ let cat = |parts: &[&[&'static str]]| parts.concat();
+ vec![
+ ("h264_bframes.mp4", cat(&[V, A, &["-t", "2", "-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac"]])),
+ ("h264.mov", cat(&[V, A, &["-t", "2", "-c:v", "libx264", "-bf", "3", "-g", "25", "-pix_fmt", "yuv420p", "-c:a", "pcm_s16le"]])),
+ ("hevc.mp4", cat(&[V, &["-t", "2", "-c:v", "libx265", "-tag:v", "hvc1", "-x265-params", "log-level=error:bframes=3", "-pix_fmt", "yuv420p"]])),
+ ("prores.mov", cat(&[V, A, &["-t", "1", "-c:v", "prores_ks", "-profile:v", "3", "-c:a", "pcm_s24le"]])),
+ ("prores4444.mov", cat(&[V, &["-t", "0.5", "-c:v", "prores_ks", "-profile:v", "4", "-pix_fmt", "yuva444p10le"]])),
+ ("mjpeg.mov", cat(&[V, &["-t", "1", "-c:v", "mjpeg", "-q:v", "5"]])),
+ (
+ "dnxhd.mov",
+ vec!["-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=25", "-t", "0.2", "-c:v", "dnxhd", "-profile:v", "dnxhr_lb", "-pix_fmt", "yuv422p"],
+ ),
+ ("pcm_f32.mov", cat(&[A, &["-t", "1", "-c:a", "pcm_f32le"]])),
+ ("pcm_s16be.mov", cat(&[A, &["-t", "1", "-c:a", "pcm_s16be"]])),
+ ("aac.mp4", cat(&[A, &["-t", "2", "-c:a", "aac", "-b:a", "96k"]])),
+ ("aac_stereo44.m4a", vec!["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1.5", "-ac", "2", "-c:a", "aac"]),
+ (
+ "frag.mp4",
+ cat(&[
+ V,
+ A,
+ &["-t", "3", "-c:v", "libx264", "-bf", "2", "-g", "25", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov"],
+ ]),
+ ),
+ (
+ "frag_dash.mp4",
+ cat(&[
+ V,
+ &["-t", "3", "-c:v", "libx264", "-bf", "2", "-g", "25", "-pix_fmt", "yuv420p", "-movflags", "frag_keyframe+empty_moov+default_base_moof"],
+ ]),
+ ),
+ ("faststart.mp4", cat(&[V, A, &["-t", "2", "-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart"]])),
+ ("tmcd_2997df.mov", vec!["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=30000/1001", "-t", "1", "-c:v", "mjpeg", "-timecode", "01:00:00;00"]),
+ (
+ "tmcd_23976.mov",
+ vec!["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=24000/1001", "-t", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-timecode", "01:00:00:00"],
+ ),
+ ("h264_2997.mp4", vec!["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=30000/1001", "-t", "2", "-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p"]),
+ ("flac.mp4", cat(&[A, &["-t", "1", "-c:a", "flac"]])),
+ ("alac.m4a", cat(&[A, &["-t", "1", "-c:a", "alac"]])),
+ ("opus.mp4", cat(&[A, &["-t", "1", "-c:a", "libopus"]])),
+ ("ac3.mp4", cat(&[A, &["-t", "1", "-c:a", "ac3"]])),
+ ("vp9.mp4", cat(&[V, &["-t", "1", "-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8"]])),
+ ("av1.mp4", cat(&[V, &["-t", "1", "-c:v", "libsvtav1", "-preset", "12"]])),
+ (
+ "colr_pasp.mov",
+ cat(&[
+ V,
+ &[
+ "-t",
+ "0.5",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-color_primaries",
+ "bt709",
+ "-color_trc",
+ "bt709",
+ "-colorspace",
+ "bt709",
+ "-aspect",
+ "16:9",
+ ],
+ ]),
+ ),
+ ]
+}
+
+fn run_ffmpeg(ff: &Path, args: &[&str], out: &Path) -> bool {
+ static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+ let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let ext = out.extension().unwrap().to_str().unwrap();
+ let tmp = out.with_extension(format!("tmp{}_{n}.{ext}", std::process::id()));
+ let st = Command::new(ff).args(["-v", "error", "-y", "-nostdin"]).args(args).arg(&tmp).output();
+ match st {
+ Ok(o) if o.status.success() => std::fs::rename(&tmp, out).is_ok(),
+ Ok(o) => {
+ eprintln!("ffmpeg failed for {}: {}", out.display(), String::from_utf8_lossy(&o.stderr));
+ let _ = std::fs::remove_file(&tmp);
+ false
+ }
+ Err(_) => false,
+ }
+}
+
+/// Path to a fixture, generating it with ffmpeg if needed. `None` if ffmpeg is missing or the
+/// encoder isn't available.
+pub fn fixture(name: &str) -> Option<PathBuf> {
+ let ff = tool("ffmpeg")?;
+ let path = fixture_dir().join(name);
+ if path.exists() {
+ return Some(path);
+ }
+ if name == "editlist_cut.mp4" {
+ let src = fixture("h264_bframes.mp4")?;
+ let s = src.to_str()?.to_string();
+ return run_ffmpeg(&ff, &["-ss", "0.5", "-i", &s, "-c", "copy"], &path).then_some(path);
+ }
+ let (_, args) = fixture_specs().into_iter().find(|(n, _)| *n == name)?;
+ run_ffmpeg(&ff, &args, &path).then_some(path)
+}
+
+pub fn all_fixture_names() -> Vec<&'static str> {
+ let mut v: Vec<&str> = fixture_specs().iter().map(|(n, _)| *n).collect();
+ v.push("editlist_cut.mp4");
+ v
+}
+
+pub fn probe_json(path: &Path, what: &[&str]) -> Option<Value> {
+ let fp = tool("ffprobe")?;
+ let o = Command::new(fp).args(["-v", "error", "-of", "json"]).args(what).arg(path).output().ok()?;
+ if !o.status.success() {
+ return None;
+ }
+ serde_json::from_slice(&o.stdout).ok()
+}
+
+pub fn packets(path: &Path) -> Vec<Value> {
+ probe_json(path, &["-show_packets"]).and_then(|v| v["packets"].as_array().cloned()).unwrap_or_default()
+}
+
+pub fn streams(path: &Path) -> Vec<Value> {
+ probe_json(path, &["-show_streams"]).and_then(|v| v["streams"].as_array().cloned()).unwrap_or_default()
+}
+
+pub fn int(v: &Value) -> Option<i64> {
+ match v {
+ Value::Number(n) => n.as_i64(),
+ Value::String(s) => s.parse().ok(),
+ _ => None,
+ }
+}
+
+/// Decode a file with ffmpeg to the null muxer; returns stderr (empty on success).
+pub fn ffmpeg_decode_errors(path: &Path) -> Option<String> {
+ let ff = tool("ffmpeg")?;
+ let o = Command::new(ff).args(["-v", "error", "-nostdin", "-i"]).arg(path).args(["-f", "null", "-"]).output().ok()?;
+ let mut s = String::from_utf8_lossy(&o.stderr).into_owned();
+ if !o.status.success() {
+ s.push_str("\n(ffmpeg exited with failure)");
+ }
+ Some(s)
+}
diff --git a/crates/isobmff/tests/fuzz.rs b/crates/isobmff/tests/fuzz.rs
new file mode 100644
index 000000000..b6d2fcea6
--- /dev/null
+++ b/crates/isobmff/tests/fuzz.rs
@@ -0,0 +1,160 @@
+//! Deterministic mutation fuzzing: the demuxer must never panic on corrupted input.
+
+mod common;
+
+use filmcraft_isobmff::*;
+use std::io::Cursor;
+
+struct Rng(u64);
+impl Rng {
+ fn next(&mut self) -> u64 {
+ // xorshift64*
+ self.0 ^= self.0 >> 12;
+ self.0 ^= self.0 << 25;
+ self.0 ^= self.0 >> 27;
+ self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
+ }
+ fn below(&mut self, n: usize) -> usize {
+ (self.next() % n.max(1) as u64) as usize
+ }
+}
+
+fn synthetic_files() -> Vec<Vec<u8>> {
+ let mut out = Vec::new();
+ for brand in [Brand::Mp4, Brand::Mov] {
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(brand)).unwrap();
+ let v = w.add_track(TrackConfig::new(SampleEntry::avc(AvcConfig::new(vec![vec![0x67, 0x64, 0, 0x1F]], vec![vec![0x68]], 4), 64, 64), 25)).unwrap();
+ let mut cfg = TrackConfig::new(SampleEntry::aac(vec![0x11, 0x90], 2, 48000), 48000);
+ cfg.media_start = Some(1024);
+ let a = w.add_track(cfg).unwrap();
+ let p = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 1, sample_rate: 8000.0 };
+ let pc = w.add_track(TrackConfig::new(SampleEntry::pcm(p), 8000)).unwrap();
+ w.add_timecode_track(v, TimecodeConfig { flags: 1, timescale: 30000, frame_duration: 1001, frames_per_second: 30, ..Default::default() }, 1000)
+ .unwrap();
+ for i in 0..20u8 {
+ w.write_sample(v, WriteSample { data: &[i; 20], duration: 1, composition_offset: (i % 3) as i32, is_sync: i % 10 == 0 }).unwrap();
+ w.write_sample(a, WriteSample { data: &[i; 7], duration: 1024, composition_offset: 0, is_sync: true }).unwrap();
+ w.write_sample(pc, WriteSample { data: &[i; 16], duration: 0, composition_offset: 0, is_sync: true }).unwrap();
+ }
+ out.push(w.finish().unwrap().into_inner());
+ }
+ let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4));
+ let v = w.add_track(TrackConfig::new(SampleEntry::jpeg(16, 16), 1000)).unwrap();
+ for i in 0..12u8 {
+ w.write_sample(v, WriteSample { data: &[i; 9], duration: 40, composition_offset: -1, is_sync: i % 4 == 0 }).unwrap();
+ if i % 4 == 3 {
+ w.flush_fragment().unwrap();
+ }
+ }
+ out.push(w.finish().unwrap());
+ out
+}
+
+fn exercise(data: &[u8]) -> bool {
+ let r = open(data);
+ let ok = r.is_ok();
+ if let Ok(f) = r {
+ for (ti, t) in f.tracks.iter().enumerate() {
+ let n = t.samples.len();
+ for i in [0, n / 2, n.saturating_sub(1)] {
+ let _ = f.read_sample(data, ti, i);
+ let _ = t.sync_sample_before(i);
+ let _ = t.presentation_pts(i);
+ }
+ let _ = t.sample_at_pts(i64::MIN);
+ let _ = t.sample_at_pts(i64::MAX);
+ let _ = t.sample_at_presentation_time(0);
+ if let Some(CodecConfig::Timecode(tc)) = t.codec() {
+ let _ = tc.format_frame(tc.start_frame.unwrap_or(u32::MAX));
+ }
+ }
+ }
+ ok
+}
+
+fn mutate_all(base: &[u8], seed: u64, iterations: usize) {
+ let mut rng = Rng(seed | 1);
+ // Focus mutations on the moov/moof boxes (where parsing happens).
+ let hot: Vec<(usize, usize)> = {
+ let mut v = Vec::new();
+ for name in [b"moov", b"moof"] {
+ let mut from = 0;
+ while let Some(p) = base[from..].windows(4).position(|w| w == name) {
+ let at = from + p;
+ let start = at.saturating_sub(4);
+ let size = u32::from_be_bytes(base[start..start + 4].try_into().unwrap()) as usize;
+ v.push((start, (start + size.max(8)).min(base.len())));
+ from = at + 4;
+ }
+ }
+ if v.is_empty() {
+ v.push((0, base.len()));
+ }
+ v
+ };
+ let mut parsed = 0usize;
+ for _ in 0..iterations {
+ let mut d = base.to_vec();
+ let (lo, hi) = hot[rng.below(hot.len())];
+ let edits = 1 + rng.below(4);
+ for _ in 0..edits {
+ let pos = if rng.below(10) < 8 { lo + rng.below(hi - lo) } else { rng.below(d.len()) };
+ let pos = pos.min(d.len() - 1);
+ match rng.below(6) {
+ 0 => d[pos] ^= 1 << rng.below(8),
+ 1 => d[pos] = rng.next() as u8,
+ 2 | 3 => {
+ // Overwrite a 32-bit field with an extreme value.
+ let v: u32 = match rng.below(5) {
+ 0 => 0,
+ 1 => 1,
+ 2 => u32::MAX,
+ 3 => 0x8000_0000,
+ _ => rng.next() as u32,
+ };
+ let end = (pos + 4).min(d.len());
+ d[pos..end].copy_from_slice(&v.to_be_bytes()[..end - pos]);
+ }
+ 4 => d.truncate(pos.max(8)),
+ _ => {
+ let n = rng.below(16).min(d.len() - pos);
+ d.drain(pos..pos + n);
+ }
+ }
+ if d.is_empty() {
+ break;
+ }
+ }
+ parsed += exercise(&d) as usize;
+ }
+ eprintln!("seed {seed:#x}: {parsed}/{iterations} mutated files still parsed");
+}
+
+#[test]
+fn mutated_synthetic_files_never_panic() {
+ for (i, f) in synthetic_files().iter().enumerate() {
+ exercise(f);
+ mutate_all(f, 0x5EED_0000 + i as u64, 20_000);
+ }
+}
+
+#[test]
+fn mutated_ffmpeg_fixtures_never_panic() {
+ for (i, name) in ["h264_bframes.mp4", "frag.mp4", "tmcd_2997df.mov", "prores.mov", "hevc.mp4", "aac.mp4"].iter().enumerate() {
+ let Some(p) = common::fixture(name) else {
+ eprintln!("skipping {name}: fixture unavailable");
+ continue;
+ };
+ let data = std::fs::read(p).unwrap();
+ mutate_all(&data, 0xF00D + i as u64, 5000);
+ }
+}
+
+#[test]
+fn truncations_never_panic() {
+ for f in synthetic_files() {
+ for n in 0..f.len().min(4096) {
+ exercise(&f[..n]);
+ }
+ }
+}
diff --git a/crates/isobmff/tests/oracle_demux.rs b/crates/isobmff/tests/oracle_demux.rs
new file mode 100644
index 000000000..ee621ee7d
--- /dev/null
+++ b/crates/isobmff/tests/oracle_demux.rs
@@ -0,0 +1,273 @@
+//! Oracle tests: compare our demuxer's sample tables and codec parameters with ffprobe.
+
+mod common;
+
+use common::*;
+use filmcraft_isobmff::{CodecConfig, Mp4File, TrackKind, open};
+use serde_json::Value;
+
+fn pcm_name_matches(ff: &str, c: &CodecConfig) -> bool {
+ let CodecConfig::Pcm(p) = c else { return false };
+ let Some(rest) = ff.strip_prefix("pcm_") else { return false };
+ let kind = rest.as_bytes()[0];
+ let digits: String = rest[1..].chars().take_while(|c| c.is_ascii_digit()).collect();
+ let bits: u16 = digits.parse().unwrap_or(0);
+ let endian = &rest[1 + digits.len()..];
+ let kind_ok = match kind {
+ b'f' => p.float,
+ b's' => p.signed && !p.float,
+ b'u' => !p.signed && !p.float,
+ _ => false,
+ };
+ let endian_ok = match endian {
+ "le" => !p.big_endian,
+ "be" => p.big_endian,
+ _ => true, // 8-bit has no endianness
+ };
+ kind_ok && endian_ok && bits == p.bits
+}
+
+fn check_stream(file: &Mp4File, idx: usize, st: &Value) -> Result<(), String> {
+ let t = &file.tracks[idx];
+ let codec = t.codec().ok_or("no sample entry")?;
+ let ffname = st["codec_name"].as_str().unwrap_or("");
+ let tag = st["codec_tag_string"].as_str().unwrap_or("");
+ let entry = &t.entries[0];
+ if tag != entry.format.to_string() {
+ return Err(format!("tag {tag} vs {}", entry.format));
+ }
+ let name_ok = match codec {
+ CodecConfig::Pcm(_) => pcm_name_matches(ffname, codec),
+ CodecConfig::Timecode(_) => st["codec_type"] == "data",
+ c => c.name() == ffname,
+ };
+ if !name_ok {
+ return Err(format!("codec {ffname} vs {codec:?}"));
+ }
+ let tb = format!("1/{}", t.timescale);
+ if st["time_base"].as_str() != Some(tb.as_str()) {
+ return Err(format!("time_base {} vs {tb}", st["time_base"]));
+ }
+ match t.kind {
+ TrackKind::Video => {
+ let v = t.video().ok_or("no video params")?;
+ if int(&st["width"]) != Some(v.width as i64) || int(&st["height"]) != Some(v.height as i64) {
+ return Err(format!("size {}x{} vs {}x{}", st["width"], st["height"], v.width, v.height));
+ }
+ if let Some(n) = int(&st["nb_frames"])
+ && n != t.samples.len() as i64
+ {
+ return Err(format!("nb_frames {n} vs {}", t.samples.len()));
+ }
+ if let CodecConfig::Avc(a) = codec {
+ if int(&st["level"]) != Some(a.level as i64) {
+ return Err(format!("level {} vs {}", st["level"], a.level));
+ }
+ if st["nal_length_size"].as_str() != Some(&a.length_size.to_string()) {
+ return Err("nal_length_size".into());
+ }
+ }
+ if let Some(cp) = st["color_primaries"].as_str()
+ && cp == "bt709"
+ {
+ match &v.color {
+ Some(filmcraft_isobmff::ColorInfo::Nclx { primaries: 1, .. }) | Some(filmcraft_isobmff::ColorInfo::Nclc { primaries: 1, .. }) => {}
+ other => return Err(format!("colr {other:?}")),
+ }
+ }
+ if let Some(sar) = st["sample_aspect_ratio"].as_str()
+ && sar != "1:1"
+ && sar != "0:1"
+ {
+ let (h, vv) = v.pixel_aspect.ok_or("no pasp")?;
+ let want = format!("{}:{}", h / gcd(h, vv), vv / gcd(h, vv));
+ if sar != want {
+ return Err(format!("sar {sar} vs {want}"));
+ }
+ }
+ }
+ TrackKind::Audio => {
+ let a = t.audio().ok_or("no audio params")?;
+ let sr = int(&st["sample_rate"]).unwrap_or(0);
+ let ch = int(&st["channels"]).unwrap_or(0);
+ let (our_sr, our_ch) = match codec {
+ CodecConfig::Pcm(p) => (p.sample_rate, p.channels),
+ CodecConfig::Flac(f) => (f.sample_rate as f64, f.channels as u32),
+ CodecConfig::Opus(o) => (48000.0, o.output_channels as u32),
+ _ => (a.sample_rate, a.channels),
+ };
+ if sr != our_sr.round() as i64 || ch != our_ch as i64 {
+ return Err(format!("audio {sr}/{ch} vs {our_sr}/{our_ch}"));
+ }
+ if let CodecConfig::Aac(c) = codec
+ && c.object_type != 2
+ {
+ return Err(format!("aac object type {}", c.object_type));
+ }
+ }
+ TrackKind::Timecode => {
+ let CodecConfig::Timecode(tc) = codec else { return Err("tmcd codec".into()) };
+ let want = st["tags"]["timecode"].as_str().ok_or("no timecode tag")?;
+ let got = tc.format_frame(tc.start_frame.ok_or("no start frame")?);
+ if got != want {
+ return Err(format!("timecode {got} vs {want}"));
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+fn gcd(a: u32, b: u32) -> u32 {
+ if b == 0 { a.max(1) } else { gcd(b, a % b) }
+}
+
+/// `strict`: ffprobe timestamps must equal ours + edit offset. Otherwise (edit starting mid-frame,
+/// which ffmpeg snaps to a frame boundary) only a constant shift within one frame is required.
+fn check_packets(file: &Mp4File, idx: usize, pk: &[&Value], strict: bool) -> Result<(), String> {
+ let t = &file.tracks[idx];
+ if t.pcm_chunked {
+ // ffmpeg re-packetizes raw PCM; compare totals.
+ let ours: u64 = t.samples.iter().map(|s| s.size as u64).sum();
+ let theirs: i64 = pk.iter().filter_map(|p| int(&p["size"])).sum();
+ let od: u64 = t.samples.iter().map(|s| s.duration as u64).sum();
+ let td: i64 = pk.iter().filter_map(|p| int(&p["duration"])).sum();
+ if ours as i64 != theirs || od as i64 != td {
+ return Err(format!("pcm totals: bytes {ours} vs {theirs}, dur {od} vs {td}"));
+ }
+ return Ok(());
+ }
+ if pk.len() != t.samples.len() {
+ return Err(format!("packet count {} vs {}", pk.len(), t.samples.len()));
+ }
+ let e = if strict || pk.is_empty() {
+ t.edit_offset
+ } else {
+ let e = int(&pk[0]["pts"]).unwrap_or(0) - t.samples[0].pts;
+ let max_dur = t.samples.iter().map(|s| s.duration as i64).max().unwrap_or(0);
+ if (e - t.edit_offset).abs() >= max_dur {
+ return Err(format!("shift {e} vs edit offset {}", t.edit_offset));
+ }
+ e
+ };
+ let last = pk.len() - 1;
+ for (i, (p, s)) in pk.iter().zip(&t.samples).enumerate() {
+ let size = int(&p["size"]);
+ let pos = int(&p["pos"]);
+ let pts = int(&p["pts"]);
+ let dts = int(&p["dts"]);
+ let key = p["flags"].as_str().unwrap_or("").starts_with('K');
+ // ffmpeg extends the last packet's duration when it carries discard padding.
+ let ok = size == Some(s.size as i64)
+ && pos == Some(s.offset as i64)
+ && pts == Some(s.pts + e)
+ && dts == Some(s.dts + e)
+ && key == s.is_sync
+ && (i == last || int(&p["duration"]).is_none_or(|d| d == s.duration as i64));
+ if !ok {
+ return Err(format!("packet {i}: ffprobe {p} vs ours {s:?} (edit_offset {e})"));
+ }
+ }
+ Ok(())
+}
+
+fn check_fixture(name: &str) {
+ let Some(path) = fixture(name) else {
+ eprintln!("skipping {name}: ffmpeg or encoder unavailable");
+ return;
+ };
+ if ffprobe().is_none() {
+ return;
+ }
+ let f = std::fs::File::open(&path).unwrap();
+ let file = open(&f).unwrap_or_else(|e| panic!("{name}: open failed: {e}"));
+ let streams = streams(&path);
+ assert_eq!(streams.len(), file.tracks.len(), "{name}: stream count");
+ let packets = packets(&path);
+ let mut errors = Vec::new();
+ for (i, st) in streams.iter().enumerate() {
+ if let Err(e) = check_stream(&file, i, st) {
+ errors.push(format!("stream {i}: {e}"));
+ }
+ if matches!(file.tracks[i].kind, TrackKind::Video | TrackKind::Audio) {
+ let pk: Vec<&Value> = packets.iter().filter(|p| int(&p["stream_index"]) == Some(i as i64)).collect();
+ if let Err(e) = check_packets(&file, i, &pk, name != "editlist_cut.mp4") {
+ errors.push(format!("stream {i}: {e}"));
+ }
+ }
+ }
+ // Every sample must be readable.
+ for (ti, t) in file.tracks.iter().enumerate() {
+ for si in [0, t.samples.len() / 2, t.samples.len().saturating_sub(1)] {
+ if si < t.samples.len() {
+ let d = file.read_sample(&f, ti, si).unwrap();
+ assert_eq!(d.len(), t.samples[si].size as usize);
+ }
+ }
+ }
+ assert!(errors.is_empty(), "{name}:\n{}", errors.join("\n"));
+ eprintln!("{name}: ok ({} tracks)", file.tracks.len());
+}
+
+macro_rules! fixture_tests {
+ ($($fn:ident => $name:expr),* $(,)?) => {
+ $(#[test] fn $fn() { check_fixture($name); })*
+ };
+}
+
+fixture_tests! {
+ h264_bframes_mp4 => "h264_bframes.mp4",
+ h264_mov => "h264.mov",
+ hevc_mp4 => "hevc.mp4",
+ prores_mov => "prores.mov",
+ prores4444_mov => "prores4444.mov",
+ mjpeg_mov => "mjpeg.mov",
+ dnxhd_mov => "dnxhd.mov",
+ pcm_f32_mov => "pcm_f32.mov",
+ pcm_s16be_mov => "pcm_s16be.mov",
+ aac_mp4 => "aac.mp4",
+ aac_m4a => "aac_stereo44.m4a",
+ frag_mp4 => "frag.mp4",
+ frag_dash_mp4 => "frag_dash.mp4",
+ faststart_mp4 => "faststart.mp4",
+ tmcd_2997df_mov => "tmcd_2997df.mov",
+ tmcd_23976_mov => "tmcd_23976.mov",
+ h264_2997_mp4 => "h264_2997.mp4",
+ flac_mp4 => "flac.mp4",
+ alac_m4a => "alac.m4a",
+ opus_mp4 => "opus.mp4",
+ ac3_mp4 => "ac3.mp4",
+ vp9_mp4 => "vp9.mp4",
+ av1_mp4 => "av1.mp4",
+ colr_pasp_mov => "colr_pasp.mov",
+ editlist_cut_mp4 => "editlist_cut.mp4",
+}
+
+#[test]
+fn specific_properties() {
+ let Some(p) = fixture("h264_bframes.mp4") else { return };
+ let data = std::fs::read(&p).unwrap();
+ let f = open(data.as_slice()).unwrap();
+ assert!(!f.is_quicktime);
+ let v = &f.tracks[f.track_of_kind(TrackKind::Video).unwrap()];
+ // B-frames → non-trivial composition offsets.
+ assert!(v.samples.iter().any(|s| s.pts != s.dts));
+ assert!(v.samples.iter().filter(|s| s.is_sync).count() >= 4);
+ let i = v.sample_at_pts(v.samples[7].pts).unwrap();
+ assert_eq!(i, 7);
+ assert_eq!(v.sync_sample_before(13), 12);
+ let a = &f.tracks[f.track_of_kind(TrackKind::Audio).unwrap()];
+ assert_eq!(a.edits.len(), 1);
+ assert_eq!(a.edit_offset, -1024);
+
+ let Some(p) = fixture("tmcd_2997df.mov") else { return };
+ let f = open(std::fs::read(&p).unwrap()).unwrap();
+ assert!(f.is_quicktime);
+ let t = &f.tracks[f.track_of_kind(TrackKind::Timecode).unwrap()];
+ let CodecConfig::Timecode(tc) = t.codec().unwrap() else { panic!() };
+ assert!(tc.drop_frame());
+ assert_eq!(tc.frames_per_second, 30);
+ assert_eq!(tc.start_frame, Some(107892));
+ let v = &f.tracks[f.track_of_kind(TrackKind::Video).unwrap()];
+ assert!(v.references.iter().any(|(k, ids)| k.to_string() == "tmcd" && ids == &vec![t.id]));
+}
diff --git a/crates/isobmff/tests/oracle_mux.rs b/crates/isobmff/tests/oracle_mux.rs
new file mode 100644
index 000000000..4b9144241
--- /dev/null
+++ b/crates/isobmff/tests/oracle_mux.rs
@@ -0,0 +1,269 @@
+//! Muxer oracle tests: remux ffmpeg-made files with our writers and validate with ffmpeg/ffprobe.
+
+mod common;
+
+use common::*;
+use filmcraft_isobmff::*;
+use serde_json::Value;
+use std::io::Cursor;
+use std::path::{Path, PathBuf};
+
+/// All samples of all tracks in decode order interleaved by decode time: (track, sample index).
+fn interleave(f: &Mp4File, tracks: &[usize]) -> Vec<(usize, usize)> {
+ let mut v: Vec<(usize, usize)> = tracks.iter().flat_map(|&t| (0..f.tracks[t].samples.len()).map(move |i| (t, i))).collect();
+ v.sort_by(|a, b| {
+ let ta = &f.tracks[a.0];
+ let tb = &f.tracks[b.0];
+ let x = ta.samples[a.1].dts as i128 * tb.timescale as i128;
+ let y = tb.samples[b.1].dts as i128 * ta.timescale as i128;
+ x.cmp(&y).then(a.0.cmp(&b.0)).then(a.1.cmp(&b.1))
+ });
+ v
+}
+
+fn track_config(f: &Mp4File, t: &Track, copy_edits: bool) -> TrackConfig {
+ let mut cfg = TrackConfig::new(t.entries[0].clone(), t.timescale);
+ cfg.language = t.language.clone();
+ if copy_edits {
+ cfg.edits = t.edits.clone();
+ }
+ let _ = f;
+ cfg
+}
+
+enum Finish {
+ Normal,
+ Faststart,
+}
+
+fn remux(input: &Path, out_name: &str, brand: Brand, finish: Finish, timecode: Option<(TimecodeConfig, u32)>) -> Option<(Mp4File, PathBuf)> {
+ let data = std::fs::read(input).ok()?;
+ let f = open(data.as_slice()).unwrap();
+ let mut opts = WriterOptions::new(brand);
+ opts.movie_timescale = f.timescale;
+ opts.metadata.push(("©nam".into(), "FilmCraft test".into()));
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), opts).unwrap();
+ let av: Vec<usize> = (0..f.tracks.len()).filter(|&i| matches!(f.tracks[i].kind, TrackKind::Video | TrackKind::Audio)).collect();
+ let mut map = vec![usize::MAX; f.tracks.len()];
+ for &i in &av {
+ map[i] = w.add_track(track_config(&f, &f.tracks[i], true)).unwrap();
+ }
+ if let Some((tc, start)) = timecode {
+ let v = av.iter().copied().find(|&i| f.tracks[i].kind == TrackKind::Video).unwrap();
+ w.add_timecode_track(map[v], tc, start).unwrap();
+ }
+ for (t, i) in interleave(&f, &av) {
+ let s = f.tracks[t].samples[i];
+ let bytes = f.read_sample(data.as_slice(), t, i).unwrap();
+ w.write_sample(map[t], WriteSample { data: &bytes, duration: s.duration, composition_offset: (s.pts - s.dts) as i32, is_sync: s.is_sync }).unwrap();
+ }
+ let out = match finish {
+ Finish::Normal => w.finish(),
+ Finish::Faststart => w.finish_faststart(),
+ }
+ .unwrap()
+ .into_inner();
+ let path = out_dir().join(out_name);
+ std::fs::write(&path, &out).unwrap();
+ // Our own reader must see identical sample tables and bytes.
+ let g = open(out.as_slice()).unwrap();
+ for (k, &i) in av.iter().enumerate() {
+ let (a, b) = (&f.tracks[i], &g.tracks[k]);
+ assert_eq!(a.samples.len(), b.samples.len(), "{out_name}: sample count");
+ assert_eq!(a.edit_offset, b.edit_offset, "{out_name}: edit offset");
+ assert_eq!(a.codec(), b.codec(), "{out_name}: codec");
+ for (j, (x, y)) in a.samples.iter().zip(&b.samples).enumerate() {
+ assert_eq!((x.size, x.dts, x.pts, x.duration, x.is_sync), (y.size, y.dts, y.pts, y.duration, y.is_sync), "{out_name}: sample {j}");
+ }
+ for j in 0..a.samples.len() {
+ assert_eq!(f.read_sample(data.as_slice(), i, j).unwrap(), g.read_sample(out.as_slice(), k, j).unwrap());
+ }
+ }
+ assert_eq!(g.metadata.title(), Some("FilmCraft test"));
+ Some((f, path))
+}
+
+fn stream_packets(path: &Path) -> Vec<Vec<Value>> {
+ let pk = packets(path);
+ let n = pk.iter().filter_map(|p| int(&p["stream_index"])).max().map(|m| m + 1).unwrap_or(0);
+ (0..n).map(|i| pk.iter().filter(|p| int(&p["stream_index"]) == Some(i)).cloned().collect()).collect()
+}
+
+/// Compare ffprobe's view of two files (per-stream packets: pts, dts, size, key flag).
+fn assert_same_packets(a: &Path, b: &Path) {
+ let pa = stream_packets(a);
+ let pb = stream_packets(b);
+ for (i, (x, y)) in pa.iter().zip(&pb).enumerate() {
+ let key = |p: &Value| (int(&p["pts"]), int(&p["dts"]), int(&p["size"]), p["flags"].as_str().map(|f| f.starts_with('K')));
+ let kx: Vec<_> = x.iter().map(key).collect();
+ let ky: Vec<_> = y.iter().map(key).collect();
+ assert_eq!(kx.len(), ky.len(), "stream {i}: packet count {} vs {}", a.display(), b.display());
+ for (j, (p, q)) in kx.iter().zip(&ky).enumerate() {
+ assert_eq!(p, q, "stream {i} packet {j}");
+ }
+ }
+}
+
+fn assert_same_streams(a: &Path, b: &Path) {
+ let sa = streams(a);
+ let sb = streams(b);
+ for (x, y) in sa.iter().zip(&sb) {
+ if x["codec_type"] == "data" {
+ continue;
+ }
+ for k in ["codec_name", "width", "height", "sample_rate", "channels", "nb_frames", "duration_ts", "time_base", "profile", "pix_fmt"] {
+ assert_eq!(x[k], y[k], "stream field {k}");
+ }
+ }
+}
+
+fn decode_clean(path: &Path) {
+ let err = ffmpeg_decode_errors(path).unwrap();
+ assert!(err.trim().is_empty(), "ffmpeg reported errors for {}: {err}", path.display());
+}
+
+#[test]
+fn remux_h264_aac_mp4_variants() {
+ let (Some(src), Some(_)) = (fixture("h264_bframes.mp4"), ffprobe()) else { return };
+ for (name, brand, finish) in [
+ ("remux_h264_aac.mp4", Brand::Mp4, Finish::Normal),
+ ("remux_h264_aac_fast.mp4", Brand::Mp4, Finish::Faststart),
+ ("remux_h264_aac.mov", Brand::Mov, Finish::Normal),
+ ] {
+ let (_, out) = remux(&src, name, brand, finish, None).unwrap();
+ decode_clean(&out);
+ assert_same_packets(&src, &out);
+ assert_same_streams(&src, &out);
+ eprintln!("{name}: ok");
+ }
+ // Faststart layout: moov before mdat.
+ let d = std::fs::read(out_dir().join("remux_h264_aac_fast.mp4")).unwrap();
+ let moov = d.windows(4).position(|w| w == b"moov").unwrap();
+ let mdat = d.windows(4).position(|w| w == b"mdat").unwrap();
+ assert!(moov < mdat);
+}
+
+#[test]
+fn remux_other_codecs() {
+ if ffprobe().is_none() {
+ return;
+ }
+ for (src, name, brand) in [
+ ("hevc.mp4", "remux_hevc.mp4", Brand::Mp4),
+ ("h264.mov", "remux_h264_pcm.mov", Brand::Mov),
+ ("mjpeg.mov", "remux_mjpeg.mov", Brand::Mov),
+ ("pcm_f32.mov", "remux_pcm_f32.mov", Brand::Mov),
+ ("pcm_s16be.mov", "remux_pcm_s16be.mov", Brand::Mov),
+ ("aac_stereo44.m4a", "remux_aac.m4a", Brand::Mp4),
+ ("colr_pasp.mov", "remux_colr_pasp.mov", Brand::Mov),
+ ("editlist_cut.mp4", "remux_editlist.mp4", Brand::Mp4),
+ ("alac.m4a", "remux_alac.m4a", Brand::Mp4),
+ ("flac.mp4", "remux_flac.mp4", Brand::Mp4),
+ ("opus.mp4", "remux_opus.mp4", Brand::Mp4),
+ ("av1.mp4", "remux_av1.mp4", Brand::Mp4),
+ ("vp9.mp4", "remux_vp9.mp4", Brand::Mp4),
+ ("ac3.mp4", "remux_ac3.mp4", Brand::Mp4),
+ ("dnxhd.mov", "remux_dnxhd.mov", Brand::Mov),
+ ] {
+ let Some(p) = fixture(src) else { continue };
+ let (f, out) = remux(&p, name, brand, Finish::Faststart, None).unwrap();
+ decode_clean(&out);
+ let pcm = f.tracks.iter().any(|t| t.pcm_chunked);
+ if !pcm {
+ assert_same_packets(&p, &out);
+ }
+ assert_same_streams(&p, &out);
+ eprintln!("{name}: ok");
+ }
+}
+
+#[test]
+fn remux_prores_pcm24_with_timecode() {
+ let (Some(src), Some(_)) = (fixture("prores.mov"), ffprobe()) else { return };
+ let tc = TimecodeConfig { flags: 0, timescale: 25, frame_duration: 1, frames_per_second: 25, start_frame: None, name: None };
+ let (f, out) = remux(&src, "remux_prores_tc.mov", Brand::Mov, Finish::Normal, Some((tc, 25 * 3600))).unwrap();
+ decode_clean(&out);
+ assert_same_streams(&src, &out);
+ let st = streams(&out);
+ assert!(st.iter().any(|s| s["tags"]["timecode"] == "01:00:00:00"), "timecode missing: {st:?}");
+ // PCM byte totals survive ffmpeg's repacketisation.
+ let g = open(std::fs::read(&out).unwrap()).unwrap();
+ let a = f.track_of_kind(TrackKind::Audio).unwrap();
+ let sum = |m: &Mp4File, i: usize| m.tracks[i].samples.iter().map(|s| s.size as u64).sum::<u64>();
+ assert_eq!(sum(&f, a), sum(&g, g.track_of_kind(TrackKind::Audio).unwrap()));
+ let t = &g.tracks[g.track_of_kind(TrackKind::Timecode).unwrap()];
+ let CodecConfig::Timecode(tc) = t.codec().unwrap() else { panic!() };
+ assert_eq!(tc.start_frame, Some(90000));
+}
+
+#[test]
+fn pcm_in_mp4_ipcm() {
+ let (Some(src), Some(_)) = (fixture("pcm_s16be.mov"), ffprobe()) else { return };
+ let (_, out) = remux(&src, "remux_ipcm.mp4", Brand::Mp4, Finish::Normal, None).unwrap();
+ let st = streams(&out);
+ assert_eq!(st[0]["codec_tag_string"], "ipcm");
+ assert_eq!(st[0]["codec_name"], "pcm_s16be");
+ decode_clean(&out);
+}
+
+#[test]
+fn aac_priming_edit() {
+ let (Some(src), Some(_)) = (fixture("aac.mp4"), ffprobe()) else { return };
+ let data = std::fs::read(&src).unwrap();
+ let f = open(data.as_slice()).unwrap();
+ let t = &f.tracks[0];
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
+ let mut cfg = TrackConfig::new(t.entries[0].clone(), t.timescale);
+ cfg.media_start = Some(1024);
+ let k = w.add_track(cfg).unwrap();
+ for (i, s) in t.samples.iter().enumerate() {
+ let d = f.read_sample(data.as_slice(), 0, i).unwrap();
+ w.write_sample(k, WriteSample { data: &d, duration: s.duration, composition_offset: 0, is_sync: true }).unwrap();
+ }
+ let out = out_dir().join("aac_priming.mp4");
+ std::fs::write(&out, w.finish().unwrap().into_inner()).unwrap();
+ decode_clean(&out);
+ let pk = packets(&out);
+ assert_eq!(int(&pk[0]["pts"]), Some(-1024));
+ assert_eq!(int(&streams(&out)[0]["duration_ts"]), int(&streams(&src)[0]["duration_ts"]));
+}
+
+#[test]
+fn fragmented_writer_ffmpeg() {
+ let (Some(src), Some(_)) = (fixture("h264_bframes.mp4"), ffprobe()) else { return };
+ let data = std::fs::read(&src).unwrap();
+ let f = open(data.as_slice()).unwrap();
+ let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4));
+ let tracks: Vec<usize> = (0..f.tracks.len()).collect();
+ for t in &f.tracks {
+ w.add_track(TrackConfig::new(t.entries[0].clone(), t.timescale)).unwrap();
+ }
+ let v = f.track_of_kind(TrackKind::Video).unwrap();
+ for (t, i) in interleave(&f, &tracks) {
+ let s = f.tracks[t].samples[i];
+ if t == v && s.is_sync && i > 0 {
+ w.flush_fragment().unwrap();
+ }
+ let d = f.read_sample(data.as_slice(), t, i).unwrap();
+ w.write_sample(t, WriteSample { data: &d, duration: s.duration, composition_offset: (s.pts - s.dts) as i32, is_sync: s.is_sync }).unwrap();
+ }
+ let bytes = w.finish().unwrap();
+ let out = out_dir().join("our_frag.mp4");
+ std::fs::write(&out, &bytes).unwrap();
+ decode_clean(&out);
+ let g = open(bytes.as_slice()).unwrap();
+ assert!(g.fragmented && g.fragment_count >= 4);
+ // ffprobe sees raw timestamps (no edit list in our init segment).
+ let ours = stream_packets(&out);
+ for (ti, t) in f.tracks.iter().enumerate() {
+ assert_eq!(ours[ti].len(), t.samples.len());
+ for (p, s) in ours[ti].iter().zip(&t.samples) {
+ assert_eq!(int(&p["pts"]), Some(s.pts));
+ assert_eq!(int(&p["dts"]), Some(s.dts));
+ assert_eq!(int(&p["size"]), Some(s.size as i64));
+ }
+ for i in 0..t.samples.len() {
+ assert_eq!(f.read_sample(data.as_slice(), ti, i).unwrap(), g.read_sample(bytes.as_slice(), ti, i).unwrap());
+ }
+ }
+}
diff --git a/crates/isobmff/tests/roundtrip.rs b/crates/isobmff/tests/roundtrip.rs
new file mode 100644
index 000000000..584b767ad
--- /dev/null
+++ b/crates/isobmff/tests/roundtrip.rs
@@ -0,0 +1,206 @@
+//! Property tests: write with our muxers, read back, compare sample tables and bytes.
+
+use filmcraft_isobmff::*;
+use proptest::prelude::*;
+use std::io::Cursor;
+
+#[derive(Clone, Debug)]
+struct S {
+ size: usize,
+ duration: u32,
+ cto: i32,
+ sync: bool,
+}
+
+fn sample_strategy() -> impl Strategy<Value = S> {
+ (0usize..300, 1u32..3000, -200i32..2000, any::<bool>()).prop_map(|(size, duration, cto, sync)| S { size, duration, cto, sync })
+}
+
+fn payload(track: usize, i: usize, n: usize) -> Vec<u8> {
+ (0..n).map(|k| (track * 31 + i * 7 + k) as u8).collect()
+}
+
+fn entry(kind: u8) -> SampleEntry {
+ match kind {
+ 0 => SampleEntry::avc(AvcConfig::new(vec![vec![0x67, 0x64, 0, 0x28, 1, 2]], vec![vec![0x68, 3]], 4), 320, 240),
+ 1 => SampleEntry::prores(FourCc(*b"apcn"), 1920, 1080),
+ 2 => SampleEntry::aac(vec![0x11, 0x90], 2, 48000),
+ _ => SampleEntry::jpeg(64, 64),
+ }
+}
+
+proptest! {
+ #![proptest_config(ProptestConfig::with_cases(64))]
+
+ #[test]
+ fn progressive_roundtrip(
+ tracks in prop::collection::vec((0u8..4, prop::collection::vec(sample_strategy(), 0..40)), 1..4),
+ order in prop::collection::vec(0usize..4, 0..200),
+ mov in any::<bool>(),
+ fast in any::<bool>(),
+ with_pcm in any::<bool>(),
+ start in prop::option::of(0i64..500),
+ ) {
+ let brand = if mov { Brand::Mov } else { Brand::Mp4 };
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(brand)).unwrap();
+ for (k, (kind, _)) in tracks.iter().enumerate() {
+ let mut cfg = TrackConfig::new(entry(*kind), 1000 + k as u32 * 11);
+ cfg.media_start = start;
+ w.add_track(cfg).unwrap();
+ }
+ let pcm_track = if with_pcm {
+ let p = PcmConfig { bits: 24, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48000.0 };
+ Some(w.add_track(TrackConfig::new(SampleEntry::pcm(p), 48000)).unwrap())
+ } else { None };
+ // Interleave: follow `order`, then flush the rest.
+ let mut next = vec![0usize; tracks.len()];
+ let mut pcm_chunks = Vec::new();
+ let emit = |w: &mut Mp4Writer<Cursor<Vec<u8>>>, t: usize, next: &mut Vec<usize>| {
+ let i = next[t];
+ let s = &tracks[t].1[i];
+ let d = payload(t, i, s.size);
+ w.write_sample(t, WriteSample { data: &d, duration: s.duration, composition_offset: s.cto, is_sync: s.sync }).unwrap();
+ next[t] += 1;
+ };
+ for (step, &o) in order.iter().enumerate() {
+ if let Some(p) = pcm_track && step % 5 == 0 {
+ let d = payload(9, step, 6 * (1 + step % 7));
+ w.write_sample(p, WriteSample { data: &d, duration: 0, composition_offset: 0, is_sync: true }).unwrap();
+ pcm_chunks.push(d);
+ }
+ let t = o % tracks.len();
+ if next[t] < tracks[t].1.len() {
+ emit(&mut w, t, &mut next);
+ }
+ }
+ for t in 0..tracks.len() {
+ while next[t] < tracks[t].1.len() {
+ emit(&mut w, t, &mut next);
+ }
+ }
+ let out = if fast { w.finish_faststart() } else { w.finish() }.unwrap().into_inner();
+ let f = open(out.as_slice()).unwrap();
+ prop_assert_eq!(f.is_quicktime, mov);
+ prop_assert_eq!(f.tracks.len(), tracks.len() + pcm_track.is_some() as usize);
+ for (k, (kind, samples)) in tracks.iter().enumerate() {
+ let t = &f.tracks[k];
+ prop_assert_eq!(t.codec(), Some(&entry(*kind).codec));
+ prop_assert_eq!(t.samples.len(), samples.len());
+ let mut dts = 0i64;
+ for (i, (s, r)) in samples.iter().zip(&t.samples).enumerate() {
+ prop_assert_eq!(r.size as usize, s.size);
+ prop_assert_eq!(r.duration, s.duration);
+ prop_assert_eq!(r.dts, dts);
+ prop_assert_eq!(r.pts, dts + s.cto as i64);
+ prop_assert_eq!(r.is_sync, s.sync);
+ prop_assert_eq!(f.read_sample(out.as_slice(), k, i).unwrap(), payload(k, i, s.size));
+ dts += s.duration as i64;
+ }
+ prop_assert_eq!(t.duration, dts as u64);
+ match start {
+ Some(st) if !samples.is_empty() || st == 0 => prop_assert_eq!(t.edit_offset, -st),
+ _ => {}
+ }
+ }
+ if let Some(p) = pcm_track {
+ let t = &f.tracks[p];
+ let got: Vec<u8> = (0..t.samples.len()).flat_map(|i| f.read_sample(out.as_slice(), p, i).unwrap()).collect();
+ prop_assert_eq!(got, pcm_chunks.concat());
+ let frames: u64 = t.samples.iter().map(|s| s.duration as u64).sum();
+ prop_assert_eq!(frames, pcm_chunks.iter().map(|c| c.len() as u64 / 6).sum::<u64>());
+ }
+ }
+
+ #[test]
+ fn fragmented_roundtrip(
+ samples in prop::collection::vec(sample_strategy(), 1..60),
+ cuts in prop::collection::vec(any::<bool>(), 60),
+ ) {
+ let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4));
+ let v = w.add_track(TrackConfig::new(entry(0), 90000)).unwrap();
+ let a = w.add_track(TrackConfig::new(entry(2), 48000)).unwrap();
+ for (i, s) in samples.iter().enumerate() {
+ w.write_sample(v, WriteSample { data: &payload(0, i, s.size), duration: s.duration, composition_offset: s.cto, is_sync: s.sync }).unwrap();
+ w.write_sample(a, WriteSample { data: &payload(1, i, s.size / 2), duration: 1024, composition_offset: 0, is_sync: true }).unwrap();
+ if cuts[i] { w.flush_fragment().unwrap(); }
+ }
+ let out = w.finish().unwrap();
+ let f = open(out.as_slice()).unwrap();
+ prop_assert!(f.fragmented);
+ let mut dts = 0i64;
+ for (i, s) in samples.iter().enumerate() {
+ let r = f.tracks[0].samples[i];
+ prop_assert_eq!((r.size as usize, r.dts, r.pts, r.is_sync), (s.size, dts, dts + s.cto as i64, s.sync));
+ prop_assert_eq!(f.read_sample(out.as_slice(), 0, i).unwrap(), payload(0, i, s.size));
+ prop_assert_eq!(f.read_sample(out.as_slice(), 1, i).unwrap(), payload(1, i, s.size / 2));
+ prop_assert_eq!(f.tracks[1].samples[i].dts, 1024 * i as i64);
+ dts += s.duration as i64;
+ }
+ }
+}
+
+#[test]
+fn sample_lookup() {
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
+ let t = w.add_track(TrackConfig::new(entry(0), 25)).unwrap();
+ // I P B B pattern: decode order I0 P3 B1 B2 | I4 P7 B5 B6
+ let cto = [1, 3, 0, 0, 1, 3, 0, 0];
+ for (i, c) in cto.iter().enumerate() {
+ w.write_sample(t, WriteSample { data: &[i as u8], duration: 1, composition_offset: *c, is_sync: i % 4 == 0 }).unwrap();
+ }
+ let out = w.finish().unwrap().into_inner();
+ let f = open(out.as_slice()).unwrap();
+ let tr = &f.tracks[0];
+ // pts: 1,4,2,3,5,8,6,7
+ assert_eq!(tr.sample_at_pts(0), Some(0));
+ assert_eq!(tr.sample_at_pts(2), Some(2));
+ assert_eq!(tr.sample_at_pts(4), Some(1));
+ assert_eq!(tr.sample_at_pts(7), Some(7));
+ assert_eq!(tr.sample_at_pts(100), Some(5));
+ assert_eq!(tr.sync_sample_before(3), 0);
+ assert_eq!(tr.sync_sample_before(4), 4);
+ assert_eq!(tr.sync_sample_before(7), 4);
+ assert_eq!(tr.sync_samples(), &[0, 4]);
+}
+
+#[test]
+fn large_offsets_use_co64_and_largesize_mdat() {
+ // Files > 4 GiB are impractical in tests, so patch a small file into the same layout the
+ // writer produces for them: co64 chunk offsets and a 16-byte large-size mdat header.
+ let mut moov = Vec::new();
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
+ let t = w.add_track(TrackConfig::new(entry(3), 30)).unwrap();
+ w.write_sample(t, WriteSample { data: b"abc", duration: 1, composition_offset: 0, is_sync: true }).unwrap();
+ let out = w.finish().unwrap().into_inner();
+ // Replace stco with co64 (same entry count, 64-bit offsets) and rebuild.
+ let f = open(out.as_slice()).unwrap();
+ let off = f.tracks[0].samples[0].offset;
+ let stco = out.windows(4).position(|w| w == b"stco").unwrap() - 4;
+ let moov_at = out.windows(4).position(|w| w == b"moov").unwrap() - 4;
+ moov.extend_from_slice(&out[moov_at..stco]);
+ moov.extend_from_slice(&24u32.to_be_bytes());
+ moov.extend_from_slice(b"co64");
+ moov.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 1]);
+ moov.extend_from_slice(&off.to_be_bytes());
+ // Fix up sizes of moov/trak/mdia/minf/stbl (+4 bytes each).
+ for name in [b"moov", b"trak", b"mdia", b"minf", b"stbl"] {
+ let p = moov.windows(4).position(|w| w == name).unwrap() - 4;
+ let s = u32::from_be_bytes(moov[p..p + 4].try_into().unwrap()) + 4;
+ moov[p..p + 4].copy_from_slice(&s.to_be_bytes());
+ }
+ let mut file = out[..moov_at].to_vec();
+ file.extend_from_slice(&moov);
+ // ftyp is 32 bytes for MP4; then `free` (8) + `mdat` (8) → one large-size mdat header.
+ let ftyp_len = u32::from_be_bytes(file[0..4].try_into().unwrap()) as usize;
+ assert_eq!(&file[ftyp_len + 4..ftyp_len + 8], b"free");
+ let mdat_len = (moov_at - ftyp_len) as u64;
+ file[ftyp_len..ftyp_len + 4].copy_from_slice(&1u32.to_be_bytes());
+ file[ftyp_len + 4..ftyp_len + 8].copy_from_slice(b"mdat");
+ file[ftyp_len + 8..ftyp_len + 16].copy_from_slice(&mdat_len.to_be_bytes());
+ let g = open(file.as_slice()).unwrap();
+ assert_eq!(g.read_sample(file.as_slice(), 0, 0).unwrap(), b"abc");
+ // size == 0 ("extends to end of file") on a trailing box.
+ let mut z = file.clone();
+ z.extend_from_slice(&[0, 0, 0, 0, b'f', b'r', b'e', b'e', 1, 2, 3]);
+ assert!(open(z.as_slice()).is_ok());
+}