FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Merge main into M9.8 (VP9): Opus + VP9 together in codecs/mkv; vp9 at opt-level 3 in dev builds
Brandon Thomas0aaa4f41de4c
diff --cc Cargo.lockindex 33417898d,c551bf47b..c27278dbc--- a/Cargo.lock+++ b/Cargo.lock@@@ -1361,9 -1392,9 +1392,10 @@@ dependencies ="filmcraft-isobmff","filmcraft-matroska","filmcraft-media",+ "filmcraft-opus","filmcraft-prores","filmcraft-time",+ "filmcraft-vp9","image","log","symphonia",diff --cc Cargo.tomlindex cec84e286,a718dffde..ac63d11f0--- a/Cargo.toml+++ b/Cargo.toml@@@ -20,9 -20,9 +20,10 @@@ filmcraft-isobmff = { path = "crates/isfilmcraft-matroska = { path = "crates/matroska" }filmcraft-h264 = { path = "crates/h264" }filmcraft-hevc = { path = "crates/hevc" }+filmcraft-vp9 = { path = "crates/vp9" }filmcraft-prores = { path = "crates/prores" }filmcraft-aac = { path = "crates/aac" }+ filmcraft-opus = { path = "crates/opus" }filmcraft-h264enc = { path = "crates/h264enc" }filmcraft-audio-dsp = { path = "crates/audio-dsp" }filmcraft-frame = { path = "crates/frame" }@@@ -69,6 -72,25 +73,28 @@@ opt-level =[profile.dev]opt-level = 1+ # Codec hot loops: debug-build tests (RFC/oracle vectors) are minutes slower below opt-level 3.+ [profile.dev.package.filmcraft-h264]+ opt-level = 3++ [profile.dev.package.filmcraft-h264enc]+ opt-level = 3++ [profile.dev.package.filmcraft-hevc]+ opt-level = 3++ [profile.dev.package.filmcraft-prores]+ opt-level = 3++ [profile.dev.package.filmcraft-aac]+ opt-level = 3++ [profile.dev.package.filmcraft-opus]+ opt-level = 3+++[profile.dev.package.filmcraft-vp9]++opt-level = 3++[profile.release]lto = "thin"codegen-units = 1diff --cc ROADMAP.mdindex a2a78bd53,f86088ad3..332c3f5b8--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -37,14 -37,14 +37,13 @@@ Status: ✅ done · 🟡 in progress �| 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 basics, peak meters, BS.1770 loudness meters (M/S/I LUFS, true peak; matches ffmpeg), DSP crate, 12 clip audio effects running on it (EQ, filters, dynamics, limiter, delay, reverb, DeNoise, DeHum, pitch) with keyframes | Effects UI polish (EQ curve), remaining effects (multiband, convolution reverb), track effects/mixers with automation, Essential Sound, audio transitions, 5.1 | 6–10 || M8 | Colour | 🟡 | Lumetri: basic, creative + looks, RGB & hue curves, wheels, HSL secondary, vignette; basic scopes | LUT import UI, colour match, colour management + HDR (PQ/HLG, log, tone mapping) | 8–12 |- | 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/FLAC/MP3/Vorbis/PCM) | VP9 frame threading, Opus (in progress), AV1 (rav1d), DNxHR, MXF, hardware decode | 12–20 |- | M10 | Graphics & captions | ⬜ | — | Text engine, Type tool, Essential Graphics, captions (SRT/VTT/SCC), speech-to-text | 20–30 |- | M11 | Interchange & project management | 🟡 | `.fcproj` save/open | Autosave/recovery, FCP7 XML, FCPXML, EDL, OTIO, relink, project manager, proxies | 15 |-| M9 | More codecs | 🟡 | ProRes decode+encode, AAC decode+encode, HEVC Main/Main 10 decoder (bit-exact on 41 fixtures, ~225 fps 1080p), Matroska/WebM import (H.264/HEVC/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) | VP9 (in progress), Ogg Opus files, AV1 (rav1d), DNxHR, 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) | VP9 frame threading, Ogg Opus files, AV1 (rav1d), DNxHR, MXF, 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 with shaping, Type tool, Essential Graphics, rolls/crawls, MCC/STL/TTML, 608/708 embedding, speech-to-text | 18–27 |+ | 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 | Relink/offline, project manager, proxies | 8 || M12–M16 | Web (WASM), platform, long tail | 🟡 | L0–L4 crates compile to wasm32 | Web app shell (file access, WebCodecs, audio), ~850 remaining commands and dialogs, performance hardening | 40–65 |## Running now- - Opus decoder (`crates/opus`), from RFC 6716/8251-- VP9 decoder (`crates/vp9`), from the public VP9 bitstream spec- Interchange (`crates/interchange`): CMX 3600 EDL, FCP7 XML, FCPXML, OTIO import and export## Logdiff --cc crates/codecs/Cargo.tomlindex c9189eb67,ee250a8c5..843bd4f1a--- a/crates/codecs/Cargo.toml+++ b/crates/codecs/Cargo.toml@@@ -19,9 -19,9 +19,10 @@@ filmcraft-matroska = { workspace = trufilmcraft-bitstream = { workspace = true }filmcraft-h264 = { workspace = true }filmcraft-hevc = { workspace = true }+filmcraft-vp9 = { workspace = true }filmcraft-prores = { workspace = true }filmcraft-aac = { workspace = true }+ filmcraft-opus = { workspace = true }thiserror = { workspace = true }log = { workspace = true }image = { version = "0.25", default-features = false, features = ["jpeg"] }diff --cc crates/codecs/src/mkv.rsindex a5aacdafa,e5134fd95..b6c56a395--- a/crates/codecs/src/mkv.rs+++ b/crates/codecs/src/mkv.rs@@@ -1,8 -1,13 +1,13 @@@//! Matroska/WebM media source (`filmcraft-matroska` demux, GOP-aware video via [`crate::gop`]).//!//! Video codecs are mapped onto ISO-BMFF sample entries so the same decoder factories serve both- //! containers (H.264, HEVC, VP9, ProRes, MJPEG; AV1 once its decoder lands). Audio: AAC via our- //! decoder, PCM directly, MP3/FLAC/Vorbis via the bootstrap decoders.-//! containers (H.264, HEVC, ProRes, MJPEG; VP9/AV1 once their decoders land). Audio: AAC and Opus++//! containers (H.264, HEVC, VP9, ProRes, MJPEG; AV1 once its decoder lands). Audio: AAC and Opus+ //! via our decoders, PCM directly, MP3/FLAC/Vorbis via the bootstrap decoders.+ //!+ //! Opus (`A_OPUS`): `CodecPrivate` is the `OpusHead`; output is always 48 kHz. The demuxer+ //! subtracts `CodecDelay` from timestamps, so the pre-skip samples land before zero and are never+ //! read; random access decodes `SeekPreRoll` (at least [`crate::audio::OPUS_PRE_ROLL`]) of preceding+ //! packets before the target. Packet starts are accumulated from TOC durations (see [`opus_starts`]).use std::collections::HashMap;use std::sync::{Arc, Mutex};diff --cc crates/codecs/src/tests.rsindex ff3fa9ded,601f2048b..fc35862aa--- a/crates/codecs/src/tests.rs+++ b/crates/codecs/src/tests.rs@@@ -179,165 -179,125 +179,288 @@@ fn matroska_prores_pcm()check_mkv("blue_prores_pcm.mkv", &["-c:v", "prores_ks", "-profile:v", "2"], &["-c:a", "pcm_s16le"]);}+/// Path of a fixture under `target/fixtures/codecs/`, generated with ffmpeg when missing+/// (`None` when ffmpeg or the encoder is unavailable).+fn fixture_path(name: &str, args: &[&str]) -> Option<PathBuf> {+ fixture(name, args)?;+ Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/codecs").join(name))+}++/// ffmpeg's decode of `src` as raw planar video (the oracle).+fn reference_yuv(src: &std::path::Path, pix_fmt: &str) -> Option<Vec<u8>> {+ let name = format!("{}.{pix_fmt}.yuv", src.file_name()?.to_str()?);+ let path = src.to_str()?;+ let b = fixture(&name, &["-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt])?;+ Some(b.to_vec())+}++/// Planes of a decoded YUV frame as little-endian bytes (ffmpeg rawvideo layout).+fn yuv_bytes(f: &filmcraft_frame::VideoFrame) -> Vec<u8> {+ match &f.data {+ filmcraft_frame::PixelData::Yuv8 { planes, .. } => planes.iter().flat_map(|p| p.iter().copied()).collect(),+ filmcraft_frame::PixelData::Yuv16 { planes, .. } => planes.iter().flat_map(|p| p.iter().flat_map(|s| s.to_le_bytes())).collect(),+ _ => panic!("not a YUV frame: {}", f.format_label()),+ }+}++/// Random access into a VP9 file: frames requested out of order (seeks back and forth across key+/// frames, then sequential playback) are sample-exact against ffmpeg's decode.+fn check_vp9_seeks(name: &str, container: &str, pix_fmt: &str, extra: &[&str], frames: usize) {+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/codecs");+ let log = dir.join(format!("{name}.passlog")).to_string_lossy().into_owned();+ let mut args = vec!["-f", "lavfi", "-i", "testsrc2=s=352x288:r=25,noise=alls=8:allf=t", "-frames:v"];+ let n = frames.to_string();+ args.push(&n);+ args.extend_from_slice(&["-c:v", "libvpx-vp9", "-pix_fmt", pix_fmt, "-g", "25", "-b:v", "600k"]);+ args.extend_from_slice(extra);+ if extra.contains(&"-auto-alt-ref") {+ // libvpx only uses alternate reference frames in two-pass mode: run the first pass.+ let Some(ff) = ffmpeg() else { return };+ if !dir.join(name).exists() {+ let _ = std::fs::create_dir_all(&dir);+ let ok = Command::new(ff).args(["-y", "-v", "error"]).args(&args).args(["-pass", "1", "-passlogfile"]).arg(&log).args(["-f", "null", "-"]).status();+ if !ok.is_ok_and(|s| s.success()) {+ eprintln!("first pass for {name} failed; skipping");+ return;+ }+ }+ args.extend_from_slice(&["-pass", "2", "-passlogfile"]);+ args.push(&log);+ }+ let Some(path) = fixture_path(name, &args) else { return };+ let Some(reference) = reference_yuv(&path, pix_fmt) else { return };+ let bytes: Arc<[u8]> = std::fs::read(&path).unwrap().into();+ let src = crate::open_bytes(name, bytes).unwrap();+ let info = src.info().clone();+ assert_eq!(info.container, container);+ let v = info.video.as_ref().unwrap();+ assert!(v.codec.contains("VP9"), "{}", v.codec);+ assert_eq!((v.width, v.height), (352, 288));+ let frame_len = reference.len() / frames;+ let rate = info.frame_rate();+ let order: Vec<usize> = [frames - 3, 3, 40, 26, 24, frames - 1, 0, 12].into_iter().chain(30..45).filter(|&k| k < frames).collect();+ for k in order {+ let f = src.video_frame(FrameRequest::full(rate.tick_of(k as i64))).unwrap();+ assert_eq!((f.width, f.height), (352, 288));+ let got = yuv_bytes(&f);+ assert!(got == reference[k * frame_len..(k + 1) * frame_len], "{name}: frame {k} differs from ffmpeg");+ }+}++#[test]+fn webm_vp9_seeks_bit_exact() {+ check_vp9_seeks("noise_vp9.webm", "WebM", "yuv420p", &["-deadline", "realtime", "-speed", "8"], 60);+}++#[test]+fn webm_vp9_altref_superframes_seek_bit_exact() {+ // Good-quality encode with alternate reference frames: hidden frames packed into superframes.+ check_vp9_seeks("noise_vp9_altref.webm", "WebM", "yuv420p", &["-speed", "4", "-auto-alt-ref", "1", "-lag-in-frames", "16"], 60);+}++#[test]+fn mp4_vp9_10bit_seeks_bit_exact() {+ check_vp9_seeks("noise_vp9_10bit.mp4", "MPEG-4", "yuv420p10le", &["-profile:v", "2", "-deadline", "realtime", "-speed", "8"], 50);+}++#[test]+fn mkv_vp9_444_12bit_seeks_bit_exact() {+ check_vp9_seeks("noise_vp9_444_12bit.mkv", "Matroska", "yuv444p12le", &["-profile:v", "3", "-deadline", "realtime", "-speed", "8"], 30);+}++#[test]+fn mkv_vp9_422_seeks_bit_exact() {+ check_vp9_seeks("noise_vp9_422.mkv", "Matroska", "yuv422p", &["-profile:v", "1", "-deadline", "realtime", "-speed", "8"], 30);+}++/// Every sample flagged as sync (as in an MP4 without `stss`): the GOP cache must still start+/// decoding at a real VP9 key frame.+#[test]+fn vp9_random_access_ignores_bogus_sync_flags() {+ use crate::gop::{GopCache, VideoSamples};+ let Some(path) = fixture_path(+ "noise_vp9_g20.ivf",+ &["-f", "lavfi", "-i", "testsrc2=s=176x144:r=25", "-frames:v", "50", "-c:v", "libvpx-vp9", "-g", "20", "-deadline", "realtime", "-speed", "8"],+ ) else {+ return;+ };+ let Some(reference) = reference_yuv(&path, "yuv420p") else { return };+ let data = std::fs::read(&path).unwrap();+ let mut chunks = Vec::new();+ let mut p = 32;+ while p + 12 <= data.len() {+ let sz = u32::from_le_bytes(data[p..p + 4].try_into().unwrap()) as usize;+ chunks.push(data[p + 12..p + 12 + sz].to_vec());+ p += 12 + sz;+ }+ struct AllSync(Vec<Vec<u8>>);+ impl VideoSamples for AllSync {+ fn count(&self) -> usize {+ self.0.len()+ }+ fn pts(&self, i: usize) -> i64 {+ i as i64+ }+ fn sync_before(&self, i: usize) -> usize {+ i+ }+ fn sample_at(&self, t: i64) -> Option<usize> {+ (t >= 0 && (t as usize) < self.0.len()).then_some(t as usize)+ }+ fn read(&self, i: usize) -> crate::Result<Vec<u8>> {+ Ok(self.0[i].clone())+ }+ fn make_decoder(&self) -> crate::Result<Box<dyn crate::VideoDecoder>> {+ Ok(Box::new(crate::video::Vp9Decoder::new(None)))+ }+ }+ let s = AllSync(chunks);+ let cache = GopCache::new(None);+ let frame_len = 176 * 144 * 3 / 2;+ for k in [37usize, 5, 49, 21, 20, 19] {+ let f = cache.frame(&s, k as i64).unwrap();+ assert!(yuv_bytes(&f) == reference[k * frame_len..(k + 1) * frame_len], "frame {k} differs from ffmpeg");+ }+}++/// VP9 RGB (profile 1, colour space sRGB; planes G, B, R) decodes to RGBA in the right order.+#[test]+fn mkv_vp9_rgb() {+ let Some(b) = fixture(+ "orange_vp9_gbrp.mkv",+ &["-f", "lavfi", "-i", "color=c=0xe08020:s=128x96:r=25:d=0.4", "-c:v", "libvpx-vp9", "-pix_fmt", "gbrp", "-deadline", "realtime", "-lossless", "1"],+ ) else {+ return;+ };+ let src = crate::open_bytes("orange_vp9_gbrp.mkv", b).unwrap();+ let f = src.video_frame(FrameRequest::full(Tick(TICKS_PER_SECOND / 5))).unwrap();+ let px = f.to_rgba8();+ let c = &px[(48 * 128 + 64) * 4..][..3];+ // (the lavfi colour source is converted to RGB by ffmpeg, which rounds by a level)+ for (got, want) in c.iter().zip([0xe0u8, 0x80, 0x20]) {+ assert!((*got as i32 - want as i32).abs() <= 2, "{c:?}");+ }+}+++ /// ffmpeg + libopus decode of a container fixture (pre-skip / codec delay / edit list applied) as+ /// interleaved f32 at 48 kHz: the reference for our Opus path.+ fn opus_reference(name: &str) -> Option<Vec<f32>> {+ let ff = ffmpeg()?;+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/codecs");+ let out = dir.join(format!("{name}.ref.f32"));+ let st = Command::new(ff)+ .args(["-y", "-v", "error", "-c:a", "libopus", "-i"])+ .arg(dir.join(name))+ .args(["-f", "f32le", "-ar", "48000"])+ .arg(&out)+ .status()+ .ok()?;+ if !st.success() {+ return None;+ }+ Some(std::fs::read(out).ok()?.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())+ }++ fn snr_db(reference: &[f32], test: &[f32]) -> f64 {+ let (mut s, mut e) = (0f64, 0f64);+ for (r, t) in reference.iter().zip(test) {+ s += (*r as f64).powi(2);+ e += (*r as f64 - *t as f64).powi(2);+ }+ if e == 0.0 { 200.0 } else { 10.0 * (s.max(1e-20) / e).log10() }+ }++ /// Interleaves `frames` of `src.audio` from `start` (48 kHz).+ fn read_interleaved(src: &filmcraft_media::SharedSource, start: i64, frames: usize) -> Vec<f32> {+ let a = src.audio(start, frames, 48_000).expect("audio");+ let ch = a.channels.len();+ let mut v = vec![0f32; frames * ch];+ for (c, chan) in a.channels.iter().enumerate() {+ for (i, s) in chan.iter().enumerate() {+ v[i * ch + c] = *s;+ }+ }+ v+ }++ /// Opus in a container: metadata, sample-exact alignment (pre-skip honoured) against libopus for a+ /// sequential read, and the same samples after random access (pre-roll).+ fn check_opus(name: &str, channels: usize, expr: &str, extra: &[&str], container: &str) {+ let mut args: Vec<&str> = vec!["-f", "lavfi", "-i", expr, "-t", "3", "-c:a", "libopus"];+ args.extend_from_slice(extra);+ let Some(b) = fixture(name, &args) else { return };+ let Some(reference) = opus_reference(name) else {+ eprintln!("libopus decoder unavailable; skipping {name}");+ return;+ };+ let src = crate::open_bytes(name, b).expect("open");+ let info = src.info().clone();+ assert_eq!(info.container, container);+ let a = info.audio.as_ref().expect("audio");+ assert_eq!((a.codec.as_str(), a.sample_rate, a.channels as usize), ("Opus", 48_000, channels));+ let d = info.duration.seconds();+ assert!((d - 3.0).abs() < 0.03, "{name}: duration {d}");+ let total = reference.len() / channels;+ assert!((total as i64 - 144_000).abs() < 960, "{name}: reference length {total}");++ // Sequential read in 100 ms blocks.+ let mut ours = Vec::with_capacity(reference.len());+ let mut pos = 0;+ while pos < total {+ let n = 4800.min(total - pos);+ ours.extend(read_interleaved(&src, pos as i64, n));+ pos += n;+ }+ let snr = snr_db(&reference, &ours);+ eprintln!("{name}: sequential SNR vs libopus {snr:.1} dB");+ assert!(snr > 40.0, "{name}: sequential SNR {snr:.1} dB");++ // Random access on a fresh source (cold decoder): 100 ms at 1.7 s, then back to 0.5 s.+ let src = crate::open_bytes(name, fixture(name, &args).expect("fixture")).expect("open");+ for start in [81_600usize, 24_000] {+ let got = read_interleaved(&src, start as i64, 4800);+ let want = &reference[start * channels..(start + 4800) * channels];+ let snr = snr_db(want, &got);+ eprintln!("{name}: random access at {start}: SNR {snr:.1} dB");+ assert!(snr > 40.0, "{name}: random access at {start}: SNR {snr:.1} dB");+ }+ }++ #[test]+ fn opus_webm_stereo() {+ check_opus(+ "tones_opus.webm",+ 2,+ "aevalsrc=0.4*sin(2*PI*440*t)+0.1*sin(2*PI*5000*t)|0.3*sin(2*PI*660*t)+0.1*sin(2*PI*3100*t):s=48000",+ &["-b:a", "128k"],+ "WebM",+ );+ }++ #[test]+ fn opus_mkv_mono_speechlike_16k() {+ // Low bitrate VoIP mode exercises SILK/hybrid; the input rate is 16 kHz but Opus still outputs 48 kHz.+ check_opus("tones_opus_voip.mkv", 1, "aevalsrc=0.4*sin(2*PI*220*t)*(0.6+0.4*sin(2*PI*3*t)):s=16000", &["-b:a", "16k", "-application", "voip"], "Matroska");+ }++ #[test]+ fn opus_mkv_surround_51() {+ check_opus(+ "tones_opus_51.mkv",+ 6,+ "aevalsrc=0.3*sin(2*PI*300*t)|0.3*sin(2*PI*400*t)|0.3*sin(2*PI*500*t)|0.3*sin(2*PI*60*t)|0.3*sin(2*PI*700*t)|0.3*sin(2*PI*800*t):s=48000:c=5.1",+ &["-b:a", "256k"],+ "Matroska",+ );+ }++ #[test]+ fn opus_mp4_stereo() {+ check_opus(+ "tones_opus.mp4",+ 2,+ "aevalsrc=0.4*sin(2*PI*440*t)+0.1*sin(2*PI*5000*t)|0.3*sin(2*PI*660*t)+0.1*sin(2*PI*3100*t):s=48000",+ &["-b:a", "128k"],+ "MPEG-4",+ );+ }