FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M9.14: MXF (OP1a/OP-Atom) and Ogg demuxers, image sequences, BWF timecode
Brandon Thomasefa8167962b2
diff --git a/Cargo.lock b/Cargo.lockindex 95b99cff3..1c6ccca44 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1745,6 +1745,8 @@ dependencies = ["filmcraft-codecs","filmcraft-engine","filmcraft-media",+ "filmcraft-mxf",+ "filmcraft-ogg","filmcraft-time","serde_json","tokio",@@ -1765,8 +1767,11 @@ dependencies = ["filmcraft-isobmff","filmcraft-matroska","filmcraft-media",+ "filmcraft-mxf",+ "filmcraft-ogg","filmcraft-opus","filmcraft-prores",+ "filmcraft-testkit","filmcraft-time","filmcraft-vp9","image",@@ -2002,6 +2007,20 @@ dependencies = ["thiserror 2.0.21",]+[[package]]+name = "filmcraft-mxf"+version = "0.1.0"+dependencies = [+ "filmcraft-testkit",+]++[[package]]+name = "filmcraft-ogg"+version = "0.1.0"+dependencies = [+ "filmcraft-testkit",+]+[[package]]name = "filmcraft-opus"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex aa6515074..8f0e61bd2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -18,6 +18,8 @@ filmcraft-color = { path = "crates/color" }filmcraft-bitstream = { path = "crates/bitstream" }filmcraft-isobmff = { path = "crates/isobmff" }filmcraft-matroska = { path = "crates/matroska" }+filmcraft-mxf = { path = "crates/mxf" }+filmcraft-ogg = { path = "crates/ogg" }filmcraft-h264 = { path = "crates/h264" }filmcraft-hevc = { path = "crates/hevc" }filmcraft-vp9 = { path = "crates/vp9" }@@ -103,6 +105,9 @@ opt-level = 3[profile.dev.package.filmcraft-audio-dsp]opt-level = 3+[profile.dev.package.filmcraft-mxf]+opt-level = 3+[profile.dev.package.filmcraft-opus]opt-level = 3diff --git a/ROADMAP.md b/ROADMAP.mdindex 60d209b54..d88739177 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -15,7 +15,7 @@ matched against `filmcraft-cli commands` and the UI command table. Effects: the| Editing, timeline, trimming, multicam | 20% | core edit algebra, trim modes, sync, multicam, menu long tail, Scene Edit Detection, Automate to Sequence | ~80% || Menus / commands | (cross-check) | ~325 of 344 in-scope menu items | ~95% || Effects and transitions | 12% | video effects 93/93 (+Legacy, Obsolete), audio effects 53/53, video transitions 84/84 (+21 Legacy), audio transitions 3/3; some approximations (Warp Stabilizer 2-D, Morph Cut, Auto Reframe) | ~92% |-| Media I/O and codecs | 12% | H.264, HEVC, VP9, AV1, ProRes, DNx, MJPEG, Opus, AAC, MP4/MOV/MKV/WebM; no MXF, image sequences, HW decode | ~70% |+| Media I/O and codecs | 12% | H.264, HEVC, VP9, AV1, ProRes, DNx, MJPEG, Opus, AAC, MP4/MOV/MKV/WebM; MXF (OP1a/OP-Atom), Ogg Opus/Vorbis, image sequences, BWF timecode; no HW decode | ~70% || Panels and UI fidelity | 12% | all main panels, audio effect editor windows; Metadata, Media Browser, scopes (parade/histogram), Timecode, Events panels thin or missing | ~65% || Audio | 10% | mixer, automation, Essential Sound, meters, all 53 effects; no 5.1 buses, voice-over record | ~70% || Colour | 8% | Lumetri complete, LUTs, colour management, HDR | ~80% |@@ -66,7 +66,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining| M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 + own AAC; ProRes, MJPEG, PNG, GIF, WAV; background jobs | Preset library, queue UI, smart render | 6–8 || M7 | Audio | 🟡 | Mixer graph (tracks → submixes → Mix, pre/post-fader inserts and sends, latency-compensated, sample-accurate, ~6× realtime for 24 tracks × 3 effects on one core), Audio Track Mixer + Audio Clip Mixer panels, track automation (Off/Read/Latch/Touch/Write, recorded live while playing, thinned to keyframes, timeline lanes with pen editing), solo/solo-safe, channel mapping basics, peak + BS.1770 loudness meters (match ffmpeg), DSP crate with 16 clip/track effects, Audio Gain (set/adjust/normalize), Constant Power / Constant Gain / Exponential Fade, Essential Sound (types, Loudness auto-match, Repair incl. DeEss/DeReverb, Clarity, Creative, Ducking keyframes, presets; full Dialogue chain 22× realtime) | Music duration remix, ML speech enhancement, 5.1 panner and multichannel buses, voice-over record, effect editor windows (EQ curve), remaining effects (multiband, convolution reverb), clip-mixer automation recording | 6–9 || M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette, section bypass; Input LUT / Look LUT (.cube 1D/3D/shaper, .3dl; tetrahedral CPU + WGSL; project LUT library; built-in camera conversions); Colour Match (Oklab tonal-range statistics, skin protection, solved in Lumetri wheels); colour management: Rec. 709 / Rec. 2100 PQ / HLG working spaces + wide gamut, Interpret Footage colour space (S-Log3, V-Log, Canon Log 2/3, LogC3/4, Apple Log, D-Log from published specs), metadata auto-detect, BT.2390 tone mapping, gamut mapping, HDR export signalling (VUI/colr/mdcv/clli/SEI, ffprobe-verified); scopes incl. HDR nits waveform | Parade/histogram/HLS scopes, HDR-aware Lumetri maths, macOS EDR monitors, mastering metadata → tone-map peak, D-Log M (no published formula), HSL Secondary refine | 3–5 |-| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), VP9 decoder (profiles 0–3, 8/10/12-bit, bit-exact on 50+ fixtures; WebM/MKV `V_VP9` and MP4 `vp09` import with key-frame-checked seeking), Matroska/WebM import (H.264/HEVC/VP9/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4), DNxHD/DNxHR decoder (all SMPTE ST 2019-1 CIDs, 8/10/12-bit, 4:2:2/4:4:4, interlaced, alpha; within IDCT precision of ffmpeg on 22 fixtures) + DNxHR LB/SQ/HQ/HQX/444 encoder and MOV `AVdh` export, AV1 decoder (Main profile, 8/10-bit, all intra/inter tools, loop filters, superres, film grain, intra BC, spatial layers; bit-exact vs libdav1d on 19 SVT fixtures + 22 libaom vectors; MP4 `av01` / WebM `V_AV1` import) | VP9 frame threading, AV1 threading/SIMD (~4 fps 1080p today), AV1 High/Professional profiles, Ogg Opus files, MXF, hardware decode | 12–20 |+| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), VP9 decoder (profiles 0–3, 8/10/12-bit, bit-exact on 50+ fixtures; WebM/MKV `V_VP9` and MP4 `vp09` import with key-frame-checked seeking), Matroska/WebM import (H.264/HEVC/VP9/ProRes/MJPEG + AAC/Opus/FLAC/MP3/Vorbis/PCM), Opus decoder (SILK/CELT/hybrid, 5.1/7.1 multistream; all RFC 8251 vectors range-exact; WebM/MKV/MP4), DNxHD/DNxHR decoder (all SMPTE ST 2019-1 CIDs, 8/10/12-bit, 4:2:2/4:4:4, interlaced, alpha; within IDCT precision of ffmpeg on 22 fixtures) + DNxHR LB/SQ/HQ/HQX/444 encoder and MOV `AVdh` export, AV1 decoder (Main profile, 8/10-bit, all intra/inter tools, loop filters, superres, film grain, intra BC, spatial layers; bit-exact vs libdav1d on 19 SVT fixtures + 22 libaom vectors; MP4 `av01` / WebM `V_AV1` import), MXF import (OP1a/OP-Atom; AVC with POC-ordered B pictures bit-exact, DNxHD/DNxHR, ProRes, PCM/AES3; MPEG-2 reported unsupported; index-table seeking, material package timecode), Ogg Opus/Vorbis (granule seeking, pre-skip, end trimming), image sequences, Broadcast WAV timecode | VP9 frame threading, AV1 threading/SIMD (~4 fps 1080p today), AV1 High/Professional profiles, MPEG-2 decoder, hardware decode | 12–20 || M10 | Graphics & captions | 🟡 | Caption tracks (Subtitle/CEA-608/708/Teletext formats, track style), SRT/WebVTT/SCC import+export (frame-exact, property-tested), caption editing (add/split/merge/trim/move, sync-locked insert/extract), Text panel Captions tab, burn-in in Program monitor and export; text engine (`crates/text`: bundled + system fonts, harfrust shaping, bidi, line breaking, paragraph layout, glyph cache; 3-line 1080p title ≈ 0.15 ms warm); graphic clips with text + shape layers (fill, 2 strokes, background, shadow, keyframable transform), Type tool with on-monitor editing, shape/pen tools, Properties/Essential Graphics editor, align/distribute | Responsive design pins, rolls/crawls, per-character styles, motion graphics templates, MCC/STL/TTML, 608/708 embedding, speech-to-text | 12–18 || M11 | Interchange & project management | ✅ | `.fcproj` schema versions + migrations, atomic saves, Save a Copy/Revert, auto-save ring + crash-recovery journal (Preferences ▸ Auto Save, recovery prompt), FCP7 XML, FCPXML, EDL, OTIO; offline media (own slate) + Link Media (fingerprint-checked relink, folder remap, search, Align Timecode, Make Offline); proxies (ProRes Proxy/LT, H.264 ¼/½ background jobs, attach/detach/reconnect, monitor toggle, export full-res) + ingest (copy/transcode/proxies); Project Manager (collect, consolidate + transcode with handles, size estimate) | Rename media to clip names, image-sequence conversion, Media Browser-driven relink, smart (cross-drive) path tracking | 1–2 || M12–M16 | Multicam, web (WASM), platform, long tail | 🟡 | Multicam: audio sync (GCC-PHAT, sub-sample), Merge Clips, multi-camera source sequences, Multi-Camera view with live switching (1–9); L0–L4 crates compile to wasm32 | Web app shell (file access, WebCodecs, audio), scene detection, auto reframe, ~800 remaining commands and dialogs, performance hardening | 35–55 |diff --git a/apps/filmcraft-cli/Cargo.toml b/apps/filmcraft-cli/Cargo.tomlindex 7d530e79b..ac19c2b91 100644--- a/apps/filmcraft-cli/Cargo.toml+++ b/apps/filmcraft-cli/Cargo.toml@@ -21,6 +21,8 @@ whisper = ["filmcraft-engine/whisper", "filmcraft-engine/speech-download"]filmcraft-engine = { workspace = true }filmcraft-media = { workspace = true }filmcraft-codecs = { workspace = true }+filmcraft-mxf = { workspace = true }+filmcraft-ogg = { workspace = true }filmcraft-time = { workspace = true }filmcraft-automation = { workspace = true }serde_json = { workspace = true }diff --git a/apps/filmcraft-cli/src/main.rs b/apps/filmcraft-cli/src/main.rsindex df8b76c5a..6771bfd43 100644--- a/apps/filmcraft-cli/src/main.rs+++ b/apps/filmcraft-cli/src/main.rs@@ -3,6 +3,7 @@//! Run `filmcraft-cli help` for the full reference (also in docs/agents.md).mod args;+mod probe;use args::{Args, parse_value};use filmcraft_automation::BridgeClient;@@ -26,7 +27,9 @@ SUBCOMMANDSexport <out> [--format f] export the active sequence (h264|prores|dnxhr|mjpeg|png|gif|wav;guessed from the extension) and wait for it to finishrender --seconds S --out f.png [--scale 0.5] render one Program frame to PNG- probe <media> media info as JSON+ probe <media> [--image-sequence]+ media info as JSON, with MXF / Ogg / BWF details; with+ --image-sequence <media> is the first numbered still of a sequencebench-decode <media> [--frames N]mcp MCP server on stdio (headless, or --bridge to the live app)help this text@@ -141,11 +144,10 @@ async fn main() {"help" | "--help" | "-h" => print!("{HELP}"),"version" => println!("filmcraft-cli {}", env!("CARGO_PKG_VERSION")),"probe" => {- let path = a.pos(1).unwrap_or_else(|| usage("probe <media>"));- let bytes = std::fs::read(path).unwrap_or_else(|e| fail(format!("{path}: {e}")));- match filmcraft_codecs::open_bytes(path, bytes.into()) {- Ok(src) => print(&a, &serde_json::to_value(src.info()).unwrap_or_default()),- Err(e) => fail(format!("{path}: {e}")),+ let path = a.pos(1).unwrap_or_else(|| usage("probe <media> [--image-sequence]"));+ match probe::probe(path, a.flag("--image-sequence")) {+ Ok(v) => print(&a, &v),+ Err(e) => fail(e),}}"bench-decode" => {diff --git a/apps/filmcraft-cli/src/probe.rs b/apps/filmcraft-cli/src/probe.rsnew file mode 100644index 000000000..27e3537ad--- /dev/null+++ b/apps/filmcraft-cli/src/probe.rs@@ -0,0 +1,130 @@+//! `filmcraft-cli probe`: media info as JSON, plus container details for MXF (operational+//! pattern, tracks, index, timecode), Ogg (logical streams, pre-skip, granules), Broadcast WAV+//! (time reference) and image sequences (frames, missing numbers).++use std::sync::Arc;++use serde_json::{Value, json};++fn rate(r: filmcraft_mxf::Rational) -> String {+ format!("{}/{}", r.num, r.den)+}++fn mxf_details(src: &filmcraft_codecs::MxfSource) -> Value {+ let f = src.file();+ let tracks: Vec<Value> = f+ .tracks+ .iter()+ .map(|t| {+ let mut v = json!({+ "trackId": t.track_id,+ "trackNumber": format!("{:08x}", t.track_number),+ "kind": format!("{:?}", t.kind),+ "codec": t.codec.name(),+ "wrapping": format!("{:?}", t.wrapping),+ "editRate": rate(t.edit_rate),+ "origin": t.origin,+ "startPosition": t.start_position,+ "duration": t.duration,+ });+ if t.kind == filmcraft_mxf::TrackKind::Picture {+ v["pictures"] = json!(t.samples.len());+ v["keyFrames"] = json!(t.samples.iter().filter(|s| s.key).count());+ v["indexed"] = json!(t.indexed);+ v["temporalOffsets"] = json!(t.temporal_offsets);+ v["reorderedFromBitstream"] = json!(t.needs_reorder);+ }+ if let Some(s) = &t.sound {+ v["sampleRate"] = json!(rate(s.sample_rate));+ v["channels"] = json!(s.channels);+ v["bits"] = json!(s.bits);+ v["sampleFrames"] = json!(t.stored_sample_frames());+ }+ v+ })+ .collect();+ json!({+ "operationalPattern": f.operational_pattern.name(),+ "timecode": f.timecode.map(|t| json!({"start": t.start, "roundedBase": t.rounded_base, "dropFrame": t.drop_frame, "text": t.format()})),+ "materialPackage": f.material_package_name,+ "product": f.product_name,+ "company": f.company_name,+ "partitions": f.partitions.len(),+ "indexSegments": f.index_segments.len(),+ "runIn": f.run_in,+ "tracks": tracks,+ "warnings": f.warnings,+ })+}++fn ogg_details(src: &filmcraft_codecs::OggSource) -> Value {+ let f = src.file();+ let streams: Vec<Value> = f+ .streams+ .iter()+ .map(|s| {+ let mut v = json!({"serial": s.serial, "codec": s.codec.name(), "packets": s.packets.len(), "pages": s.pages, "lastGranule": s.last_granule, "endOfStream": s.saw_eos});+ if s.codec == filmcraft_ogg::Codec::Opus+ && let Some(h) = s.headers.first()+ && h.len() >= 12+ {+ let pre_skip = u16::from_le_bytes([h[10], h[11]]);+ let t = filmcraft_ogg::OpusTiming::of(s, pre_skip as u32);+ v["preSkip"] = json!(pre_skip);+ v["samples48k"] = json!(t.total);+ }+ v+ })+ .collect();+ json!({"streams": streams, "warnings": f.warnings})+}++/// Probe `path`; with `image_sequence`, `path` is the first frame of a numbered still sequence.+pub fn probe(path: &str, image_sequence: bool) -> Result<Value, String> {+ if image_sequence {+ use filmcraft_media::sequence::{ImageSequenceSource, Numbered, sequence_frames};+ let n = Numbered::parse(path).ok_or_else(|| format!("{path}: not a numbered still image"))?;+ let dir = if n.dir.is_empty() { ".".to_string() } else { n.dir.clone() };+ let names: Vec<String> =+ std::fs::read_dir(&dir).map_err(|e| format!("{dir}: {e}"))?.flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect();+ let frames = sequence_frames(&n, &names);+ let name = std::path::Path::new(path).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();+ let loader: filmcraft_media::sequence::FrameLoader = Arc::new(|p: &str| std::fs::read(p));+ // the timebase of a fresh install (Settings ▸ Media ▸ Indeterminate Media Timebase)+ let src = ImageSequenceSource::new(&name, frames, filmcraft_time::FrameRate::FPS_29_97, loader).map_err(|e| format!("{path}: {e}"))?;+ let mut v = serde_json::to_value(filmcraft_media::MediaSource::info(&src)).unwrap_or_default();+ v["imageSequence"] = json!({+ "first": src.frame_path(0),+ "firstNumber": n.number,+ "lastNumber": n.number + src.frame_count() as u64 - 1,+ "frames": src.frame_count(),+ "missing": src.missing_frames().iter().map(|i| n.number + *i as u64).collect::<Vec<_>>(),+ });+ return Ok(v);+ }+ let bytes: Arc<[u8]> = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?.into();+ let name = std::path::Path::new(path).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ let head = &bytes[..bytes.len().min(70_000)];+ if filmcraft_mxf::sniff(head) {+ let src = filmcraft_codecs::MxfSource::open(&name, bytes).map_err(|e| format!("{path}: {e}"))?;+ let mut v = serde_json::to_value(filmcraft_media::MediaSource::info(&src)).unwrap_or_default();+ v["mxf"] = mxf_details(&src);+ return Ok(v);+ }+ if filmcraft_ogg::sniff(head)+ && let Ok(src) = filmcraft_codecs::OggSource::open(&name, bytes.clone())+ {+ let mut v = serde_json::to_value(filmcraft_media::MediaSource::info(&src)).unwrap_or_default();+ v["ogg"] = ogg_details(&src);+ return Ok(v);+ }+ let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(|e| format!("{path}: {e}"))?;+ let mut v = serde_json::to_value(src.info()).unwrap_or_default();+ if filmcraft_media::wav::sniff(head)+ && let Ok(w) = filmcraft_media::wav::WavSource::parse(&name, bytes)+ && let Some(tr) = w.time_reference()+ {+ v["bwf"] = json!({"timeReference": tr});+ }+ Ok(v)+}diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.tomlindex 1d704831f..f262d452a 100644--- a/crates/codecs/Cargo.toml+++ b/crates/codecs/Cargo.toml@@ -1,6 +1,6 @@[package]name = "filmcraft-codecs"-description = "Container + codec hub: MP4/MOV sources, GOP-aware seeking, decoder registry, audio decoding"+description = "Container + codec hub: MP4/MOV, Matroska, MXF and Ogg sources, image sequences, GOP-aware seeking, decoder registry, audio decoding"version.workspace = trueedition.workspace = truelicense.workspace = true@@ -16,6 +16,8 @@ filmcraft-frame = { workspace = true }filmcraft-media = { workspace = true }filmcraft-isobmff = { workspace = true }filmcraft-matroska = { workspace = true }+filmcraft-mxf = { workspace = true }+filmcraft-ogg = { workspace = true }filmcraft-bitstream = { workspace = true }filmcraft-h264 = { workspace = true }filmcraft-hevc = { workspace = true }@@ -32,3 +34,6 @@ web-time = "1"image = { version = "0.25", default-features = false, features = ["jpeg"] }# Bootstrap audio decoding (MPL-2.0, used unmodified); replaced by own decoders over time.symphonia = { version = "0.5.5", default-features = false, features = ["aac", "mp3", "flac", "alac", "pcm", "wav", "ogg", "vorbis", "isomp4"] }++[dev-dependencies]+filmcraft-testkit = { workspace = true }diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rsindex fe280f55a..a93c99bf8 100644--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@ -7,13 +7,18 @@//! `filmcraft-isobmff`: GOP-aware random access (seek to the preceding sync sample and decode//! forward, caching every decoded frame of the GOP), sequential fast path for playback, and//! packet-cached audio decoding.-//! - [`AudioFileSource`]: standalone compressed audio files (MP3, FLAC, Ogg Vorbis, …).+//! - [`MkvSource`], [`MxfSource`] (OP1a / OP-Atom: AVC, VC-3, ProRes, PCM; MPEG-2 reported as+//! unsupported) and [`OggSource`] (Ogg Opus with granule-position seeking, Ogg Vorbis): the same+//! GOP-aware video access and packet-cached audio.+//! - [`AudioFileSource`]: standalone compressed audio files (MP3, FLAC, AIFF, …).//! - [`openers`]: the openers to register with the engine's media pool.pub mod audio;pub mod gop;pub mod mkv;pub mod mp4;+pub mod mxf;+pub mod ogg;pub mod video;use std::sync::{Arc, RwLock};@@ -22,6 +27,8 @@ pub use audio::AudioFileSource;pub use gop::{GopStats, gop_stats};pub use mkv::MkvSource;pub use mp4::Mp4Source;+pub use mxf::MxfSource;+pub use ogg::OggSource;pub use video::{DecodedFrame, VideoDecoder, VideoDecoderFactory};#[derive(Debug, thiserror::Error)]@@ -83,14 +90,14 @@ pub fn make_video_decoder(entry: &filmcraft_isobmff::SampleEntry) -> Result<Box<Err(CodecError::Unsupported(format!("no decoder for {} video", entry.codec.name())))}-/// Openers for the engine's media pool (MP4/MOV, Matroska/WebM, standalone audio).+/// Openers for the engine's media pool (MP4/MOV, Matroska/WebM, MXF, Ogg Opus/Vorbis, standalone audio).pub fn openers() -> Vec<filmcraft_media::Opener> {- vec![mp4::opener, mkv::opener, audio::opener]+ vec![mp4::opener, mkv::opener, mxf::opener, ogg::opener, audio::opener]}fn reader_registry() -> &'static RwLock<Vec<filmcraft_media::ReaderOpener>> {static R: std::sync::OnceLock<RwLock<Vec<filmcraft_media::ReaderOpener>>> = std::sync::OnceLock::new();- R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener]))+ R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener, mxf::reader_opener, ogg::reader_opener]))}/// Openers that read containers through a [`filmcraft_media::ByteReader`] (index now, samples ondiff --git a/crates/codecs/src/mxf.rs b/crates/codecs/src/mxf.rsnew file mode 100644index 000000000..2ea53ea65--- /dev/null+++ b/crates/codecs/src/mxf.rs@@ -0,0 +1,492 @@+//! MXF media source (`filmcraft-mxf` demux, GOP-aware video via [`crate::gop`]).+//!+//! - Video: H.264 / AVC-Intra (Annex B byte stream, our decoder), VC-3 (DNxHD/DNxHR) and ProRes+//! through the decoder factories. MPEG-2 video (D-10/IMX, XDCAM) and other codings are+//! identified and reported as unsupported; the file still opens so its audio can be used.+//! - Presentation order: the index table's temporal offsets; for AVC whose index marks B pictures+//! but carries no temporal offsets, the picture order counts of the slice headers (8.2.1).+//! - Audio: every PCM sound track (Broadcast Wave / AES3, ST 382; ST 331 AES3 elements in D-10)+//! is presented as one multichannel stream, sample-exact.+//! - Start timecode: the material package's timecode track.++use std::sync::Arc;++use filmcraft_frame::{AudioBuffer, VideoFrame};+use filmcraft_isobmff::{FourCc, SampleEntry};+use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};+use filmcraft_mxf::{Codec, MxfFile, Timecode, TrackKind};+use filmcraft_time::{FrameRate, Tick};++use crate::gop::{GopCache, VideoSamples};+use crate::video::VideoDecoder;+use crate::{CodecError, make_video_decoder};++impl filmcraft_mxf::ByteSource for crate::Src {+ fn len(&self) -> u64 {+ self.0.len()+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {+ self.0.read_at(offset, buf)+ }+}++pub fn sniff(head: &[u8]) -> bool {+ filmcraft_mxf::sniff(head)+}++pub struct MxfSource {+ info: MediaInfo,+ bytes: crate::Src,+ file: MxfFile,+ vtrack: Option<usize>,+ /// Presentation position of each stored picture (overrides the container's when the order+ /// comes from the bitstream).+ vpts: Vec<i64>,+ /// Display position → stored picture.+ vorder: Vec<usize>,+ /// First presented display position, and the number presented.+ vfirst: i64,+ vcount: i64,+ video: GopCache,+ /// Why the video cannot be decoded (no decoder for the coding).+ unsupported: Option<String>,+ /// Sound tracks combined into one stream: (track, first stored sample frame).+ atracks: Vec<(usize, u64)>,+ /// Presented sample frames.+ aframes: u64,+}++/// Picture order counts of AVC access units (Annex B), in stored order, as presentation+/// positions: the rank of (IDR period, POC) (8.2.1.1, picture order count type 0; types 1 and 2+/// never reorder for the streams written by AVC encoders we have seen, so they keep stored order).+pub fn avc_presentation_order(heads: &[Vec<u8>]) -> Option<Vec<i64>> {+ use filmcraft_bitstream::{annexb_nals, unescape_rbsp};+ use filmcraft_h264::params::{Pps, Sps};+ use filmcraft_h264::slice::{NalHeader, SliceHeader};+ let mut spss: Vec<Option<Sps>> = vec![None; 32];+ let mut ppss: Vec<Option<Pps>> = vec![None; 256];+ let (mut prev_msb, mut prev_lsb) = (0i64, 0i64);+ let mut period = 0i64;+ let mut keys: Vec<(i64, i64)> = Vec::with_capacity(heads.len());+ for (i, h) in heads.iter().enumerate() {+ let mut key = None;+ for nal in annexb_nals(h) {+ let Ok(hdr) = NalHeader::parse(nal[0]) else { continue };+ let rbsp = unescape_rbsp(&nal[1..]);+ match hdr.nal_unit_type {+ 7 => {+ let sps = Sps::parse(&rbsp).ok()?;+ let id = sps.id as usize;+ *spss.get_mut(id)? = Some(sps);+ }+ 8 => {+ let pps = Pps::parse(&rbsp, &spss).ok()?;+ let id = pps.id as usize;+ *ppss.get_mut(id)? = Some(pps);+ }+ 1 | 5 => {+ let mut sps_of = None;+ let (sh, _, _) = SliceHeader::parse(&rbsp, hdr, |id| {+ let pps = ppss.get(id as usize).and_then(Option::as_ref).ok_or(filmcraft_h264::Error::MissingParameterSet("PPS".into()))?;+ let sps = spss.get(pps.sps_id as usize).and_then(Option::as_ref).ok_or(filmcraft_h264::Error::MissingParameterSet("SPS".into()))?;+ sps_of = Some(sps);+ Ok((pps, sps))+ })+ .ok()?;+ let sps = sps_of?;+ if sh.idr {+ if i > 0 {+ period += 1;+ }+ prev_msb = 0;+ prev_lsb = 0;+ }+ let poc = match sps.pic_order_cnt_type {+ 0 => {+ let max = 1i64 << sps.log2_max_poc_lsb;+ let lsb = sh.pic_order_cnt_lsb as i64;+ let msb = if lsb < prev_lsb && prev_lsb - lsb >= max / 2 {+ prev_msb + max+ } else if lsb > prev_lsb && lsb - prev_lsb > max / 2 {+ prev_msb - max+ } else {+ prev_msb+ };+ let top = msb + lsb;+ let poc = if sh.field_pic { top } else { top.min(top + sh.delta_pic_order_cnt_bottom as i64) };+ if hdr.nal_ref_idc != 0 {+ prev_msb = msb;+ prev_lsb = lsb;+ }+ poc+ }+ _ => i as i64,+ };+ if sh.has_mmco5() {+ // memory_management_control_operation 5: later pictures start a new period+ period += 1;+ prev_msb = 0;+ prev_lsb = 0;+ key = Some((period - 1, poc));+ } else {+ key = Some((period, poc));+ }+ break;+ }+ _ => {}+ }+ }+ keys.push(key?);+ }+ let mut order: Vec<usize> = (0..keys.len()).collect();+ order.sort_by_key(|&i| (keys[i], i));+ let mut pts = vec![0i64; keys.len()];+ for (rank, &i) in order.iter().enumerate() {+ pts[i] = rank as i64;+ }+ Some(pts)+}++/// ProRes FourCC from the RDD 44 coding label profile byte.+fn prores_fourcc(profile: Option<u8>) -> FourCc {+ FourCc(match profile {+ Some(1) => *b"apco",+ Some(2) => *b"apcs",+ Some(4) => *b"apch",+ Some(5) => *b"ap4h",+ Some(6) => *b"ap4x",+ _ => *b"apcn",+ })+}++fn prores_name(profile: Option<u8>) -> &'static str {+ match profile {+ Some(1) => "Apple ProRes 422 Proxy",+ Some(2) => "Apple ProRes 422 LT",+ Some(3) => "Apple ProRes 422",+ Some(4) => "Apple ProRes 422 HQ",+ Some(5) => "Apple ProRes 4444",+ Some(6) => "Apple ProRes 4444 XQ",+ _ => "Apple ProRes",+ }+}++/// The start timecode as a frame count at `rate` (the media's frame rate).+fn start_frames(tc: &Timecode, rate: FrameRate) -> i64 {+ let base = tc.rounded_base.max(1) as i64;+ // the real rate of the timecode: the media rate when it rounds to the base+ let (num, den) = if (rate.as_f64().round() as i64) == base {+ (rate.num, rate.den)+ } else if tc.drop_frame {+ (base * 1000, 1001)+ } else {+ (base, 1)+ };+ // frames at the tc rate → frames at `rate` (exact when they are the same rate)+ let n = tc.start as i128 * rate.num as i128 * den as i128;+ let d = num as i128 * rate.den as i128;+ ((n + d / 2) / d) as i64+}++impl MxfSource {+ pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {+ Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))+ }++ /// Open from a random-access reader: only the KLV headers, metadata and index are read now.+ pub fn open_reader(name: &str, reader: filmcraft_media::SharedReader) -> crate::Result<Self> {+ let bytes = crate::Src(reader);+ let file = filmcraft_mxf::open(&bytes).map_err(|e| match e {+ filmcraft_mxf::Error::Unsupported(s) => CodecError::Unsupported(format!("MXF: {s}")),+ other => CodecError::Container(other.to_string()),+ })?;+ for w in &file.warnings {+ log::warn!("{name}: {w}");+ }+ let vtrack = file.track_of_kind(TrackKind::Picture);+ let atracks: Vec<usize> = file+ .tracks+ .iter()+ .enumerate()+ .filter(|(_, t)| t.kind == TrackKind::Sound && !t.chunks.is_empty() && t.sound_format != filmcraft_mxf::SoundFormat::Other)+ .map(|(i, _)| i)+ .collect();+ if vtrack.is_none() && atracks.is_empty() {+ return Err(CodecError::Unsupported("MXF: no playable picture or PCM sound tracks".into()));+ }+ // Video+ let mut video = None;+ let mut unsupported = None;+ let (mut vpts, mut vorder, mut vfirst, mut vcount) = (Vec::new(), Vec::new(), 0, 0);+ let mut explicit_color = None;+ if let Some(vi) = vtrack {+ let t = &file.tracks[vi];+ let p = t.picture.clone().unwrap_or_default();+ vpts = t.samples.iter().map(|s| s.pts).collect();+ vorder = t.display_order.clone();+ if t.needs_reorder && matches!(t.codec, Codec::Avc { .. }) {+ let heads: Vec<Vec<u8>> = (0..t.samples.len())+ .map(|i| {+ let s = t.samples[i];+ filmcraft_media::reader::read_range(&*bytes.0, s.offset, (s.size as usize).min(16 << 10)).unwrap_or_default()+ })+ .collect();+ match avc_presentation_order(&heads) {+ Some(pts) => {+ vorder = vec![0; pts.len()];+ for (s, &d) in pts.iter().enumerate() {+ vorder[d as usize] = s;+ }+ vpts = pts;+ }+ None => log::warn!("{name}: B pictures without temporal offsets and unreadable picture order: using stored order"),+ }+ }+ vfirst = t.first_edit_unit().min(vorder.len() as i64);+ let avail = vorder.len() as i64 - vfirst;+ vcount = t.duration.map_or(avail, |d| d.min(avail)).max(0);+ let rate = if t.edit_rate.is_valid() { FrameRate::new(t.edit_rate.num as i64, t.edit_rate.den as i64) } else { FrameRate::FPS_25 };+ let (w, h) = (p.frame_width(), p.frame_height());+ let par = if p.aspect_ratio.is_valid() && w > 0 && h > 0 {+ let n = p.aspect_ratio.num as u64 * h as u64;+ let d = p.aspect_ratio.den as u64 * w as u64;+ let g = gcd(n, d).max(1);+ ((n / g) as u32, (d / g) as u32)+ } else {+ (1, 1)+ };+ let codec = match t.codec {+ Codec::Vc3 => file+ .read_sample(&bytes, vi, 0)+ .ok()+ .and_then(|f| filmcraft_dnx::probe(&f).ok())+ .map(|h| filmcraft_dnx::cid_name(h.cid))+ .unwrap_or_else(|| "DNxHD/DNxHR".into()),+ Codec::ProRes { profile } => prores_name(profile).into(),+ c @ Codec::Avc { .. } => c.name().into(),+ other => {+ let why = format!("{} video in MXF (FilmCraft has no {} decoder)", other.name(), other.name());+ unsupported = Some(why);+ format!("{} (unsupported)", other.name())+ }+ };+ let chroma = match (p.horizontal_subsampling, p.vertical_subsampling) {+ (2, 2) => "4:2:0",+ (2, 1) => "4:2:2",+ (1, 1) => "4:4:4",+ _ => "",+ };+ let pixel_format = if p.component_depth > 0 && !chroma.is_empty() { format!("YUV {chroma} {}-bit", p.component_depth) } else { String::new() };+ let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), ..filmcraft_color::ColorInfo::REC709 };+ if p.full_range() {+ color.range = filmcraft_color::Range::Full;+ explicit_color = Some(color);+ }+ let secs = vcount as f64 / rate.as_f64().max(1e-9);+ let bytes_total: u64 = t.samples.iter().map(|s| s.size as u64).sum();+ video = Some(VideoStreamInfo {+ width: w,+ height: h,+ frame_rate: rate,+ par,+ codec,+ pixel_format,+ color,+ has_alpha: p.alpha_depth > 0,+ bitrate: (secs > 0.0).then(|| (bytes_total as f64 * 8.0 / (t.samples.len().max(1) as f64 / rate.as_f64().max(1e-9))) as u64),+ });+ }+ // Audio: all PCM sound tracks of the first track's rate, channels in track order+ let mut audio = None;+ let mut combined = Vec::new();+ let mut aframes = u64::MAX;+ if let Some(&a0) = atracks.first() {+ let si0 = file.tracks[a0].sound.clone().unwrap_or_default();+ let rate = si0.sample_rate;+ let mut channels = 0;+ for &ai in &atracks {+ let t = &file.tracks[ai];+ let si = t.sound.as_ref().expect("sound info");+ if si.sample_rate != rate {+ continue;+ }+ let (n, d) = t.samples_per_edit_unit();+ let first = (t.first_edit_unit() as i128 * n as i128 / d.max(1) as i128) as u64;+ let stored = t.stored_sample_frames().saturating_sub(first);+ let presented = t.duration.map_or(stored, |du| ((du as i128 * n as i128 / d.max(1) as i128) as u64).min(stored));+ aframes = aframes.min(presented);+ channels += si.channels.max(1);+ combined.push((ai, first));+ }+ let sr = if rate.is_valid() { (rate.num as f64 / rate.den as f64).round() as u32 } else { 48_000 };+ audio = Some(AudioStreamInfo { sample_rate: sr.max(1), channels, codec: file.tracks[a0].codec.name().into(), bits_per_sample: Some(si0.bits) });+ }+ if aframes == u64::MAX {+ aframes = 0;+ }+ let duration = match (&video, &audio) {+ (Some(v), _) => v.frame_rate.tick_of(vcount),+ (None, Some(a)) => Tick::from_units(aframes as i64, a.sample_rate as i64),+ _ => Tick::ZERO,+ };+ let mut info = MediaInfo {+ name: name.to_string(),+ kind: if video.is_some() { MediaKind::Movie } else { MediaKind::AudioOnly },+ duration,+ video,+ audio,+ container: format!("MXF {}", file.operational_pattern.name()),+ start_timecode: None,+ file_size: Some(bytes.0.len()),+ };+ info.start_timecode = file.timecode.as_ref().map(|tc| start_frames(tc, info.frame_rate()));+ Ok(Self { info, bytes, vtrack, vpts, vorder, vfirst, vcount, video: GopCache::new(explicit_color), unsupported, atracks: combined, aframes, file })+ }++ /// The demuxed file (tracks, partitions, index, timecode).+ pub fn file(&self) -> &MxfFile {+ &self.file+ }+}++fn gcd(a: u64, b: u64) -> u64 {+ if b == 0 { a } else { gcd(b, a % b) }+}++/// The MXF picture track as a [`VideoSamples`] table (pts in display positions).+struct MxfVideo<'a> {+ src: &'a MxfSource,+ track: usize,+}++impl VideoSamples for MxfVideo<'_> {+ fn count(&self) -> usize {+ self.src.vpts.len()+ }+ fn pts(&self, i: usize) -> i64 {+ self.src.vpts[i]+ }+ fn sync_before(&self, i: usize) -> usize {+ self.src.file.tracks[self.track].sync_before(i)+ }+ fn sample_at(&self, t: i64) -> Option<usize> {+ usize::try_from(t).ok().and_then(|t| self.src.vorder.get(t).copied())+ }+ fn read(&self, i: usize) -> crate::Result<Vec<u8>> {+ self.src.file.read_sample(&self.src.bytes, self.track, i).map_err(|e| CodecError::Container(e.to_string()))+ }+ fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {+ if let Some(why) = &self.src.unsupported {+ return Err(CodecError::Unsupported(why.clone()));+ }+ let t = &self.src.file.tracks[self.track];+ let v = self.src.info.video.as_ref().expect("video info");+ let (w, h) = (v.width.min(u16::MAX as u32) as u16, v.height.min(u16::MAX as u32) as u16);+ match t.codec {+ Codec::Avc { .. } => Ok(Box::new(crate::video::H264Decoder::annexb())),+ Codec::Vc3 => make_video_decoder(&SampleEntry::dnx(FourCc(*b"AVdh"), w, h)),+ Codec::ProRes { profile } => make_video_decoder(&SampleEntry::prores(prores_fourcc(profile), w, h)),+ other => Err(CodecError::Unsupported(format!("{} video in MXF", other.name()))),+ }+ }+}++impl MediaSource for MxfSource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }++ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>, MediaError> {+ let ti = self.vtrack.ok_or(MediaError::NoStream("video"))?;+ if let Some(why) = &self.unsupported {+ return Err(MediaError::Unsupported(why.clone()));+ }+ if self.vcount == 0 {+ return Err(MediaError::Decode("MXF: no pictures".into()));+ }+ let rate = self.info.frame_rate();+ let f = rate.frame_at(req.time.max(Tick::ZERO)).clamp(0, self.vcount - 1);+ let late = filmcraft_media::cancel::catch_up().map(|m| self.vfirst + rate.frame_at(req.time - m));+ let frame = self.video.frame_late(&MxfVideo { src: self, track: ti }, self.vfirst + f, late)?;+ Ok(frame)+ }++ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer, MediaError> {+ let ainfo = self.info.audio.as_ref().ok_or(MediaError::NoStream("audio"))?;+ let src_rate = ainfo.sample_rate;+ let ch = ainfo.channels.max(1) as usize;+ let mut out = AudioBuffer::silence(sample_rate, ch, frames);+ let ratio = src_rate as f64 / sample_rate as f64;+ let exact = src_rate == sample_rate;+ let s0 = if exact { start } else { (start as f64 * ratio).floor() as i64 };+ let need = if exact { frames as i64 } else { (frames as f64 * ratio).ceil() as i64 + 2 };+ // clip the request to the presented range [0, aframes)+ let a = s0.max(0);+ let b = (s0 + need).min(self.aframes as i64);+ let mut src: Vec<Vec<f32>> = vec![vec![0.0; need.max(0) as usize]; ch];+ if b > a {+ let mut c0 = 0;+ for &(ti, first) in &self.atracks {+ let pcm = self.file.read_pcm(&self.bytes, ti, first + a as u64, (b - a) as usize).map_err(|e| MediaError::Decode(e.to_string()))?;+ for (k, p) in pcm.into_iter().enumerate() {+ if let Some(dst) = src.get_mut(c0 + k) {+ let at = (a - s0) as usize;+ dst[at..at + p.len()].copy_from_slice(&p);+ }+ }+ c0 += self.file.tracks[ti].sound.as_ref().map_or(1, |s| s.channels.max(1) as usize);+ }+ }+ if exact {+ out.channels = src;+ return Ok(out);+ }+ let frac = s0 as f64 - start as f64 * ratio;+ for k in 0..frames {+ let pos = k as f64 * ratio - frac;+ let i0 = pos.floor().max(0.0) as usize;+ let f = (pos - i0 as f64) as f32;+ for c in 0..ch {+ let a = src[c].get(i0).copied().unwrap_or(0.0);+ let b = src[c].get(i0 + 1).copied().unwrap_or(a);+ out.channels[c][k] = a + (b - a) * f;+ }+ }+ Ok(out)+ }+}++pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, MediaError>> {+ if !sniff(&bytes[..bytes.len().min(70_000)]) {+ return None;+ }+ Some(MxfSource::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))+}++/// [`filmcraft_media::ReaderOpener`] for MXF.+pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {+ if !sniff(head) {+ return None;+ }+ Some(MxfSource::open_reader(name, reader.clone()).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn timecode_frames_at_the_media_rate() {+ let tc = Timecode { start: 90_000, rounded_base: 25, drop_frame: false };+ assert_eq!(start_frames(&tc, FrameRate::FPS_25), 90_000);+ // 50p media with a 25 fps timecode track+ assert_eq!(start_frames(&tc, FrameRate::FPS_50), 180_000);+ // 29.97 DF: the frame count is already at 29.97+ let df = Timecode { start: 107_892, rounded_base: 30, drop_frame: true };+ assert_eq!(start_frames(&df, FrameRate::FPS_29_97), 107_892);+ // audio-only media (default 23.976): one hour of DF timecode is one real hour minus 3.6 s+ let f = start_frames(&df, FrameRate::FPS_23_976);+ let secs = f as f64 * 1001.0 / 24000.0;+ assert!((secs - 107_892.0 * 1001.0 / 30000.0).abs() < 0.05, "{secs}");+ }+}diff --git a/crates/codecs/src/ogg.rs b/crates/codecs/src/ogg.rsnew file mode 100644index 000000000..7c5414c8b--- /dev/null+++ b/crates/codecs/src/ogg.rs@@ -0,0 +1,287 @@+//! Ogg audio source (`filmcraft-ogg` demux): Ogg Opus with our Opus decoder and Ogg Vorbis with the+//! bootstrap Vorbis decoder.+//!+//! Opus (RFC 7845): packet positions come from granule positions and TOC durations+//! ([`filmcraft_ogg::OpusTiming`]); the pre-skip samples land before 0 and are never returned, the+//! final page's end trimming is applied, and random access decodes [`crate::audio::OPUS_PRE_ROLL`]+//! of preceding packets first (so a seek gives the same samples as continuous playback).+//!+//! Vorbis: decoded once when opened (audio files are small next to video), aligned to the granule+//! positions (leading samples before the first page's granule and samples after the last page's+//! granule are dropped).++use std::collections::HashMap;+use std::sync::{Arc, Mutex};++use filmcraft_frame::{AudioBuffer, VideoFrame};+use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource};+use filmcraft_ogg::{Codec, OggFile, OpusTiming};+use filmcraft_time::Tick;++use crate::CodecError;+use crate::audio::{OPUS_PRE_ROLL, OPUS_RATE, PacketDecoder, read_resampled};++impl filmcraft_ogg::ByteSource for crate::Src {+ fn len(&self) -> u64 {+ self.0.len()+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {+ self.0.read_at(offset, buf)+ }+}++pub fn sniff(head: &[u8]) -> bool {+ filmcraft_ogg::sniff(head)+}++struct OpusState {+ decoder: Option<PacketDecoder>,+ packets: HashMap<usize, Arc<Vec<Vec<f32>>>>,+ order: Vec<usize>,+ last_decoded: Option<usize>,+}++enum Kind {+ Opus {+ head: Box<filmcraft_opus::OpusHead>,+ timing: OpusTiming,+ state: Mutex<OpusState>,+ },+ /// Fully decoded planar samples.+ Pcm {+ rate: u32,+ samples: Vec<Vec<f32>>,+ },+}++pub struct OggSource {+ info: MediaInfo,+ bytes: crate::Src,+ file: OggFile,+ stream: usize,+ kind: Kind,+}++impl OggSource {+ pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {+ Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))+ }++ pub fn open_reader(name: &str, reader: filmcraft_media::SharedReader) -> crate::Result<Self> {+ let bytes = crate::Src(reader);+ let file = filmcraft_ogg::open(&bytes).map_err(|e| CodecError::Container(e.to_string()))?;+ for w in &file.warnings {+ log::warn!("{name}: {w}");+ }+ let stream = file+ .streams+ .iter()+ .position(|s| matches!(s.codec, Codec::Opus | Codec::Vorbis) && !s.packets.is_empty())+ .ok_or_else(|| CodecError::Unsupported("Ogg: no Opus or Vorbis stream".into()))?;+ let st = &file.streams[stream];+ let (kind, rate, channels, codec) = match st.codec {+ Codec::Opus => {+ let head = filmcraft_opus::OpusHead::parse(&st.headers[0]).map_err(|e| CodecError::Unsupported(format!("Opus: {e}")))?;+ let timing = OpusTiming::of(st, head.pre_skip as u32);+ let channels = head.channels as u32;+ (+ Kind::Opus {+ head: Box::new(head),+ timing,+ state: Mutex::new(OpusState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),+ },+ OPUS_RATE,+ channels,+ "Opus",+ )+ }+ _ => {+ let (rate, samples) = decode_vorbis(&file, &bytes, stream)?;+ let ch = samples.len() as u32;+ (Kind::Pcm { rate, samples }, rate, ch, "Vorbis")+ }+ };+ let frames = match &kind {+ Kind::Opus { timing, .. } => timing.total,+ Kind::Pcm { samples, .. } => samples.first().map_or(0, Vec::len) as i64,+ };+ let info = MediaInfo {+ name: name.to_string(),+ kind: MediaKind::AudioOnly,+ duration: Tick::from_units(frames, rate as i64),+ video: None,+ audio: Some(AudioStreamInfo { sample_rate: rate, channels: channels.max(1), codec: codec.into(), bits_per_sample: None }),+ container: "Ogg".into(),+ start_timecode: None,+ file_size: Some(bytes.0.len()),+ };+ Ok(Self { info, bytes, file, stream, kind })+ }++ /// The demuxed file.+ pub fn file(&self) -> &OggFile {+ &self.file+ }++ fn opus_packet(&self, st: &mut OpusState, head: &filmcraft_opus::OpusHead, timing: &OpusTiming, i: usize) -> crate::Result<Arc<Vec<Vec<f32>>>> {+ if let Some(p) = st.packets.get(&i) {+ return Ok(p.clone());+ }+ let read = |k: usize| self.file.read_packet(&self.bytes, self.stream, k).map_err(|e| CodecError::Container(e.to_string()));+ if st.decoder.is_none() {+ st.decoder = Some(PacketDecoder::opus(head.clone())?);+ }+ // Non-sequential access: reset and decode the pre-roll (RFC 7845 §4.6; see OPUS_PRE_ROLL).+ if st.last_decoded.is_none_or(|l| l + 1 != i) {+ let d = st.decoder.as_mut().expect("decoder");+ d.reset();+ let from = timing.starts.partition_point(|&x| x <= timing.starts[i] - OPUS_PRE_ROLL as i64).saturating_sub(1);+ for j in from..i {+ if let Ok(prev) = read(j) {+ let _ = d.decode(&prev, 0);+ }+ }+ }+ let data = read(i)?;+ let r = st.decoder.as_mut().expect("decoder").decode(&data, 0);+ st.last_decoded = Some(i);+ let p = Arc::new(r.unwrap_or_default());+ st.packets.insert(i, p.clone());+ st.order.push(i);+ if st.order.len() > 2048 {+ let old = st.order.remove(0);+ st.packets.remove(&old);+ }+ Ok(p)+ }+}++/// Decode a Vorbis stream fully, aligned to its granule positions.+fn decode_vorbis(file: &OggFile, bytes: &crate::Src, s: usize) -> crate::Result<(u32, Vec<Vec<f32>>)> {+ use symphonia::core::codecs::CODEC_TYPE_VORBIS;+ let st = &file.streams[s];+ if st.headers.len() < 3 {+ return Err(CodecError::Decode("Vorbis: missing header packets".into()));+ }+ let vi = filmcraft_ogg::VorbisInfo::parse(&st.headers[0]).ok_or_else(|| CodecError::Decode("Vorbis: bad identification header".into()))?;+ let mut extra = st.headers[0].clone();+ extra.extend_from_slice(&st.headers[2]);+ let mut dec = PacketDecoder::new(CODEC_TYPE_VORBIS, vi.sample_rate, Some(extra))?;+ let ch = vi.channels.max(1) as usize;+ let mut out: Vec<Vec<f32>> = vec![Vec::new(); ch];+ let mut lead: Option<i64> = None;+ for (i, p) in st.packets.iter().enumerate() {+ let data = file.read_packet(bytes, s, i).map_err(|e| CodecError::Container(e.to_string()))?;+ if let Ok(pcm) = dec.decode(&data, 0) {+ for (c, o) in out.iter_mut().enumerate() {+ if let Some(src) = pcm.get(c) {+ o.extend_from_slice(src);+ }+ }+ }+ if lead.is_none()+ && let Some(g) = p.granule+ {+ // samples decoded through the first granule page beyond its granule precede time 0+ lead = Some((out[0].len() as i64 - g).max(0));+ }+ }+ let lead = lead.unwrap_or(0) as usize;+ for o in &mut out {+ o.drain(..lead.min(o.len()));+ }+ if st.saw_eos+ && let Some(g) = st.last_granule+ {+ for o in &mut out {+ o.truncate(g.max(0) as usize);+ }+ }+ Ok((vi.sample_rate, out))+}++impl MediaSource for OggSource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }++ fn video_frame(&self, _req: FrameRequest) -> Result<Arc<VideoFrame>, MediaError> {+ Err(MediaError::NoStream("video"))+ }++ fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer, MediaError> {+ let (head, timing, state) = match &self.kind {+ Kind::Pcm { rate, samples } => return Ok(read_resampled(samples, *rate, start, frames, sample_rate)),+ Kind::Opus { head, timing, state } => (head, timing, state),+ };+ let ch = head.channels.max(1);+ let ratio = OPUS_RATE as f64 / sample_rate as f64;+ let exact = sample_rate == OPUS_RATE;+ let s0 = if exact { start } else { (start as f64 * ratio).floor() as i64 };+ let need = if exact { frames as i64 } else { (frames as f64 * ratio).ceil() as i64 + 2 };+ let mut src: Vec<Vec<f32>> = vec![vec![0.0; need.max(0) as usize]; ch];+ let mut st = state.lock().unwrap_or_else(|e| e.into_inner());+ let n = timing.starts.len();+ let mut i = timing.starts.partition_point(|&x| x <= s0.max(0)).saturating_sub(1);+ while i < n {+ let pk_start = timing.starts[i];+ if pk_start >= s0 + need || pk_start >= timing.total {+ break;+ }+ let pk = self.opus_packet(&mut st, head, timing, i)?;+ for (c, dst) in src.iter_mut().enumerate() {+ let Some(chan) = pk.get(c.min(pk.len().saturating_sub(1))) else { continue };+ for (k, v) in chan.iter().enumerate() {+ let pos = pk_start + k as i64;+ // before 0: pre-skip; at or after total: end trimming+ if pos < 0 || pos >= timing.total {+ continue;+ }+ let at = pos - s0;+ if at >= 0 && (at as usize) < dst.len() {+ dst[at as usize] = *v;+ }+ }+ }+ i += 1;+ }+ drop(st);+ let mut out = AudioBuffer::silence(sample_rate, ch, frames);+ if exact {+ out.channels = src;+ return Ok(out);+ }+ let frac = s0 as f64 - start as f64 * ratio;+ for k in 0..frames {+ let pos = k as f64 * ratio - frac;+ let i0 = pos.floor().max(0.0) as usize;+ let f = (pos - i0 as f64) as f32;+ for c in 0..ch {+ let a = src[c].get(i0).copied().unwrap_or(0.0);+ let b = src[c].get(i0 + 1).copied().unwrap_or(a);+ out.channels[c][k] = a + (b - a) * f;+ }+ }+ Ok(out)+ }+}++/// Ogg Opus / Vorbis; other Ogg codecs (FLAC) fall through to the bootstrap audio opener.+fn handles(head: &[u8]) -> bool {+ sniff(head) && (head.windows(8).any(|w| w == b"OpusHead") || head.windows(7).any(|w| w == b"\x01vorbis"))+}++pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, MediaError>> {+ if !handles(&bytes[..bytes.len().min(4096)]) {+ return None;+ }+ Some(OggSource::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))+}++/// [`filmcraft_media::ReaderOpener`] for Ogg Opus / Vorbis.+pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {+ if !handles(&head[..head.len().min(4096)]) {+ return None;+ }+ Some(OggSource::open_reader(name, reader.clone()).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))+}diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rsindex 39b479783..be39c6adb 100644--- a/crates/codecs/src/video.rs+++ b/crates/codecs/src/video.rs@@ -71,6 +71,21 @@ pub fn h264_disposable(sample: &[u8], length_size: usize) -> bool {slices > 0}+/// [`h264_disposable`] for an Annex B (start-code) sample.+pub fn h264_disposable_annexb(sample: &[u8]) -> bool {+ let mut slices = 0;+ for n in filmcraft_bitstream::annexb_nals(sample) {+ let Some(&h) = n.first() else { continue };+ if (1..=5).contains(&(h & 0x1f)) {+ if h & 0x60 != 0 {+ return false;+ }+ slices += 1;+ }+ }+ slices > 0+}+/// HEVC (7.4.2.2): every VCL NAL unit is a sub-layer non-reference picture (TRAIL_N, TSA_N,/// STSA_N, RADL_N, RASL_N, RSV_VCL_N10/12/14) of the highest temporal sub-layer, so no picture/// references it. `highest_tid` = numTemporalLayers - 1 from the hvcC (None: unknown).@@ -148,6 +163,10 @@ impl H264Decoder {let length_size = avcc.get(4).map_or(4, |b| (b & 3) as usize + 1);Ok(Self { avcc, dec, length_size })}+ /// A decoder for Annex B byte-stream samples (start codes, in-band parameter sets: MXF, TS).+ pub fn annexb() -> Self {+ Self { avcc: Vec::new(), dec: filmcraft_h264::Decoder::new(), length_size: 0 }+ }fn convert(p: filmcraft_h264::Picture) -> DecodedFrame {use std::sync::Arc;let (w, h) = (p.width as usize, p.height as usize);@@ -187,7 +206,9 @@ impl VideoDecoder for H264Decoder {self.dec.flush().into_iter().map(Self::convert).collect()}fn reset(&mut self) {- if let Ok(d) = filmcraft_h264::Decoder::from_avcc(&self.avcc) {+ if self.avcc.is_empty() {+ self.dec = filmcraft_h264::Decoder::new();+ } else if let Ok(d) = filmcraft_h264::Decoder::from_avcc(&self.avcc) {self.dec = d;}}@@ -195,8 +216,15 @@ impl VideoDecoder for H264Decoder {"FilmCraft H.264"}fn is_disposable(&self, sample: &[u8]) -> bool {+ if self.length_size == 0 {+ return h264_disposable_annexb(sample);+ }h264_disposable(sample, self.length_size)}+ fn is_random_access(&self, sample: &[u8]) -> Option<bool> {+ // Annex B samples carry their parameter sets: an IDR access unit is a starting point.+ (self.length_size == 0).then(|| filmcraft_bitstream::annexb_nals(sample).iter().any(|n| n.first().is_some_and(|h| h & 0x1f == 5)))+ }}pub fn h264_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {diff --git a/crates/codecs/tests/common/mod.rs b/crates/codecs/tests/common/mod.rsnew file mode 100644index 000000000..9a4bbbd2b--- /dev/null+++ b/crates/codecs/tests/common/mod.rs@@ -0,0 +1,94 @@+//! Shared helpers for the codecs oracle tests (MXF, Ogg). ffmpeg/ffprobe are external fixture+//! generators and oracles only (never linked).+#![allow(dead_code)]++use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::sync::Arc;++use filmcraft_frame::{PixelData, VideoFrame};++pub fn dir() -> PathBuf {+ filmcraft_testkit::fixtures_dir("codecs")+}++/// Generate `name` with `ffmpeg -y -v error <args> <out>` (cached).+pub fn fixture(ff: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {+ let out = dir().join(name);+ filmcraft_testkit::fixtures::generate(&out, |tmp| {+ let st = Command::new(ff).args(["-y", "-v", "error"]).args(args).arg(tmp).stdin(Stdio::null()).status();+ match st {+ Ok(s) if s.success() => true,+ other => {+ eprintln!("fixture {name}: ffmpeg failed: {other:?}");+ false+ }+ }+ })+}++pub fn bytes(p: &Path) -> Arc<[u8]> {+ std::fs::read(p).unwrap().into()+}++/// Run ffmpeg and capture stdout.+pub fn ffmpeg_out(ff: &Path, args: &[&str]) -> Vec<u8> {+ let o = Command::new(ff).args(["-v", "error"]).args(args).stdin(Stdio::null()).output().expect("run ffmpeg");+ assert!(o.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&o.stderr));+ o.stdout+}++/// Decoded frames of the first video stream as raw planes in `pix_fmt`.+pub fn ffmpeg_frames(ff: &Path, file: &Path, pix_fmt: &str) -> Vec<u8> {+ ffmpeg_out(ff, &["-i", file.to_str().unwrap(), "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])+}++/// Interleaved f32 samples of the first audio stream (all channels).+pub fn ffmpeg_audio_f32(ff: &Path, file: &Path, extra: &[&str]) -> Vec<f32> {+ let mut args = vec!["-i", file.to_str().unwrap()];+ args.extend_from_slice(extra);+ args.extend_from_slice(&["-map", "0:a:0", "-f", "f32le", "-"]);+ ffmpeg_out(ff, &args).chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()+}++/// Our frame's three planes widened to u16 (and their sizes).+pub fn planes(f: &VideoFrame) -> Vec<Vec<u16>> {+ match &f.data {+ PixelData::Yuv8 { planes, .. } => planes.iter().map(|p| p.iter().map(|&v| v as u16).collect()).collect(),+ PixelData::Yuv16 { planes, .. } => planes.iter().map(|p| p.to_vec()).collect(),+ _ => panic!("expected a YUV frame"),+ }+}++/// Split one raw frame of `ffmpeg_frames` into planes (`bps` bytes per sample, chroma `cw`×`ch`).+pub fn raw_planes(raw: &[u8], w: usize, h: usize, cw: usize, ch: usize, bps: usize) -> Vec<Vec<u16>> {+ let get = |b: &[u8]| -> Vec<u16> {+ if bps == 1 { b.iter().map(|&v| v as u16).collect() } else { b.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect() }+ };+ let y = w * h * bps;+ let c = cw * ch * bps;+ vec![get(&raw[..y]), get(&raw[y..y + c]), get(&raw[y + c..y + 2 * c])]+}++/// Largest absolute difference between plane sets.+pub fn max_diff(a: &[Vec<u16>], b: &[Vec<u16>]) -> u16 {+ a.iter()+ .zip(b)+ .map(|(x, y)| {+ assert_eq!(x.len(), y.len(), "plane size");+ x.iter().zip(y).map(|(p, q)| p.abs_diff(*q)).max().unwrap_or(0)+ })+ .max()+ .unwrap_or(0)+}++/// Deterministic pseudo-random numbers (xorshift).+pub struct Rng(pub u64);+impl Rng {+ pub fn below(&mut self, n: u64) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0 % n.max(1)+ }+}diff --git a/crates/codecs/tests/media_oracle.rs b/crates/codecs/tests/media_oracle.rsnew file mode 100644index 000000000..76f058457--- /dev/null+++ b/crates/codecs/tests/media_oracle.rs@@ -0,0 +1,149 @@+//! Image sequences and Broadcast WAV against ffmpeg: ffmpeg writes numbered stills (PNG, JPEG,+//! TIFF, BMP, WebP when available) and BWF files; the sequence frames must equal ffmpeg's decode of+//! the same image2 sequence (lossless formats exactly, JPEG within a few levels), and the BWF+//! TimeReference must give the start timecode.++mod common;++use std::path::Path;+use std::sync::Arc;++use common::*;+use filmcraft_media::sequence::{FrameLoader, ImageSequenceSource, Numbered, sequence_frames};+use filmcraft_media::{FrameRequest, MediaKind, MediaSource};+use filmcraft_time::FrameRate;++fn make_sequence(ff: &Path, ext: &str, codec_args: &[&str]) -> Option<std::path::PathBuf> {+ let d = dir().join(format!("seq_{ext}"));+ let first = d.join(format!("img_0001.{ext}"));+ if first.exists() && d.join(format!("img_0012.{ext}")).exists() {+ return Some(d);+ }+ let _ = std::fs::create_dir_all(&d);+ let pattern = d.join(format!("img_%04d.{ext}"));+ let mut args = vec!["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=96x64:rate=25", "-frames:v", "12"];+ args.extend_from_slice(codec_args);+ args.extend_from_slice(&["-f", "image2"]);+ let st = std::process::Command::new(ff).args(&args).arg(&pattern).status().ok()?;+ st.success().then_some(d)+}++fn loader() -> FrameLoader {+ Arc::new(|p: &str| std::fs::read(p))+}++fn open_sequence(d: &Path, ext: &str) -> ImageSequenceSource {+ let first = d.join(format!("img_0001.{ext}")).to_string_lossy().to_string();+ let n = Numbered::parse(&first).unwrap();+ let names: Vec<String> = std::fs::read_dir(d).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect();+ ImageSequenceSource::new("img_0001", sequence_frames(&n, &names), FrameRate::FPS_25, loader()).unwrap()+}++fn rgba(f: &filmcraft_frame::VideoFrame) -> Vec<u8> {+ match &f.data {+ filmcraft_frame::PixelData::Rgba8(p) => p.to_vec(),+ _ => panic!("still frames are RGBA"),+ }+}++fn check(ff: &Path, ext: &str, codec_args: &[&str], tol: u8) {+ let Some(d) = make_sequence(ff, ext, codec_args) else {+ eprintln!("SKIPPED: ffmpeg cannot write {ext} stills");+ return;+ };+ let src = open_sequence(&d, ext);+ assert_eq!(src.info().kind, MediaKind::ImageSequence);+ assert_eq!(src.frame_count(), 12);+ assert_eq!(src.info().duration, FrameRate::FPS_25.tick_of(12));+ let pattern = d.join(format!("img_%04d.{ext}"));+ let raw = ffmpeg_out(ff, &["-f", "image2", "-start_number", "1", "-i", pattern.to_str().unwrap(), "-f", "rawvideo", "-pix_fmt", "rgba", "-"]);+ let fsize = 96 * 64 * 4;+ assert_eq!(raw.len() / fsize, 12);+ let mut rng = Rng(5);+ let mut worst = 0u8;+ // in order, then random access+ let order: Vec<usize> = (0..12).chain((0..12).map(|_| rng.below(12) as usize)).collect();+ for i in order {+ let f = src.video_frame(FrameRequest::full(FrameRate::FPS_25.tick_of(i as i64))).unwrap();+ let ours = rgba(&f);+ let want = &raw[i * fsize..(i + 1) * fsize];+ let d = ours.iter().zip(want).map(|(a, b)| a.abs_diff(*b)).max().unwrap();+ worst = worst.max(d);+ assert!(d <= tol, "{ext}: frame {i} differs by {d}");+ }+ eprintln!("{ext} sequence: 12 frames, max diff {worst}");+}++#[test]+fn png_sequence_exact() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ check(&ff, "png", &[], 0);+}++#[test]+fn tiff_and_bmp_sequences_exact() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ check(&ff, "tif", &["-pix_fmt", "rgb24"], 0);+ check(&ff, "bmp", &[], 0);+}++#[test]+fn jpeg_sequence_close() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ // different IDCT and chroma upsampling than ffmpeg's: a few levels+ check(&ff, "jpg", &["-q:v", "2", "-pix_fmt", "yuvj444p"], 12);+}++#[test]+fn webp_sequence_lossless() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ check(&ff, "webp", &["-c:v", "libwebp", "-lossless", "1"], 0);+}++#[test]+fn missing_frames_hold_the_previous_frame() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let Some(d) = make_sequence(&ff, "png", &[]) else { return };+ // a copy without frames 5 and 6+ let gap = dir().join("seq_png_gap");+ let _ = std::fs::create_dir_all(&gap);+ for n in (1..=12).filter(|n| *n != 5 && *n != 6) {+ let name = format!("img_{n:04}.png");+ std::fs::copy(d.join(&name), gap.join(&name)).unwrap();+ }+ let _ = std::fs::remove_file(gap.join("img_0005.png"));+ let _ = std::fs::remove_file(gap.join("img_0006.png"));+ let src = open_sequence(&gap, "png");+ assert_eq!(src.missing_frames(), vec![4, 5]);+ let at = |i: i64| rgba(&src.video_frame(FrameRequest::full(FrameRate::FPS_25.tick_of(i))).unwrap());+ assert_eq!(at(4), at(3));+ assert_eq!(at(5), at(3));+ assert_ne!(at(6), at(3));+}++#[test]+fn broadcast_wav_time_reference() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ // 01:00:00:00 at 23.976: 86 400 frames × 2002 samples+ let tr = (86_400u64 * 2002).to_string();+ let meta = format!("time_reference={tr}");+ let Some(f) = fixture(+ &ff,+ "bwf_1h.wav",+ &["-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000", "-t", "0.5", "-c:a", "pcm_s24le", "-write_bext", "1", "-metadata", &meta],+ ) else {+ panic!("could not write BWF")+ };+ let src = filmcraft_codecs::open_bytes("bwf_1h.wav", bytes(&f)).unwrap();+ assert_eq!(src.info().container, "Broadcast WAV");+ assert_eq!(src.info().start_timecode, Some(86_400));+ // ffprobe agrees on the time reference+ if let Some(fp) = filmcraft_testkit::ffprobe() {+ let o = std::process::Command::new(fp).args(["-v", "error", "-show_entries", "format_tags=time_reference", "-of", "csv=p=0"]).arg(&f).output().unwrap();+ assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), tr);+ }+ // samples are exact+ let want = ffmpeg_audio_f32(&ff, &f, &[]);+ let got = src.audio(0, want.len(), 48_000).unwrap();+ assert_eq!(got.channels[0], want);+}diff --git a/crates/codecs/tests/mxf_oracle.rs b/crates/codecs/tests/mxf_oracle.rsnew file mode 100644index 000000000..5ba655237--- /dev/null+++ b/crates/codecs/tests/mxf_oracle.rs@@ -0,0 +1,348 @@+//! MXF against ffmpeg: ffmpeg writes the files (OP1a, OP-Atom, D-10) and decodes them as the+//! oracle. Our decode must match frame for frame (H.264 bit-exact, VC-3 ±2, ProRes ±1 LSB), seek+//! to random frames exactly, and give sample-exact PCM.++mod common;++use std::path::{Path, PathBuf};++use common::*;+use filmcraft_codecs::MxfSource;+use filmcraft_media::{FrameRequest, MediaError, MediaKind, MediaSource};+use filmcraft_time::FrameRate;++const V25: &[&str] = &["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25"];+const TONE: &[&str] = &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000"];+const NOISE: &[&str] = &["-f", "lavfi", "-i", "anoisesrc=color=pink:sample_rate=48000:amplitude=0.5:seed=7"];++fn spec(name: &str) -> Vec<String> {+ let cat = |p: &[&[&str]]| p.concat().into_iter().map(String::from).collect::<Vec<_>>();+ match name {+ // long-GOP H.264 with B pictures (ffmpeg writes no temporal offsets: order from the POCs)+ "mxf_h264_bf2.mxf" => cat(&[+ V25,+ NOISE,+ &["-t", "2", "-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "pcm_s16le", "-ac", "2", "-timecode", "01:00:00:00"],+ ]),+ "mxf_h264_2997df.mxf" => cat(&[+ &["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=30000/1001"],+ NOISE,+ &["-t", "1", "-c:v", "libx264", "-bf", "0", "-g", "10", "-pix_fmt", "yuv420p", "-c:a", "pcm_s24le", "-ac", "2", "-timecode", "01:00:00;00"],+ ]),+ "mxf_dnxhr_lb.mxf" => {+ cat(&[V25, TONE, &["-t", "1", "-c:v", "dnxhd", "-profile:v", "dnxhr_lb", "-pix_fmt", "yuv422p", "-c:a", "pcm_s24le", "-ac", "2"]])+ }+ "mxf_prores.mxf" => cat(&[V25, TONE, &["-t", "1", "-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le", "-c:a", "pcm_s16le"]]),+ "mxf_mpeg2.mxf" => cat(&[V25, NOISE, &["-t", "1", "-c:v", "mpeg2video", "-bf", "2", "-c:a", "pcm_s16le"]]),+ "mxf_atom_dnxhr.mxf" => cat(&[V25, &["-t", "1", "-c:v", "dnxhd", "-profile:v", "dnxhr_lb", "-pix_fmt", "yuv422p", "-f", "mxf_opatom"]]),+ "mxf_atom_pcm.mxf" => cat(&[NOISE, &["-t", "1", "-c:a", "pcm_s24le", "-ac", "1", "-f", "mxf_opatom"]]),+ "mxf_d10.mxf" => cat(&[+ &["-f", "lavfi", "-i", "testsrc2=size=720x608:rate=25"],+ NOISE,+ &[+ "-t",+ "0.4",+ "-c:v",+ "mpeg2video",+ "-pix_fmt",+ "yuv422p",+ "-minrate",+ "30M",+ "-maxrate",+ "30M",+ "-b:v",+ "30M",+ "-bufsize",+ "1200000",+ "-rc_init_occupancy",+ "1200000",+ "-intra_vlc",+ "1",+ "-non_linear_quant",+ "1",+ "-g",+ "1",+ "-flags",+ "+ildct+low_delay",+ "-dc",+ "10",+ "-ps",+ "1",+ "-qmin",+ "1",+ "-qmax",+ "3",+ "-c:a",+ "pcm_s16le",+ "-ac",+ "4",+ "-f",+ "mxf_d10",+ ],+ ]),+ other => panic!("unknown fixture {other}"),+ }+}++pub const ALL: &[&str] = &[+ "mxf_h264_bf2.mxf",+ "mxf_h264_2997df.mxf",+ "mxf_dnxhr_lb.mxf",+ "mxf_prores.mxf",+ "mxf_mpeg2.mxf",+ "mxf_atom_dnxhr.mxf",+ "mxf_atom_pcm.mxf",+ "mxf_d10.mxf",+];++fn make(ff: &Path, name: &str) -> PathBuf {+ let args = spec(name);+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();+ fixture(ff, name, &refs).unwrap_or_else(|| panic!("could not generate {name}"))+}++fn open(p: &Path) -> MxfSource {+ MxfSource::open(p.file_name().unwrap().to_str().unwrap(), bytes(p)).unwrap()+}++/// Number of video packets ffprobe lists.+fn ffprobe_video_packets(file: &Path) -> Option<usize> {+ let fp = filmcraft_testkit::ffprobe()?;+ let o = std::process::Command::new(fp)+ .args(["-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0"])+ .arg(file)+ .output()+ .ok()?;+ String::from_utf8_lossy(&o.stdout).trim().parse().ok()+}++/// Every frame in order, then `seeks` random frames, against ffmpeg's decode (within `tol`).+fn check_video(ff: &Path, file: &Path, pix_fmt: &str, chroma: (usize, usize), bps: usize, tol: u16, seeks: usize) {+ let src = open(file);+ let v = src.info().video.clone().unwrap();+ let (w, h) = (v.width as usize, v.height as usize);+ let (cw, ch) = (w / chroma.0, h / chroma.1);+ let raw = ffmpeg_frames(ff, file, pix_fmt);+ let fsize = (w * h + 2 * cw * ch) * bps;+ let n = raw.len() / fsize;+ let rate = v.frame_rate;+ assert_eq!(src.info().duration, rate.tick_of(n as i64), "{}: duration = ffmpeg's frame count {n}", file.display());+ if let Some(p) = ffprobe_video_packets(file) {+ assert_eq!(p, n, "packets = frames");+ }+ let frame = |i: usize| raw_planes(&raw[i * fsize..(i + 1) * fsize], w, h, cw, ch, bps);+ let mut worst = 0;+ for i in 0..n {+ let f = src.video_frame(FrameRequest::full(rate.tick_of(i as i64))).unwrap();+ let d = max_diff(&planes(&f), &frame(i));+ worst = worst.max(d);+ assert!(d <= tol, "{}: frame {i} differs by {d}", file.display());+ }+ // random access on a fresh source (no warm cache), out of order+ let src = open(file);+ let mut rng = Rng(0x9E37_79B9_7F4A_7C15);+ for _ in 0..seeks {+ let i = rng.below(n as u64) as usize;+ let f = src.video_frame(FrameRequest::full(rate.tick_of(i as i64))).unwrap();+ let d = max_diff(&planes(&f), &frame(i));+ assert!(d <= tol, "{}: seek to frame {i} differs by {d}", file.display());+ }+ eprintln!("{}: {n} frames, max diff {worst}", file.display());+}++/// Our audio, as interleaved f32, equals ffmpeg's decode exactly.+fn check_audio_exact(ff: &Path, file: &Path, extra: &[&str]) {+ let src = open(file);+ let a = src.info().audio.clone().unwrap();+ let ch = a.channels as usize;+ let want = ffmpeg_audio_f32(ff, file, extra);+ let n = want.len() / ch;+ assert!(n > 0);+ let got = src.audio(0, n, a.sample_rate).unwrap();+ for i in 0..n {+ for c in 0..ch {+ assert_eq!(got.channels[c][i], want[i * ch + c], "{}: sample {i} channel {c}", file.display());+ }+ }+ // random windows (sample-exact seeking)+ let mut rng = Rng(77);+ for _ in 0..20 {+ let s = rng.below(n as u64 - 100) as usize;+ let len = 1 + rng.below(3000) as usize;+ let got = src.audio(s as i64, len, a.sample_rate).unwrap();+ for k in 0..len.min(n - s) {+ for c in 0..ch {+ assert_eq!(got.channels[c][k], want[(s + k) * ch + c], "window at {s}+{k}");+ }+ }+ }+ eprintln!("{}: {n} sample frames × {ch} channels exact", file.display());+}++#[test]+fn h264_long_gop_with_b_frames_bit_exact() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "mxf_h264_bf2.mxf");+ let src = open(&f);+ let info = src.info();+ assert_eq!(info.container, "MXF OP1a");+ assert_eq!(info.kind, MediaKind::Movie);+ let v = info.video.as_ref().unwrap();+ assert_eq!((v.width, v.height, v.frame_rate), (320, 240, FrameRate::FPS_25));+ assert_eq!(v.codec, "H.264");+ assert_eq!(info.start_timecode, Some(90_000), "01:00:00:00 at 25 fps");+ assert_eq!(src.file().timecode.unwrap().format(), "01:00:00:00");+ let t = &src.file().tracks[src.file().track_of_kind(filmcraft_mxf::TrackKind::Picture).unwrap()];+ assert!(t.needs_reorder && !t.temporal_offsets, "ffmpeg marks B pictures without temporal offsets");+ assert_eq!(t.samples.iter().filter(|s| s.key).count(), 5, "an IDR every 12 frames over 50");+ check_video(&ff, &f, "yuv420p", (2, 2), 1, 0, 25);+ check_audio_exact(&ff, &f, &[]);+}++#[test]+fn h264_2997_drop_frame_timecode_and_24_bit_audio() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "mxf_h264_2997df.mxf");+ let src = open(&f);+ let info = src.info();+ assert_eq!(info.video.as_ref().unwrap().frame_rate, FrameRate::FPS_29_97);+ let tc = src.file().timecode.unwrap();+ assert!(tc.drop_frame);+ assert_eq!(tc.format(), "01:00:00;00");+ assert_eq!(info.start_timecode, Some(107_892));+ assert_eq!(info.audio.as_ref().unwrap().bits_per_sample, Some(24));+ check_video(&ff, &f, "yuv420p", (2, 2), 1, 0, 10);+ check_audio_exact(&ff, &f, &[]);+}++#[test]+fn dnxhr_op1a_within_two_lsb() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "mxf_dnxhr_lb.mxf");+ let src = open(&f);+ assert_eq!(src.info().video.as_ref().unwrap().codec, "DNxHR LB");+ check_video(&ff, &f, "yuv422p", (2, 1), 1, 2, 10);+ check_audio_exact(&ff, &f, &[]);+}++#[test]+fn prores_op1a_within_one_lsb() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "mxf_prores.mxf");+ let src = open(&f);+ assert!(src.info().video.as_ref().unwrap().codec.starts_with("Apple ProRes 422"), "{}", src.info().video.as_ref().unwrap().codec);+ check_video(&ff, &f, "yuv422p10le", (2, 1), 2, 1, 10);+ check_audio_exact(&ff, &f, &[]);+}++#[test]+fn mpeg2_is_reported_unsupported_but_audio_plays() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "mxf_mpeg2.mxf");+ let src = open(&f);+ let v = src.info().video.as_ref().unwrap();+ assert!(v.codec.contains("MPEG-2") && v.codec.contains("unsupported"), "{}", v.codec);+ match src.video_frame(FrameRequest::full(filmcraft_time::Tick::ZERO)) {+ Err(MediaError::Unsupported(why)) => assert!(why.contains("MPEG-2"), "{why}"),+ other => panic!("expected unsupported, got {:?}", other.map(|_| ())),+ }+ // temporal offsets: ffmpeg's MPEG-2 index carries them+ let t = &src.file().tracks[src.file().track_of_kind(filmcraft_mxf::TrackKind::Picture).unwrap()];+ assert!(t.temporal_offsets);+ check_audio_exact(&ff, &f, &[]);+}++#[test]+fn op_atom_video_and_audio_files() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let v = make(&ff, "mxf_atom_dnxhr.mxf");+ let src = open(&v);+ assert_eq!(src.info().container, "MXF OP-Atom");+ assert!(src.info().audio.is_none());+ assert_eq!(src.file().tracks[0].wrapping, filmcraft_mxf::Wrapping::Clip);+ check_video(&ff, &v, "yuv422p", (2, 1), 1, 2, 10);+ let a = make(&ff, "mxf_atom_pcm.mxf");+ let src = open(&a);+ assert_eq!(src.info().kind, MediaKind::AudioOnly);+ assert_eq!(src.info().container, "MXF OP-Atom");+ let ai = src.info().audio.clone().unwrap();+ assert_eq!((ai.sample_rate, ai.channels, ai.bits_per_sample), (48_000, 1, Some(24)));+ assert_eq!(src.info().duration, filmcraft_time::Tick::from_units(48_000, 48_000));+ check_audio_exact(&ff, &a, &[]);+}++#[test]+fn d10_aes3_elements_sample_exact() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "mxf_d10.mxf");+ let src = open(&f);+ let a = src.info().audio.clone().unwrap();+ assert_eq!(a.codec, "AES3 PCM");+ assert!(a.channels >= 4, "{}", a.channels);+ assert!(src.info().video.as_ref().unwrap().codec.contains("MPEG-2"));+ // ffmpeg presents D-10 sound as one multichannel stream too+ check_audio_exact(&ff, &f, &[]);+}++#[test]+fn truncated_and_corrupt_files_never_panic() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ for name in ["mxf_h264_bf2.mxf", "mxf_atom_pcm.mxf", "mxf_prores.mxf"] {+ let f = make(&ff, name);+ let full = std::fs::read(&f).unwrap();+ let mut rng = Rng(0xDEAD_BEEF);+ for k in 1..=16 {+ let cut = full.len() * k / 17;+ let part: std::sync::Arc<[u8]> = full[..cut].to_vec().into();+ if let Ok(s) = MxfSource::open(name, part) {+ let info = s.info().clone();+ if let Some(v) = &info.video {+ for _ in 0..4 {+ let t = v.frame_rate.tick_of(rng.below(60) as i64);+ let _ = s.video_frame(FrameRequest::full(t));+ }+ }+ if let Some(a) = &info.audio {+ let _ = s.audio(rng.below(96_000) as i64, 4000, a.sample_rate);+ }+ }+ }+ for _ in 0..30 {+ let mut g = full.clone();+ for _ in 0..8 {+ let at = rng.below(g.len() as u64) as usize;+ g[at] = rng.below(256) as u8;+ }+ if let Ok(s) = MxfSource::open(name, g.into()) {+ if s.info().video.is_some() {+ for i in [0, 7, 30] {+ let _ = s.video_frame(FrameRequest::full(s.info().frame_rate().tick_of(i)));+ }+ }+ if s.info().audio.is_some() {+ let _ = s.audio(0, 9600, 48_000);+ }+ }+ }+ }+}++/// `cargo xtask fixtures codecs`: build every MXF fixture.+#[test]+#[ignore]+fn generate_fixtures() {+ let Some(ff) = filmcraft_testkit::ffmpeg() else {+ for n in ALL {+ filmcraft_testkit::fixtures::report(n, filmcraft_testkit::fixtures::Status::Skipped);+ }+ return;+ };+ for n in ALL {+ let out = dir().join(n);+ filmcraft_testkit::fixtures::generate_and_report(n, std::slice::from_ref(&out), || {+ let args = spec(n);+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();+ fixture(&ff, n, &refs)+ });+ }+}diff --git a/crates/codecs/tests/ogg_oracle.rs b/crates/codecs/tests/ogg_oracle.rsnew file mode 100644index 000000000..48a30e919--- /dev/null+++ b/crates/codecs/tests/ogg_oracle.rs@@ -0,0 +1,226 @@+//! Ogg Opus / Vorbis against ffmpeg: ffmpeg (libopus, its Vorbis encoder) writes the files and+//! decodes them as the oracle. Length must match exactly (pre-skip and end trimming), the signal+//! must match (libopus: SNR ≥ 50 dB on CELT music, ≥ 10 dB on SILK/hybrid speech, as in+//! `filmcraft-opus`'s own oracle; Vorbis: SNR ≥ 60 dB), and any random window must equal the+//! continuous decode (granule-position seeking with pre-roll).++mod common;++use std::path::{Path, PathBuf};++use common::*;+use filmcraft_codecs::OggSource;+use filmcraft_media::{MediaKind, MediaSource};++const MUSIC: &[&str] = &[+ "-f",+ "lavfi",+ "-i",+ "sine=frequency=440:sample_rate=48000",+ "-f",+ "lavfi",+ "-i",+ "anoisesrc=color=pink:sample_rate=48000:amplitude=0.2:seed=3",+ "-filter_complex",+ "[0:a][1:a]amerge=inputs=2[a]",+ "-map",+ "[a]",+];++fn spec(name: &str) -> Vec<&'static str> {+ match name {+ "ogg_opus_music.opus" => [MUSIC, &["-t", "3", "-c:a", "libopus", "-b:a", "160k", "-application", "audio"]].concat(),+ "ogg_opus_trim.ogg" => [MUSIC, &["-t", "1.2345", "-c:a", "libopus", "-b:a", "96k", "-frame_duration", "10"]].concat(),+ "ogg_opus_speech.opus" => {+ vec![+ "-f",+ "lavfi",+ "-i",+ "anoisesrc=color=brown:sample_rate=16000:amplitude=0.3:seed=5",+ "-t",+ "2",+ "-ac",+ "1",+ "-c:a",+ "libopus",+ "-b:a",+ "12k",+ "-application",+ "voip",+ ]+ }+ // the same signal on both channels: ffmpeg's experimental Vorbis encoder (stereo only)+ // codes an independent second channel so poorly (1.7 dB SNR against the source, with its+ // own decoder) that decoders legitimately disagree on it+ "ogg_vorbis.ogg" => vec![+ "-f",+ "lavfi",+ "-i",+ "aevalsrc=0.5*sin(2*PI*440*t)+0.2*sin(2*PI*1234*t)*sin(2*PI*3*t):s=44100",+ "-t",+ "2",+ "-ac",+ "2",+ "-c:a",+ "vorbis",+ "-strict",+ "-2",+ ],+ other => panic!("unknown fixture {other}"),+ }+}++const ALL: &[&str] = &["ogg_opus_music.opus", "ogg_opus_trim.ogg", "ogg_opus_speech.opus", "ogg_vorbis.ogg"];++fn make(ff: &Path, name: &str) -> PathBuf {+ fixture(ff, name, &spec(name)).unwrap_or_else(|| panic!("could not generate {name}"))+}++fn snr_db(reference: &[f32], ours: &[f32]) -> f64 {+ let (mut s, mut n) = (0f64, 0f64);+ for (r, o) in reference.iter().zip(ours) {+ s += (*r as f64).powi(2);+ n += (*r as f64 - *o as f64).powi(2);+ }+ if n == 0.0 { f64::INFINITY } else { 10.0 * (s / n).log10() }+}++/// (our continuous decode interleaved, ffmpeg's decode interleaved, channels, rate)+fn decode_both(ff: &Path, file: &Path, decoder: &[&str]) -> (OggSource, Vec<f32>, Vec<f32>, usize, u32) {+ let src = OggSource::open(file.file_name().unwrap().to_str().unwrap(), bytes(file)).unwrap();+ let a = src.info().audio.clone().unwrap();+ let ch = a.channels as usize;+ let mut args: Vec<&str> = decoder.to_vec();+ args.extend_from_slice(&["-i", file.to_str().unwrap(), "-map", "0:a:0", "-f", "f32le", "-"]);+ let want: Vec<f32> = ffmpeg_out(ff, &args).chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();+ let n = want.len() / ch;+ let frames = src.info().duration.to_units_floor(a.sample_rate as i64) as usize;+ assert_eq!(frames, n, "{}: our length = ffmpeg's ({} samples)", file.display(), n);+ let buf = src.audio(0, n, a.sample_rate).unwrap();+ let mut ours = Vec::with_capacity(n * ch);+ for i in 0..n {+ for c in 0..ch {+ ours.push(buf.channels[c][i]);+ }+ }+ (src, ours, want, ch, a.sample_rate)+}++/// Random windows on a fresh source equal the continuous decode.+fn check_seeks(file: &Path, ours: &[f32], ch: usize, rate: u32, tol: f32) {+ let src = OggSource::open("seek", bytes(file)).unwrap();+ let n = ours.len() / ch;+ let mut rng = Rng(0xA5A5_1234);+ let mut worst = 0f32;+ for _ in 0..25 {+ let s = rng.below(n as u64 - 10) as usize;+ let len = 1 + rng.below(4000) as usize;+ let got = src.audio(s as i64, len, rate).unwrap();+ for k in 0..len.min(n - s) {+ for c in 0..ch {+ worst = worst.max((got.channels[c][k] - ours[(s + k) * ch + c]).abs());+ }+ }+ }+ assert!(worst <= tol, "{}: seek differs from continuous decode by {worst}", file.display());+ eprintln!("{}: seeks within {worst:e} of the continuous decode", file.display());+}++#[test]+fn opus_celt_music_matches_libopus() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "ogg_opus_music.opus");+ let (src, ours, want, ch, rate) = decode_both(&ff, &f, &["-c:a", "libopus"]);+ assert_eq!(src.info().container, "Ogg");+ assert_eq!(src.info().kind, MediaKind::AudioOnly);+ assert_eq!((rate, ch), (48_000, 2));+ assert_eq!(src.info().audio.as_ref().unwrap().codec, "Opus");+ let snr = snr_db(&want, &ours);+ eprintln!("{}: {} samples, SNR {snr:.1} dB vs libopus", f.display(), want.len() / ch);+ assert!(snr >= 50.0, "SNR {snr:.1} dB");+ check_seeks(&f, &ours, ch, rate, 2e-3);+}++#[test]+fn opus_end_trimming_and_10ms_frames() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "ogg_opus_trim.ogg");+ let (src, ours, want, ch, rate) = decode_both(&ff, &f, &["-c:a", "libopus"]);+ // 1.2345 s is not a whole number of 10 ms packets: the last page's granule trims the end+ let t = filmcraft_ogg::OpusTiming::of(&src.file().streams[0], filmcraft_opus::OpusHead::parse(&src.file().streams[0].headers[0]).unwrap().pre_skip as u32);+ let decoded: i64 = t.durations.iter().map(|&d| d as i64).sum::<i64>() - t.pre_skip as i64;+ assert!(t.total < decoded, "end trimmed: {} < {}", t.total, decoded);+ assert_eq!(t.total, 59_256, "1.2345 s at 48 kHz");+ let snr = snr_db(&want, &ours);+ assert!(snr >= 50.0, "SNR {snr:.1} dB");+ check_seeks(&f, &ours, ch, rate, 2e-3);+}++#[test]+fn opus_silk_speech_matches_libopus() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "ogg_opus_speech.opus");+ let (_src, ours, want, ch, rate) = decode_both(&ff, &f, &["-c:a", "libopus"]);+ assert_eq!(ch, 1);+ let snr = snr_db(&want, &ours);+ eprintln!("{}: SNR {snr:.1} dB vs libopus", f.display());+ assert!(snr >= 10.0, "SNR {snr:.1} dB");+ check_seeks(&f, &ours, ch, rate, 2e-2);+}++#[test]+fn vorbis_matches_ffmpeg() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "ogg_vorbis.ogg");+ let (src, ours, want, ch, rate) = decode_both(&ff, &f, &[]);+ assert_eq!(src.info().audio.as_ref().unwrap().codec, "Vorbis");+ assert_eq!((rate, ch), (44_100, 2));+ let snr = snr_db(&want, &ours);+ eprintln!("{}: SNR {snr:.1} dB vs ffmpeg's Vorbis decoder", f.display());+ assert!(snr >= 60.0, "SNR {snr:.1} dB");+ check_seeks(&f, &ours, ch, rate, 0.0);+}++#[test]+fn opened_through_open_bytes_and_robust_to_damage() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let f = make(&ff, "ogg_opus_music.opus");+ let s = filmcraft_codecs::open_bytes("x.opus", bytes(&f)).unwrap();+ assert_eq!(s.info().container, "Ogg");+ let full = std::fs::read(&f).unwrap();+ let mut rng = Rng(42);+ for k in 1..12 {+ let cut = full.len() * k / 12;+ if let Ok(s) = OggSource::open("cut", full[..cut].to_vec().into()) {+ let n = s.info().duration.to_units_floor(48_000);+ let _ = s.audio(rng.below(n.max(1) as u64) as i64, 5000, 48_000).unwrap();+ }+ }+ for _ in 0..40 {+ let mut g = full.clone();+ for _ in 0..6 {+ let at = rng.below(g.len() as u64) as usize;+ g[at] = rng.below(256) as u8;+ }+ if let Ok(s) = OggSource::open("bad", g.into()) {+ let _ = s.audio(0, 48_000, 48_000);+ let _ = s.audio(30_000, 4_000, 44_100);+ }+ }+}++/// `cargo xtask fixtures codecs`: build every Ogg fixture.+#[test]+#[ignore]+fn generate_fixtures() {+ let Some(ff) = filmcraft_testkit::ffmpeg() else {+ for n in ALL {+ filmcraft_testkit::fixtures::report(n, filmcraft_testkit::fixtures::Status::Skipped);+ }+ return;+ };+ for n in ALL {+ let out = dir().join(n);+ filmcraft_testkit::fixtures::generate_and_report(n, std::slice::from_ref(&out), || fixture(&ff, n, &spec(n)));+ }+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 83d5f2091..860b2902c 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -243,6 +243,25 @@ pub fn import_streamed(s: &mut Session, path: &str, bin: Option<filmcraft_projecimport_source(s, path, name, src, identity, bin)}+/// Import the image sequence that the numbered still `path` starts (File ▸ Import with Image+/// Sequence): one movie item at Settings ▸ Media ▸ Indeterminate Media Timebase. Returns the item,+/// the frame count and the missing frame numbers (relative to the first).+pub fn import_image_sequence(s: &mut Session, path: &str, bin: Option<filmcraft_project::BinId>) -> Result<(ItemId, usize, Vec<usize>)> {+ let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ let rate = crate::settings::timebase_rate(&s.prefs.media.indeterminate_timebase);+ let frames = crate::media_pool::image_sequence_frames(path, &*s.services)?;+ let missing: Vec<usize> = frames.iter().enumerate().filter(|(_, f)| f.is_none()).map(|(i, _)| i).collect();+ let src = crate::media_pool::open_image_sequence(path, &*s.services, rate, &name)?;+ let identity = crate::relink::identity_of(&*s.services, path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let id = import_source(s, path, name, src, identity, bin)?;+ Ok((id, frames.len(), missing))+}++/// Settings ▸ Media ▸ Import image sequences: a single numbered still with later frames beside it.+fn detect_image_sequence(s: &Session, path: &str) -> bool {+ filmcraft_media::sequence::Numbered::parse(path).is_some() && crate::media_pool::image_sequence_frames(path, &*s.services).is_ok_and(|f| f.len() > 1)+}+fn import_source(s: &mut Session,path: &str,@@ -593,7 +612,7 @@ fn build() -> Vec<CommandSpec> {Ok(json!({"items": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))}),- cmd!("file.import", "Import…", ["File"], Some("Cmd+I"), r#"{"paths":[str],"bin":binId?}"#, always, |s, p| {+ cmd!("file.import", "Import…", ["File"], Some("Cmd+I"), r#"{"paths":[str],"bin":binId?,"imageSequence":bool?}"#, always, |s, p| {let bin = u64_p(p, "bin").map(filmcraft_project::BinId);let paths: Vec<String> = match p.get("paths").and_then(Value::as_array) {Some(a) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),@@ -606,7 +625,22 @@ fn build() -> Vec<CommandSpec> {let mut errors = Vec::new();let mut sequences = Vec::new();let mut reports = Vec::new();+ let mut image_sequences = Vec::new();+ // Image Sequence: each path is the first frame of a numbered still sequence. With+ // Settings ▸ Media ▸ Import image sequences on, a single numbered still is detected.+ let as_sequence = p.get("imageSequence").and_then(Value::as_bool).unwrap_or(false);+ let detect = !as_sequence && s.prefs.media.import_image_sequences && paths.len() == 1;for path in paths {+ if as_sequence || (detect && detect_image_sequence(s, &path)) {+ match import_image_sequence(s, &path, bin) {+ Ok((id, frames, missing)) => {+ ids.push(id.0);+ image_sequences.push(json!({"item": id.0, "frames": frames, "missing": missing}));+ }+ Err(e) => errors.push(format!("{path}: {e}")),+ }+ continue;+ }// Media files through the host's reader (no whole-file read) when it has one.let streamed = filmcraft_media::is_importable(std::path::Path::new(&path)) && s.services.reader(&path).is_some();let read = if streamed { Ok(Vec::new()) } else { s.services.read_file(&path) };@@ -643,7 +677,8 @@ fn build() -> Vec<CommandSpec> {return Err(EngineError::Other(errors.join("; ")));}// Project Settings ▸ Ingest: copy / transcode / create proxies- let item_ids: Vec<ItemId> = ids.iter().map(|i| ItemId(*i)).collect();+ // (image sequences are many files: ingest copies and transcodes single files only)+ let item_ids: Vec<ItemId> = ids.iter().filter(|i| !image_sequences.iter().any(|q| q["item"].as_u64() == Some(**i))).map(|i| ItemId(*i)).collect();// Settings ▸ Media Analysis & Transcription ▸ Automatically transcribe clipslet ma = &s.prefs.media_analysis;if ma.auto_transcribe@@ -665,14 +700,17 @@ fn build() -> Vec<CommandSpec> {Value::Null}};- if !ingest.is_null() {- return Ok(json!({"items": ids, "sequences": sequences, "documents": reports, "errors": errors, "ingest": ingest}));- }- if reports.is_empty() {- Ok(json!({"items": ids, "errors": errors}))+ let mut out = if !ingest.is_null() {+ json!({"items": ids, "sequences": sequences, "documents": reports, "errors": errors, "ingest": ingest})+ } else if reports.is_empty() {+ json!({"items": ids, "errors": errors})} else {- Ok(json!({"items": ids, "sequences": sequences, "documents": reports, "errors": errors}))+ json!({"items": ids, "sequences": sequences, "documents": reports, "errors": errors})+ };+ if !image_sequences.is_empty() {+ out["imageSequences"] = json!(image_sequences);}+ Ok(out)}),cmd!("file.exportInterchange", "Export Interchange", [], None, r#"{"format":"edl|xml|fcpxml|otio","path":str,"sequence":id?}"#, has_seq, |s, p| {crate::interchange::export(s, p)diff --git a/crates/engine/src/image_sequence_tests.rs b/crates/engine/src/image_sequence_tests.rsnew file mode 100644index 000000000..ca36d9cce--- /dev/null+++ b/crates/engine/src/image_sequence_tests.rs@@ -0,0 +1,137 @@+//! Image sequences: File ▸ Import with Image Sequence, the Import image sequences setting,+//! missing frames, the indeterminate media timebase, timeline placement and project reopen.++use std::path::Path;++use filmcraft_media::{FrameRequest, MediaKind};+use filmcraft_project::{ClipId, ItemId};+use filmcraft_time::FrameRate;+use serde_json::{Value, json};++use crate::Session;+use crate::media_test_util::tmp_dir;++fn demo() -> Session {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s+}++/// Frame `i` is a flat colour whose red channel is `10 * i`.+fn write_frames(dir: &Path, prefix: &str, numbers: &[u32], ext: &str) -> Vec<String> {+ numbers+ .iter()+ .map(|&n| {+ let p = dir.join(format!("{prefix}{n:04}.{ext}"));+ image::RgbaImage::from_pixel(32, 18, image::Rgba([(10 * n) as u8, 99, 7, 255])).save(&p).unwrap();+ p.to_string_lossy().to_string()+ })+ .collect()+}++fn red_at(s: &Session, item: ItemId, frame: i64) -> u8 {+ let src = s.media.source_for(&s.project, item, &*s.services).unwrap();+ let rate = src.info().frame_rate();+ let f = src.video_frame(FrameRequest::full(rate.tick_of(frame))).unwrap();+ match &f.data {+ filmcraft_frame::PixelData::Rgba8(p) => p[0],+ _ => panic!("rgba frames"),+ }+}++fn item_of(r: &Value) -> ItemId {+ ItemId(r["items"][0].as_u64().unwrap_or_else(|| panic!("{r}")))+}++#[test]+fn import_as_image_sequence_with_missing_frames() {+ let dir = tmp_dir("imgseq-import");+ let mut s = demo();+ s.execute("prefs.set", json!({"key": "media.indeterminateTimebase", "value": "25"})).unwrap();+ // frames 1..=6 with 4 missing, plus an unrelated file+ let paths = write_frames(&dir, "shot_", &[1, 2, 3, 5, 6], "png");+ write_frames(&dir, "other_", &[1], "png");+ let r = s.execute("file.import", json!({"paths": [paths[0]], "imageSequence": true})).unwrap();+ let id = item_of(&r);+ assert_eq!(r["imageSequences"][0]["frames"], 6);+ assert_eq!(r["imageSequences"][0]["missing"], json!([3]));+ let m = s.project.item(id).unwrap().as_media().unwrap().clone();+ assert_eq!(m.info.kind, MediaKind::ImageSequence);+ assert_eq!(m.info.frame_rate(), FrameRate::FPS_25, "Indeterminate Media Timebase");+ assert_eq!(m.info.duration, FrameRate::FPS_25.tick_of(6));+ assert_eq!((m.info.video.as_ref().unwrap().width, m.info.video.as_ref().unwrap().height), (32, 18));+ assert_eq!(red_at(&s, id, 0), 10);+ assert_eq!(red_at(&s, id, 2), 30);+ assert_eq!(red_at(&s, id, 3), 30, "missing frame 4 holds frame 3");+ assert_eq!(red_at(&s, id, 5), 60);+ // starting mid-sequence: from the chosen number on+ let r = s.execute("file.importImageSequence", json!({"path": paths[2]})).unwrap();+ let mid = item_of(&r);+ assert_eq!(r["imageSequences"][0]["frames"], 4);+ assert_eq!(red_at(&s, mid, 0), 30);+ // onto the timeline: a clip of the sequence's length+ let end = s.active_sequence().unwrap().duration();+ let r = s.execute("timeline.place", json!({"item": id.0, "track": "V1", "time": end.0})).unwrap();+ let clip = ClipId(r["clips"][0].as_u64().unwrap());+ let rate = s.sequence_rate();+ let dur = s.active_sequence().unwrap().find_item(clip).unwrap().1.duration;+ assert_eq!(dur, rate.snap_nearest(FrameRate::FPS_25.tick_of(6)), "{dur:?}");+ // a non-numbered file cannot start a sequence+ let plain = dir.join("plain.png");+ image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).save(&plain).unwrap();+ let e = s.execute("file.import", json!({"paths": [plain.to_string_lossy()], "imageSequence": true})).unwrap_err().to_string();+ assert!(e.contains("numbered"), "{e}");+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn import_image_sequences_setting_detects_a_numbered_still() {+ let dir = tmp_dir("imgseq-auto");+ let mut s = demo();+ let paths = write_frames(&dir, "render.", &[10, 11, 12], "png");+ // off (default): a still+ let r = s.execute("file.import", json!({"paths": [paths[0]]})).unwrap();+ assert_eq!(s.project.item(item_of(&r)).unwrap().as_media().unwrap().info.kind, MediaKind::Still);+ // on: the sequence+ s.execute("prefs.set", json!({"key": "media.importImageSequences", "value": true})).unwrap();+ let r = s.execute("file.import", json!({"paths": [paths[0]]})).unwrap();+ let id = item_of(&r);+ let m = s.project.item(id).unwrap().as_media().unwrap();+ assert_eq!(m.info.kind, MediaKind::ImageSequence);+ assert_eq!(m.info.duration, m.info.frame_rate().tick_of(3));+ // several files at once stay stills+ let r = s.execute("file.import", json!({"paths": [paths[0], paths[1]]})).unwrap();+ assert!(r.get("imageSequences").is_none());+ assert_eq!(s.project.item(item_of(&r)).unwrap().as_media().unwrap().info.kind, MediaKind::Still);+ // the last frame alone is no sequence+ let r = s.execute("file.import", json!({"paths": [paths[2]]})).unwrap();+ assert_eq!(s.project.item(item_of(&r)).unwrap().as_media().unwrap().info.kind, MediaKind::Still);+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn image_sequence_survives_save_and_reopen() {+ let dir = tmp_dir("imgseq-reopen");+ let mut s = demo();+ let paths = write_frames(&dir, "f", &[0, 1, 2, 3], "png");+ let id = item_of(&s.execute("file.importFromMediaBrowser", json!({"paths": [paths[0]], "imageSequence": true})).unwrap());+ let proj = dir.join("seq.fcproj");+ s.execute("file.saveAs", json!({"path": proj.to_string_lossy()})).unwrap();+ let mut t = Session::default();+ t.execute("file.open", json!({"path": proj.to_string_lossy()})).unwrap();+ let m = t.project.item(id).unwrap().as_media().unwrap();+ assert_eq!(m.info.kind, MediaKind::ImageSequence);+ assert_eq!(red_at(&t, id, 3), 30, "frames reopen through the media pool");+ assert!(t.media.offline_status(id).is_none());+ // a deleted frame is held over; deleting the first frame makes the item offline+ std::fs::remove_file(&paths[2]).unwrap();+ let mut u = Session::default();+ u.execute("file.open", json!({"path": proj.to_string_lossy()})).unwrap();+ assert_eq!(red_at(&u, id, 2), 10);+ std::fs::remove_file(&paths[0]).unwrap();+ let mut v = Session::default();+ v.execute("file.open", json!({"path": proj.to_string_lossy()})).unwrap();+ let _ = v.media.source_for(&v.project, id, &*v.services);+ assert!(v.media.offline_status(id).is_some(), "missing first frame: offline");+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex d87a22f8b..eb68cf18b 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -93,6 +93,16 @@ pub trait Services: Send + Sync {fn reader(&self, _path: &str) -> Option<std::io::Result<filmcraft_media::SharedReader>> {None}+ /// File names in a directory (image sequence detection). `None`: the host cannot list+ /// directories; sequences are then found by probing consecutive frame numbers.+ fn list_dir(&self, _dir: &str) -> Option<std::io::Result<Vec<String>>> {+ None+ }+ /// A loader the media pool keeps for reading files later (image sequence frames on demand).+ /// `None`: the frames are read when the sequence is opened.+ fn file_loader(&self) -> Option<filmcraft_media::sequence::FrameLoader> {+ None+ }/// Exports are encoded in memory and handed to [`Services::write_file`] (hosts without a/// filesystem, e.g. the web: the file is then offered as a download). Otherwise they stream/// to the output path.@@ -115,6 +125,13 @@ impl Services for FsServices {let m = std::fs::metadata(path)?;if m.is_file() { Ok(m.len()) } else { Err(std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path} is not a file"))) }}+ fn list_dir(&self, dir: &str) -> Option<std::io::Result<Vec<String>>> {+ let dir = if dir.is_empty() { "." } else { dir };+ Some(std::fs::read_dir(dir).map(|rd| rd.flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect()))+ }+ fn file_loader(&self) -> Option<filmcraft_media::sequence::FrameLoader> {+ Some(std::sync::Arc::new(|p: &str| std::fs::read(p)))+ }fn read_range(&self, path: &str, offset: u64, len: usize) -> std::io::Result<Vec<u8>> {use std::io::{Read, Seek, SeekFrom};let mut f = std::fs::File::open(path)?;@@ -752,6 +769,8 @@ mod essential_sound_tests;#[cfg(test)]mod file_tests;#[cfg(test)]+mod image_sequence_tests;+#[cfg(test)]mod masks_tests;#[cfg(test)]mod media_test_util;diff --git a/crates/engine/src/media_pool.rs b/crates/engine/src/media_pool.rsindex 5aa5338e1..b8e7bc729 100644--- a/crates/engine/src/media_pool.rs+++ b/crates/engine/src/media_pool.rs@@ -63,6 +63,56 @@ pub fn media_key(m: &MediaClip) -> String {}}+/// Open the image sequence that `first` (a numbered still) starts: its frames from that number to+/// the highest present one, played at `rate`. Frames are listed with [`Services::list_dir`], or+/// found by probing consecutive numbers (stopping after 100 missing in a row) when the host cannot+/// list directories.+pub fn open_image_sequence(first: &str, services: &dyn Services, rate: filmcraft_time::FrameRate, name: &str) -> Result<SharedSource, MediaError> {+ let frames = image_sequence_frames(first, services)?;+ let loader = match services.file_loader() {+ Some(l) => l,+ None => {+ // no lasting file access: read the (encoded) frames now+ let mut files = HashMap::new();+ for p in frames.iter().flatten() {+ if let Ok(b) = services.read_file(p) {+ files.insert(p.clone(), Arc::<[u8]>::from(b));+ }+ }+ Arc::new(move |p: &str| files.get(p).map(|b| b.to_vec()).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, p.to_string())))+ }+ };+ Ok(Arc::new(filmcraft_media::sequence::ImageSequenceSource::new(name, frames, rate, loader)?))+}++/// The frames of the image sequence starting at `first` (see [`open_image_sequence`]).+pub fn image_sequence_frames(first: &str, services: &dyn Services) -> Result<Vec<Option<String>>, MediaError> {+ use filmcraft_media::sequence::{Numbered, sequence_frames};+ let n = Numbered::parse(first).ok_or_else(|| MediaError::Unsupported(format!("{first}: not a numbered still image")))?;+ let io = |e: std::io::Error| {+ if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(format!("{first}: {e}")) } else { MediaError::Io(format!("{first}: {e}")) }+ };+ services.file_size(first).map_err(io)?;+ match services.list_dir(n.dir.trim_end_matches(['/', '\\'])) {+ Some(list) => Ok(sequence_frames(&n, &list.map_err(io)?)),+ None => {+ let mut names = vec![n.file_name(n.number)];+ let mut misses = 0;+ let mut k = n.number + 1;+ while misses < 100 && names.len() < 1_000_000 {+ if services.file_size(&n.path(k)).is_ok() {+ names.push(n.file_name(k));+ misses = 0;+ } else {+ misses += 1;+ }+ k += 1;+ }+ Ok(sequence_frames(&n, &names))+ }+ }+}+fn file_name(path: &str) -> String {path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()}@@ -176,7 +226,11 @@ impl MediaPool {self.set_offline(item, OfflineReason::MadeOffline, path, "made offline");Arc::new(SlateSource::new(m.info.clone(), &file_name(path), OfflineReason::MadeOffline))}- MediaRef::File { path } => match self.open_file(path, services) {+ MediaRef::File { path } => match if m.info.kind == filmcraft_media::MediaKind::ImageSequence {+ open_image_sequence(path, services, m.info.frame_rate(), &it.name)+ } else {+ self.open_file(path, services)+ } {Ok(s) => {self.offline.write().unwrap_or_else(|e| e.into_inner()).remove(&item);sdiff --git a/crates/engine/src/project_tools.rs b/crates/engine/src/project_tools.rsindex d6be89c0d..6ac9253d0 100644--- a/crates/engine/src/project_tools.rs+++ b/crates/engine/src/project_tools.rs@@ -92,11 +92,29 @@ pub(crate) fn commands() -> Vec<CommandSpec> {spec("file.saveAsTemplate", "Save as Template…", &["File"], None, r#"{"name":str?,"path":str?}"#, always, save_as_template),query("file.templates", "List Project Templates", &[], None, "{}", always, list_templates),spec("file.newProjectFromTemplate", "New Project from Template", &[], None, r#"{"template":name|path,"name":str?}"#, always, new_from_template),- spec("file.importFromMediaBrowser", "Import from Media Browser", &["File"], Some("Cmd+Alt+I"), r#"{"paths":[str]}"#, always, |s, p| {- if p.get("paths").and_then(Value::as_array).is_none_or(|a| a.is_empty()) {- return Err(bad("file.importFromMediaBrowser", "select files in the Media Browser"));+ spec(+ "file.importFromMediaBrowser",+ "Import from Media Browser",+ &["File"],+ Some("Cmd+Alt+I"),+ r#"{"paths":[str],"imageSequence":bool?}"#,+ always,+ |s, p| {+ if p.get("paths").and_then(Value::as_array).is_none_or(|a| a.is_empty()) {+ return Err(bad("file.importFromMediaBrowser", "select files in the Media Browser"));+ }+ let seq = p.get("imageSequence").and_then(Value::as_bool).unwrap_or(false);+ s.execute("file.import", json!({"paths": p["paths"], "imageSequence": seq}))+ },+ ),+ // File ▸ Import with "Image Sequence" checked (the UI asks for the first frame).+ spec("file.importImageSequence", "Import Image Sequence…", &["File"], None, r#"{"path":str,"bin":binId?}"#, always, |s, p| {+ let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("file.importImageSequence", "need `path` (the first numbered still)"))?;+ let mut q = json!({"paths": [path], "imageSequence": true});+ if let Some(b) = p.get("bin") {+ q["bin"] = b.clone();}- s.execute("file.import", json!({"paths": p["paths"]}))+ s.execute("file.import", q)}),spec("file.exportSelectionProject",@@ -229,7 +247,7 @@ pub(crate) fn apply_layout(v: &mut Vec<CommandSpec>) {(At::After("captions.showAll"), vec!["captions.showActiveOnly"]),(At::After("markers.addChapter"), vec!["markers.addFlashCue"]),(At::Before("file.close"), vec!["file.open"]),- (At::After("media.makeOffline"), vec!["file.importFromMediaBrowser", "file.import"]),+ (At::After("media.makeOffline"), vec!["file.importFromMediaBrowser", "file.import", "file.importImageSequence"]),];for (at, ids) in layout {let mut run = Vec::new();diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rsindex 691929fad..7a2e68efb 100644--- a/crates/media/src/lib.rs+++ b/crates/media/src/lib.rs@@ -13,6 +13,7 @@ pub mod digits;pub mod generators;pub mod pending;pub mod reader;+pub mod sequence;pub mod still;pub mod wav;diff --git a/crates/media/src/sequence.rs b/crates/media/src/sequence.rsnew file mode 100644index 000000000..63d0568de--- /dev/null+++ b/crates/media/src/sequence.rs@@ -0,0 +1,308 @@+//! Image sequences: numbered stills (`shot_0001.png`, `shot_0002.png`, …) as one movie clip.+//!+//! - [`Numbered`] splits a file name around its last run of digits; [`sequence_frames`] lists the+//! frames from the chosen file's number up to the highest number present (gaps are `None`).+//! - [`ImageSequenceSource`] decodes frames on demand through a [`FrameLoader`] (the host's file+//! access) with the still decoders (PNG, JPEG, TIFF, BMP, WebP, GIF), keeps recently used frames+//! in a byte-budgeted [`FrameCache`], and shows the nearest earlier frame for a missing or+//! undecodable one (the nearest later frame before the first).+//! - The frame rate is the caller's (Settings ▸ Media ▸ Indeterminate Media Timebase).++use std::sync::Arc;++use filmcraft_frame::{AudioBuffer, VideoFrame};+use filmcraft_time::FrameRate;++use crate::{FrameCache, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, VideoStreamInfo};++/// Reads a file's bytes (the host's file access).+pub type FrameLoader = Arc<dyn Fn(&str) -> std::io::Result<Vec<u8>> + Send + Sync>;++/// A file name with a frame number: `<dir><prefix><digits><suffix>`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Numbered {+ /// Directory part including the trailing separator ("" when none).+ pub dir: String,+ pub prefix: String,+ pub number: u64,+ /// Width of the digit run as written (zero padding).+ pub digits: usize,+ /// Everything after the digits, including the extension.+ pub suffix: String,+}++impl Numbered {+ /// Split `path` at the last run of digits in its file stem. `None` when the stem has no digits+ /// or the file is not a still image.+ pub fn parse(path: &str) -> Option<Numbered> {+ let cut = path.rfind(['/', '\\']).map_or(0, |i| i + 1);+ let (dir, name) = path.split_at(cut);+ let ext_at = name.rfind('.').filter(|&i| i > 0)?;+ let ext = name[ext_at + 1..].to_ascii_lowercase();+ if !crate::STILL_EXTENSIONS.contains(&ext.as_str()) {+ return None;+ }+ let stem = &name[..ext_at];+ let end = stem.rfind(|c: char| c.is_ascii_digit())? + 1;+ let start = stem[..end].rfind(|c: char| !c.is_ascii_digit()).map_or(0, |i| i + 1);+ let digits = &stem[start..end];+ if digits.len() > 18 {+ return None;+ }+ Some(Numbered {+ dir: dir.to_string(),+ prefix: stem[..start].to_string(),+ number: digits.parse().ok()?,+ digits: digits.len(),+ suffix: name[end..].to_string(),+ })+ }++ /// Whether the numbers are zero-padded to a fixed width.+ pub fn padded(&self) -> bool {+ self.digits > 1 && self.number.to_string().len() < self.digits+ }++ /// The file name (no directory) of frame number `n`.+ pub fn file_name(&self, n: u64) -> String {+ format!("{}{:0w$}{}", self.prefix, n, self.suffix, w = self.digits)+ }++ /// The path of frame number `n`.+ pub fn path(&self, n: u64) -> String {+ format!("{}{}", self.dir, self.file_name(n))+ }++ /// The frame number of a sibling file name of this sequence (same prefix, suffix and padding).+ pub fn number_of(&self, file_name: &str) -> Option<u64> {+ let mid = file_name.strip_prefix(self.prefix.as_str())?.strip_suffix(self.suffix.as_str())?;+ if mid.is_empty() || !mid.bytes().all(|b| b.is_ascii_digit()) || mid.len() > 18 {+ return None;+ }+ // every number has the first one's width, or is wider without leading zeros (overflowing+ // the padding, or an unpadded sequence counting past 9, 99…)+ if mid.len() != self.digits && (mid.len() < self.digits || mid.starts_with('0')) {+ return None;+ }+ mid.parse().ok()+ }+}++/// The frames of the sequence `first` belongs to, from `first.number` to the highest number among+/// `siblings` (file names in its directory): each frame's path, or `None` for a missing number.+pub fn sequence_frames(first: &Numbered, siblings: &[String]) -> Vec<Option<String>> {+ let mut nums: Vec<(u64, &String)> = siblings.iter().filter_map(|n| first.number_of(n).map(|k| (k, n))).filter(|(k, _)| *k >= first.number).collect();+ nums.sort();+ nums.dedup_by_key(|x| x.0);+ let last = nums.last().map_or(first.number, |x| x.0);+ // a sequence longer than this is a numbering accident (e.g. a date in the name)+ let span = (last - first.number).min(1_000_000) as usize + 1;+ let mut frames = vec![None; span];+ for (k, name) in nums {+ let i = (k - first.number) as usize;+ if i < span {+ frames[i] = Some(format!("{}{}", first.dir, name));+ }+ }+ if frames[0].is_none() {+ frames[0] = Some(first.path(first.number));+ }+ frames+}++/// Numbered stills played as a movie.+pub struct ImageSequenceSource {+ info: MediaInfo,+ frames: Vec<Option<String>>,+ loader: FrameLoader,+ cache: FrameCache<usize>,+}++impl ImageSequenceSource {+ /// `frames`: path per frame (`None`: missing). The first present frame is decoded now (size,+ /// alpha); the rest on demand.+ pub fn new(name: &str, frames: Vec<Option<String>>, rate: FrameRate, loader: FrameLoader) -> Result<Self> {+ let first = frames.iter().flatten().next().ok_or_else(|| MediaError::Offline(format!("{name}: no frames")))?.clone();+ let bytes = loader(&first).map_err(|e| {+ if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(format!("{first}: {e}")) } else { MediaError::Io(format!("{first}: {e}")) }+ })?;+ let img = image::load_from_memory(&bytes).map_err(|e| MediaError::Decode(format!("{first}: {e}")))?;+ let has_alpha = img.color().has_alpha();+ let (w, h) = (img.width(), img.height());+ let ext = first.rsplit('.').next().unwrap_or("image").to_ascii_uppercase();+ let n = frames.len() as i64;+ let info = MediaInfo {+ name: name.to_string(),+ kind: MediaKind::ImageSequence,+ duration: rate.tick_of(n),+ video: Some(VideoStreamInfo {+ width: w,+ height: h,+ frame_rate: rate,+ par: (1, 1),+ codec: format!("{ext} sequence"),+ pixel_format: if has_alpha { "RGBA 8-bit".into() } else { "RGB 8-bit".into() },+ color: filmcraft_color::ColorInfo::SRGB_FULL,+ has_alpha,+ bitrate: None,+ }),+ audio: None,+ container: "Image Sequence".into(),+ start_timecode: None,+ file_size: None,+ };+ let cache = FrameCache::new(256 << 20);+ cache.insert(frames.iter().position(Option::is_some).unwrap_or(0), Arc::new(VideoFrame::rgba8(w, h, img.to_rgba8().into_raw())));+ Ok(Self { info, frames, loader, cache })+ }++ pub fn frame_count(&self) -> usize {+ self.frames.len()+ }++ /// Indices of missing frames.+ pub fn missing_frames(&self) -> Vec<usize> {+ self.frames.iter().enumerate().filter(|(_, f)| f.is_none()).map(|(i, _)| i).collect()+ }++ /// Path of frame `i` (`None` when missing).+ pub fn frame_path(&self, i: usize) -> Option<&str> {+ self.frames.get(i).and_then(|f| f.as_deref())+ }++ fn decode(&self, i: usize) -> Result<Arc<VideoFrame>> {+ if let Some(f) = self.cache.get(&i) {+ return Ok(f);+ }+ let path = self.frames[i].as_deref().ok_or(MediaError::NoStream("video"))?;+ let bytes = (self.loader)(path).map_err(|e| MediaError::Io(format!("{path}: {e}")))?;+ let img = image::load_from_memory(&bytes).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?;+ let f = Arc::new(VideoFrame::rgba8(img.width(), img.height(), img.to_rgba8().into_raw()));+ self.cache.insert(i, f.clone());+ Ok(f)+ }+}++impl MediaSource for ImageSequenceSource {+ fn info(&self) -> &MediaInfo {+ &self.info+ }++ fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {+ let n = self.frames.len();+ let want = self.info.frame_rate().frame_at(req.time.max(filmcraft_time::Tick::ZERO)).clamp(0, n as i64 - 1) as usize;+ // the wanted frame, else the nearest earlier present frame, else the nearest later one+ let candidates = (0..=want).rev().chain(want + 1..n);+ let mut last_err = None;+ for i in candidates.filter(|&i| self.frames[i].is_some()).take(8) {+ match self.decode(i) {+ Ok(f) => return Ok(f),+ Err(e) => last_err = Some(e),+ }+ }+ Err(last_err.unwrap_or(MediaError::NoStream("video")))+ }++ fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result<AudioBuffer> {+ Err(MediaError::NoStream("audio"))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;+ use std::sync::Mutex;++ #[test]+ fn numbered_names() {+ let n = Numbered::parse("/shots/A001_C002_0099.png").unwrap();+ assert_eq!((n.dir.as_str(), n.prefix.as_str(), n.number, n.digits, n.suffix.as_str()), ("/shots/", "A001_C002_", 99, 4, ".png"));+ assert!(n.padded());+ assert_eq!(n.path(100), "/shots/A001_C002_0100.png");+ assert_eq!(n.number_of("A001_C002_0100.png"), Some(100));+ assert_eq!(n.number_of("A001_C002_100.png"), None, "padding differs");+ assert_eq!(n.number_of("A001_C002_12345.png"), Some(12345), "overflowing the padding");+ assert_eq!(n.number_of("A001_C002_0100.jpg"), None);+ assert_eq!(n.number_of("B001_C002_0100.png"), None);+ let u = Numbered::parse("frame7.TIF").unwrap();+ assert_eq!((u.prefix.as_str(), u.number, u.suffix.as_str()), ("frame", 7, ".TIF"));+ assert!(!u.padded());+ assert_eq!(u.file_name(10), "frame10.TIF");+ assert_eq!(u.number_of("frame10.TIF"), Some(10));+ assert_eq!(Numbered::parse("clip.mov"), None, "not a still");+ assert_eq!(Numbered::parse("nodigits.png"), None);+ let w = Numbered::parse("C:\\renders\\out.0010.exr.png").unwrap();+ assert_eq!((w.dir.as_str(), w.prefix.as_str(), w.number), ("C:\\renders\\", "out.", 10));+ }++ #[test]+ fn frames_with_gaps() {+ let n = Numbered::parse("/d/s_003.png").unwrap();+ let names: Vec<String> = ["s_001.png", "s_003.png", "s_004.png", "s_007.png", "other.png", "s_005.jpg"].iter().map(|s| s.to_string()).collect();+ let f = sequence_frames(&n, &names);+ assert_eq!(f.len(), 5);+ assert_eq!(f[0].as_deref(), Some("/d/s_003.png"));+ assert_eq!(f[1].as_deref(), Some("/d/s_004.png"));+ assert_eq!((f[2].as_deref(), f[3].as_deref()), (None, None));+ assert_eq!(f[4].as_deref(), Some("/d/s_007.png"));+ }++ fn png(w: u32, h: u32, v: u8) -> Vec<u8> {+ let img = image::RgbaImage::from_pixel(w, h, image::Rgba([v, 255 - v, 7, 255]));+ let mut out = std::io::Cursor::new(Vec::new());+ img.write_to(&mut out, image::ImageFormat::Png).unwrap();+ out.into_inner()+ }++ #[test]+ fn webp_frames_lossless() {+ let enc = |v: u8| {+ let img = image::RgbaImage::from_fn(6, 4, |x, y| image::Rgba([v, (x * 40) as u8, (y * 60) as u8, 255]));+ let mut out = Vec::new();+ image::codecs::webp::WebPEncoder::new_lossless(&mut out).encode(img.as_raw(), 6, 4, image::ExtendedColorType::Rgba8).unwrap();+ (img.into_raw(), out)+ };+ let (a, wa) = enc(1);+ let (b, wb) = enc(2);+ let files: HashMap<String, Vec<u8>> = [("w1.webp".to_string(), wa), ("w2.webp".to_string(), wb)].into_iter().collect();+ let loader: FrameLoader = Arc::new(move |p: &str| files.get(p).cloned().ok_or_else(|| std::io::Error::other("missing")));+ let s = ImageSequenceSource::new("w1.webp", vec![Some("w1.webp".into()), Some("w2.webp".into())], FrameRate::FPS_24, loader).unwrap();+ for (i, want) in [a, b].iter().enumerate() {+ match &s.video_frame(FrameRequest::full(FrameRate::FPS_24.tick_of(i as i64))).unwrap().data {+ filmcraft_frame::PixelData::Rgba8(p) => assert_eq!(&p[..], &want[..]),+ _ => panic!(),+ }+ }+ }++ #[test]+ fn plays_frames_holds_missing_and_caches() {+ let files: HashMap<String, Vec<u8>> = [(0, 10u8), (1, 20), (3, 40)].iter().map(|(i, v)| (format!("f{i}.png"), png(8, 4, *v))).collect();+ let reads = Arc::new(Mutex::new(0usize));+ let r = reads.clone();+ let loader: FrameLoader = Arc::new(move |p: &str| {+ *r.lock().unwrap() += 1;+ files.get(p).cloned().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, p.to_string()))+ });+ let frames = vec![Some("f0.png".to_string()), Some("f1.png".into()), None, Some("f3.png".into())];+ let s = ImageSequenceSource::new("f0.png", frames, FrameRate::FPS_25, loader).unwrap();+ assert_eq!(s.info().kind, MediaKind::ImageSequence);+ assert_eq!(s.info().duration, FrameRate::FPS_25.tick_of(4));+ assert_eq!(s.missing_frames(), vec![2]);+ let px = |i: i64| match &s.video_frame(FrameRequest::full(FrameRate::FPS_25.tick_of(i))).unwrap().data {+ filmcraft_frame::PixelData::Rgba8(p) => p[0],+ _ => panic!(),+ };+ assert_eq!(px(0), 10);+ assert_eq!(px(1), 20);+ assert_eq!(px(2), 20, "missing frame holds the previous one");+ assert_eq!(px(3), 40);+ assert_eq!(px(99), 40, "past the end: the last frame");+ let n = *reads.lock().unwrap();+ for i in 0..4 {+ px(i);+ }+ assert_eq!(*reads.lock().unwrap(), n, "frames come from the cache");+ }+}diff --git a/crates/media/src/wav.rs b/crates/media/src/wav.rsindex 07e1cae4f..a7d9acb0d 100644--- a/crates/media/src/wav.rs+++ b/crates/media/src/wav.rs@@ -1,5 +1,6 @@-//! Minimal WAV (RIFF/RF64 PCM 8/16/24/32-bit int, 32/64-bit float) source. The full `riff` crate-//! (BWF metadata, AIFF) will replace this.+//! Minimal WAV (RIFF/RF64 PCM 8/16/24/32-bit int, 32/64-bit float) source, with the Broadcast Wave+//! start time: `bext` TimeReference (EBU Tech 3285), else iXML `BWF_TIME_REFERENCE_LOW/HIGH`. The+//! full `riff` crate (all BWF metadata, AIFF) will replace this.use std::sync::Arc;@@ -21,6 +22,7 @@ pub struct WavSource {bits: u16,float: bool,rate: u32,+ time_reference: Option<u64>,}fn le16(b: &[u8], o: usize) -> u16 {@@ -36,6 +38,8 @@ impl WavSource {let mut pos = 12;let mut fmt = None;let mut data = None;+ let mut bext_tr = None;+ let mut ixml_tr = None;while pos + 8 <= b.len() {let id = &b[pos..pos + 4];let mut len = le32(b, pos + 4) as usize;@@ -58,6 +62,10 @@ impl WavSource {fmt = Some((tag, ch, rate, bits));}b"data" => data = Some((body, len)),+ // bext: Description 256, Originator 32, OriginatorReference 32, OriginationDate 10,+ // OriginationTime 8, then TimeReference (low u32, high u32)+ b"bext" if len >= 346 => bext_tr = Some(le32(b, body + 338) as u64 | (le32(b, body + 342) as u64) << 32),+ b"iXML" => ixml_tr = ixml_time_reference(&b[body..body + len]),_ => {}}pos = body + len + (len & 1);@@ -70,7 +78,8 @@ impl WavSource {}let frame_bytes = ch as usize * bits as usize / 8;let frames = len / frame_bytes;- let info = MediaInfo {+ let time_reference = bext_tr.or(ixml_tr);+ let mut info = MediaInfo {name: name.into(),kind: MediaKind::AudioOnly,duration: Tick::from_units(frames as i64, rate as i64),@@ -81,11 +90,23 @@ impl WavSource {codec: if float { "PCM float".into() } else { "PCM".into() },bits_per_sample: Some(bits as u32),}),- container: "WAV".into(),+ container: if time_reference.is_some() { "Broadcast WAV".into() } else { "WAV".into() },start_timecode: None,file_size: Some(b.len() as u64),};- Ok(Self { info, data_off: off, data_len: frames * frame_bytes, channels: ch as usize, bits, float, rate, bytes })+ // start timecode: frames at the media's frame rate (the default rate for audio-only media)+ if let Some(tr) = time_reference.filter(|_| rate > 0) {+ let r = info.frame_rate();+ let n = tr as i128 * r.num as i128;+ let d = rate as i128 * r.den as i128;+ info.start_timecode = Some(((n + d / 2) / d) as i64);+ }+ Ok(Self { info, data_off: off, data_len: frames * frame_bytes, channels: ch as usize, bits, float, rate, bytes, time_reference })+ }++ /// Broadcast Wave start time: samples since midnight.+ pub fn time_reference(&self) -> Option<u64> {+ self.time_reference}fn sample(&self, frame: usize, ch: usize) -> f32 {@@ -136,6 +157,19 @@ impl MediaSource for WavSource {}}+/// TimeReference from an iXML chunk (`<BWF_TIME_REFERENCE_LOW>` / `<BWF_TIME_REFERENCE_HIGH>`).+fn ixml_time_reference(x: &[u8]) -> Option<u64> {+ let text = String::from_utf8_lossy(x);+ let field = |tag: &str| -> Option<u64> {+ let open = format!("<{tag}>");+ let a = text.find(&open)? + open.len();+ let b = a + text[a..].find('<')?;+ text[a..b].trim().parse().ok()+ };+ let low = field("BWF_TIME_REFERENCE_LOW")?;+ Some(low | field("BWF_TIME_REFERENCE_HIGH").unwrap_or(0) << 32)+}+/// Encode interleaved f32 samples as a 16-bit PCM WAV file.pub fn write_wav16(samples: &[f32], channels: u16, rate: u32) -> Vec<u8> {let data_len = samples.len() * 2;@@ -172,5 +206,55 @@ mod tests {assert!((a.channels[0][3] - s[6]).abs() < 1e-4);assert!((a.channels[1][3] - s[7]).abs() < 1e-4);assert_eq!(src.info().duration, Tick::from_units(100, 48000));+ assert_eq!(src.time_reference(), None);+ assert_eq!(src.info().start_timecode, None);+ }++ /// Insert a chunk before `data`.+ fn with_chunk(wav: &[u8], id: &[u8; 4], body: &[u8]) -> Vec<u8> {+ let mut v = wav[..36].to_vec();+ v.extend_from_slice(id);+ v.extend_from_slice(&(body.len() as u32).to_le_bytes());+ v.extend_from_slice(body);+ if body.len() % 2 == 1 {+ v.push(0);+ }+ v.extend_from_slice(&wav[36..]);+ let riff = (v.len() - 8) as u32;+ v[4..8].copy_from_slice(&riff.to_le_bytes());+ v+ }++ #[test]+ fn bwf_time_reference_from_bext() {+ let wav = write_wav16(&[0.0; 96], 2, 48_000);+ // 01:00:00:00 at 23.976 fps: 86 400 frames of 2002 samples+ let tr: u64 = 86_400 * 2002;+ let mut bext = vec![0u8; 602];+ bext[338..342].copy_from_slice(&(tr as u32).to_le_bytes());+ bext[342..346].copy_from_slice(&((tr >> 32) as u32).to_le_bytes());+ let src = WavSource::parse("bwf.wav", with_chunk(&wav, b"bext", &bext).into()).unwrap();+ assert_eq!(src.time_reference(), Some(tr));+ assert_eq!(src.info().frame_rate(), filmcraft_time::FrameRate::FPS_23_976);+ assert_eq!(src.info().start_timecode, Some(86_400));+ assert_eq!(src.info().container, "Broadcast WAV");+ // the audio is unaffected+ assert_eq!(src.info().duration, Tick::from_units(48, 48_000));+ }++ #[test]+ fn bwf_time_reference_from_ixml_and_large_values() {+ let wav = write_wav16(&[0.0; 4], 1, 48_000);+ let tr: u64 = (1 << 32) + 5;+ let xml = format!(+ "<?xml version=\"1.0\"?><BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>{}</BWF_TIME_REFERENCE_LOW><BWF_TIME_REFERENCE_HIGH>{}</BWF_TIME_REFERENCE_HIGH></BEXT></BWFXML>",+ tr & 0xFFFF_FFFF,+ tr >> 32+ );+ let src = WavSource::parse("ixml.wav", with_chunk(&wav, b"iXML", xml.as_bytes()).into()).unwrap();+ assert_eq!(src.time_reference(), Some(tr));+ // a short bext (no TimeReference) is ignored+ let src = WavSource::parse("short.wav", with_chunk(&wav, b"bext", &[0u8; 100]).into()).unwrap();+ assert_eq!(src.time_reference(), None);}}diff --git a/crates/mxf/Cargo.toml b/crates/mxf/Cargo.tomlnew file mode 100644index 000000000..60e2060dd--- /dev/null+++ b/crates/mxf/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "filmcraft-mxf"+description = "Clean-room MXF (SMPTE ST 377-1) demuxer: OP1a and OP-Atom, index tables, AVC/VC-3/ProRes/MPEG-2/PCM essence"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++[dependencies]++[dev-dependencies]+filmcraft-testkit = { workspace = true }diff --git a/crates/mxf/README.md b/crates/mxf/README.mdnew file mode 100644index 000000000..8c6ab6a47--- /dev/null+++ b/crates/mxf/README.md@@ -0,0 +1,84 @@+# filmcraft-mxf++A clean-room MXF demuxer. Layer L0: no dependencies beyond `std`, no `unsafe`, builds for+`wasm32-unknown-unknown`. No GPL/LGPL code (FFmpeg, libMXF, bmx, MXFLib) was consulted; FFmpeg is+used only as an external fixture generator and test oracle.++## Specifications++Implemented from the SMPTE documents (editions used):++| Document | Edition | Used for |+|---|---|---|+| SMPTE ST 336 | 2017 | KLV coding: 16-byte UL keys, BER lengths |+| SMPTE ST 377-1 | 2011 (+ Amd 1:2012) | partitions, primer pack, header metadata sets and local tags, index table segments, random index pack, run-in |+| SMPTE ST 378 | 2004 | OP1a |+| SMPTE ST 390 | 2011 | OP-Atom |+| SMPTE ST 379-1 / 379-2 | 2009 / 2010 | generic container: content packages, element keys, frame / clip wrapping |+| SMPTE ST 381-1 | 2005 | MPEG video mapping (MPEG-2 identified, MPEG video descriptor) |+| SMPTE ST 381-3 | 2013 | AVC byte-stream mapping and AVC sub-descriptor |+| SMPTE ST 382 | 2007 | AES3 and Broadcast Wave audio mapping (wave / AES3 descriptors) |+| SMPTE ST 331 | 2011 | element data of 8-channel AES3 sound (D-10) |+| SMPTE ST 386 | 2004 | D-10 (IMX) mapping: container label, sound element type |+| SMPTE ST 2019-4 | 2009 | VC-3 (DNxHD / DNxHR) mapping |+| SMPTE RDD 44 | 2017 | Apple ProRes mapping |+| SMPTE RP 224 / RP 210 | registers | labels: data definitions, picture coding, essence containers, operational patterns |++## Reading a file++```rust+let file = std::fs::read("clip.mxf")?;+let mxf = filmcraft_mxf::open(&file)?;+println!("{} {:?}", mxf.operational_pattern.name(), mxf.timecode.map(|t| t.format()));+let v = mxf.track_of_kind(filmcraft_mxf::TrackKind::Picture).unwrap();+let t = &mxf.tracks[v];+let key = t.sync_before(t.sample_at(42).unwrap()); // stored index of the random-access picture+let bytes = mxf.read_sample(&file, v, key)?; // one edit unit's essence+let a = mxf.track_of_kind(filmcraft_mxf::TrackKind::Sound).unwrap();+let pcm = mxf.read_pcm(&file, a, 48_000, 1920)?; // planar f32, sample-exact+```++- **Open.** The header partition pack is found in the run-in (≤ 64 KiB). Every KLV packet is then+ walked (keys and lengths only; essence values are skipped, never read): partition packs, primer+ packs, header metadata local sets, index table segments, fill, and generic-container elements+ (system items are ignored). A lost KLV sync resynchronises on the next partition pack; a+ truncated file keeps everything before the cut (a truncated frame-wrapped picture is dropped,+ clip-wrapped essence keeps its whole edit units).+- **Metadata.** The header metadata of the most complete partition is used (closed complete >+ open complete > closed > open; later partitions win ties, so the footer's final durations are+ preferred). Dynamic local tags resolve through the primer pack (e.g. `SubDescriptors`).+- **Tracks.** Material package picture/sound tracks → source clip → file package track (track+ number, edit rate, origin) → descriptor (a multiple descriptor's sub-descriptor by+ `LinkedTrackID`). Without a usable material package the file packages' tracks are used directly.+ Elements are matched by track number, or — when the number is 0 or does not match (some OP-Atom+ writers) — the only unclaimed element stream of the right kind.+- **Pictures.** One `Sample` per edit unit in stored order: frame wrapping (one element each) or+ clip wrapping (one element split by the index: constant `EditUnitByteCount` or VBR entries).+ Random access from index flag bit 7 (intra-only codings: every picture); without an index the+ essence is scanned (AVC IDR, MPEG-2 sequence header). Presentation order from the index temporal+ offsets (display position *n* is stored at *n* + `TemporalOffset[n]`). When the index marks B+ pictures but has no temporal offsets (FFmpeg-written AVC), `needs_reorder` is set: the caller+ orders by the bitstream (`filmcraft-codecs` uses the AVC picture order counts).+- **Codecs.** From the picture essence coding label, then the essence container label, then the+ essence bytes: AVC / AVC-Intra, VC-3, ProRes (profile from the label), MPEG-2 (identified only),+ MPEG-4 visual, JPEG 2000, DV, uncompressed.+- **Sound.** PCM chunks (frame- or clip-wrapped) with sample counts; `read_pcm` decodes+ little-endian 8/16/24/32-bit PCM (wave / AES3 descriptors) and ST 331 AES3 elements (D-10).+- **Timecode.** The material package timecode component (start frame count, rounded base,+ drop frame), falling back to the file package's; `Timecode::format` gives `HH:MM:SS:FF` /+ `HH:MM:SS;FF`.++Not supported: OP1b/OP2x+ edit lists beyond the first source clip, external essence (OP-Atom+material packages whose other tracks live in other files are opened track by track), partial or+encrypted essence (ST 429-6), and descriptive metadata (parsed sets are ignored).++## Tests++- `src/tests.rs`: a small OP1a writer builds synthetic files (temporal offsets, key flags, PCM,+ timecode); open, presentation order, sample bytes, PCM values; truncation at every 37 bytes and+ 600 random mutations never panic and only list fully-present samples.+- `crates/codecs/tests/mxf_oracle.rs` (FFmpeg-written fixtures, FFmpeg as the decode oracle):+ H.264 long-GOP with B pictures (bit-exact every frame + 25 random seeks), H.264 29.97 DF+ timecode, DNxHR LB (±2), ProRes 422 (±1), MPEG-2 (reported unsupported, audio exact),+ OP-Atom VC-3 (clip-wrapped) and PCM, D-10 AES3 audio; PCM sample-exact in every file;+ truncated and corrupted files. `cargo xtask fixtures codecs` pre-generates them.diff --git a/crates/mxf/src/essence.rs b/crates/mxf/src/essence.rsnew file mode 100644index 000000000..f1524a436--- /dev/null+++ b/crates/mxf/src/essence.rs@@ -0,0 +1,310 @@+//! Essence identification and PCM sound decoding.+//!+//! Picture codecs are identified from the descriptor's picture essence coding label, then the+//! essence container label (ST 379-2 mapping numbers), then the first bytes of the essence.++use crate::klv::Ul;+use crate::{Rational, Result};++/// The essence codec of a track.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Codec {+ /// H.264 / AVC byte stream (ST 381-3). `intra`: AVC-Intra / an intra-only profile.+ Avc {+ intra: bool,+ },+ /// SMPTE VC-3 (DNxHD / DNxHR, ST 2019-4).+ Vc3,+ /// Apple ProRes (RDD 44). `profile`: byte 14 of the coding label (1 Proxy … 6 4444 XQ).+ ProRes {+ profile: Option<u8>,+ },+ /// MPEG-2 video (ST 381-1, or D-10 / IMX).+ Mpeg2,+ /// MPEG-4 part 2 visual.+ Mpeg4Visual,+ Jpeg2000,+ Dv,+ /// Uncompressed pictures (ST 384).+ Uncompressed,+ /// Linear PCM, little-endian (Broadcast Wave and AES3 descriptors, ST 382).+ Pcm,+ /// 8-channel AES3 element data (ST 331, D-10 sound).+ Aes3Element,+ Unknown,+}++impl Codec {+ pub fn name(&self) -> &'static str {+ match self {+ Codec::Avc { intra: true } => "AVC-Intra",+ Codec::Avc { intra: false } => "H.264",+ Codec::Vc3 => "VC-3",+ Codec::ProRes { .. } => "Apple ProRes",+ Codec::Mpeg2 => "MPEG-2 Video",+ Codec::Mpeg4Visual => "MPEG-4 Visual",+ Codec::Jpeg2000 => "JPEG 2000",+ Codec::Dv => "DV",+ Codec::Uncompressed => "Uncompressed",+ Codec::Pcm => "PCM",+ Codec::Aes3Element => "AES3 PCM",+ Codec::Unknown => "unknown",+ }+ }+ /// Every picture is coded independently.+ pub fn intra_only(&self) -> bool {+ matches!(self, Codec::Avc { intra: true } | Codec::Vc3 | Codec::ProRes { .. } | Codec::Jpeg2000 | Codec::Dv | Codec::Uncompressed)+ }+}++/// Identify a picture codec from the picture essence coding label and the essence container label.+pub fn identify_picture(coding: Option<Ul>, container: Option<Ul>, mpeg_descriptor: bool) -> Codec {+ if let Some(c) = coding.filter(Ul::is_smpte) {+ let b = &c.0;+ // 04 01 02 02 .. : compressed picture coding+ if b[8..12] == [0x04, 0x01, 0x02, 0x02] {+ match (b[12], b[13]) {+ // 01: MPEG compression (ISO/IEC 13818-2 profiles, 14496-2, 14496-10)+ (0x01, 0x01..=0x1F) => return Codec::Mpeg2,+ (0x01, 0x20..=0x2F) => return Codec::Mpeg4Visual,+ (0x01, 0x32) => return Codec::Avc { intra: true },+ (0x01, 0x30..=0x3F) => return Codec::Avc { intra: false },+ (0x02, _) => return Codec::Dv,+ (0x03, 0x01) => return Codec::Jpeg2000,+ (0x03, 0x02) => return Codec::Vc3,+ (0x03, 0x06) => return Codec::ProRes { profile: Some(b[14]) },+ // Avid-registered VC-3 coding labels+ (0x71, _) => return Codec::Vc3,+ _ => {}+ }+ }+ if b[8..11] == [0x04, 0x01, 0x02] && b[11] == 0x01 {+ return Codec::Uncompressed;+ }+ }+ if let Some(c) = container.filter(Ul::is_smpte)+ && c.item_starts_with(&[0x0D, 0x01, 0x03, 0x01, 0x02])+ {+ match c.0[13] {+ 0x01 => return Codec::Mpeg2,+ 0x02 => return Codec::Dv,+ 0x04 if mpeg_descriptor => return Codec::Mpeg2,+ 0x05 => return Codec::Uncompressed,+ 0x0C => return Codec::Jpeg2000,+ 0x0F | 0x10 => return Codec::Avc { intra: false },+ 0x11 => return Codec::Vc3,+ 0x1C => return Codec::ProRes { profile: None },+ _ => {}+ }+ }+ if mpeg_descriptor { Codec::Mpeg2 } else { Codec::Unknown }+}++/// Identify a picture codec from the first bytes of an essence element.+pub fn sniff_picture(b: &[u8]) -> Option<Codec> {+ if b.len() >= 8 && &b[4..8] == b"icpf" {+ return Some(Codec::ProRes { profile: None });+ }+ if b.len() >= 5 && b[..4] == [0x00, 0x00, 0x02, 0x80] {+ return Some(Codec::Vc3);+ }+ if b.len() >= 4 && b[..4] == [0x00, 0x00, 0x01, 0xB3] {+ return Some(Codec::Mpeg2);+ }+ let sc4 = b.len() >= 5 && b[..4] == [0, 0, 0, 1];+ let sc3 = b.len() >= 4 && b[..3] == [0, 0, 1];+ if sc4 || sc3 {+ let nal = b[if sc4 { 4 } else { 3 }];+ if nal & 0x80 == 0 && matches!(nal & 0x1F, 1 | 5 | 6 | 7 | 8 | 9) {+ return Some(Codec::Avc { intra: false });+ }+ }+ None+}++/// Picture descriptor properties (ST 377-1 generic picture / CDCI / RGBA descriptors).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct PictureInfo {+ pub stored_width: u32,+ pub stored_height: u32,+ pub display_width: u32,+ pub display_height: u32,+ /// 0 full frame, 1 separate fields, 2 single field, 3 mixed fields, 4 segmented frame.+ pub frame_layout: u8,+ /// Display aspect ratio of the whole image.+ pub aspect_ratio: Rational,+ pub component_depth: u32,+ pub horizontal_subsampling: u32,+ pub vertical_subsampling: u32,+ pub black_ref_level: Option<u32>,+ pub white_ref_level: Option<u32>,+ pub alpha_depth: u32,+ /// RGBA descriptor (pixel layout present).+ pub rgba: bool,+ pub picture_coding: Option<Ul>,+ pub transfer_characteristic: Option<Ul>,+ pub coding_equations: Option<Ul>,+ pub color_primaries: Option<Ul>,+}++impl PictureInfo {+ /// Frame height: field-based layouts code the height of one field.+ pub fn frame_height(&self) -> u32 {+ let h = if self.display_height > 0 { self.display_height } else { self.stored_height };+ if matches!(self.frame_layout, 1 | 3) { h * 2 } else { h }+ }+ pub fn frame_width(&self) -> u32 {+ if self.display_width > 0 { self.display_width } else { self.stored_width }+ }+ /// Full-range coding (black at 0 and white at the maximum code value).+ pub fn full_range(&self) -> bool {+ let d = self.component_depth;+ d > 0 && self.black_ref_level == Some(0) && self.white_ref_level == Some((1u32 << d.min(31)) - 1)+ }+}++/// PCM layout of a sound track.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SoundFormat {+ /// Interleaved little-endian samples (`bits` per sample, `block_align` bytes per frame).+ Pcm,+ /// ST 331 8-channel AES3 element data (4-byte header, 8 × 32-bit sub-frames per sample).+ Aes3Element,+ /// A coding we do not decode.+ Other,+}++/// Sound descriptor properties (ST 377-1 generic sound descriptor, ST 382 wave / AES3).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct SoundInfo {+ pub sample_rate: Rational,+ pub channels: u32,+ pub bits: u32,+ pub block_align: u32,+ pub locked: Option<bool>,+ pub sound_coding: Option<Ul>,+}++impl SoundInfo {+ /// Bytes per sample frame of plain PCM.+ pub fn frame_bytes(&self) -> usize {+ if self.block_align > 0 { self.block_align as usize } else { self.channels.max(1) as usize * (self.bits as usize).div_ceil(8).max(1) }+ }+}++/// Number of sample frames in a ST 331 AES3 element (from its header; 0 if too short).+pub fn aes3_element_samples(v: &[u8]) -> usize {+ if v.len() < 4 {+ return 0;+ }+ let declared = u16::from_le_bytes([v[1], v[2]]) as usize;+ declared.min((v.len() - 4) / 32)+}++/// Decode PCM chunk bytes into planar f32 (`channels` channels).+///+/// `Pcm`: interleaved little-endian signed integers of `bits` (8-bit is unsigned, per WAVE),+/// `frame_bytes` per sample frame. `Aes3Element`: the 24-bit sample of each ST 331 sub-frame+/// (bits 4-27 of the little-endian 32-bit word), first `channels` of the 8 channels.+pub fn decode_pcm(v: &[u8], format: SoundFormat, channels: usize, bits: u32, frame_bytes: usize) -> Result<Vec<Vec<f32>>> {+ let ch = channels.max(1);+ match format {+ SoundFormat::Pcm => {+ let bps = (bits as usize).div_ceil(8);+ if bps == 0 || bps > 4 || frame_bytes < bps * ch {+ return Err(crate::Error::Unsupported(format!("{bits}-bit PCM with {frame_bytes}-byte frames")));+ }+ let n = v.len() / frame_bytes;+ let mut out = vec![Vec::with_capacity(n); ch];+ let scale = 1.0 / (1u64 << (8 * bps - 1)) as f32;+ for i in 0..n {+ let f = &v[i * frame_bytes..];+ for (c, o) in out.iter_mut().enumerate() {+ let s = &f[c * bps..c * bps + bps];+ let x = match bps {+ 1 => (s[0] as i32 - 128) << 24,+ 2 => i32::from_le_bytes([0, 0, s[0], s[1]]),+ 3 => i32::from_le_bytes([0, s[0], s[1], s[2]]),+ _ => i32::from_le_bytes([s[0], s[1], s[2], s[3]]),+ };+ o.push((x >> (32 - 8 * bps)) as f32 * scale);+ }+ }+ Ok(out)+ }+ SoundFormat::Aes3Element => {+ let n = aes3_element_samples(v);+ let mut out = vec![Vec::with_capacity(n); ch];+ for i in 0..n {+ for (c, o) in out.iter_mut().enumerate().take(8) {+ let p = 4 + (i * 8 + c) * 4;+ let w = u32::from_le_bytes([v[p], v[p + 1], v[p + 2], v[p + 3]]);+ let s = (((w >> 4) & 0xFF_FFFF) << 8) as i32 >> 8;+ o.push(s as f32 / 8_388_608.0);+ }+ }+ Ok(out)+ }+ SoundFormat::Other => Err(crate::Error::Unsupported("sound coding".into())),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ul(item: &[u8]) -> Ul {+ let mut b = [0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x0A, 0, 0, 0, 0, 0, 0, 0, 0];+ b[8..8 + item.len()].copy_from_slice(item);+ Ul(b)+ }++ #[test]+ fn identifies_picture_codings() {+ assert_eq!(identify_picture(Some(ul(&[4, 1, 2, 2, 1, 0x31, 0x40, 1])), None, false), Codec::Avc { intra: false });+ assert_eq!(identify_picture(Some(ul(&[4, 1, 2, 2, 1, 0x32, 0x21, 1])), None, false), Codec::Avc { intra: true });+ assert_eq!(identify_picture(Some(ul(&[4, 1, 2, 2, 0x71, 0x11])), None, false), Codec::Vc3);+ assert_eq!(identify_picture(Some(ul(&[4, 1, 2, 2, 3, 6, 4])), None, false), Codec::ProRes { profile: Some(4) });+ assert_eq!(identify_picture(Some(ul(&[4, 1, 2, 2, 1, 1, 0x11])), None, true), Codec::Mpeg2);+ // container fallback+ assert_eq!(identify_picture(None, Some(ul(&[0x0D, 1, 3, 1, 2, 0x11, 1])), false), Codec::Vc3);+ assert_eq!(identify_picture(None, Some(ul(&[0x0D, 1, 3, 1, 2, 0x04, 0x60, 1])), true), Codec::Mpeg2);+ assert_eq!(identify_picture(None, None, false), Codec::Unknown);+ }++ #[test]+ fn sniffs_essence() {+ assert_eq!(sniff_picture(&[0, 0, 0, 1, 0x09, 0x10]), Some(Codec::Avc { intra: false }));+ assert_eq!(sniff_picture(&[0, 0, 1, 0xB3, 0]), Some(Codec::Mpeg2));+ assert_eq!(sniff_picture(&[0, 0, 2, 0x80, 1]), Some(Codec::Vc3));+ assert_eq!(sniff_picture(&[0, 0, 0, 9, b'i', b'c', b'p', b'f']), Some(Codec::ProRes { profile: None }));+ assert_eq!(sniff_picture(&[1, 2, 3]), None);+ }++ #[test]+ fn decodes_pcm_and_aes3() {+ let v = [0x00, 0x80, 0xFF, 0x7F, 0x01, 0x00, 0x00, 0x00];+ let p = decode_pcm(&v, SoundFormat::Pcm, 2, 16, 4).unwrap();+ assert_eq!(p[0], vec![-1.0, 1.0 / 32768.0]);+ assert_eq!(p[1], vec![32767.0 / 32768.0, 0.0]);+ let v24 = [0x00, 0x00, 0x80, 0xFF, 0xFF, 0x7F];+ let p = decode_pcm(&v24, SoundFormat::Pcm, 1, 24, 3).unwrap();+ assert_eq!(p[0], vec![-1.0, 8_388_607.0 / 8_388_608.0]);+ // one AES3 element: 1 sample, channel 0 = -1, channel 1 = 0.5+ let mut e = vec![0x00, 1, 0, 0xFF];+ for c in 0..8u32 {+ let s: i32 = match c {+ 0 => -8_388_608,+ 1 => 4_194_304,+ _ => 0,+ };+ let w = (((s as u32) & 0xFF_FFFF) << 4) | c;+ e.extend_from_slice(&w.to_le_bytes());+ }+ assert_eq!(aes3_element_samples(&e), 1);+ let p = decode_pcm(&e, SoundFormat::Aes3Element, 2, 24, 0).unwrap();+ assert_eq!(p, vec![vec![-1.0], vec![0.5]]);+ // truncated: no panic, no samples+ assert!(decode_pcm(&e[..10], SoundFormat::Aes3Element, 2, 24, 0).unwrap()[0].is_empty());+ }+}diff --git a/crates/mxf/src/file.rs b/crates/mxf/src/file.rsnew file mode 100644index 000000000..34ae62e0a--- /dev/null+++ b/crates/mxf/src/file.rs@@ -0,0 +1,1044 @@+//! Opening an MXF file: KLV walk, partitions, metadata resolution, sample tables.++use std::collections::HashMap;++use crate::essence::{Codec, PictureInfo, SoundFormat, SoundInfo, decode_pcm, identify_picture, sniff_picture};+use crate::index::{IndexEntry, IndexSegment};+use crate::klv::{KeyClass, Ul, ber_length, classify, find_header_partition};+use crate::meta::{Metadata, Primer, SUB_DESCRIPTORS_ITEM, Set, set_type as st, tag};+use crate::source::{ByteSource, read_upto};+use crate::{Error, Rational, Result};++/// Partition kinds (ST 377-1 §7).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PartitionKind {+ Header,+ Body,+ Footer,+}++/// A partition pack.+#[derive(Clone, Debug, PartialEq)]+pub struct Partition {+ /// File offset of the partition pack key.+ pub offset: u64,+ pub kind: PartitionKind,+ /// 1 open incomplete, 2 closed incomplete, 3 open complete, 4 closed complete.+ pub status: u8,+ pub major_version: u16,+ pub minor_version: u16,+ pub kag_size: u32,+ pub this_partition: u64,+ pub previous_partition: u64,+ pub footer_partition: u64,+ pub header_byte_count: u64,+ pub index_byte_count: u64,+ pub index_sid: u32,+ pub body_offset: u64,+ pub body_sid: u32,+ pub operational_pattern: Ul,+ pub essence_containers: Vec<Ul>,+ /// File offset of the first essence container KLV in this partition.+ pub essence_start: Option<u64>,+}++impl Partition {+ fn parse(offset: u64, kind: u8, status: u8, v: &[u8]) -> Option<Partition> {+ let mut c = crate::klv::Cur::new(v);+ let mut p = Partition {+ offset,+ kind: match kind {+ 2 => PartitionKind::Header,+ 3 => PartitionKind::Body,+ _ => PartitionKind::Footer,+ },+ status,+ major_version: c.u16()?,+ minor_version: c.u16()?,+ kag_size: c.u32()?,+ this_partition: c.u64()?,+ previous_partition: c.u64()?,+ footer_partition: c.u64()?,+ header_byte_count: c.u64()?,+ index_byte_count: c.u64()?,+ index_sid: c.u32()?,+ body_offset: c.u64()?,+ body_sid: c.u32()?,+ operational_pattern: c.ul()?,+ essence_containers: Vec::new(),+ essence_start: None,+ };+ let rest = &v[c.pos..];+ p.essence_containers = crate::klv::batch_of(rest).into_iter().filter_map(crate::klv::ul_of).collect();+ Some(p)+ }+ pub fn closed(&self) -> bool {+ self.status == 2 || self.status == 4+ }+ pub fn complete(&self) -> bool {+ self.status >= 3+ }+}++/// The operational pattern (ST 377-1 §5, ST 378, ST 390).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum OperationalPattern {+ /// Generalized OP: item complexity 1-3 (1 single item, 2 playlist, 3 edit), package+ /// complexity 1-3 (a single, b ganged, c alternate). OP1a = `Generalized { item: 1, package: 1 }`.+ Generalized {+ item: u8,+ package: u8,+ },+ /// OP-Atom (ST 390): one essence track per file.+ Atom,+ Unknown,+}++impl OperationalPattern {+ pub fn from_ul(ul: &Ul) -> Self {+ if !ul.is_smpte() || !ul.item_starts_with(&[0x0D, 0x01, 0x02, 0x01]) {+ return OperationalPattern::Unknown;+ }+ match (ul.0[12], ul.0[13]) {+ (0x10, _) => OperationalPattern::Atom,+ (i @ 1..=3, p @ 1..=3) => OperationalPattern::Generalized { item: i, package: p },+ _ => OperationalPattern::Unknown,+ }+ }+ pub fn name(&self) -> String {+ match self {+ OperationalPattern::Generalized { item, package } => format!("OP{item}{}", (b'a' + package - 1) as char),+ OperationalPattern::Atom => "OP-Atom".into(),+ OperationalPattern::Unknown => "OP?".into(),+ }+ }+}++/// A timecode component (ST 377-1 §B.?: StartTimecode in frames at RoundedTimecodeBase).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Timecode {+ /// Frame count of the first frame.+ pub start: i64,+ pub rounded_base: u16,+ pub drop_frame: bool,+}++impl Timecode {+ /// `HH:MM:SS:FF` (`;` before the frames when drop-frame).+ pub fn format(&self) -> String {+ let base = self.rounded_base.max(1) as i64;+ let mut f = self.start.max(0);+ if self.drop_frame && base % 30 == 0 {+ // SMPTE 12M drop-frame: skip 2 (4 at 60) frame numbers each minute except every tenth.+ let drop = 2 * base / 30;+ let per_10min = base * 600 - 9 * drop;+ let per_min = base * 60 - drop;+ let d = f / per_10min;+ let m = f % per_10min;+ f += 9 * drop * d + if m > drop { drop * ((m - drop) / per_min) } else { 0 };+ }+ let (hh, mm, ss, ff) = (f / (base * 3600), (f / (base * 60)) % 60, (f / base) % 60, f % base);+ format!("{hh:02}:{mm:02}:{ss:02}{}{ff:02}", if self.drop_frame { ';' } else { ':' })+ }+}++/// Essence track kinds (from the data definition label).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TrackKind {+ Picture,+ Sound,+ Data,+}++/// Frame wrapping (one element per edit unit) or clip wrapping (one element for the whole clip).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Wrapping {+ Frame,+ Clip,+}++/// One picture edit unit, in stored (decode) order.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Sample {+ /// File offset of the picture data.+ pub offset: u64,+ pub size: u32,+ /// Presentation position in edit units (stored position when the order is unknown).+ pub pts: i64,+ /// A decoder can start here.+ pub key: bool,+ /// The index marks this picture as bidirectionally predicted.+ pub b_picture: bool,+}++/// A run of sound sample frames stored contiguously.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Chunk {+ pub offset: u64,+ pub size: u64,+ /// Index of the chunk's first sample frame in the track.+ pub first_sample: u64,+ pub samples: u64,+}++/// A track of the file (source) package with essence in this file, as presented by the material+/// package.+#[derive(Clone, Debug)]+pub struct EssenceTrack {+ pub track_id: u32,+ pub track_number: u32,+ pub kind: TrackKind,+ pub name: Option<String>,+ /// Edit rate of the file package track.+ pub edit_rate: Rational,+ /// File package track origin (edit units of pre-charge before the zero point).+ pub origin: i64,+ /// Material package source clip start position (edit units after the origin).+ pub start_position: i64,+ /// Material package duration (edit units of `edit_rate`), when known.+ pub duration: Option<i64>,+ pub codec: Codec,+ pub wrapping: Wrapping,+ pub essence_container: Option<Ul>,+ pub picture: Option<PictureInfo>,+ pub sound: Option<SoundInfo>,+ pub sound_format: SoundFormat,+ pub body_sid: u32,+ pub index_sid: u32,+ /// Pictures in stored order.+ pub samples: Vec<Sample>,+ /// Display position → stored index (identity unless the index has temporal offsets).+ pub display_order: Vec<usize>,+ /// Sound data.+ pub chunks: Vec<Chunk>,+ /// The index carries temporal offsets (exact presentation order).+ pub temporal_offsets: bool,+ /// The index marks bidirectionally predicted pictures but has no temporal offsets: the+ /// presentation order must come from the bitstream.+ pub needs_reorder: bool,+ /// Random-access flags came from an index table.+ pub indexed: bool,+}++impl EssenceTrack {+ /// First presented edit unit (stored position of the material package's zero point).+ pub fn first_edit_unit(&self) -> i64 {+ (self.origin + self.start_position).max(0)+ }+ /// Total sound sample frames stored.+ pub fn stored_sample_frames(&self) -> u64 {+ self.chunks.last().map_or(0, |c| c.first_sample + c.samples)+ }+ /// Sound sample frames per edit unit (rational), e.g. 48000/25.+ pub fn samples_per_edit_unit(&self) -> (i64, i64) {+ let sr = self.sound.as_ref().map(|s| s.sample_rate).unwrap_or_default();+ let er = self.edit_rate;+ if !sr.is_valid() || !er.is_valid() {+ return (1, 1);+ }+ (sr.num as i64 * er.den as i64, sr.den as i64 * er.num as i64)+ }+ /// Nearest random-access sample at or before stored index `i`.+ pub fn sync_before(&self, i: usize) -> usize {+ let i = i.min(self.samples.len().saturating_sub(1));+ (0..=i).rev().find(|&k| self.samples[k].key).unwrap_or(0)+ }+ /// The stored sample presented at display position `d`.+ pub fn sample_at(&self, d: i64) -> Option<usize> {+ if d < 0 {+ return None;+ }+ self.display_order.get(d as usize).copied()+ }+}++/// An opened MXF file.+#[derive(Clone, Debug)]+pub struct MxfFile {+ /// Bytes before the header partition pack.+ pub run_in: u64,+ pub operational_pattern: OperationalPattern,+ pub operational_pattern_label: Ul,+ pub partitions: Vec<Partition>,+ pub index_segments: Vec<IndexSegment>,+ pub tracks: Vec<EssenceTrack>,+ /// Start timecode of the material package (file package when the material package has none).+ pub timecode: Option<Timecode>,+ pub material_package_name: Option<String>,+ pub product_name: Option<String>,+ pub company_name: Option<String>,+ /// Index of the partition whose header metadata was used.+ pub metadata_partition: usize,+ /// Problems recovered from (truncation, unresolved references…).+ pub warnings: Vec<String>,+ pub file_size: u64,+}++/// An essence element found by the KLV walk.+#[derive(Clone, Copy, Debug)]+struct Element {+ key: Ul,+ value_offset: u64,+ size: u64,+ /// Cut short by the end of the file.+ truncated: bool,+}++struct WalkResult {+ run_in: u64,+ partitions: Vec<Partition>,+ /// Header metadata per partition index: (primer, sets as (key, value)).+ metadata: Vec<(usize, Primer, Vec<(Ul, Vec<u8>)>)>,+ index: Vec<IndexSegment>,+ elements: Vec<Element>,+ warnings: Vec<String>,+}++/// Values larger than this are never read while opening (metadata and index values are small).+const MAX_META_VALUE: u64 = 64 << 20;++/// Buffered reads of KLV headers.+struct Window<'a, S: ByteSource + ?Sized> {+ src: &'a S,+ off: u64,+ buf: Vec<u8>,+}++impl<S: ByteSource + ?Sized> Window<'_, S> {+ fn get(&mut self, at: u64, n: usize) -> std::io::Result<&[u8]> {+ let have = at >= self.off && at + n as u64 <= self.off + self.buf.len() as u64;+ if !have {+ self.buf = read_upto(self.src, at, n.max(64 * 1024))?;+ self.off = at;+ }+ let a = (at - self.off) as usize;+ Ok(&self.buf[a..(a + n).min(self.buf.len())])+ }+}++fn walk(src: &(impl ByteSource + ?Sized)) -> Result<WalkResult> {+ let len = src.len();+ let head = read_upto(src, 0, 65_536 + 32)?;+ let run_in = find_header_partition(&head).ok_or_else(|| Error::NotMxf("no header partition pack".into()))? as u64;+ let mut w = WalkResult { run_in, partitions: Vec::new(), metadata: Vec::new(), index: Vec::new(), elements: Vec::new(), warnings: Vec::new() };+ let mut win = Window { src, off: 0, buf: Vec::new() };+ let mut pos = run_in;+ let mut cur_meta: Option<usize> = None;+ while pos + 17 <= len {+ let hdr = win.get(pos, 25)?.to_vec();+ let key = Ul(hdr[..16].try_into().unwrap_or([0; 16]));+ if !key.is_smpte() {+ // Lost sync (corrupt data): look for the next partition pack.+ match resync(src, pos + 1, len)? {+ Some(p) => {+ w.warnings.push(format!("lost KLV sync at byte {pos}; resumed at {p}"));+ pos = p;+ continue;+ }+ None => {+ w.warnings.push(format!("lost KLV sync at byte {pos}"));+ break;+ }+ }+ }+ let Some((vlen, n)) = ber_length(&hdr[16..]) else {+ w.warnings.push(format!("bad KLV length at byte {pos}"));+ break;+ };+ let vstart = pos + 16 + n as u64;+ let Some(vend) = vstart.checked_add(vlen) else { break };+ let class = classify(&key);+ if vend > len {+ w.warnings.push(format!("file truncated: KLV at byte {pos} needs {} bytes, {} left", vlen, len.saturating_sub(vstart)));+ if class == KeyClass::Essence && vstart < len && len - vstart > 0 && is_essence_item(&key) {+ // keep a truncated clip-wrapped element's whole edit units+ w.elements.push(Element { key, value_offset: vstart, size: len - vstart, truncated: true });+ }+ break;+ }+ let read_value = || -> Result<Vec<u8>> {+ if vlen > MAX_META_VALUE {+ return Err(Error::Invalid(format!("metadata value of {vlen} bytes at {pos}")));+ }+ Ok(read_upto(src, vstart, vlen as usize)?)+ };+ match class {+ KeyClass::Partition { kind, status } => {+ let v = read_value()?;+ match Partition::parse(pos, kind, status, &v) {+ Some(p) => w.partitions.push(p),+ None => w.warnings.push(format!("short partition pack at byte {pos}")),+ }+ cur_meta = None;+ }+ KeyClass::Primer => {+ let v = read_value()?;+ if let Some(pi) = w.partitions.len().checked_sub(1) {+ w.metadata.push((pi, Primer::parse(&v), Vec::new()));+ cur_meta = Some(w.metadata.len() - 1);+ }+ }+ KeyClass::LocalSet => {+ if let Some(m) = cur_meta {+ let v = read_value()?;+ w.metadata[m].2.push((key, v));+ }+ }+ KeyClass::IndexSegment => {+ let v = read_value()?;+ w.index.push(IndexSegment::parse(&v));+ cur_meta = None;+ }+ KeyClass::Essence => {+ cur_meta = None;+ if let Some(p) = w.partitions.last_mut()+ && p.essence_start.is_none()+ {+ p.essence_start = Some(pos);+ }+ if is_essence_item(&key) {+ w.elements.push(Element { key, value_offset: vstart, size: vlen, truncated: false });+ }+ }+ KeyClass::Fill | KeyClass::RandomIndexPack | KeyClass::Other => {}+ }+ pos = vend;+ }+ if w.partitions.is_empty() {+ return Err(Error::NotMxf("no readable partition pack".into()));+ }+ Ok(w)+}++/// Generic container picture / sound / data / compound items (not system items).+fn is_essence_item(k: &Ul) -> bool {+ matches!(k.0[12], 0x05 | 0x06 | 0x07 | 0x15 | 0x16 | 0x17 | 0x18)+}++/// The next partition pack key at or after `from` (scans at most 16 MiB).+fn resync(src: &(impl ByteSource + ?Sized), from: u64, len: u64) -> Result<Option<u64>> {+ let mut at = from;+ let end = len.min(from + (16 << 20));+ while at < end {+ let chunk = read_upto(src, at, 1 << 20)?;+ if chunk.len() < 16 {+ break;+ }+ for i in 0..=chunk.len() - 16 {+ if chunk[i..i + 13] == crate::klv::PARTITION_PREFIX && (2..=4).contains(&chunk[i + 13]) {+ return Ok(Some(at + i as u64));+ }+ }+ at += (chunk.len() - 15) as u64;+ }+ Ok(None)+}++/// Data definition labels (ST 377-1 Annex / RP 224): 06 0E 2B 34 04 01 01 01 01 03 02 kk tt 00 00 00.+fn track_kind_of(def: Option<Ul>) -> Option<(bool, TrackKind)> {+ let d = def?;+ if !d.item_starts_with(&[0x01, 0x03, 0x02]) {+ return None;+ }+ match (d.0[11], d.0[12]) {+ (0x01, _) => Some((true, TrackKind::Data)),+ (0x02, 0x01) => Some((false, TrackKind::Picture)),+ (0x02, 0x02) => Some((false, TrackKind::Sound)),+ _ => Some((false, TrackKind::Data)),+ }+}++/// The structural components of a track's sequence (or the component itself).+fn components<'a>(md: &'a Metadata, track: &Set) -> (Option<&'a Set>, Vec<&'a Set>) {+ let Some(seq) = track.reference(tag::TRACK_SEQUENCE).and_then(|r| md.get(&r)) else { return (None, Vec::new()) };+ if seq.kind() == Some(st::SEQUENCE) {+ (Some(seq), seq.references(tag::STRUCTURAL_COMPONENTS).iter().filter_map(|r| md.get(r)).collect())+ } else {+ (Some(seq), vec![seq])+ }+}++fn timecode_of(c: &Set) -> Option<Timecode> {+ Some(Timecode {+ start: c.i(tag::START_TIMECODE)?,+ rounded_base: c.u(tag::ROUNDED_TIMECODE_BASE).unwrap_or(0) as u16,+ drop_frame: c.u(tag::DROP_FRAME).unwrap_or(0) != 0,+ })+}++/// The first timecode component of a package's timecode tracks.+fn package_timecode(md: &Metadata, pkg: &Set) -> Option<Timecode> {+ for r in pkg.references(tag::PACKAGE_TRACKS) {+ let Some(t) = md.get(&r) else { continue };+ let (_, comps) = components(md, t);+ if let Some(tc) = comps.iter().filter(|c| c.kind() == Some(st::TIMECODE_COMPONENT)).find_map(|c| timecode_of(c)) {+ return Some(tc);+ }+ }+ None+}++/// The descriptor of file package track `track_id`: the package descriptor, or the matching+/// sub-descriptor of a multiple descriptor.+fn descriptor_for<'a>(md: &'a Metadata, pkg: &Set, track_id: u32, kind: TrackKind) -> Option<&'a Set> {+ let d = md.get(&pkg.reference(tag::SOURCE_PACKAGE_DESCRIPTOR)?)?;+ if d.kind() != Some(st::MULTIPLE_DESCRIPTOR) {+ return Some(d);+ }+ let subs: Vec<&Set> = d.references(tag::SUB_DESCRIPTORS).iter().filter_map(|r| md.get(r)).collect();+ subs.iter().find(|s| s.u(tag::LINKED_TRACK_ID) == Some(track_id as i64)).or_else(|| subs.iter().find(|s| descriptor_kind(s) == Some(kind))).copied()+}++fn descriptor_kind(s: &Set) -> Option<TrackKind> {+ match s.kind()? {+ st::GENERIC_PICTURE_DESCRIPTOR | st::CDCI_DESCRIPTOR | st::RGBA_DESCRIPTOR | st::MPEG2_VIDEO_DESCRIPTOR => Some(TrackKind::Picture),+ st::GENERIC_SOUND_DESCRIPTOR | st::AES3_DESCRIPTOR | st::WAVE_DESCRIPTOR => Some(TrackKind::Sound),+ st::GENERIC_DATA_DESCRIPTOR => Some(TrackKind::Data),+ _ => None,+ }+}++fn picture_info(d: &Set) -> PictureInfo {+ let u = |t| d.u(t).unwrap_or(0) as u32;+ PictureInfo {+ stored_width: u(tag::STORED_WIDTH),+ stored_height: u(tag::STORED_HEIGHT),+ display_width: u(tag::DISPLAY_WIDTH),+ display_height: u(tag::DISPLAY_HEIGHT),+ frame_layout: u(tag::FRAME_LAYOUT) as u8,+ aspect_ratio: d.rational(tag::ASPECT_RATIO).unwrap_or_default(),+ component_depth: u(tag::COMPONENT_DEPTH),+ horizontal_subsampling: u(tag::HORIZONTAL_SUBSAMPLING),+ vertical_subsampling: u(tag::VERTICAL_SUBSAMPLING),+ black_ref_level: d.u(tag::BLACK_REF_LEVEL).map(|v| v as u32),+ white_ref_level: d.u(tag::WHITE_REF_LEVEL).map(|v| v as u32),+ alpha_depth: u(tag::ALPHA_SAMPLE_DEPTH),+ rgba: d.kind() == Some(st::RGBA_DESCRIPTOR),+ picture_coding: d.ul(tag::PICTURE_ESSENCE_CODING),+ transfer_characteristic: d.ul(tag::TRANSFER_CHARACTERISTIC),+ coding_equations: d.ul(tag::CODING_EQUATIONS),+ color_primaries: d.ul(tag::COLOR_PRIMARIES),+ }+}++fn sound_info(d: &Set) -> SoundInfo {+ SoundInfo {+ sample_rate: d.rational(tag::AUDIO_SAMPLING_RATE).filter(Rational::is_valid).or_else(|| d.rational(tag::SAMPLE_RATE)).unwrap_or_default(),+ channels: d.u(tag::CHANNEL_COUNT).unwrap_or(1) as u32,+ bits: d.u(tag::QUANTIZATION_BITS).unwrap_or(16) as u32,+ block_align: d.u(tag::BLOCK_ALIGN).unwrap_or(0) as u32,+ locked: d.u(tag::LOCKED).map(|v| v != 0),+ sound_coding: d.ul(tag::SOUND_ESSENCE_CODING),+ }+}++/// Resolved track before the sample tables are built.+struct TrackRef {+ track_id: u32,+ track_number: u32,+ kind: TrackKind,+ name: Option<String>,+ edit_rate: Rational,+ origin: i64,+ start_position: i64,+ duration: Option<i64>,+ descriptor: Option<Set>,+ sub_descriptors: Vec<Set>,+ body_sid: u32,+ index_sid: u32,+}++fn umid_of(s: &Set, t: u16) -> Option<[u8; 32]> {+ s.get(t).and_then(|v| v.get(..32)).map(|b| b.try_into().unwrap_or([0; 32]))+}++/// Material package tracks → file package tracks with descriptors.+fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>, Option<Timecode>, Option<String>) {+ let sources: Vec<&Set> = md.of_kind(st::SOURCE_PACKAGE).collect();+ let file_pkg = |umid: &[u8; 32]| sources.iter().find(|p| umid_of(p, tag::PACKAGE_UID).as_ref() == Some(umid)).copied();+ // EssenceContainerData: package → (body SID, index SID)+ let mut sids: HashMap<[u8; 32], (u32, u32)> = HashMap::new();+ for e in md.of_kind(st::ESSENCE_CONTAINER_DATA) {+ if let Some(u) = umid_of(e, tag::ESSENCE_CONTAINER_DATA_LINKED_PACKAGE) {+ sids.insert(u, (e.u(tag::BODY_SID).unwrap_or(0) as u32, e.u(tag::INDEX_SID).unwrap_or(0) as u32));+ }+ }+ let material = md.of_kind(st::MATERIAL_PACKAGE).next();+ let mut out = Vec::new();+ let mut timecode = material.and_then(|m| package_timecode(md, m));+ let name = material.and_then(|m| m.string(tag::PACKAGE_NAME));+ let file_track = |pkg: &Set, kind: Option<TrackKind>, id: Option<u32>, start: i64, duration: Option<i64>, name: Option<String>| -> Option<TrackRef> {+ let umid = umid_of(pkg, tag::PACKAGE_UID).unwrap_or([0; 32]);+ for r in pkg.references(tag::PACKAGE_TRACKS) {+ let Some(t) = md.get(&r) else { continue };+ let tid = t.u(tag::TRACK_ID).unwrap_or(0) as u32;+ if id.is_some_and(|i| i != tid) {+ continue;+ }+ let (seq, _) = components(md, t);+ let k = track_kind_of(seq.and_then(|s| s.ul(tag::DATA_DEFINITION)));+ let tk = match (k, kind) {+ (Some((false, k)), _) => k,+ (_, Some(k)) => k,+ _ => continue,+ };+ if tk == TrackKind::Data && k.is_some_and(|(tc, _)| tc) {+ continue;+ }+ let desc = descriptor_for(md, pkg, tid, tk);+ let subs: Vec<Set> = desc+ .and_then(|d| d.dynamic_item(&SUB_DESCRIPTORS_ITEM))+ .map(|v| {+ crate::klv::batch_of(v).into_iter().filter_map(|b| b.get(..16)).filter_map(|b| md.get(&b.try_into().unwrap_or([0; 16]))).cloned().collect()+ })+ .unwrap_or_default();+ let (body_sid, index_sid) = sids.get(&umid).copied().unwrap_or((0, 0));+ return Some(TrackRef {+ track_id: tid,+ track_number: t.u(tag::TRACK_NUMBER).unwrap_or(0) as u32,+ kind: tk,+ name: name.clone().or_else(|| t.string(tag::TRACK_NAME)),+ edit_rate: t.rational(tag::EDIT_RATE).unwrap_or_default(),+ origin: t.i(tag::ORIGIN).unwrap_or(0),+ start_position: start,+ duration,+ descriptor: desc.cloned(),+ sub_descriptors: subs,+ body_sid,+ index_sid,+ });+ }+ None+ };+ if let Some(m) = material {+ for r in m.references(tag::PACKAGE_TRACKS) {+ let Some(t) = md.get(&r) else { continue };+ let (seq, comps) = components(md, t);+ let Some((false, kind)) = track_kind_of(seq.and_then(|s| s.ul(tag::DATA_DEFINITION))) else { continue };+ if kind == TrackKind::Data {+ continue;+ }+ let Some(clip) = comps.iter().find(|c| c.kind() == Some(st::SOURCE_CLIP)) else { continue };+ let Some(umid) = umid_of(clip, tag::SOURCE_PACKAGE_ID) else { continue };+ let Some(pkg) = file_pkg(&umid) else {+ warnings.push(format!("material track {} refers to a package not in this file", t.u(tag::TRACK_ID).unwrap_or(0)));+ continue;+ };+ let src_track = clip.u(tag::SOURCE_TRACK_ID).map(|v| v as u32);+ let duration = clip.i(tag::DURATION).or_else(|| seq.and_then(|s| s.i(tag::DURATION))).filter(|d| *d >= 0);+ // durations are in the material track's edit rate; convert when the file track's differs+ let mrate = t.rational(tag::EDIT_RATE).unwrap_or_default();+ if let Some(mut tr) = file_track(pkg, Some(kind), src_track, clip.i(tag::START_POSITION).unwrap_or(0), duration, t.string(tag::TRACK_NAME)) {+ if mrate.is_valid() && tr.edit_rate.is_valid() && mrate != tr.edit_rate {+ let conv = |v: i64| (v as i128 * tr.edit_rate.num as i128 * mrate.den as i128 / (tr.edit_rate.den as i128 * mrate.num as i128)) as i64;+ tr.duration = tr.duration.map(conv);+ tr.start_position = conv(tr.start_position);+ }+ if timecode.is_none() {+ timecode = package_timecode(md, pkg);+ }+ if !out.iter().any(|o: &TrackRef| o.track_id == tr.track_id && o.track_number == tr.track_number) {+ out.push(tr);+ }+ }+ }+ }+ if out.is_empty() {+ // No usable material package: present the file packages' essence tracks directly.+ for pkg in &sources {+ if pkg.reference(tag::SOURCE_PACKAGE_DESCRIPTOR).is_none() {+ continue;+ }+ for r in pkg.references(tag::PACKAGE_TRACKS) {+ let Some(t) = md.get(&r) else { continue };+ let id = t.u(tag::TRACK_ID).unwrap_or(0) as u32;+ if let Some(tr) = file_track(pkg, None, Some(id), 0, None, None) {+ out.push(tr);+ }+ }+ if timecode.is_none() {+ timecode = package_timecode(md, pkg);+ }+ }+ }+ (out, timecode, name)+}++/// Open an MXF file: walk the KLV structure and resolve the essence tracks.+pub fn open(src: &(impl ByteSource + ?Sized)) -> Result<MxfFile> {+ let w = walk(src)?;+ let mut warnings = w.warnings;+ // Metadata of the most complete partition (closed complete > open complete > closed > open;+ // later partitions win ties: the footer has the final durations).+ let best = w+ .metadata+ .iter()+ .enumerate()+ .filter(|(_, m)| !m.2.is_empty())+ .max_by_key(|(_, m)| {+ let p = &w.partitions[m.0];+ (p.complete(), p.closed(), p.offset)+ })+ .map(|(i, _)| i);+ let Some(best) = best else { return Err(Error::Invalid("no header metadata".into())) };+ let (meta_partition, primer, sets) = &w.metadata[best];+ let mut md = Metadata::default();+ for (k, v) in sets {+ md.push(Set::parse(*k, v, primer));+ }+ let preface = md.of_kind(st::PREFACE).next();+ let op_label = preface.and_then(|p| p.ul(tag::OPERATIONAL_PATTERN)).unwrap_or(w.partitions[0].operational_pattern);+ let ident = md.of_kind(st::IDENTIFICATION).last();+ let product_name = ident.and_then(|i| i.string(tag::PRODUCT_NAME));+ let company_name = ident.and_then(|i| i.string(tag::COMPANY_NAME));+ let (refs, timecode, material_name) = resolve_tracks(&md, &mut warnings);+ if refs.is_empty() {+ return Err(Error::Invalid("no essence tracks in the header metadata".into()));+ }+ let mut tracks = Vec::new();+ let mut claimed: Vec<[u8; 4]> = Vec::new();+ let all_numbers: Vec<[u8; 4]> = {+ let mut v: Vec<[u8; 4]> = w.elements.iter().map(|e| e.key.0[12..16].try_into().unwrap_or([0; 4])).collect();+ v.dedup();+ v.sort_unstable();+ v.dedup();+ v+ };+ for r in &refs {+ let number = r.track_number.to_be_bytes();+ let mut key4 = all_numbers.iter().find(|n| **n == number).copied();+ if key4.is_none() {+ // Track number missing or not matching (some OP-Atom writers): the only unclaimed+ // element stream of the right kind.+ let kind_items: &[u8] = match r.kind {+ TrackKind::Picture => &[0x05, 0x15],+ TrackKind::Sound => &[0x06, 0x16],+ TrackKind::Data => &[0x07, 0x17],+ };+ let cands: Vec<[u8; 4]> = all_numbers.iter().filter(|n| kind_items.contains(&n[0]) && !claimed.contains(n)).copied().collect();+ if cands.len() == 1 {+ key4 = Some(cands[0]);+ }+ }+ let Some(key4) = key4 else {+ warnings.push(format!("no essence in this file for track {} (number {:08x})", r.track_id, r.track_number));+ continue;+ };+ claimed.push(key4);+ let elements: Vec<Element> = w.elements.iter().filter(|e| e.key.0[12..16] == key4).copied().collect();+ tracks.push(build_track(src, r, &elements, key4, &w.index, &mut warnings)?);+ }+ if tracks.is_empty() {+ return Err(Error::Unsupported("no essence of the material package is stored in this file".into()));+ }+ Ok(MxfFile {+ run_in: w.run_in,+ operational_pattern: OperationalPattern::from_ul(&op_label),+ operational_pattern_label: op_label,+ index_segments: w.index,+ partitions: w.partitions.clone(),+ tracks,+ timecode,+ material_package_name: material_name,+ product_name,+ company_name,+ metadata_partition: *meta_partition,+ warnings,+ file_size: src.len(),+ })+}++/// Index entries per stored edit unit for an index SID (all segments when `sid` is 0 or unmatched).+fn index_entries(index: &[IndexSegment], sid: u32) -> (Vec<Option<IndexEntry>>, u32) {+ let any = index.iter().any(|s| s.index_sid == sid);+ let segs: Vec<&IndexSegment> = index.iter().filter(|s| !any || s.index_sid == sid).collect();+ let mut out: Vec<Option<IndexEntry>> = Vec::new();+ let mut eubc = 0;+ for s in segs {+ if s.edit_unit_byte_count > 0 {+ eubc = s.edit_unit_byte_count;+ }+ for (k, e) in s.entries.iter().enumerate() {+ let Ok(p) = usize::try_from(s.start_position + k as i64) else { continue };+ if p > 50_000_000 {+ break;+ }+ if out.len() <= p {+ out.resize(p + 1, None);+ }+ out[p] = Some(*e);+ }+ }+ (out, eubc)+}++fn build_track(+ src: &(impl ByteSource + ?Sized),+ r: &TrackRef,+ elements: &[Element],+ key4: [u8; 4],+ index: &[IndexSegment],+ warnings: &mut Vec<String>,+) -> Result<EssenceTrack> {+ let desc = r.descriptor.as_ref();+ let container = desc.and_then(|d| d.ul(tag::ESSENCE_CONTAINER));+ let mut t = EssenceTrack {+ track_id: r.track_id,+ track_number: u32::from_be_bytes(key4),+ kind: r.kind,+ name: r.name.clone(),+ edit_rate: r.edit_rate,+ origin: r.origin,+ start_position: r.start_position,+ duration: r.duration,+ codec: Codec::Unknown,+ wrapping: Wrapping::Frame,+ essence_container: container,+ picture: None,+ sound: None,+ sound_format: SoundFormat::Other,+ body_sid: r.body_sid,+ index_sid: r.index_sid,+ samples: Vec::new(),+ display_order: Vec::new(),+ chunks: Vec::new(),+ temporal_offsets: false,+ needs_reorder: false,+ indexed: false,+ };+ match r.kind {+ TrackKind::Picture => {+ let pi = desc.map(picture_info).unwrap_or_default();+ let mpeg_desc = desc.is_some_and(|d| d.kind() == Some(st::MPEG2_VIDEO_DESCRIPTOR));+ let mut codec = identify_picture(pi.picture_coding, container, mpeg_desc);+ if r.sub_descriptors.iter().any(|s| s.kind() == Some(st::AVC_SUBDESCRIPTOR)) && !matches!(codec, Codec::Avc { .. }) {+ codec = Codec::Avc { intra: false };+ }+ // A wrong or missing label: trust the essence bytes.+ if let Some(first) = elements.first() {+ let head = read_upto(src, first.value_offset, 64)?;+ if let Some(sniffed) = sniff_picture(&head) {+ let agree = std::mem::discriminant(&sniffed) == std::mem::discriminant(&codec);+ if !agree && !matches!(codec, Codec::Avc { intra: true }) {+ codec = sniffed;+ }+ }+ }+ t.codec = codec;+ t.picture = Some(pi);+ build_pictures(src, &mut t, elements, index, warnings)?;+ }+ TrackKind::Sound => {+ let si = desc.map(sound_info).unwrap_or(SoundInfo { channels: 1, bits: 16, ..Default::default() });+ let d10 = container.is_some_and(|c| c.item_starts_with(&[0x0D, 0x01, 0x03, 0x01, 0x02, 0x01]));+ let aes_element = d10 || key4[0] == 0x06 && key4[2] == 0x10;+ let pcm_desc = desc.is_some_and(|d| matches!(d.kind(), Some(st::AES3_DESCRIPTOR) | Some(st::WAVE_DESCRIPTOR)));+ let pcm_coding = si.sound_coding.is_none_or(|c| !c.is_smpte() || c.item_starts_with(&[0x04, 0x02, 0x02, 0x01]) || c.0 == [0; 16]);+ t.sound_format = if aes_element {+ SoundFormat::Aes3Element+ } else if pcm_desc || pcm_coding {+ SoundFormat::Pcm+ } else {+ SoundFormat::Other+ };+ t.codec = match t.sound_format {+ SoundFormat::Aes3Element => Codec::Aes3Element,+ SoundFormat::Pcm => Codec::Pcm,+ SoundFormat::Other => Codec::Unknown,+ };+ let fb = si.frame_bytes() as u64;+ let mut first = 0u64;+ for e in elements {+ let n = match t.sound_format {+ SoundFormat::Aes3Element => e.size.saturating_sub(4) / 32,+ _ => e.size / fb.max(1),+ };+ t.chunks.push(Chunk { offset: e.value_offset, size: e.size, first_sample: first, samples: n });+ first += n;+ }+ t.wrapping = if elements.len() == 1 && r.duration.is_some_and(|d| d > 1) { Wrapping::Clip } else { Wrapping::Frame };+ t.sound = Some(si);+ }+ TrackKind::Data => {}+ }+ Ok(t)+}++fn build_pictures(+ src: &(impl ByteSource + ?Sized),+ t: &mut EssenceTrack,+ elements: &[Element],+ index: &[IndexSegment],+ warnings: &mut Vec<String>,+) -> Result<()> {+ let (entries, eubc) = index_entries(index, t.index_sid);+ let expected = t.duration.map(|d| (d + t.first_edit_unit()).max(0) as usize);+ let clip = elements.len() == 1 && expected.is_none_or(|n| n > 1) && (eubc > 0 || entries.len() > 1);+ let mut samples: Vec<Sample> = Vec::new();+ if clip {+ t.wrapping = Wrapping::Clip;+ let e = elements[0];+ if eubc > 0 {+ let n = e.size / eubc as u64;+ for i in 0..n {+ samples.push(Sample { offset: e.value_offset + i * eubc as u64, size: eubc, pts: i as i64, key: true, b_picture: false });+ }+ } else {+ let offs: Vec<u64> = entries.iter().map_while(|x| x.map(|x| x.stream_offset)).collect();+ let base = offs.first().copied().unwrap_or(0);+ for (i, o) in offs.iter().enumerate() {+ let start = o - base.min(*o);+ let end = offs.get(i + 1).map_or(e.size, |n| n - base.min(*n)).min(e.size);+ if end <= start {+ break;+ }+ samples.push(Sample { offset: e.value_offset + start, size: (end - start) as u32, pts: i as i64, key: true, b_picture: false });+ }+ }+ } else {+ for (i, e) in elements.iter().filter(|e| !e.truncated).enumerate() {+ samples.push(Sample { offset: e.value_offset, size: e.size.min(u32::MAX as u64) as u32, pts: i as i64, key: true, b_picture: false });+ }+ }+ let n = samples.len();+ // Key frames and B pictures from the index.+ let flagged = entries.iter().flatten().any(|e| e.random_access());+ if !t.codec.intra_only() {+ if flagged {+ t.indexed = true;+ for (i, s) in samples.iter_mut().enumerate() {+ let e = entries.get(i).copied().flatten();+ s.key = e.is_some_and(|e| e.random_access()) || i == 0;+ s.b_picture = e.is_some_and(|e| e.is_b());+ }+ } else {+ // No index flags: find the random-access pictures in the bitstream.+ if !samples.is_empty() {+ warnings.push("no index table with random-access flags: key frames found by scanning the essence".into());+ }+ for (i, s) in samples.iter_mut().enumerate() {+ let head = read_upto(src, s.offset, (s.size as usize).min(1024))?;+ s.key = i == 0 || is_random_access(t.codec, &head);+ }+ }+ }+ // Presentation order from the temporal offsets: display d is stored at d + TO[d].+ let mut display: Vec<usize> = (0..n).collect();+ let has_to = entries.iter().take(n).flatten().any(|e| e.temporal_offset != 0);+ if has_to {+ let mut pts = vec![i64::MIN; n];+ let mut ok = true;+ for d in 0..n {+ let to = entries.get(d).copied().flatten().map_or(0, |e| e.temporal_offset as i64);+ let s = d as i64 + to;+ if s < 0 || s >= n as i64 || pts[s as usize] != i64::MIN {+ ok = false;+ break;+ }+ pts[s as usize] = d as i64;+ display[d] = s as usize;+ }+ if ok {+ t.temporal_offsets = true;+ for (s, p) in samples.iter_mut().zip(pts) {+ s.pts = p;+ }+ } else {+ warnings.push("inconsistent index temporal offsets: using stored order".into());+ display = (0..n).collect();+ }+ } else {+ t.needs_reorder = samples.iter().any(|s| s.b_picture);+ }+ t.samples = samples;+ t.display_order = display;+ Ok(())+}++/// Whether a picture can start decoding (no index): AVC IDR / recovery point, MPEG-2 sequence+/// header + I picture; other codecs: always.+fn is_random_access(codec: Codec, head: &[u8]) -> bool {+ match codec {+ Codec::Avc { .. } => {+ let mut i = 0;+ while i + 3 < head.len() {+ if head[i] == 0 && head[i + 1] == 0 && head[i + 2] == 1 {+ let t = head[i + 3] & 0x1F;+ if t == 5 {+ return true;+ }+ if t == 1 {+ return false;+ }+ i += 3;+ } else {+ i += 1;+ }+ }+ false+ }+ Codec::Mpeg2 => head.windows(4).any(|w| w == [0, 0, 1, 0xB3]),+ _ => true,+ }+}++impl MxfFile {+ /// The first track of a kind.+ pub fn track_of_kind(&self, kind: TrackKind) -> Option<usize> {+ self.tracks.iter().position(|t| t.kind == kind && (!t.samples.is_empty() || !t.chunks.is_empty()))+ }++ /// The bytes of picture sample `i` (stored order) of track `track`.+ pub fn read_sample(&self, src: &(impl ByteSource + ?Sized), track: usize, i: usize) -> Result<Vec<u8>> {+ let t = self.tracks.get(track).ok_or_else(|| Error::Invalid(format!("no track {track}")))?;+ let s = t.samples.get(i).ok_or_else(|| Error::Invalid(format!("no sample {i}")))?;+ let mut v = vec![0u8; s.size as usize];+ src.read_at(s.offset, &mut v)?;+ Ok(v)+ }++ /// `frames` sound sample frames from stored sample `start` of track `track`, planar f32+ /// (zero past the end of the essence).+ pub fn read_pcm(&self, src: &(impl ByteSource + ?Sized), track: usize, start: u64, frames: usize) -> Result<Vec<Vec<f32>>> {+ let t = self.tracks.get(track).ok_or_else(|| Error::Invalid(format!("no track {track}")))?;+ let si = t.sound.as_ref().ok_or_else(|| Error::Invalid("not a sound track".into()))?;+ let ch = si.channels.max(1) as usize;+ let mut out = vec![vec![0f32; frames]; ch];+ let end = start + frames as u64;+ let fb = si.frame_bytes();+ let mut ci = t.chunks.partition_point(|c| c.first_sample + c.samples <= start);+ while let Some(c) = t.chunks.get(ci) {+ if c.first_sample >= end {+ break;+ }+ let a = start.max(c.first_sample);+ let b = end.min(c.first_sample + c.samples);+ if b > a {+ let decoded = match t.sound_format {+ SoundFormat::Pcm => {+ let off = c.offset + (a - c.first_sample) * fb as u64;+ let mut v = vec![0u8; ((b - a) as usize) * fb];+ src.read_at(off, &mut v)?;+ decode_pcm(&v, SoundFormat::Pcm, ch, si.bits, fb)?+ }+ SoundFormat::Aes3Element => {+ let mut v = vec![0u8; c.size as usize];+ src.read_at(c.offset, &mut v)?;+ let all = decode_pcm(&v, SoundFormat::Aes3Element, ch, si.bits, 0)?;+ let s0 = (a - c.first_sample) as usize;+ all.into_iter().map(|p| p.get(s0..).map(<[f32]>::to_vec).unwrap_or_default()).collect()+ }+ SoundFormat::Other => return Err(Error::Unsupported("sound essence coding".into())),+ };+ let at = (a - start) as usize;+ for (c, d) in decoded.iter().enumerate().take(ch) {+ for (k, v) in d.iter().take((b - a) as usize).enumerate() {+ out[c][at + k] = *v;+ }+ }+ }+ ci += 1;+ }+ Ok(out)+ }+}diff --git a/crates/mxf/src/index.rs b/crates/mxf/src/index.rsnew file mode 100644index 000000000..d483dbfbb--- /dev/null+++ b/crates/mxf/src/index.rs@@ -0,0 +1,124 @@+//! Index table segments (ST 377-1 §11).++use crate::Rational;+use crate::klv::{Cur, int_of, rational_of};++/// One index entry (ST 377-1 §11.2.4), for one edit unit in stored order.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct IndexEntry {+ /// Display-order position `n` is stored at `n + temporal_offset` (the offset belongs to the+ /// entry at the display position).+ pub temporal_offset: i8,+ /// Stored-order offset from this edit unit to the key frame it depends on (≤ 0).+ pub key_frame_offset: i8,+ /// Bit 7 random access, bit 6 sequence header, bits 5-4 prediction (00 I, 10 P, 11 B).+ pub flags: u8,+ /// Byte offset of the edit unit in the essence container stream.+ pub stream_offset: u64,+}++impl IndexEntry {+ pub fn random_access(&self) -> bool {+ self.flags & 0x80 != 0+ }+ /// Uses backward prediction (a B picture).+ pub fn is_b(&self) -> bool {+ self.flags & 0x30 == 0x30+ }+}++/// An index table segment.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct IndexSegment {+ pub edit_rate: Rational,+ pub start_position: i64,+ /// Edit units covered (0 with a constant byte count: the whole container).+ pub duration: i64,+ /// Constant bytes per edit unit (CBR); 0 when the entries give the offsets (VBR).+ pub edit_unit_byte_count: u32,+ pub index_sid: u32,+ pub body_sid: u32,+ pub slice_count: u8,+ pub pos_table_count: u8,+ /// (pos table index, slice, element delta) per element of a content package.+ pub delta_entries: Vec<(i8, u8, u32)>,+ pub entries: Vec<IndexEntry>,+}++impl IndexSegment {+ pub fn parse(v: &[u8]) -> IndexSegment {+ let mut s = IndexSegment::default();+ let mut c = Cur::new(v);+ let mut entry_array: Option<&[u8]> = None;+ while c.remaining() >= 4 {+ let (Some(tag), Some(len)) = (c.u16(), c.u16()) else { break };+ let Some(val) = c.bytes(len as usize) else { break };+ match tag {+ 0x3F0B => s.edit_rate = rational_of(val).unwrap_or_default(),+ 0x3F0C => s.start_position = int_of(val, true).unwrap_or(0),+ 0x3F0D => s.duration = int_of(val, true).unwrap_or(0),+ 0x3F05 => s.edit_unit_byte_count = int_of(val, false).unwrap_or(0) as u32,+ 0x3F06 => s.index_sid = int_of(val, false).unwrap_or(0) as u32,+ 0x3F07 => s.body_sid = int_of(val, false).unwrap_or(0) as u32,+ 0x3F08 => s.slice_count = val.first().copied().unwrap_or(0),+ 0x3F0E => s.pos_table_count = val.first().copied().unwrap_or(0),+ 0x3F09 => {+ for d in crate::klv::batch_of(val) {+ if d.len() >= 6 {+ s.delta_entries.push((d[0] as i8, d[1], u32::from_be_bytes([d[2], d[3], d[4], d[5]])));+ }+ }+ }+ 0x3F0A => entry_array = Some(val),+ _ => {}+ }+ }+ if let Some(val) = entry_array {+ for e in crate::klv::batch_of(val) {+ if e.len() >= 11 {+ s.entries.push(IndexEntry {+ temporal_offset: e[0] as i8,+ key_frame_offset: e[1] as i8,+ flags: e[2],+ stream_offset: u64::from_be_bytes(e[3..11].try_into().unwrap_or([0; 8])),+ });+ }+ }+ }+ s+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_vbr_segment() {+ let mut v = Vec::new();+ let mut prop = |tag: u16, val: &[u8]| {+ v.extend_from_slice(&tag.to_be_bytes());+ v.extend_from_slice(&(val.len() as u16).to_be_bytes());+ v.extend_from_slice(val);+ };+ prop(0x3F0B, &[0, 0, 0, 25, 0, 0, 0, 1]);+ prop(0x3F0C, &0i64.to_be_bytes());+ prop(0x3F0D, &2i64.to_be_bytes());+ prop(0x3F06, &2u32.to_be_bytes());+ prop(0x3F07, &1u32.to_be_bytes());+ let mut arr = vec![0, 0, 0, 2, 0, 0, 0, 11];+ arr.extend_from_slice(&[0, 0, 0xC0]);+ arr.extend_from_slice(&0u64.to_be_bytes());+ arr.extend_from_slice(&[0xFF, 0xFF, 0x33]);+ arr.extend_from_slice(&1000u64.to_be_bytes());+ prop(0x3F0A, &arr);+ let s = IndexSegment::parse(&v);+ assert_eq!(s.edit_rate, Rational::new(25, 1));+ assert_eq!(s.duration, 2);+ assert_eq!(s.entries.len(), 2);+ assert!(s.entries[0].random_access());+ assert_eq!(s.entries[1].temporal_offset, -1);+ assert!(s.entries[1].is_b());+ assert_eq!(s.entries[1].stream_offset, 1000);+ }+}diff --git a/crates/mxf/src/klv.rs b/crates/mxf/src/klv.rsnew file mode 100644index 000000000..76e31eeb7--- /dev/null+++ b/crates/mxf/src/klv.rs@@ -0,0 +1,250 @@+//! KLV coding (SMPTE ST 336): 16-byte universal label keys, BER lengths, and the key classes used+//! by ST 377-1.++use std::fmt;++/// A SMPTE universal label (16 bytes).+#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]+pub struct Ul(pub [u8; 16]);++impl Ul {+ /// Every SMPTE label starts with the object identifier 06 0E 2B 34.+ pub fn is_smpte(&self) -> bool {+ self.0[..4] == [0x06, 0x0E, 0x2B, 0x34]+ }+ /// Compare ignoring byte 7 (the registry version, which varies between writers).+ pub fn matches(&self, other: &[u8; 16]) -> bool {+ self.0.iter().zip(other).enumerate().all(|(i, (a, b))| i == 7 || a == b)+ }+ /// Bytes 8.. start with `prefix` (registry-independent comparison of the item designator).+ pub fn item_starts_with(&self, prefix: &[u8]) -> bool {+ self.0[8..].starts_with(prefix)+ }+}++impl fmt::Debug for Ul {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ for (i, b) in self.0.iter().enumerate() {+ if i > 0 {+ f.write_str(".")?;+ }+ write!(f, "{b:02x}")?;+ }+ Ok(())+ }+}++impl fmt::Display for Ul {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ fmt::Debug::fmt(self, f)+ }+}++/// A rational number (edit rates, sample rates, aspect ratios).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct Rational {+ pub num: i32,+ pub den: i32,+}++impl Rational {+ pub fn new(num: i32, den: i32) -> Self {+ Rational { num, den }+ }+ pub fn is_valid(&self) -> bool {+ self.num > 0 && self.den > 0+ }+ pub fn as_f64(&self) -> f64 {+ if self.den == 0 { 0.0 } else { self.num as f64 / self.den as f64 }+ }+}++/// Partition pack keys: 06 0E 2B 34 02 05 01 01 0D 01 02 01 01 kk ss 00 (kk: 02 header, 03 body,+/// 04 footer; ss: status).+pub const PARTITION_PREFIX: [u8; 13] = [0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01];++/// The kinds of KLV packets the demuxer distinguishes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum KeyClass {+ /// Partition pack: kind byte (2 header, 3 body, 4 footer) and status byte.+ Partition {+ kind: u8,+ status: u8,+ },+ Primer,+ /// Header metadata local set (structural or descriptive).+ LocalSet,+ IndexSegment,+ RandomIndexPack,+ Fill,+ /// Generic container content (system items and essence elements, ST 379-1).+ Essence,+ Other,+}++pub fn classify(k: &Ul) -> KeyClass {+ let b = &k.0;+ if !k.is_smpte() {+ return KeyClass::Other;+ }+ if b[..13] == PARTITION_PREFIX && (2..=4).contains(&b[13]) && b[15] == 0 {+ return KeyClass::Partition { kind: b[13], status: b[14] };+ }+ // 06 0E 2B 34 02 05 01 01 0D 01 02 01 01 05 01 00+ if b[4] == 0x02 && b[5] == 0x05 && b[8..16] == [0x0D, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00] {+ return KeyClass::Primer;+ }+ // 06 0E 2B 34 02 05 01 01 0D 01 02 01 01 11 01 00+ if b[4] == 0x02 && b[5] == 0x05 && b[8..16] == [0x0D, 0x01, 0x02, 0x01, 0x01, 0x11, 0x01, 0x00] {+ return KeyClass::RandomIndexPack;+ }+ // 06 0E 2B 34 02 53 01 01 0D 01 02 01 01 10 01 00 (also seen with 2-byte BER lengths: 02 13 / 02 33)+ if b[4] == 0x02 && b[8..16] == [0x0D, 0x01, 0x02, 0x01, 0x01, 0x10, 0x01, 0x00] {+ return KeyClass::IndexSegment;+ }+ // 06 0E 2B 34 01 01 01 0x 03 01 02 10 01 00 00 00 (KLV fill; the "01 02 10 01" legacy variant too)+ if b[4] == 0x01 && b[5] == 0x01 && b[8..12] == [0x03, 0x01, 0x02, 0x10] {+ return KeyClass::Fill;+ }+ // Generic container content: 06 0E 2B 34 xx xx xx xx 0D 01 03 01 ...+ if b[8..12] == [0x0D, 0x01, 0x03, 0x01] {+ return KeyClass::Essence;+ }+ // Header metadata sets: 06 0E 2B 34 02 53 ... (local sets with 2-byte tags and lengths)+ if b[4] == 0x02 && b[5] == 0x53 {+ return KeyClass::LocalSet;+ }+ KeyClass::Other+}++/// Decode a BER length at `b[0..]`: (length, bytes used). `None` if truncated or longer than 8 bytes.+pub fn ber_length(b: &[u8]) -> Option<(u64, usize)> {+ let first = *b.first()?;+ if first < 0x80 {+ return Some((first as u64, 1));+ }+ let n = (first & 0x7F) as usize;+ if n == 0 || n > 8 || b.len() < 1 + n {+ return None;+ }+ Some((b[1..=n].iter().fold(0u64, |a, &x| (a << 8) | x as u64), 1 + n))+}++/// Offset of the header partition pack key in the run-in (ST 377-1: at most 65 535 bytes).+pub fn find_header_partition(head: &[u8]) -> Option<usize> {+ let limit = head.len().min(65_536 + 16);+ let mut i = 0;+ while i + 16 <= limit {+ if head[i..i + 13] == PARTITION_PREFIX && head[i + 13] == 0x02 {+ return Some(i);+ }+ i += 1;+ }+ None+}++/// Big-endian cursor over a value.+pub struct Cur<'a> {+ b: &'a [u8],+ pub pos: usize,+}++impl<'a> Cur<'a> {+ pub fn new(b: &'a [u8]) -> Self {+ Cur { b, pos: 0 }+ }+ pub fn remaining(&self) -> usize {+ self.b.len().saturating_sub(self.pos)+ }+ pub fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {+ let s = self.b.get(self.pos..self.pos.checked_add(n)?)?;+ self.pos += n;+ Some(s)+ }+ pub fn u16(&mut self) -> Option<u16> {+ self.bytes(2).map(|b| u16::from_be_bytes([b[0], b[1]]))+ }+ pub fn u32(&mut self) -> Option<u32> {+ self.bytes(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))+ }+ pub fn u64(&mut self) -> Option<u64> {+ self.bytes(8).map(|b| u64::from_be_bytes(b.try_into().unwrap_or([0; 8])))+ }+ pub fn ul(&mut self) -> Option<Ul> {+ self.bytes(16).map(|b| Ul(b.try_into().unwrap_or([0; 16])))+ }+}++/// Integer value of a property (1, 2, 4 or 8 bytes, big-endian, sign-extended when `signed`).+pub fn int_of(v: &[u8], signed: bool) -> Option<i64> {+ if v.is_empty() || v.len() > 8 {+ return None;+ }+ let u = v.iter().fold(0u64, |a, &x| (a << 8) | x as u64);+ if signed && v.len() < 8 && v[0] & 0x80 != 0 {+ let shift = 64 - 8 * v.len();+ return Some(((u << shift) as i64) >> shift);+ }+ Some(u as i64)+}++/// A rational property (two big-endian i32).+pub fn rational_of(v: &[u8]) -> Option<Rational> {+ if v.len() < 8 {+ return None;+ }+ Some(Rational::new(i32::from_be_bytes([v[0], v[1], v[2], v[3]]), i32::from_be_bytes([v[4], v[5], v[6], v[7]])))+}++/// A UL property.+pub fn ul_of(v: &[u8]) -> Option<Ul> {+ v.get(..16).map(|b| Ul(b.try_into().unwrap_or([0; 16])))+}++/// A batch / array property: count (u32), item size (u32), items.+pub fn batch_of(v: &[u8]) -> Vec<&[u8]> {+ let mut c = Cur::new(v);+ let (Some(n), Some(size)) = (c.u32(), c.u32()) else { return Vec::new() };+ let size = size as usize;+ if size == 0 {+ return Vec::new();+ }+ let mut out = Vec::new();+ for _ in 0..n {+ match c.bytes(size) {+ Some(b) => out.push(b),+ None => break,+ }+ }+ out+}++/// A UTF-16BE string property (trailing NULs removed).+pub fn utf16_of(v: &[u8]) -> String {+ let units: Vec<u16> = v.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).take_while(|&u| u != 0).collect();+ String::from_utf16_lossy(&units)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ber_lengths() {+ assert_eq!(ber_length(&[0x05]), Some((5, 1)));+ assert_eq!(ber_length(&[0x83, 0x01, 0x00, 0x00]), Some((65536, 4)));+ assert_eq!(ber_length(&[0x88, 0, 0, 0, 0, 0, 0, 1, 2]), Some((258, 9)));+ assert_eq!(ber_length(&[0x83, 0x01]), None);+ assert_eq!(ber_length(&[0x80]), None);+ assert_eq!(ber_length(&[0x89, 0, 0, 0, 0, 0, 0, 0, 0, 0]), None);+ }++ #[test]+ fn integers_and_strings() {+ assert_eq!(int_of(&[0xFF, 0xFE], true), Some(-2));+ assert_eq!(int_of(&[0xFF, 0xFE], false), Some(0xFFFE));+ assert_eq!(utf16_of(&[0, b'A', 0, b'b', 0, 0]), "Ab");+ let b = [0, 0, 0, 2, 0, 0, 0, 1, 7, 9];+ assert_eq!(batch_of(&b), vec![&[7u8][..], &[9u8][..]]);+ }+}diff --git a/crates/mxf/src/lib.rs b/crates/mxf/src/lib.rsnew file mode 100644index 000000000..7a46947de--- /dev/null+++ b/crates/mxf/src/lib.rs@@ -0,0 +1,74 @@+//! Clean-room MXF demuxer, written from the SMPTE specifications (editions in the README):+//! ST 377-1 (file format: KLV, partitions, primer pack, header metadata, index tables, random+//! index pack), ST 378 (OP1a), ST 390 (OP-Atom), ST 379-1/2 (generic container), ST 381-1 (MPEG+//! video mapping), ST 381-3 (AVC mapping), ST 382 (AES3 / Broadcast Wave audio mapping), ST 331+//! (AES3 element data, D-10 sound), ST 2019-4 (VC-3 mapping) and RDD 44 (ProRes mapping).+//!+//! [`open`] walks the file's KLV packets (keys and lengths only; essence payloads are never read+//! while opening), parses the partition packs, the primer pack and header metadata of the most+//! complete partition, and every index table segment, then resolves the material package to the+//! file (source) package tracks that carry essence in this file. The result is a list of+//! [`EssenceTrack`]s with per-edit-unit [`Sample`] tables for pictures (file offset, size,+//! presentation position from the index temporal offsets, random-access flag) and PCM chunk+//! tables for sound, plus the start timecode of the material package.+//!+//! Layer L0: no dependencies beyond `std`, no `unsafe`, builds for `wasm32-unknown-unknown`.++mod essence;+mod file;+mod index;+mod klv;+mod meta;+mod source;++pub use essence::{Codec, PictureInfo, SoundFormat, SoundInfo, aes3_element_samples, decode_pcm};+pub use file::{Chunk, EssenceTrack, MxfFile, OperationalPattern, Partition, PartitionKind, Sample, Timecode, TrackKind, Wrapping, open};+pub use index::{IndexEntry, IndexSegment};+pub use klv::{Rational, Ul};+pub use source::ByteSource;++use std::fmt;+use std::io;++/// Errors produced by the demuxer.+#[derive(Debug)]+pub enum Error {+ /// Underlying I/O failure.+ Io(io::Error),+ /// Not an MXF file (no header partition pack).+ NotMxf(String),+ /// Structurally invalid data that could not be recovered from.+ Invalid(String),+ /// Valid but unsupported (e.g. essence stored in another file).+ Unsupported(String),+}++impl fmt::Display for Error {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Error::Io(e) => write!(f, "I/O error: {e}"),+ Error::NotMxf(s) => write!(f, "not an MXF file: {s}"),+ Error::Invalid(s) => write!(f, "invalid MXF: {s}"),+ Error::Unsupported(s) => write!(f, "unsupported MXF: {s}"),+ }+ }+}++impl std::error::Error for Error {}++impl From<io::Error> for Error {+ fn from(e: io::Error) -> Self {+ Error::Io(e)+ }+}++pub type Result<T> = std::result::Result<T, Error>;++/// Whether `head` (the first bytes of a file) looks like MXF: a header partition pack key within+/// the run-in (at most 64 KiB, ST 377-1 §6.5).+pub fn sniff(head: &[u8]) -> bool {+ klv::find_header_partition(head).is_some()+}++#[cfg(test)]+mod tests;diff --git a/crates/mxf/src/meta.rs b/crates/mxf/src/meta.rsnew file mode 100644index 000000000..bb122683f--- /dev/null+++ b/crates/mxf/src/meta.rs@@ -0,0 +1,213 @@+//! Header metadata (ST 377-1 §9, Annex A/B): the primer pack and local sets.+//!+//! Local sets code each property as a 2-byte local tag and a 2-byte length. Tags below 0x8000 are+//! static (fixed by ST 377-1 and the mapping documents); dynamic tags (0x8000 and up) are mapped+//! to their property UL by the partition's primer pack.++use std::collections::HashMap;++use crate::klv::{Cur, Ul, batch_of, int_of, rational_of, ul_of, utf16_of};++/// Local tag → property UL (ST 377-1 §9.2).+#[derive(Clone, Debug, Default)]+pub struct Primer(pub HashMap<u16, Ul>);++impl Primer {+ pub fn parse(v: &[u8]) -> Primer {+ let mut map = HashMap::new();+ for item in batch_of(v) {+ if item.len() >= 18 {+ map.insert(u16::from_be_bytes([item[0], item[1]]), Ul(item[2..18].try_into().unwrap_or([0; 16])));+ }+ }+ Primer(map)+ }+}++/// Header metadata set types: byte 14 of `06 0E 2B 34 02 53 01 01 0D 01 01 01 01 01 tt 00`.+#[allow(dead_code)]+pub mod set_type {+ pub const PREFACE: u8 = 0x2F;+ pub const IDENTIFICATION: u8 = 0x30;+ pub const CONTENT_STORAGE: u8 = 0x18;+ pub const ESSENCE_CONTAINER_DATA: u8 = 0x23;+ pub const MATERIAL_PACKAGE: u8 = 0x36;+ pub const SOURCE_PACKAGE: u8 = 0x37;+ pub const TIMELINE_TRACK: u8 = 0x3B;+ pub const EVENT_TRACK: u8 = 0x39;+ pub const STATIC_TRACK: u8 = 0x3A;+ pub const SEQUENCE: u8 = 0x0F;+ pub const SOURCE_CLIP: u8 = 0x11;+ pub const TIMECODE_COMPONENT: u8 = 0x14;+ pub const FILLER: u8 = 0x09;+ pub const MULTIPLE_DESCRIPTOR: u8 = 0x44;+ pub const GENERIC_PICTURE_DESCRIPTOR: u8 = 0x27;+ pub const CDCI_DESCRIPTOR: u8 = 0x28;+ pub const RGBA_DESCRIPTOR: u8 = 0x29;+ pub const GENERIC_SOUND_DESCRIPTOR: u8 = 0x42;+ pub const GENERIC_DATA_DESCRIPTOR: u8 = 0x43;+ pub const AES3_DESCRIPTOR: u8 = 0x47;+ pub const WAVE_DESCRIPTOR: u8 = 0x48;+ pub const MPEG2_VIDEO_DESCRIPTOR: u8 = 0x51;+ pub const JPEG2000_SUBDESCRIPTOR: u8 = 0x5A;+ pub const AVC_SUBDESCRIPTOR: u8 = 0x6E;+}++/// One header metadata local set.+#[derive(Clone, Debug, Default)]+pub struct Set {+ pub key: Ul,+ pub instance_uid: [u8; 16],+ /// Static-tag properties.+ pub props: HashMap<u16, Vec<u8>>,+ /// Dynamic-tag properties, by property UL.+ pub dynamic: HashMap<Ul, Vec<u8>>,+}++impl Set {+ pub fn parse(key: Ul, v: &[u8], primer: &Primer) -> Set {+ let mut s = Set { key, ..Default::default() };+ let mut c = Cur::new(v);+ while c.remaining() >= 4 {+ let (Some(tag), Some(len)) = (c.u16(), c.u16()) else { break };+ let Some(val) = c.bytes(len as usize) else { break };+ if tag == 0x3C0A && val.len() >= 16 {+ s.instance_uid.copy_from_slice(&val[..16]);+ }+ if tag >= 0x8000 {+ if let Some(ul) = primer.0.get(&tag) {+ s.dynamic.insert(*ul, val.to_vec());+ }+ } else {+ s.props.insert(tag, val.to_vec());+ }+ }+ s+ }++ /// The set type byte when this is a structural metadata set.+ pub fn kind(&self) -> Option<u8> {+ self.key.item_starts_with(&[0x0D, 0x01, 0x01, 0x01, 0x01, 0x01]).then_some(self.key.0[14])+ }+ pub fn get(&self, tag: u16) -> Option<&[u8]> {+ self.props.get(&tag).map(Vec::as_slice)+ }+ pub fn u(&self, tag: u16) -> Option<i64> {+ self.get(tag).and_then(|v| int_of(v, false))+ }+ pub fn i(&self, tag: u16) -> Option<i64> {+ self.get(tag).and_then(|v| int_of(v, true))+ }+ pub fn rational(&self, tag: u16) -> Option<crate::Rational> {+ self.get(tag).and_then(rational_of)+ }+ pub fn ul(&self, tag: u16) -> Option<Ul> {+ self.get(tag).and_then(ul_of)+ }+ pub fn string(&self, tag: u16) -> Option<String> {+ self.get(tag).map(utf16_of).filter(|s| !s.is_empty())+ }+ /// A strong / weak reference (16-byte UUID).+ pub fn reference(&self, tag: u16) -> Option<[u8; 16]> {+ self.get(tag).and_then(|v| v.get(..16)).map(|b| b.try_into().unwrap_or([0; 16]))+ }+ /// A batch of references.+ pub fn references(&self, tag: u16) -> Vec<[u8; 16]> {+ self.get(tag).map(|v| batch_of(v).into_iter().filter_map(|b| b.get(..16).map(|x| x.try_into().unwrap_or([0; 16]))).collect()).unwrap_or_default()+ }+ /// A dynamic property whose UL's item designator (bytes 8..) equals `item`.+ pub fn dynamic_item(&self, item: &[u8]) -> Option<&[u8]> {+ self.dynamic.iter().find(|(k, _)| k.item_starts_with(item)).map(|(_, v)| v.as_slice())+ }+}++/// All sets of one partition's header metadata, by instance UID.+#[derive(Clone, Debug, Default)]+pub struct Metadata {+ pub sets: Vec<Set>,+ by_uid: HashMap<[u8; 16], usize>,+}++impl Metadata {+ pub fn push(&mut self, s: Set) {+ if s.instance_uid != [0; 16] {+ self.by_uid.insert(s.instance_uid, self.sets.len());+ }+ self.sets.push(s);+ }+ pub fn get(&self, uid: &[u8; 16]) -> Option<&Set> {+ self.by_uid.get(uid).map(|&i| &self.sets[i])+ }+ pub fn of_kind(&self, kind: u8) -> impl Iterator<Item = &Set> {+ self.sets.iter().filter(move |s| s.kind() == Some(kind))+ }+}++/// Static local tags (ST 377-1 Annex B and the mapping documents).+#[allow(dead_code)]+pub mod tag {+ // Generic package+ pub const PACKAGE_UID: u16 = 0x4401;+ pub const PACKAGE_NAME: u16 = 0x4402;+ pub const PACKAGE_TRACKS: u16 = 0x4403;+ pub const SOURCE_PACKAGE_DESCRIPTOR: u16 = 0x4701;+ // Track+ pub const TRACK_ID: u16 = 0x4801;+ pub const TRACK_NUMBER: u16 = 0x4804;+ pub const TRACK_NAME: u16 = 0x4802;+ pub const TRACK_SEQUENCE: u16 = 0x4803;+ pub const EDIT_RATE: u16 = 0x4B01;+ pub const ORIGIN: u16 = 0x4B02;+ // Structural components+ pub const DATA_DEFINITION: u16 = 0x0201;+ pub const DURATION: u16 = 0x0202;+ pub const STRUCTURAL_COMPONENTS: u16 = 0x1001;+ pub const START_POSITION: u16 = 0x1201;+ pub const SOURCE_PACKAGE_ID: u16 = 0x1101;+ pub const SOURCE_TRACK_ID: u16 = 0x1102;+ pub const START_TIMECODE: u16 = 0x1501;+ pub const ROUNDED_TIMECODE_BASE: u16 = 0x1502;+ pub const DROP_FRAME: u16 = 0x1503;+ // Preface / identification / content storage+ pub const OPERATIONAL_PATTERN: u16 = 0x3B09;+ pub const PRODUCT_NAME: u16 = 0x3C02;+ pub const COMPANY_NAME: u16 = 0x3C01;+ pub const ESSENCE_CONTAINER_DATA_LINKED_PACKAGE: u16 = 0x2701;+ pub const INDEX_SID: u16 = 0x3F06;+ pub const BODY_SID: u16 = 0x3F07;+ // Descriptors+ pub const SUB_DESCRIPTORS: u16 = 0x3F01;+ pub const LINKED_TRACK_ID: u16 = 0x3006;+ pub const SAMPLE_RATE: u16 = 0x3001;+ pub const CONTAINER_DURATION: u16 = 0x3002;+ pub const ESSENCE_CONTAINER: u16 = 0x3004;+ pub const CODEC: u16 = 0x3005;+ pub const FRAME_LAYOUT: u16 = 0x320C;+ pub const STORED_WIDTH: u16 = 0x3203;+ pub const STORED_HEIGHT: u16 = 0x3202;+ pub const SAMPLED_WIDTH: u16 = 0x3205;+ pub const SAMPLED_HEIGHT: u16 = 0x3204;+ pub const DISPLAY_WIDTH: u16 = 0x3209;+ pub const DISPLAY_HEIGHT: u16 = 0x3208;+ pub const ASPECT_RATIO: u16 = 0x320E;+ pub const TRANSFER_CHARACTERISTIC: u16 = 0x3210;+ pub const PICTURE_ESSENCE_CODING: u16 = 0x3201;+ pub const CODING_EQUATIONS: u16 = 0x321A;+ pub const COLOR_PRIMARIES: u16 = 0x3219;+ pub const COMPONENT_DEPTH: u16 = 0x3301;+ pub const HORIZONTAL_SUBSAMPLING: u16 = 0x3302;+ pub const VERTICAL_SUBSAMPLING: u16 = 0x3308;+ pub const BLACK_REF_LEVEL: u16 = 0x3304;+ pub const WHITE_REF_LEVEL: u16 = 0x3305;+ pub const ALPHA_SAMPLE_DEPTH: u16 = 0x3309;+ pub const PIXEL_LAYOUT: u16 = 0x3401;+ pub const AUDIO_SAMPLING_RATE: u16 = 0x3D03;+ pub const LOCKED: u16 = 0x3D02;+ pub const CHANNEL_COUNT: u16 = 0x3D07;+ pub const QUANTIZATION_BITS: u16 = 0x3D01;+ pub const SOUND_ESSENCE_CODING: u16 = 0x3D06;+ pub const BLOCK_ALIGN: u16 = 0x3D0A;+}++/// The `SubDescriptors` property (ST 377-1:2009, dynamic tag): 06 0E 2B 34 01 01 01 09 06 01 01 04 06 10 00 00.+pub const SUB_DESCRIPTORS_ITEM: [u8; 8] = [0x06, 0x01, 0x01, 0x04, 0x06, 0x10, 0x00, 0x00];diff --git a/crates/mxf/src/source.rs b/crates/mxf/src/source.rsnew file mode 100644index 000000000..d14139b77--- /dev/null+++ b/crates/mxf/src/source.rs@@ -0,0 +1,68 @@+//! Random-access byte sources.++use std::io;+use std::sync::Arc;++/// Random-access, read-only byte source (file, in-memory buffer, web Blob…). Same shape as the+/// other FilmCraft demuxers' `ByteSource`, so one adapter serves all of them.+pub trait ByteSource {+ /// Total length in bytes.+ fn len(&self) -> u64;+ /// Fill `buf` entirely from `offset`; `UnexpectedEof` past the end.+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>;+ /// True if the source holds no bytes.+ fn is_empty(&self) -> bool {+ self.len() == 0+ }+}++fn eof() -> io::Error {+ io::Error::new(io::ErrorKind::UnexpectedEof, "read past end of byte source")+}++impl ByteSource for [u8] {+ fn len(&self) -> u64 {+ <[u8]>::len(self) as u64+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ let start = usize::try_from(offset).map_err(|_| eof())?;+ let end = start.checked_add(buf.len()).ok_or_else(eof)?;+ buf.copy_from_slice(self.get(start..end).ok_or_else(eof)?);+ Ok(())+ }+}++impl ByteSource for Vec<u8> {+ fn len(&self) -> u64 {+ self.as_slice().len() as u64+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ self.as_slice().read_at(offset, buf)+ }+}++impl<T: ByteSource + ?Sized> ByteSource for &T {+ fn len(&self) -> u64 {+ (**self).len()+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ (**self).read_at(offset, buf)+ }+}++impl<T: ByteSource + ?Sized> ByteSource for Arc<T> {+ fn len(&self) -> u64 {+ (**self).len()+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ (**self).read_at(offset, buf)+ }+}++/// Up to `len` bytes at `offset` (fewer at the end of the source).+pub(crate) fn read_upto(src: &(impl ByteSource + ?Sized), offset: u64, len: usize) -> io::Result<Vec<u8>> {+ let n = src.len().saturating_sub(offset).min(len as u64) as usize;+ let mut v = vec![0u8; n];+ src.read_at(offset, &mut v)?;+ Ok(v)+}diff --git a/crates/mxf/src/tests.rs b/crates/mxf/src/tests.rsnew file mode 100644index 000000000..b9ed40f10--- /dev/null+++ b/crates/mxf/src/tests.rs@@ -0,0 +1,363 @@+//! Synthetic files: a small OP1a writer (enough of ST 377-1 to exercise the demuxer without+//! ffmpeg) and robustness checks.++use crate::*;++fn ul(b: &[u8]) -> [u8; 16] {+ let mut k = [0u8; 16];+ k[..b.len()].copy_from_slice(b);+ k+}++fn ber(n: usize) -> Vec<u8> {+ let mut v = vec![0x83];+ v.extend_from_slice(&(n as u32).to_be_bytes()[1..]);+ v+}++fn klv(out: &mut Vec<u8>, key: [u8; 16], v: &[u8]) {+ out.extend_from_slice(&key);+ out.extend_from_slice(&ber(v.len()));+ out.extend_from_slice(v);+}++struct LocalSet(Vec<u8>);+impl LocalSet {+ fn new(uid: u8) -> Self {+ let mut s = LocalSet(Vec::new());+ s.p(0x3C0A, &uuid(uid));+ s+ }+ fn p(&mut self, tag: u16, v: &[u8]) -> &mut Self {+ self.0.extend_from_slice(&tag.to_be_bytes());+ self.0.extend_from_slice(&(v.len() as u16).to_be_bytes());+ self.0.extend_from_slice(v);+ self+ }+}++fn uuid(n: u8) -> [u8; 16] {+ let mut u = [0xAAu8; 16];+ u[15] = n;+ u+}++fn umid(n: u8) -> [u8; 32] {+ let mut u = [0x55u8; 32];+ u[31] = n;+ u+}++fn batch(items: &[&[u8]]) -> Vec<u8> {+ let mut v = (items.len() as u32).to_be_bytes().to_vec();+ v.extend_from_slice(&(items.first().map_or(0, |i| i.len()) as u32).to_be_bytes());+ for i in items {+ v.extend_from_slice(i);+ }+ v+}++fn set_key(t: u8) -> [u8; 16] {+ ul(&[0x06, 0x0E, 0x2B, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, t, 0x00])+}++const PICTURE_DEF: [u8; 16] = [0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x01, 0, 0, 0];+const SOUND_DEF: [u8; 16] = [0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0, 0, 0];+const TC_DEF: [u8; 16] = [0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x01, 0, 0, 0];+const OP1A: [u8; 16] = [0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x01, 0x09, 0x00];+const PIC_KEY: [u8; 16] = [0x06, 0x0E, 0x2B, 0x34, 0x01, 0x02, 0x01, 0x01, 0x0D, 0x01, 0x03, 0x01, 0x15, 0x01, 0x05, 0x00];+const SND_KEY: [u8; 16] = [0x06, 0x0E, 0x2B, 0x34, 0x01, 0x02, 0x01, 0x01, 0x0D, 0x01, 0x03, 0x01, 0x16, 0x01, 0x03, 0x00];++fn partition(kind: u8, this: u64, body_sid: u32, index_sid: u32, hbc: u64) -> Vec<u8> {+ let mut v = Vec::new();+ v.extend_from_slice(&1u16.to_be_bytes());+ v.extend_from_slice(&3u16.to_be_bytes());+ v.extend_from_slice(&1u32.to_be_bytes());+ v.extend_from_slice(&this.to_be_bytes());+ v.extend_from_slice(&0u64.to_be_bytes());+ v.extend_from_slice(&0u64.to_be_bytes());+ v.extend_from_slice(&hbc.to_be_bytes());+ v.extend_from_slice(&0u64.to_be_bytes());+ v.extend_from_slice(&index_sid.to_be_bytes());+ v.extend_from_slice(&0u64.to_be_bytes());+ v.extend_from_slice(&body_sid.to_be_bytes());+ v.extend_from_slice(&OP1A);+ v.extend_from_slice(&batch(&[]));+ let mut out = Vec::new();+ klv(&mut out, ul(&[0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, kind, 0x04, 0x00]), &v);+ out+}++fn track(uid: u8, id: u32, number: u32, seq: u8) -> Vec<u8> {+ let mut s = LocalSet::new(uid);+ s.p(0x4801, &id.to_be_bytes()).p(0x4804, &number.to_be_bytes()).p(0x4B01, &[0, 0, 0, 25, 0, 0, 0, 1]).p(0x4B02, &0i64.to_be_bytes()).p(0x4803, &uuid(seq));+ s.0+}++fn sequence(uid: u8, def: [u8; 16], dur: i64, comp: u8) -> Vec<u8> {+ let mut s = LocalSet::new(uid);+ s.p(0x0201, &def).p(0x0202, &dur.to_be_bytes()).p(0x1001, &batch(&[&uuid(comp)]));+ s.0+}++fn source_clip(uid: u8, def: [u8; 16], dur: i64, pkg: [u8; 32], track: u32) -> Vec<u8> {+ let mut s = LocalSet::new(uid);+ s.p(0x0201, &def).p(0x0202, &dur.to_be_bytes()).p(0x1201, &0i64.to_be_bytes()).p(0x1101, &pkg).p(0x1102, &track.to_be_bytes());+ s.0+}++/// An OP1a file: `n` frame-wrapped content packages, each a picture element of `pic(i)` and a+/// 16-bit stereo sound element of 1920 frames (sample k of the file = k, -k on the channels);+/// a footer index with temporal offsets `to` and flags `flags`.+fn build(n: usize, pic: impl Fn(usize) -> Vec<u8>, to: &[i8], flags: &[u8]) -> Vec<u8> {+ let mut md = Vec::new();+ // primer: no dynamic tags+ klv(&mut md, ul(&[0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00]), &batch(&[]));+ let mut pre = LocalSet::new(1);+ pre.p(0x3B03, &uuid(2)).p(0x3B09, &OP1A);+ klv(&mut md, set_key(0x2F), &pre.0);+ let mut cs = LocalSet::new(2);+ cs.p(0x1901, &batch(&[&uuid(3), &uuid(4)]));+ klv(&mut md, set_key(0x18), &cs.0);+ // material package: timecode, picture, sound+ let mut mp = LocalSet::new(3);+ mp.p(0x4401, &umid(1)).p(0x4402, &[0, b'M', 0, b'P']).p(0x4403, &batch(&[&uuid(10), &uuid(11), &uuid(12)]));+ klv(&mut md, set_key(0x36), &mp.0);+ let d = n as i64;+ klv(&mut md, set_key(0x3B), &track(10, 1, 0, 20));+ klv(&mut md, set_key(0x0F), &sequence(20, TC_DEF, d, 30));+ let mut tc = LocalSet::new(30);+ tc.p(0x0201, &TC_DEF).p(0x0202, &d.to_be_bytes()).p(0x1501, &90_000i64.to_be_bytes()).p(0x1502, &25u16.to_be_bytes()).p(0x1503, &[0]);+ klv(&mut md, set_key(0x14), &tc.0);+ klv(&mut md, set_key(0x3B), &track(11, 2, 0, 21));+ klv(&mut md, set_key(0x0F), &sequence(21, PICTURE_DEF, d, 31));+ klv(&mut md, set_key(0x11), &source_clip(31, PICTURE_DEF, d, umid(2), 2));+ klv(&mut md, set_key(0x3B), &track(12, 3, 0, 22));+ klv(&mut md, set_key(0x0F), &sequence(22, SOUND_DEF, d, 32));+ klv(&mut md, set_key(0x11), &source_clip(32, SOUND_DEF, d, umid(2), 3));+ // file package+ let mut fp = LocalSet::new(4);+ fp.p(0x4401, &umid(2)).p(0x4403, &batch(&[&uuid(13), &uuid(14)])).p(0x4701, &uuid(40));+ klv(&mut md, set_key(0x37), &fp.0);+ klv(&mut md, set_key(0x3B), &track(13, 2, 0x1501_0500, 23));+ klv(&mut md, set_key(0x0F), &sequence(23, PICTURE_DEF, d, 33));+ klv(&mut md, set_key(0x11), &source_clip(33, PICTURE_DEF, d, [0; 32], 0));+ klv(&mut md, set_key(0x3B), &track(14, 3, 0x1601_0300, 24));+ klv(&mut md, set_key(0x0F), &sequence(24, SOUND_DEF, d, 34));+ klv(&mut md, set_key(0x11), &source_clip(34, SOUND_DEF, d, [0; 32], 0));+ let mut mdesc = LocalSet::new(40);+ mdesc.p(0x3001, &[0, 0, 0, 25, 0, 0, 0, 1]).p(0x3F01, &batch(&[&uuid(41), &uuid(42)]));+ klv(&mut md, set_key(0x44), &mdesc.0);+ let mut cdci = LocalSet::new(41);+ cdci.p(0x3006, &2u32.to_be_bytes())+ .p(0x3203, &64u32.to_be_bytes())+ .p(0x3202, &32u32.to_be_bytes())+ .p(0x320E, &[0, 0, 0, 2, 0, 0, 0, 1])+ .p(0x3301, &8u32.to_be_bytes())+ .p(0x3201, &ul(&[0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x0A, 0x04, 0x01, 0x02, 0x02, 0x03, 0x06, 0x03, 0x00]));+ klv(&mut md, set_key(0x28), &cdci.0);+ let mut wave = LocalSet::new(42);+ wave.p(0x3006, &3u32.to_be_bytes())+ .p(0x3D03, &[0, 0, 0xBB, 0x80, 0, 0, 0, 1])+ .p(0x3D07, &2u32.to_be_bytes())+ .p(0x3D01, &16u32.to_be_bytes())+ .p(0x3D0A, &4u16.to_be_bytes());+ klv(&mut md, set_key(0x48), &wave.0);+ let mut ecd = LocalSet::new(5);+ ecd.p(0x2701, &umid(2)).p(0x3F07, &1u32.to_be_bytes()).p(0x3F06, &2u32.to_be_bytes());+ klv(&mut md, set_key(0x23), &ecd.0);++ let mut f = partition(2, 0, 0, 0, md.len() as u64);+ f.extend_from_slice(&md);+ let body_at = f.len() as u64;+ f.extend_from_slice(&partition(3, body_at, 1, 0, 0));+ let mut offsets = Vec::new();+ let mut cp_base = None;+ for i in 0..n {+ let at = f.len() as u64;+ let base = *cp_base.get_or_insert(at);+ offsets.push(at - base);+ klv(&mut f, PIC_KEY, &pic(i));+ let mut snd = Vec::new();+ for k in 0..1920 {+ let s = ((i * 1920 + k) % 30000) as i16;+ snd.extend_from_slice(&s.to_le_bytes());+ snd.extend_from_slice(&(-s).to_le_bytes());+ }+ klv(&mut f, SND_KEY, &snd);+ }+ let footer_at = f.len() as u64;+ f.extend_from_slice(&partition(4, footer_at, 0, 2, 0));+ let mut ix = LocalSet::new(6);+ let mut entries = Vec::new();+ for i in 0..n {+ let mut e = vec![to.get(i).copied().unwrap_or(0) as u8, 0, flags.get(i).copied().unwrap_or(0)];+ e.extend_from_slice(&offsets[i].to_be_bytes());+ entries.push(e);+ }+ let refs: Vec<&[u8]> = entries.iter().map(Vec::as_slice).collect();+ ix.p(0x3F0B, &[0, 0, 0, 25, 0, 0, 0, 1])+ .p(0x3F0C, &0i64.to_be_bytes())+ .p(0x3F0D, &(n as i64).to_be_bytes())+ .p(0x3F06, &2u32.to_be_bytes())+ .p(0x3F07, &1u32.to_be_bytes())+ .p(0x3F0A, &batch(&refs));+ klv(&mut f, ul(&[0x06, 0x0E, 0x2B, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x10, 0x01, 0x00]), &ix.0);+ f+}++/// Stored order I0 P3 B1 B2 P6 B4 B5: display d is stored at d + TO[d].+fn ipbb() -> (Vec<i8>, Vec<u8>) {+ (vec![0, 1, 1, -2, 1, 1, -2], vec![0xC0, 0x22, 0x33, 0x33, 0x22, 0x33, 0x33])+}++fn prores_like(i: usize) -> Vec<u8> {+ let mut v = vec![0, 0, 0, 40];+ v.extend_from_slice(b"icpf");+ v.extend(std::iter::repeat_n(i as u8, 32));+ v+}++#[test]+fn opens_synthetic_op1a() {+ let (to, flags) = ipbb();+ let f = build(7, |i| vec![i as u8; 100 + i], &to, &flags);+ let m = open(&f).unwrap();+ assert_eq!(m.operational_pattern, OperationalPattern::Generalized { item: 1, package: 1 });+ assert_eq!(m.operational_pattern.name(), "OP1a");+ assert_eq!(m.material_package_name.as_deref(), Some("MP"));+ let tc = m.timecode.unwrap();+ assert_eq!((tc.start, tc.rounded_base, tc.drop_frame), (90_000, 25, false));+ assert_eq!(tc.format(), "01:00:00:00");+ let v = m.track_of_kind(TrackKind::Picture).unwrap();+ let t = &m.tracks[v];+ assert_eq!(t.track_number, 0x1501_0500);+ assert_eq!(t.edit_rate, Rational::new(25, 1));+ assert_eq!(t.duration, Some(7));+ assert_eq!(t.samples.len(), 7);+ let p = t.picture.as_ref().unwrap();+ assert_eq!((p.frame_width(), p.frame_height()), (64, 32));+ assert_eq!(t.codec, Codec::ProRes { profile: Some(3) }, "coding label wins (the bytes do not sniff as anything)");+ // presentation order from the temporal offsets+ let pts: Vec<i64> = t.samples.iter().map(|s| s.pts).collect();+ assert_eq!(pts, vec![0, 3, 1, 2, 6, 4, 5]);+ assert_eq!(t.display_order, vec![0, 2, 3, 1, 5, 6, 4]);+ assert!(t.temporal_offsets);+ assert_eq!(t.sample_at(3), Some(1));+ // the index marks only the first picture random-access (ProRes would be intra; this label says ProRes so all are key)+ assert!(t.samples.iter().all(|s| s.key));+ // sample bytes+ for i in 0..7 {+ assert_eq!(m.read_sample(&f, v, i).unwrap(), vec![i as u8; 100 + i]);+ }+ // sound: 7 × 1920 frames, sample k = k on the left, -k on the right+ let a = m.track_of_kind(TrackKind::Sound).unwrap();+ let s = &m.tracks[a];+ assert_eq!(s.codec, Codec::Pcm);+ assert_eq!(s.stored_sample_frames(), 7 * 1920);+ assert_eq!(s.samples_per_edit_unit(), (48000, 25));+ let pcm = m.read_pcm(&f, a, 1900, 50).unwrap();+ for k in 0..50 {+ assert_eq!(pcm[0][k], (1900 + k) as f32 / 32768.0);+ assert_eq!(pcm[1][k], -((1900 + k) as f32) / 32768.0);+ }+ // past the end: zeros+ let tail = m.read_pcm(&f, a, 7 * 1920 - 2, 4).unwrap();+ assert_eq!(tail[0][2..], [0.0, 0.0]);+}++#[test]+fn key_frames_from_index_flags_for_long_gop() {+ let (to, flags) = ipbb();+ // AVC-looking essence (start code + AUD) and no coding label: sniffed as AVC+ let f = build(7, |i| vec![0, 0, 0, 1, 9, 0x10, i as u8], &to, &flags);+ // replace the ProRes coding label so the codec comes from the bytes+ let mut f2 = f.clone();+ let lbl = [0x04, 0x01, 0x02, 0x02, 0x03, 0x06, 0x03, 0x00];+ let at = f2.windows(8).position(|w| w == lbl).unwrap();+ f2[at..at + 8].copy_from_slice(&[0x04, 0x01, 0x02, 0x02, 0x01, 0x31, 0x40, 0x01]);+ let m = open(&f2).unwrap();+ let t = &m.tracks[m.track_of_kind(TrackKind::Picture).unwrap()];+ assert_eq!(t.codec, Codec::Avc { intra: false });+ let keys: Vec<bool> = t.samples.iter().map(|s| s.key).collect();+ assert_eq!(keys, vec![true, false, false, false, false, false, false]);+ assert_eq!(t.sync_before(5), 0);+ assert!(t.indexed);+ let b: Vec<bool> = t.samples.iter().map(|s| s.b_picture).collect();+ assert_eq!(b, vec![false, false, true, true, false, true, true]);+}++#[test]+fn missing_temporal_offsets_with_b_pictures_ask_for_reordering() {+ let (_, flags) = ipbb();+ let m = open(&build(7, prores_like, &[], &flags)).unwrap();+ let t = &m.tracks[0];+ assert!(!t.temporal_offsets);+ // ProRes is intra-only: the B flags are ignored for key frames, reordering still reported+ assert!(t.samples.iter().all(|s| s.key));+}++#[test]+fn not_mxf_and_empty() {+ assert!(matches!(open(&b"RIFF....WAVE".to_vec()), Err(Error::NotMxf(_))));+ assert!(open(&Vec::new()).is_err());+ assert!(!sniff(b"\x1aE\xdf\xa3"));+}++#[test]+fn truncation_never_panics_and_keeps_whole_frames() {+ let (to, flags) = ipbb();+ let f = build(7, prores_like, &to, &flags);+ let mut opened = 0;+ for cut in (0..f.len()).step_by(37) {+ let part = f[..cut].to_vec();+ if let Ok(m) = open(&part) {+ opened += 1;+ for (ti, t) in m.tracks.iter().enumerate() {+ for i in 0..t.samples.len() {+ // every listed sample is fully inside the file+ assert!(m.read_sample(&part, ti, i).is_ok(), "cut {cut} track {ti} sample {i}");+ }+ if t.sound.is_some() {+ let _ = m.read_pcm(&part, ti, 0, 5000);+ }+ }+ }+ }+ assert!(opened > 10, "truncated files with complete metadata still open ({opened})");+}++#[test]+fn mutation_never_panics() {+ let (to, flags) = ipbb();+ let f = build(5, prores_like, &to, &flags);+ let mut seed = 0x1234_5678u64;+ for _ in 0..600 {+ let mut g = f.clone();+ for _ in 0..4 {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ let at = (seed as usize) % g.len();+ g[at] = (seed >> 32) as u8;+ }+ if let Ok(m) = open(&g) {+ for (ti, t) in m.tracks.iter().enumerate() {+ for i in 0..t.samples.len().min(8) {+ let _ = m.read_sample(&g, ti, i);+ }+ let _ = m.read_pcm(&g, ti, 0, 100);+ }+ }+ }+}++#[test]+fn drop_frame_timecode_format() {+ let tc = Timecode { start: 107_892, rounded_base: 30, drop_frame: true };+ assert_eq!(tc.format(), "01:00:00;00");+ let tc = Timecode { start: 1800, rounded_base: 30, drop_frame: true };+ assert_eq!(tc.format(), "00:01:00;02");+ let tc = Timecode { start: 90_000 + 25 * 61 + 3, rounded_base: 25, drop_frame: false };+ assert_eq!(tc.format(), "01:01:01:03");+}diff --git a/crates/ogg/Cargo.toml b/crates/ogg/Cargo.tomlnew file mode 100644index 000000000..5f76b77e8--- /dev/null+++ b/crates/ogg/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "filmcraft-ogg"+description = "Clean-room Ogg (RFC 3533) demuxer with Ogg Opus (RFC 7845) and Ogg Vorbis stream mapping"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++[dependencies]++[dev-dependencies]+filmcraft-testkit = { workspace = true }diff --git a/crates/ogg/README.md b/crates/ogg/README.mdnew file mode 100644index 000000000..a3d7f9196--- /dev/null+++ b/crates/ogg/README.md@@ -0,0 +1,42 @@+# filmcraft-ogg++A clean-room Ogg demuxer. Layer L0: no dependencies beyond `std`, no `unsafe`, builds for+`wasm32-unknown-unknown`. No libogg / libopusfile / FFmpeg code was consulted; FFmpeg is used only+as an external fixture generator and test oracle.++## Specifications++| Document | Used for |+|---|---|+| RFC 3533 (2003) | pages, lacing, packet continuation, CRC-32, logical bitstreams |+| RFC 7845 (2016) | Ogg Opus: `OpusHead` / `OpusTags`, granule positions, pre-skip, end trimming (§4) |+| RFC 6716 (2012) §3.1 | Opus TOC byte: packet durations |+| Vorbis I specification (2020-07-04), §4.2.2 and Appendix A | Vorbis identification header, Ogg mapping |++## Use++```rust+let bytes = std::fs::read("voice.opus")?;+let ogg = filmcraft_ogg::open(&bytes)?;+let s = ogg.stream_of(filmcraft_ogg::Codec::Opus).unwrap();+let head = &ogg.streams[s].headers[0]; // OpusHead+let pre_skip = u16::from_le_bytes([head[10], head[11]]) as u32;+let timing = filmcraft_ogg::OpusTiming::of(&ogg.streams[s], pre_skip);+let k = timing.starts.partition_point(|&x| x <= 48_000) - 1; // packet holding sample 48 000+let packet = ogg.read_packet(&bytes, s, k)?;+```++- Every page is read and its CRC checked; damaged pages are dropped and the reader resynchronises+ on the next `OggS`. Packets spanning pages are lists of byte ranges; a continued page whose start+ was lost drops the fragment.+- `OpusTiming`: packet durations from the TOC; positions anchored on the first page's granule+ (backwards from it), then accumulated forwards, re-anchoring on any granule discontinuity; the+ final (end-of-stream) page's smaller granule trims the end. Positions are relative to the first+ sample after the pre-skip (pre-skip samples are negative).++## Tests++`src/tests.rs` writes synthetic pages: timing with pre-skip and end trimming, packets across pages,+a corrupted page (CRC), every truncation and 300 mutations. `crates/codecs/tests/ogg_oracle.rs`+compares with FFmpeg's libopus / Vorbis decodes (exact length; SNR ≥ 50 dB CELT, ≥ 10 dB SILK,+Vorbis 139 dB) and checks random seeks against the continuous decode.diff --git a/crates/ogg/src/lib.rs b/crates/ogg/src/lib.rsnew file mode 100644index 000000000..082f5bce2--- /dev/null+++ b/crates/ogg/src/lib.rs@@ -0,0 +1,483 @@+//! Clean-room Ogg demuxer, written from RFC 3533 (the Ogg encapsulation format), RFC 7845 (Ogg+//! Opus) and the Vorbis I specification's Ogg mapping (section A).+//!+//! [`open`] reads every page (capture pattern, header, lacing values, CRC-32 checked; damaged+//! regions are skipped by searching for the next `OggS`), groups them by logical bitstream and+//! assembles packets — including packets that continue across pages — as lists of byte ranges,+//! with the granule position of the page each packet completes on. Codec headers (Opus:+//! `OpusHead` + `OpusTags`; Vorbis: identification, comment, setup) are collected separately from+//! the audio packets.+//!+//! [`OpusTiming`] implements RFC 7845 §4: packet start positions from granule positions and+//! TOC-derived durations, the pre-skip, and end trimming of the final page, so a player can seek+//! to any 48 kHz sample.+//!+//! Layer L0: no dependencies beyond `std`, no `unsafe`, builds for `wasm32-unknown-unknown`.++use std::collections::HashMap;+use std::fmt;+use std::io;++/// Random-access, read-only byte source (same shape as the other FilmCraft demuxers').+pub trait ByteSource {+ fn len(&self) -> u64;+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>;+ fn is_empty(&self) -> bool {+ self.len() == 0+ }+}++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 eof = || io::Error::new(io::ErrorKind::UnexpectedEof, "read past end");+ let a = usize::try_from(offset).map_err(|_| eof())?;+ buf.copy_from_slice(self.get(a..a.checked_add(buf.len()).ok_or_else(eof)?).ok_or_else(eof)?);+ Ok(())+ }+}++impl ByteSource for Vec<u8> {+ fn len(&self) -> u64 {+ self.as_slice().len() as u64+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ self.as_slice().read_at(offset, buf)+ }+}++impl<T: ByteSource + ?Sized> ByteSource for &T {+ fn len(&self) -> u64 {+ (**self).len()+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ (**self).read_at(offset, buf)+ }+}++#[derive(Debug)]+pub enum Error {+ Io(io::Error),+ /// No Ogg page found.+ NotOgg,+ Invalid(String),+}++impl fmt::Display for Error {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Error::Io(e) => write!(f, "I/O error: {e}"),+ Error::NotOgg => write!(f, "not an Ogg file"),+ Error::Invalid(s) => write!(f, "invalid Ogg: {s}"),+ }+ }+}++impl std::error::Error for Error {}++impl From<io::Error> for Error {+ fn from(e: io::Error) -> Self {+ Error::Io(e)+ }+}++pub type Result<T> = std::result::Result<T, Error>;++/// The capture pattern at the start of a file.+pub fn sniff(head: &[u8]) -> bool {+ head.len() >= 27 && &head[..4] == b"OggS" && head[4] == 0+}++/// CRC-32 of RFC 3533 §6: polynomial 0x04C11DB7, initial value 0, no reflection, no final XOR.+pub fn crc32(data: &[u8]) -> u32 {+ static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new();+ let t = TABLE.get_or_init(|| {+ let mut t = [0u32; 256];+ for (i, e) in t.iter_mut().enumerate() {+ let mut r = (i as u32) << 24;+ for _ in 0..8 {+ r = if r & 0x8000_0000 != 0 { (r << 1) ^ 0x04C1_1DB7 } else { r << 1 };+ }+ *e = r;+ }+ t+ });+ data.iter().fold(0u32, |c, &b| (c << 8) ^ t[((c >> 24) as u8 ^ b) as usize])+}++/// The codec of a logical bitstream (from its first packet).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Codec {+ Opus,+ Vorbis,+ Flac,+ Theora,+ Speex,+ Unknown,+}++impl Codec {+ fn of(first: &[u8]) -> Codec {+ if first.starts_with(b"OpusHead") {+ Codec::Opus+ } else if first.starts_with(b"\x01vorbis") {+ Codec::Vorbis+ } else if first.starts_with(b"\x7fFLAC") {+ Codec::Flac+ } else if first.starts_with(b"\x80theora") {+ Codec::Theora+ } else if first.starts_with(b"Speex ") {+ Codec::Speex+ } else {+ Codec::Unknown+ }+ }+ /// Header packets before the audio packets.+ fn header_count(self) -> usize {+ match self {+ Codec::Opus => 2,+ Codec::Vorbis | Codec::Theora => 3,+ Codec::Speex => 2,+ Codec::Flac | Codec::Unknown => 1,+ }+ }+ pub fn name(self) -> &'static str {+ match self {+ Codec::Opus => "Opus",+ Codec::Vorbis => "Vorbis",+ Codec::Flac => "FLAC",+ Codec::Theora => "Theora",+ Codec::Speex => "Speex",+ Codec::Unknown => "unknown",+ }+ }+}++/// A packet: its byte ranges (a packet may span pages) and the granule position of the page it+/// completes on when it is that page's last completed packet.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Packet {+ pub parts: Vec<(u64, u32)>,+ pub size: u32,+ /// Granule position of the completing page if this is the last packet completed on it.+ pub granule: Option<i64>,+ /// Index of the page (within the stream) the packet completes on.+ pub page: u32,+ /// The packet completes on the stream's end-of-stream page.+ pub eos: bool,+ /// The first bytes of the packet (TOC for Opus, packet type for Vorbis).+ pub prefix: [u8; 2],+}++/// A logical bitstream.+#[derive(Clone, Debug)]+pub struct Stream {+ pub serial: u32,+ pub codec: Codec,+ /// Codec header packets (contents).+ pub headers: Vec<Vec<u8>>,+ /// Data packets after the headers.+ pub packets: Vec<Packet>,+ pub pages: u32,+ /// Granule position of the last page with one.+ pub last_granule: Option<i64>,+ pub saw_eos: bool,+}++/// An opened Ogg file.+#[derive(Clone, Debug)]+pub struct OggFile {+ pub streams: Vec<Stream>,+ /// Pages dropped for a bad CRC, lost sync, truncation…+ pub warnings: Vec<String>,+}++struct Partial {+ parts: Vec<(u64, u32)>,+ size: u32,+ prefix: Vec<u8>,+}++/// Read every page and assemble the packets of every logical bitstream.+pub fn open(src: &(impl ByteSource + ?Sized)) -> Result<OggFile> {+ let len = src.len();+ let mut streams: Vec<Stream> = Vec::new();+ let mut by_serial: HashMap<u32, usize> = HashMap::new();+ let mut partial: HashMap<u32, Partial> = HashMap::new();+ let mut warnings = Vec::new();+ let mut pos = 0u64;+ let mut found_any = false;+ let mut hdr = [0u8; 27 + 255];+ while pos + 27 <= len {+ src.read_at(pos, &mut hdr[..27])?;+ if &hdr[..4] != b"OggS" || hdr[4] != 0 {+ match find_capture(src, pos + 1, len)? {+ Some(p) => {+ if found_any {+ warnings.push(format!("lost sync at byte {pos}; resumed at {p}"));+ }+ pos = p;+ continue;+ }+ None => break,+ }+ }+ let nseg = hdr[26] as usize;+ if pos + 27 + nseg as u64 > len {+ warnings.push(format!("truncated page header at byte {pos}"));+ break;+ }+ src.read_at(pos + 27, &mut hdr[27..27 + nseg])?;+ let body_len: u64 = hdr[27..27 + nseg].iter().map(|&b| b as u64).sum();+ let page_len = 27 + nseg as u64 + body_len;+ if pos + page_len > len {+ warnings.push(format!("truncated page at byte {pos}"));+ break;+ }+ let mut page = vec![0u8; page_len as usize];+ src.read_at(pos, &mut page)?;+ let stored_crc = u32::from_le_bytes([page[22], page[23], page[24], page[25]]);+ page[22..26].fill(0);+ if crc32(&page) != stored_crc {+ warnings.push(format!("bad CRC on page at byte {pos}"));+ pos += 1;+ continue;+ }+ found_any = true;+ let flags = page[5];+ let granule = i64::from_le_bytes(page[6..14].try_into().unwrap_or([0; 8]));+ let serial = u32::from_le_bytes([page[14], page[15], page[16], page[17]]);+ let lacing = page[27..27 + nseg].to_vec();+ let body_off = pos + 27 + nseg as u64;+ let si = *by_serial.entry(serial).or_insert_with(|| {+ streams.push(Stream { serial, codec: Codec::Unknown, headers: Vec::new(), packets: Vec::new(), pages: 0, last_granule: None, saw_eos: false });+ streams.len() - 1+ });+ let st = &mut streams[si];+ let page_index = st.pages;+ st.pages += 1;+ if flags & 0x04 != 0 {+ st.saw_eos = true;+ }+ // a continued page without a pending packet (lost a page): drop the fragment+ let continued = flags & 0x01 != 0;+ if !continued && partial.remove(&serial).is_some() {+ warnings.push(format!("incomplete packet before page at byte {pos}"));+ }+ let mut completed: Vec<Packet> = Vec::new();+ let mut off = 0u64;+ let mut seg_start = 0u64;+ let mut skip_fragment = continued && !partial.contains_key(&serial);+ for (k, &l) in lacing.iter().enumerate() {+ off += l as u64;+ if l < 255 || k + 1 == nseg {+ let (a, n) = (seg_start, off - seg_start);+ seg_start = off;+ if skip_fragment {+ if l < 255 {+ skip_fragment = false;+ }+ continue;+ }+ let p = partial.entry(serial).or_insert_with(|| Partial { parts: Vec::new(), size: 0, prefix: Vec::new() });+ if n > 0 {+ p.parts.push((body_off + a, n as u32));+ p.size += n as u32;+ let s = (body_off - pos + a) as usize;+ let need = 2usize.saturating_sub(p.prefix.len()).min(n as usize);+ p.prefix.extend_from_slice(&page[s..s + need]);+ }+ if l < 255 {+ let p = partial.remove(&serial).expect("partial");+ let mut prefix = [0u8; 2];+ prefix[..p.prefix.len().min(2)].copy_from_slice(&p.prefix[..p.prefix.len().min(2)]);+ completed.push(Packet { parts: p.parts, size: p.size, granule: None, page: page_index, eos: flags & 0x04 != 0, prefix });+ }+ }+ }+ if granule != -1 {+ st.last_granule = Some(granule);+ if let Some(last) = completed.last_mut() {+ last.granule = Some(granule);+ }+ }+ for pk in completed {+ if st.headers.is_empty() && st.packets.is_empty() {+ let data = read_parts(src, &pk.parts)?;+ st.codec = Codec::of(&data);+ }+ if st.headers.len() < st.codec.header_count() && st.packets.is_empty() {+ st.headers.push(read_parts(src, &pk.parts)?);+ } else {+ st.packets.push(pk);+ }+ }+ pos += page_len;+ }+ if !found_any {+ return Err(Error::NotOgg);+ }+ if !partial.is_empty() {+ warnings.push("file ends inside a packet".into());+ }+ Ok(OggFile { streams, warnings })+}++fn find_capture(src: &(impl ByteSource + ?Sized), from: u64, len: u64) -> Result<Option<u64>> {+ let mut at = from;+ while at + 4 <= len {+ let n = ((len - at) as usize).min(1 << 20);+ let mut buf = vec![0u8; n];+ src.read_at(at, &mut buf)?;+ if let Some(i) = buf.windows(4).position(|w| w == b"OggS") {+ return Ok(Some(at + i as u64));+ }+ if n < 4 {+ break;+ }+ at += (n - 3) as u64;+ }+ Ok(None)+}++fn read_parts(src: &(impl ByteSource + ?Sized), parts: &[(u64, u32)]) -> Result<Vec<u8>> {+ let mut v = Vec::with_capacity(parts.iter().map(|p| p.1 as usize).sum());+ for &(o, n) in parts {+ let a = v.len();+ v.resize(a + n as usize, 0);+ src.read_at(o, &mut v[a..])?;+ }+ Ok(v)+}++impl OggFile {+ /// The first stream of `codec`.+ pub fn stream_of(&self, codec: Codec) -> Option<usize> {+ self.streams.iter().position(|s| s.codec == codec)+ }+ /// The bytes of packet `i` of stream `s`.+ pub fn read_packet(&self, src: &(impl ByteSource + ?Sized), s: usize, i: usize) -> Result<Vec<u8>> {+ let p = self.streams.get(s).and_then(|st| st.packets.get(i)).ok_or_else(|| Error::Invalid(format!("no packet {i} in stream {s}")))?;+ read_parts(src, &p.parts)+ }+}++/// Duration of an Opus packet in 48 kHz samples from its TOC (RFC 6716 §3.1); `None` if invalid.+pub fn opus_packet_samples(prefix: [u8; 2], size: u32) -> Option<u32> {+ if size == 0 {+ return None;+ }+ let toc = prefix[0];+ let config = toc >> 3;+ let frame = match config {+ 0..=11 => [480, 960, 1920, 2880][(config & 3) as usize],+ 12..=15 => [480, 960][(config & 1) as usize],+ _ => [120, 240, 480, 960][(config & 3) as usize],+ };+ let frames = match toc & 3 {+ 0 => 1,+ 1 | 2 => 2,+ _ => {+ if size < 2 {+ return None;+ }+ (prefix[1] & 0x3F) as u32+ }+ };+ let n = frame * frames;+ (n > 0 && n <= 5760).then_some(n)+}++/// RFC 7845 §4 timing of an Opus stream.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct OpusTiming {+ pub pre_skip: u32,+ /// Start of each packet's decoded output in output samples (48 kHz): 0 is the first sample+ /// after the pre-skip; the pre-skip samples have negative positions.+ pub starts: Vec<i64>,+ /// Decoded samples of each packet.+ pub durations: Vec<u32>,+ /// Playable samples (end trimming applied).+ pub total: i64,+}++impl OpusTiming {+ /// Timing of the Opus stream `s` (`pre_skip` from its `OpusHead`).+ pub fn of(stream: &Stream, pre_skip: u32) -> OpusTiming {+ let durations: Vec<u32> = stream.packets.iter().map(|p| opus_packet_samples(p.prefix, p.size).unwrap_or(0)).collect();+ let n = durations.len();+ let mut ends: Vec<Option<i64>> = vec![None; n];+ let mut i = 0;+ let mut cursor: Option<i64> = None;+ let mut trimmed_end: Option<i64> = None;+ while i < n {+ // packets completing on the same page: i..j, the last carries the page granule+ let mut j = i;+ while j < n && stream.packets[j].granule.is_none() {+ j += 1;+ }+ if j == n {+ // trailing packets without a granule (truncated file): continue from the cursor+ let mut c = cursor.unwrap_or(0);+ for k in i..n {+ c += durations[k] as i64;+ ends[k] = Some(c);+ }+ break;+ }+ let g = stream.packets[j].granule.expect("granule");+ let sum: i64 = durations[i..=j].iter().map(|&d| d as i64).sum();+ let forward = cursor.map(|c| c + sum);+ let end = match forward {+ // end trimming on the last page (RFC 7845 §4.5): keep the forward positions+ Some(f) if stream.packets[j].eos && g < f => {+ trimmed_end = Some(g);+ f+ }+ Some(f) if f == g => f,+ // first page, or a discontinuity: trust the granule+ _ => g,+ };+ let mut e = end;+ for k in (i..=j).rev() {+ ends[k] = Some(e);+ e -= durations[k] as i64;+ }+ cursor = Some(end);+ i = j + 1;+ }+ let raw_starts: Vec<i64> = ends.iter().zip(&durations).map(|(e, &d)| e.unwrap_or(0) - d as i64).collect();+ let base = raw_starts.first().copied().unwrap_or(0).max(0);+ let shift = base + pre_skip as i64;+ let starts: Vec<i64> = raw_starts.iter().map(|s| s - shift).collect();+ let end_all = trimmed_end.or(cursor).unwrap_or(0);+ let total = (end_all - shift).max(0);+ OpusTiming { pre_skip, starts, durations, total }+ }+}++/// Vorbis identification header fields (Vorbis I §4.2.2).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VorbisInfo {+ pub channels: u8,+ pub sample_rate: u32,+ pub bitrate_nominal: i32,+}++impl VorbisInfo {+ pub fn parse(h: &[u8]) -> Option<VorbisInfo> {+ if h.len() < 30 || !h.starts_with(b"\x01vorbis") {+ return None;+ }+ Some(VorbisInfo {+ channels: h[11],+ sample_rate: u32::from_le_bytes([h[12], h[13], h[14], h[15]]),+ bitrate_nominal: i32::from_le_bytes([h[20], h[21], h[22], h[23]]),+ })+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/ogg/src/tests.rs b/crates/ogg/src/tests.rsnew file mode 100644index 000000000..f1879b36b--- /dev/null+++ b/crates/ogg/src/tests.rs@@ -0,0 +1,181 @@+//! Synthetic Ogg streams: a small page writer (RFC 3533) and Opus-like packets.++use super::*;++/// Write one page holding `segments` (lacing already computed by `lace`).+fn page(out: &mut Vec<u8>, flags: u8, granule: i64, serial: u32, seq: u32, lacing: &[u8], body: &[u8]) {+ let start = out.len();+ out.extend_from_slice(b"OggS");+ out.push(0);+ out.push(flags);+ out.extend_from_slice(&granule.to_le_bytes());+ out.extend_from_slice(&serial.to_le_bytes());+ out.extend_from_slice(&seq.to_le_bytes());+ out.extend_from_slice(&[0; 4]);+ out.push(lacing.len() as u8);+ out.extend_from_slice(lacing);+ out.extend_from_slice(body);+ let crc = crc32(&out[start..]);+ out[start + 22..start + 26].copy_from_slice(&crc.to_le_bytes());+}++fn lace(packets: &[&[u8]], last_continues: bool) -> (Vec<u8>, Vec<u8>) {+ let mut l = Vec::new();+ let mut b = Vec::new();+ for (i, p) in packets.iter().enumerate() {+ let mut n = p.len();+ while n >= 255 {+ l.push(255);+ n -= 255;+ }+ if !(last_continues && i + 1 == packets.len()) {+ l.push(n as u8);+ }+ b.extend_from_slice(p);+ }+ (l, b)+}++fn opus_head(pre_skip: u16) -> Vec<u8> {+ let mut h = b"OpusHead".to_vec();+ h.push(1);+ h.push(2);+ h.extend_from_slice(&pre_skip.to_le_bytes());+ h.extend_from_slice(&48_000u32.to_le_bytes());+ h.extend_from_slice(&0i16.to_le_bytes());+ h.push(0);+ h+}++/// A CELT 20 ms packet (960 samples): TOC config 31, code 0.+fn pkt(i: usize, len: usize) -> Vec<u8> {+ let mut p = vec![0xF8];+ p.extend((0..len.saturating_sub(1)).map(|k| (i * 7 + k) as u8));+ p+}++/// Header pages, then pages of 3 packets each; the last page's granule trims `trim` samples.+fn opus_file(npk: usize, pre_skip: u16, trim: i64) -> Vec<u8> {+ let mut f = Vec::new();+ let head = opus_head(pre_skip);+ let (l, b) = lace(&[&head], false);+ page(&mut f, 0x02, 0, 9, 0, &l, &b);+ let tags = b"OpusTags\x00\x00\x00\x00\x00\x00\x00\x00".to_vec();+ let (l, b) = lace(&[&tags], false);+ page(&mut f, 0, 0, 9, 1, &l, &b);+ let pkts: Vec<Vec<u8>> = (0..npk).map(|i| pkt(i, 40 + i % 5)).collect();+ let mut done = 0;+ for (seq, chunk) in (2..).zip(pkts.chunks(3)) {+ done += chunk.len();+ let last = done == npk;+ let mut g = done as i64 * 960;+ if last {+ g -= trim;+ }+ let refs: Vec<&[u8]> = chunk.iter().map(Vec::as_slice).collect();+ let (l, b) = lace(&refs, false);+ page(&mut f, if last { 0x04 } else { 0 }, g, 9, seq, &l, &b);+ }+ f+}++#[test]+fn crc_matches_known_value() {+ // CRC-32/CKSUM parameters without its final XOR (check value 0x765E7680 ^ 0xFFFFFFFF)+ assert_eq!(crc32(b"123456789"), 0x89A1_897F);+ assert_eq!(crc32(b""), 0);+ assert_ne!(crc32(b"OggS"), crc32(b"OggT"));+}++#[test]+fn opus_pages_packets_and_timing() {+ let f = opus_file(10, 312, 500);+ assert!(sniff(&f));+ let o = open(&f).unwrap();+ assert!(o.warnings.is_empty(), "{:?}", o.warnings);+ let s = o.stream_of(Codec::Opus).unwrap();+ let st = &o.streams[s];+ assert_eq!(st.headers.len(), 2);+ assert_eq!(st.packets.len(), 10);+ assert!(st.saw_eos);+ assert_eq!(o.read_packet(&f, s, 4).unwrap(), pkt(4, 44));+ let t = OpusTiming::of(st, 312);+ assert_eq!(t.durations, vec![960; 10]);+ assert_eq!(t.starts[0], -312);+ assert_eq!(t.starts[9], 9 * 960 - 312);+ // end trimming: the last page granule is 500 short+ assert_eq!(t.total, 10 * 960 - 500 - 312);+}++#[test]+fn packets_spanning_pages() {+ let mut f = Vec::new();+ let head = opus_head(0);+ let (l, b) = lace(&[&head], false);+ page(&mut f, 0x02, 0, 1, 0, &l, &b);+ let (l, b) = lace(&[b"OpusTags"], false);+ page(&mut f, 0, 0, 1, 1, &l, &b);+ let big = pkt(0, 700);+ // first 510 bytes on one page (two 255 lacing values, packet continues), rest on the next+ let (l, b) = (vec![255, 255], big[..510].to_vec());+ page(&mut f, 0, -1, 1, 2, &l, &b);+ let rest = &big[510..];+ let small = pkt(1, 30);+ let (l, b) = lace(&[rest, &small], false);+ page(&mut f, 0x01 | 0x04, 1920, 1, 3, &l, &b);+ let o = open(&f).unwrap();+ let st = &o.streams[0];+ assert_eq!(st.packets.len(), 2);+ assert_eq!(st.packets[0].parts.len(), 2);+ assert_eq!(o.read_packet(&f, 0, 0).unwrap(), big);+ assert_eq!(o.read_packet(&f, 0, 1).unwrap(), small);+ let t = OpusTiming::of(st, 0);+ assert_eq!(t.starts, vec![0, 960]);+ assert_eq!(t.total, 1920);+}++#[test]+fn corrupt_pages_are_skipped_and_truncation_is_safe() {+ let f = opus_file(12, 312, 0);+ // flip a byte inside the third data page's body: that page fails its CRC and is dropped+ let mut g = f.clone();+ let third = g.windows(4).enumerate().filter(|(_, w)| *w == b"OggS").map(|(i, _)| i).nth(4).unwrap();+ g[third + 40] ^= 0xFF;+ let o = open(&g).unwrap();+ assert!(o.warnings.iter().any(|w| w.contains("CRC")), "{:?}", o.warnings);+ assert_eq!(o.streams[0].packets.len(), 9);+ let t = OpusTiming::of(&o.streams[0], 312);+ // the granules after the gap put the later packets at their true positions+ assert_eq!(*t.starts.last().unwrap(), 11 * 960 - 312);+ for cut in 0..f.len() {+ if let Ok(o) = open(&f[..cut].to_vec()) {+ for st in &o.streams {+ let t = OpusTiming::of(st, 312);+ assert_eq!(t.starts.len(), st.packets.len());+ }+ }+ }+ let mut seed = 99u64;+ for _ in 0..300 {+ let mut g = f.clone();+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ let at = (seed >> 33) as usize % g.len();+ g[at] = (seed >> 20) as u8;+ if let Ok(o) = open(&g) {+ for st in &o.streams {+ let _ = OpusTiming::of(st, 312);+ }+ }+ }+ assert!(matches!(open(&b"not ogg at all, no capture pattern".to_vec()), Err(Error::NotOgg)));+}++#[test]+fn opus_toc_durations() {+ assert_eq!(opus_packet_samples([0x00, 0], 10), Some(480)); // SILK NB 10 ms+ assert_eq!(opus_packet_samples([0x18, 0], 10), Some(2880)); // SILK NB 60 ms+ assert_eq!(opus_packet_samples([0x78 | 1, 0], 10), Some(1920)); // hybrid 20 ms × 2+ assert_eq!(opus_packet_samples([0x80 | 3, 6], 10), Some(720)); // CELT 2.5 ms × 6+ assert_eq!(opus_packet_samples([0xF8 | 3, 7], 10), None); // 140 ms: invalid+ assert_eq!(opus_packet_samples([0xF8, 0], 0), None);+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 76c88583d..726986b4e 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -654,6 +654,16 @@ impl FilmcraftApp {}r}+ // File ▸ Import with Image Sequence: choose the first numbered still+ "file.importImageSequence" => {+ let paths = self.hooks.pick_files.as_mut().map(|f| f(filmcraft_media::STILL_EXTENSIONS)).unwrap_or_default();+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };+ let r = self.session.execute("file.importImageSequence", json!({"path": path})).map_err(|e| e.to_string());+ if let Err(e) = &r {+ self.ui.status = e.clone();+ }+ r+ }"file.saveAs" | "file.save" | "file.saveCopy" => {let suggested =if id == "file.saveCopy" { format!("{} copy.fcproj", self.session.project.name) } else { format!("{}.fcproj", self.session.project.name) };diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 1c664eeee..cc3ccb2a9 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -318,6 +318,7 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val}// File dialogs for commands that need a path.if (id == "file.import" && params.get("paths").is_none() && params.get("path").is_none())+ || (id == "file.importImageSequence" && params.get("path").is_none())|| (id == "file.saveAs" && params.get("path").is_none())|| (id == "file.saveCopy" && params.get("path").is_none())|| (id == "file.open" && params.get("path").is_none())diff --git a/crates/ui-egui/src/panels/menu_dialogs.rs b/crates/ui-egui/src/panels/menu_dialogs.rsindex d134e1760..a9562c931 100644--- a/crates/ui-egui/src/panels/menu_dialogs.rs+++ b/crates/ui-egui/src/panels/menu_dialogs.rs@@ -206,7 +206,8 @@ pub fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Valif paths.is_empty() {return Some(Err("select files in the Media Browser".into()));}- return Some(app.session.execute(id, json!({"paths": paths})).map_err(|e| e.to_string()));+ let seq = params.get("imageSequence").and_then(Value::as_bool).unwrap_or(false);+ return Some(app.session.execute(id, json!({"paths": paths, "imageSequence": seq})).map_err(|e| e.to_string()));}"file.exportSelectionProject" | "file.exportAle" if params.get("path").is_none() => {if let Err(e) = enabled(app, id) {diff --git a/crates/ui-egui/src/panels/misc.rs b/crates/ui-egui/src/panels/misc.rsindex 2564c29ff..3328d8716 100644--- a/crates/ui-egui/src/panels/misc.rs+++ b/crates/ui-egui/src/panels/misc.rs@@ -208,6 +208,7 @@ pub fn media_browser(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {.unwrap_or_default();entries.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.to_lowercase().cmp(&b.1.to_lowercase())));let mut import = Vec::new();+ let mut import_sequence = None;egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {for (is_dir, name) in &entries {let path = format!("{dir}/{name}");@@ -238,6 +239,25 @@ pub fn media_browser(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {import.push(path.clone());}}+ if !*is_dir {+ resp.context_menu(|ui| {+ let b = ui.button("Import");+ app.auto.add(&format!("mediaBrowser.import.{name}"), b.rect, "Import");+ if b.clicked() {+ import.push(path.clone());+ ui.close();+ }+ // numbered stills: the sequence starting at this frame, as one clip+ if filmcraft_media::sequence::Numbered::parse(&path).is_some() {+ let b = ui.button("Import as Image Sequence");+ app.auto.add(&format!("mediaBrowser.importSequence.{name}"), b.rect, "Import as Image Sequence");+ if b.clicked() {+ import_sequence = Some(path.clone());+ ui.close();+ }+ }+ });+ }}});ui.data_mut(|d| d.insert_temp(dir_id, dir));@@ -247,6 +267,12 @@ pub fn media_browser(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {app.ui.status = e.to_string();}}+ if let Some(first) = import_sequence {+ let r = app.session.execute("file.importFromMediaBrowser", serde_json::json!({"paths": [first], "imageSequence": true}));+ if let Err(e) = r {+ app.ui.status = e.to_string();+ }+ }}#[cfg(target_arch = "wasm32")]{diff --git a/crates/ui-egui/tests/menus_ui.rs b/crates/ui-egui/tests/menus_ui.rsindex 39926982a..c49c336f4 100644--- a/crates/ui-egui/tests/menus_ui.rs+++ b/crates/ui-egui/tests/menus_ui.rs@@ -121,6 +121,34 @@ fn menu_items_toggles_and_help() {assert_eq!(d.call("ui.menu.invoke", json!({"id": "file.importFromMediaBrowser"}))["ok"], false);}+#[test]+fn import_image_sequence_from_the_file_menu_and_media_browser() {+ let dir = std::env::temp_dir().join(format!("fc-ui-imgseq-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let paths: Vec<String> = (1..=5)+ .map(|n| {+ let p = dir.join(format!("plate_{n:03}.png"));+ image::RgbaImage::from_pixel(16, 9, image::Rgba([n as u8 * 40, 0, 0, 255])).save(&p).unwrap();+ p.to_string_lossy().to_string()+ })+ .collect();+ let mut d = Driver::new();+ let menus = d.ok("ui.menu.list", json!({}));+ let item = menus.as_array().unwrap().iter().find(|m| m["id"] == "file.importImageSequence").cloned().expect("File ▸ Import Image Sequence…");+ assert_eq!(item["path"], json!(["File"]));+ // File ▸ Import Image Sequence… with the first frame chosen+ let r = d.ok("ui.menu.invoke", json!({"id": "file.importImageSequence", "params": {"path": paths[0]}}));+ assert_eq!(r["imageSequences"][0]["frames"], 5);+ let id = ItemId(r["items"][0].as_u64().unwrap());+ let kind = d.app().session.project.item(id).unwrap().as_media().unwrap().info.kind;+ assert_eq!(kind, filmcraft_media::MediaKind::ImageSequence);+ // Media Browser ▸ Import as Image Sequence (the selection, from frame 3)+ d.app().ui.extras.media_browser_selection = vec![paths[2].clone()];+ let r = d.ok("ui.menu.invoke", json!({"id": "file.importFromMediaBrowser", "params": {"imageSequence": true}}));+ assert_eq!(r["imageSequences"][0]["frames"], 3);+ let _ = std::fs::remove_dir_all(&dir);+}+#[test]fn find_dialog_and_search_bins() {let mut d = Driver::new();diff --git a/docs/architecture.md b/docs/architecture.mdindex 243c3484f..33d96010d 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -27,7 +27,7 @@ Design principles:L2 edit · codecs · interchange · captions · speechL1 frame · media · project · audio-dsp · textL0 foundation: time · geom · color · bitstream · testkit (dev-dependency only)- codecs/containers: isobmff · matroska · h264 · h264enc · hevc · vp9 · av1 · prores · dnx · aac · opus+ codecs/containers: isobmff · matroska · mxf · ogg · h264 · h264enc · hevc · vp9 · av1 · prores · dnx · aac · opus```Crates are named `filmcraft-<dir>` (`crates/time` is `filmcraft-time`). The apps are `filmcraft`@@ -41,6 +41,8 @@ and `filmcraft-cli`.| `bitstream` | L0 | bit reader/writer, Exp-Golomb, emulation prevention || `isobmff` | L0 | MP4/MOV demux and mux || `matroska` | L0 | MKV/WebM demux |+| `mxf` | L0 | MXF demux (SMPTE ST 377-1): OP1a / OP-Atom, index tables, AVC / VC-3 / ProRes / MPEG-2 identification, PCM / AES3 sound, timecode ([README](../crates/mxf/README.md)) |+| `ogg` | L0 | Ogg demux (RFC 3533), Ogg Opus timing (RFC 7845 granules, pre-skip, end trimming), Vorbis headers || `h264`, `h264enc` | L0 | H.264 decoder; H.264 encoder || `hevc` | L0 | H.265 Main/Main 10 decoder || `prores` | L0 | ProRes decoder and encoder |@@ -49,13 +51,13 @@ and `filmcraft-cli`.| `aac` | L0 | AAC-LC decoder and encoder || `testkit` | L0 | test-only helpers, used only as a dev-dependency: ffmpeg/ffprobe discovery, fixture dirs, golden images ([testing.md](testing.md)) || `frame` | L1 | `VideoFrame` (planar YUV / RGBA8 / linear RGBA f32, colour metadata), `AudioBuffer` |-| `media` | L1 | `MediaSource` trait, probing/openers, frame cache, generators, stills, WAV |+| `media` | L1 | `MediaSource` trait, probing/openers, frame cache, generators, stills, image sequences, WAV / Broadcast WAV || `project` | L1 | document model, effect definitions, keyframes || `audio-dsp` | L1 | loudness metering (BS.1770 / R128) and audio effects; no dependencies || `text` | L1 | text engine: font database (bundled OFL fonts + system fonts), shaping (harfrust), bidi, line breaking, paragraph layout, glyph/path rasteriser, strokes ([crates/text/README.md](../crates/text/README.md)) || `edit` | L2 | pure edit algebra (insert, overwrite, razor, ripple, roll, slip, slide, rate stretch…; text-based editing: `edit::transcript`) || `speech` | L2 | speech-to-text: `Transcriber` trait, Whisper model catalogue + verified downloader (feature `download`), pure-Rust Whisper inference on candle with word timestamps (feature `whisper`), speaker labelling ([transcripts.md](transcripts.md)) |-| `codecs` | L2 | container + codec hub: MP4/MOV and MKV sources, GOP-aware seeking, decoder registry, audio decoding |+| `codecs` | L2 | container + codec hub: MP4/MOV, MKV, MXF and Ogg sources, GOP-aware seeking, decoder registry, audio decoding || `interchange` | L2 | EDL, FCP7 XML, FCPXML and OTIO import/export (no file I/O) || `render` | L3 | sequence evaluation, CPU compositor, video effects (`effects`, `vfx`; effects needing other frames or tracks read them through `vfx::FxEnv`), transitions, audio mix || `gpu` | L3 | wgpu compositor (WGSL) |diff --git a/docs/testing.md b/docs/testing.mdindex 6de0652d2..21aa05595 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -54,8 +54,8 @@ are never linked or shipped ([AGENTS.md](../AGENTS.md) §2).concurrently; migrate it when convenient).- `cargo xtask fixtures [crate…]` pre-generates the whole fixture matrix up front (useful before aparallel test run or on a fresh machine). It runs each crate's ignored `generate_fixtures` test —- the same generators the oracle tests call — for `h264`, `hevc`, `isobmff`, `matroska`, `dnx` and- `prores`, and prints one `made` / `cached` / `skipped` line per fixture plus a summary. The+ the same generators the oracle tests call — for `h264`, `hevc`, `isobmff`, `matroska`, `dnx`,+ `prores` and `codecs` (MXF and Ogg), and prints one `made` / `cached` / `skipped` line per fixture plus a summary. The`aac`, `opus` and `h264enc` oracles generate small per-test signals on demand and are not part ofthe matrix.- Fixture sources are synthetic: `testsrc2`, `mandelbrot`, SMPTE bars, noise and fades, sine tones.@@ -79,6 +79,9 @@ are never linked or shipped ([AGENTS.md](../AGENTS.md) §2).| `matroska` | `ffprobe -show_packets` | every packet (stream, size, key flag, pts, duration) equal; seeks land on the latest keyframe ≤ target || `audio-dsp` loudness | `tests/loudness_oracle.rs`: signals generated in Rust (997 Hz sine, pink noise at 48/96 kHz, speech-like bursts at 48/44.1 kHz, stereo with silence and sub-gate passages, an fs/4 inter-sample-peak tone) written as float WAV and measured with `ffmpeg -af ebur128=peak=true:metadata=1` | momentary and short-term every 100 ms **±0.1 LU**, integrated **±0.1 LU**, LRA **±0.5 LU**, true peak **±0.2 dB** (against the analytic value when one exists). Measured: ΔM/ΔS ≤ 0.0005 LU, ΔI ≤ 0.007 LU, ΔLRA ≤ 0.04 LU, ΔTP ≤ 0.045 dB against ffmpeg. On the fs/4 tone ffmpeg's own true peak is +0.6 dB high (−0.32 vs the analytic −0.92 dBTP); ours is −0.05 dB || `audio-dsp` effects | `src/effects/premiere_tests.rs`, `src/design.rs`, registry tests in `src/effects/mod.rs`: generated tones, noise and impulses | every effect: neutral settings = delayed identity (≤ 2·10⁻⁴), bit-exact determinism, latency constant and equal to where an impulse lands, block-size independence, finite / denormal-free tails at extreme settings, > 1× realtime; per effect a level or frequency-response check (measured tone vs analytic `response_db` within 0.1–0.2 dB, Butterworth vs closed form 10⁻⁶ dB, Chebyshev/elliptic ripple and stop-band bounds, LR4 crossover sum flat within 0.02 dB, comb-notch depth, echo positions to the sample, Schroeder RT60 of generated impulses within 25 %, click repair −20 dB) |+| `mxf` (via `codecs/tests/mxf_oracle.rs`) | ffmpeg-written OP1a / OP-Atom / D-10 files decoded by ffmpeg | H.264 (long GOP, B pictures without temporal offsets) **bit-exact** every frame and at 25 random seeks; DNxHR ±2, ProRes ±1; PCM / AES3 **sample-exact**; frame count = ffprobe packets; timecode (25 fps, 29.97 DF); MPEG-2 reported unsupported; truncation/mutation never panics |+| `ogg` (via `codecs/tests/ogg_oracle.rs`) | ffmpeg (libopus, Vorbis) files decoded by libopus / ffmpeg | length **exact** (pre-skip, end trimming); SNR ≥ 50 dB CELT (measured 77.7), ≥ 10 dB SILK, Vorbis 139 dB; random seeks within 6·10⁻⁶ of the continuous decode |+| image sequences / BWF (`codecs/tests/media_oracle.rs`) | ffmpeg-written PNG/TIFF/BMP/JPEG stills read by ffmpeg's image2 demuxer; ffmpeg BWF (`-write_bext`) | PNG/TIFF/BMP **exact**, JPEG ±12 (measured 3); missing frames hold the previous one; BWF TimeReference = ffprobe's, start timecode, samples exact || `export` | our own demuxer/decoder reads the file back; ffprobe counts frames when present | expected size, duration, colour, audio level; exact frame count |Each codec README has the full fixture matrix and the measured results.diff --git a/xtask/src/main.rs b/xtask/src/main.rsindex 7378d72d6..569aba086 100644--- a/xtask/src/main.rs+++ b/xtask/src/main.rs@@ -30,6 +30,8 @@ const LAYERS: &[(&str, u8)] = &[("bitstream", 0),("isobmff", 0),("matroska", 0),+ ("mxf", 0),+ ("ogg", 0),("riff", 0),("h264", 0),("h264enc", 0),@@ -374,6 +376,8 @@ const FIXTURE_GENERATORS: &[(&str, &str)] = &[("matroska", "oracle"),("prores", "oracle_decode"),("dnx", "oracle_decode"),+ ("codecs", "mxf_oracle"),+ ("codecs", "ogg_oracle"),];fn fixtures(only: &[String]) -> Result<(), String> {