Skip to content

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

M9.8: VP9 wired into codecs — WebM/MKV V_VP9 and MP4 vp09 (+vpcC) import, 8/10/12-bit 4:2:0/4:2:2/4:4:4 (4:4:0 expanded, RGB to RGBA) output, key-frame-checked GOP random access, Decoder::reset / is_keyframe, oracle seek tests

Brandon Thomas9db963e0e677
diff --git a/Cargo.lock b/Cargo.lock
index 96706d541..33417898d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1363,6 +1363,7 @@ dependencies = [
"filmcraft-media",
"filmcraft-prores",
"filmcraft-time",
+ "filmcraft-vp9",
"image",
"log",
"symphonia",
diff --git a/ROADMAP.md b/ROADMAP.md
index 245a1e2d3..a2a78bd53 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -37,14 +37,13 @@ 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 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), Matroska/WebM import (H.264/HEVC/ProRes/MJPEG + AAC/FLAC/MP3/Vorbis/PCM) | VP9 and Opus (in progress), 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/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 |
| 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
-- VP9 decoder (`crates/vp9`), from the public VP9 bitstream spec
- Opus decoder (`crates/opus`), from RFC 6716/8251
- Interchange (`crates/interchange`): CMX 3600 EDL, FCP7 XML, FCPXML, OTIO import and export
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index 9b98df6a1..c9189eb67 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -19,6 +19,7 @@ filmcraft-matroska = { workspace = true }
filmcraft-bitstream = { workspace = true }
filmcraft-h264 = { workspace = true }
filmcraft-hevc = { workspace = true }
+filmcraft-vp9 = { workspace = true }
filmcraft-prores = { workspace = true }
filmcraft-aac = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/codecs/src/gop.rs b/crates/codecs/src/gop.rs
index 13e2add2f..deafcf257 100644
--- a/crates/codecs/src/gop.rs
+++ b/crates/codecs/src/gop.rs
@@ -80,10 +80,19 @@ impl GopCache {
st.decoder = Some(s.make_decoder()?);
st.next = usize::MAX;
}
- let key = s.sync_before(i);
+ let mut key = s.sync_before(i);
// Continue the running decoder when the wanted sample is ahead within this GOP run.
let continuing = st.next != usize::MAX && st.next > key && st.next <= i + 16 && st.next <= n;
if !continuing {
+ // The container's sync flags may be wrong for the codec (an MP4 without `stss` marks
+ // every sample): step back to a sample the decoder can start from.
+ while key > 0 {
+ let data = s.read(key)?;
+ if st.decoder.as_ref().expect("decoder").is_random_access(&data) != Some(false) {
+ break;
+ }
+ key = s.sync_before(key - 1);
+ }
if let Some(d) = st.decoder.as_mut() {
d.reset();
}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 5881cf179..e5f8c48c1 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -1,6 +1,6 @@
//! The container + codec hub.
//!
-//! - [`VideoDecoder`]: the trait every video codec implements (our own H.264/ProRes/…, MJPEG, and
+//! - [`VideoDecoder`]: the trait every video codec implements (our own H.264/HEVC/VP9/ProRes/…, MJPEG, and
//! OS hardware decoders registered by the platform layer). Factories are tried in registration
//! order, so a hardware decoder can take precedence over the pure-Rust one.
//! - [`Mp4Source`]: a [`MediaSource`](filmcraft_media::MediaSource) over MP4/MOV using
@@ -46,7 +46,7 @@ impl From<CodecError> for filmcraft_media::MediaError {
fn factories() -> &'static RwLock<Vec<VideoDecoderFactory>> {
static F: std::sync::OnceLock<RwLock<Vec<VideoDecoderFactory>>> = std::sync::OnceLock::new();
- F.get_or_init(|| RwLock::new(vec![video::h264_factory, video::hevc_factory, video::prores_factory, video::mjpeg_factory]))
+ F.get_or_init(|| RwLock::new(vec![video::h264_factory, video::hevc_factory, video::vp9_factory, video::prores_factory, video::mjpeg_factory]))
}
/// Register a video decoder factory (tried before previously registered ones).
diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rs
index 90abae2b8..a5aacdafa 100644
--- a/crates/codecs/src/mkv.rs
+++ b/crates/codecs/src/mkv.rs
@@ -1,7 +1,7 @@
//! 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, ProRes, MJPEG; VP9/AV1 once their decoders land). Audio: AAC via our
+//! 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.
use std::collections::HashMap;
@@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex};
use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
use filmcraft_frame::{AudioBuffer, VideoFrame};
-use filmcraft_isobmff::{AvcConfig, FourCc, HevcConfig, PcmConfig, SampleEntry};
+use filmcraft_isobmff::{AvcConfig, CodecConfig, FourCc, HevcConfig, PcmConfig, SampleEntry, VpcConfig};
use filmcraft_matroska::{Codec, MkvFile, TrackKind};
use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};
use filmcraft_time::{FrameRate, Tick};
@@ -59,8 +59,42 @@ fn from_tick(t: &filmcraft_matroska::Track, time: Tick) -> i64 {
time.to_rational_floor(n, d)
}
-fn sample_entry(c: &Codec, w: u16, h: u16) -> Option<SampleEntry> {
+/// VP9 configuration from the Matroska `CodecPrivate` feature list (ID / length / value triples:
+/// 1 profile, 2 level, 3 bit depth, 4 chroma subsampling) and the track's `Colour`.
+fn vp9_config(private: &[u8], v: Option<&filmcraft_matroska::VideoInfo>) -> VpcConfig {
+ let mut c = VpcConfig { bit_depth: 8, colour_primaries: 2, transfer_characteristics: 2, matrix_coefficients: 2, ..Default::default() };
+ let mut p = 0;
+ while p + 2 <= private.len() {
+ let (id, len) = (private[p], private[p + 1] as usize);
+ let Some(val) = private.get(p + 2..p + 2 + len) else { break };
+ let x = val.first().copied().unwrap_or(0);
+ match id {
+ 1 => c.profile = x,
+ 2 => c.level = x,
+ 3 => c.bit_depth = x,
+ 4 => c.chroma_subsampling = x,
+ _ => {}
+ }
+ p += 2 + len;
+ }
+ if let Some(col) = v.and_then(|v| v.colour.as_ref()) {
+ if let Some(t) = col.transfer_characteristics {
+ c.transfer_characteristics = t as u8;
+ }
+ if let Some(pr) = col.primaries {
+ c.colour_primaries = pr as u8;
+ }
+ if let Some(m) = col.matrix_coefficients {
+ c.matrix_coefficients = m as u8;
+ }
+ c.full_range = col.full_range();
+ }
+ c
+}
+
+fn sample_entry(c: &Codec, v: Option<&filmcraft_matroska::VideoInfo>, w: u16, h: u16) -> Option<SampleEntry> {
Some(match c {
+ Codec::Vp9 { private } => SampleEntry::video(FourCc(*b"vp09"), CodecConfig::Vp9(vp9_config(private, v)), w, h),
Codec::Avc { avcc } => SampleEntry::avc(AvcConfig::parse(avcc).ok()?, w, h),
Codec::Hevc { hvcc } => SampleEntry::hevc(HevcConfig::parse(hvcc).ok()?, w, h),
Codec::ProRes { fourcc } => SampleEntry::prores(FourCc(fourcc.unwrap_or(*b"apcn")), w, h),
@@ -144,7 +178,7 @@ impl MkvSource {
if explicit {
explicit_color = Some(color);
}
- ventry = sample_entry(&t.codec, w as u16, h as u16);
+ ventry = sample_entry(&t.codec, t.video.as_ref(), w as u16, h as u16);
let secs = file.duration_ns().unwrap_or(0) as f64 / 1e9;
let bitrate = (secs > 0.0).then(|| (t.samples.iter().map(|s| s.size as u64).sum::<u64>() as f64 * 8.0 / secs) as u64);
VideoStreamInfo {
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 4497bc2f2..5f37b6c33 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -40,9 +40,17 @@ pub fn sniff(b: &[u8]) -> bool {
fn color_from(entry: &filmcraft_isobmff::SampleEntry, w: u32, h: u32) -> ColorInfo {
let mut c = ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited };
- if let Some(v) = &entry.video
- && let Some(col) = &v.color
- {
+ // VP9 carries its colour description in vpcC (used when there is no colr box).
+ let vpc = match &entry.codec {
+ CodecConfig::Vp9(v) => Some(filmcraft_isobmff::ColorInfo::Nclx {
+ primaries: v.colour_primaries as u16,
+ transfer: v.transfer_characteristics as u16,
+ matrix: v.matrix_coefficients as u16,
+ full_range: v.full_range,
+ }),
+ _ => None,
+ };
+ if let Some(col) = entry.video.as_ref().and_then(|v| v.color.as_ref()).or(vpc.as_ref()) {
let (p, t, m, full) = match col {
filmcraft_isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => (*primaries, *transfer, *matrix, *full_range),
filmcraft_isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => (*primaries, *transfer, *matrix, false),
@@ -339,6 +347,7 @@ fn codec_label(c: &CodecConfig) -> String {
}
),
CodecConfig::Hevc(_) => "HEVC".into(),
+ CodecConfig::Vp9(c) => format!("VP9 (Profile {})", c.profile),
CodecConfig::ProRes { fourcc } => match &fourcc.0 {
b"apco" => "Apple ProRes 422 Proxy".into(),
b"apcs" => "Apple ProRes 422 LT".into(),
@@ -368,6 +377,14 @@ fn pixfmt_label(c: &CodecConfig) -> String {
244 => "YUV 4:4:4".into(),
_ => "YUV 4:2:0 8-bit".into(),
},
+ CodecConfig::Vp9(c) => {
+ let sub = match c.chroma_subsampling {
+ 2 => "4:2:2",
+ 3 => "4:4:4",
+ _ => "4:2:0",
+ };
+ format!("YUV {sub} {}-bit", c.bit_depth.max(8))
+ }
CodecConfig::ProRes { fourcc } if fourcc.0[2] == b'4' => "YUVA 4:4:4 12-bit".into(),
CodecConfig::ProRes { .. } => "YUV 4:2:2 10-bit".into(),
CodecConfig::Jpeg { .. } => "YUV 4:2:x 8-bit".into(),
diff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rs
index 1adfdb3c9..ff3fa9ded 100644
--- a/crates/codecs/src/tests.rs
+++ b/crates/codecs/src/tests.rs
@@ -178,3 +178,166 @@ fn matroska_hevc_flac() {
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:?}");
+ }
+}
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index 76ee775cf..7f62a3c51 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -20,6 +20,12 @@ pub trait VideoDecoder: Send {
/// Forget all state (called after seeking to a sync sample).
fn reset(&mut self);
fn name(&self) -> &str;
+ /// Whether decoding can start at `sample` (`None`: unknown, trust the container's sync flags).
+ /// Containers may flag samples as sync that the codec cannot start from (an MP4 without
+ /// `stss` marks every sample), so codecs that can tell say so.
+ fn is_random_access(&self, _sample: &[u8]) -> Option<bool> {
+ None
+ }
}
/// A factory returns `None` when it does not handle the entry.
@@ -212,6 +218,141 @@ pub fn hevc_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
}
}
+/// Our pure-Rust VP9 decoder (profiles 0-3, 8/10/12-bit; tile columns and loop filter decode in
+/// parallel).
+pub struct Vp9Decoder {
+ dec: filmcraft_vp9::Decoder,
+ /// Container colour (vpcC / Matroska `Colour`): transfer and primaries are not in the VP9
+ /// bitstream.
+ transfer: Option<filmcraft_color::Transfer>,
+ primaries: Option<filmcraft_color::Primaries>,
+}
+
+/// Colour primaries from an ISO/IEC 23091-2 code.
+pub(crate) fn primaries_from_code(c: u8) -> Option<filmcraft_color::Primaries> {
+ use filmcraft_color::Primaries;
+ match c {
+ 1 => Some(Primaries::Bt709),
+ 5 => Some(Primaries::Bt601_625),
+ 6 => Some(Primaries::Bt601_525),
+ 9 => Some(Primaries::Bt2020),
+ 12 => Some(Primaries::P3D65),
+ _ => None,
+ }
+}
+
+impl Vp9Decoder {
+ pub fn new(cfg: Option<&filmcraft_isobmff::VpcConfig>) -> Self {
+ Self {
+ dec: filmcraft_vp9::Decoder::new(),
+ transfer: cfg.and_then(|c| filmcraft_color::Transfer::from_code(c.transfer_characteristics)),
+ primaries: cfg.and_then(|c| primaries_from_code(c.colour_primaries)),
+ }
+ }
+
+ fn convert(&self, p: filmcraft_vp9::Picture) -> DecodedFrame {
+ use filmcraft_color::{Matrix, Primaries, Range};
+ use filmcraft_frame::{Chroma, PixelData};
+ use filmcraft_vp9::Plane;
+ use std::sync::Arc;
+ let (w, h) = (p.width as usize, p.height as usize);
+ let (cw, ch) = (p.chroma_width as usize, p.chroma_height as usize);
+ let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(p.width, p.height), ..filmcraft_color::ColorInfo::REC709 };
+ // color_space (7.2.2): 1 BT.601, 2 BT.709, 3 SMPTE-170, 4 SMPTE-240, 5 BT.2020, 7 sRGB.
+ match p.color.color_space {
+ 1 | 3 => color.matrix = Matrix::Bt601,
+ 2 | 4 => color.matrix = Matrix::Bt709,
+ 5 => {
+ color.matrix = Matrix::Bt2020Ncl;
+ color.primaries = Primaries::Bt2020;
+ }
+ _ => {}
+ }
+ if let Some(t) = self.transfer {
+ color.transfer = t;
+ }
+ if let Some(pr) = self.primaries {
+ color.primaries = pr;
+ }
+ if p.color.full_range {
+ color.range = Range::Full;
+ }
+ let pts = p.pts;
+ if p.color.color_space == 7 {
+ // RGB (profiles 1 / 3, 4:4:4): the planes carry G, B, R.
+ let shift = p.bit_depth - 8;
+ let mut rgba = Vec::with_capacity(w * h * 4);
+ for i in 0..w * h {
+ rgba.extend_from_slice(&[(p.v.get(i) >> shift) as u8, (p.y.get(i) >> shift) as u8, (p.u.get(i) >> shift) as u8, 255]);
+ }
+ let mut frame = VideoFrame::rgba8(p.width, p.height, rgba);
+ frame.color = filmcraft_color::ColorInfo { range: Range::Full, transfer: filmcraft_color::Transfer::Srgb, ..color };
+ return DecodedFrame { pts, frame };
+ }
+ // 4:4:0 has no frame format of its own: chroma rows are repeated to 4:4:4.
+ let (chroma, rows_440) = match (p.subsampling_x, p.subsampling_y) {
+ (true, true) => (Chroma::C420, false),
+ (true, false) => (Chroma::C422, false),
+ (false, false) => (Chroma::C444, false),
+ (false, true) => (Chroma::C444, true),
+ };
+ fn expand<T: Copy>(v: &[T], cw: usize, ch: usize, h: usize, rows_440: bool) -> Vec<T> {
+ if !rows_440 {
+ return v[..cw * ch].to_vec();
+ }
+ let mut out = Vec::with_capacity(cw * h);
+ for y in 0..h {
+ out.extend_from_slice(&v[(y >> 1) * cw..(y >> 1) * cw + cw]);
+ }
+ out
+ }
+ let data = match (&p.y, &p.u, &p.v) {
+ (Plane::U8(y), Plane::U8(u), Plane::U8(v)) => PixelData::Yuv8 {
+ planes: [Arc::new(y[..w * h].to_vec()), Arc::new(expand(u, cw, ch, h, rows_440)), Arc::new(expand(v, cw, ch, h, rows_440))],
+ chroma,
+ alpha: None,
+ },
+ (Plane::U16(y), Plane::U16(u), Plane::U16(v)) => PixelData::Yuv16 {
+ planes: [Arc::new(y[..w * h].to_vec()), Arc::new(expand(u, cw, ch, h, rows_440)), Arc::new(expand(v, cw, ch, h, rows_440))],
+ chroma,
+ bits: p.bit_depth,
+ alpha: None,
+ },
+ _ => unreachable!("VP9 planes share one sample type"),
+ };
+ // render_size (the intended display size) is not applied: the container's display
+ // dimensions / pixel aspect describe the presentation.
+ let par = (1, 1);
+ DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par, pts: filmcraft_time::Tick::ZERO } }
+ }
+}
+
+impl VideoDecoder for Vp9Decoder {
+ fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
+ let pics = self.dec.decode(sample, pts).map_err(|e| CodecError::Decode(e.to_string()))?;
+ Ok(pics.into_iter().map(|p| self.convert(p)).collect())
+ }
+ fn flush(&mut self) -> Vec<DecodedFrame> {
+ self.dec.flush().into_iter().map(|p| self.convert(p)).collect()
+ }
+ fn reset(&mut self) {
+ self.dec.reset();
+ }
+ fn name(&self) -> &str {
+ "FilmCraft VP9"
+ }
+ fn is_random_access(&self, sample: &[u8]) -> Option<bool> {
+ Some(filmcraft_vp9::is_keyframe(sample))
+ }
+}
+
+pub fn vp9_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
+ match &e.codec {
+ CodecConfig::Vp9(c) => Some(Ok(Box::new(Vp9Decoder::new(Some(c))) as Box<dyn VideoDecoder>)),
+ _ => None,
+ }
+}
+
/// Our ProRes decoder (every frame is intra; slices decode in parallel).
pub struct ProResDecoder;
diff --git a/crates/vp9/README.md b/crates/vp9/README.md
index 67c444694..379156eda 100644
--- a/crates/vp9/README.md
+++ b/crates/vp9/README.md
@@ -46,9 +46,19 @@ for (pts, chunk) in chunks { // one IVF / WebM block / MP4 sample each (frame o
}
}
let _ = dec.flush(); // VP9 has no reordering: always empty, kept for API symmetry
+dec.reset(); // forget references / contexts (seek), keeps the thread pool
let stats = dec.stats(); // what the stream exercised (frame kinds, tiles, compound, scaling...)
+
+// Random access points: does a container sample start with a key frame (and its parameters)?
+let key: bool = filmcraft_vp9::is_keyframe(chunk);
+let info: Option<filmcraft_vp9::KeyframeInfo> = filmcraft_vp9::keyframe_info(chunk);
```
+`filmcraft-codecs` wires the decoder into Matroska / WebM (`V_VP9`, profile / bit depth from
+`CodecPrivate`, colour from `Colour`) and MP4 (`vp09` + `vpcC`) import; its GOP cache asks
+`is_keyframe` before starting a decode at a container sync sample, so wrongly flagged samples
+(e.g. an MP4 without `stss`) still seek correctly.
+
A superframe produces every shown frame it contains (normally one); hidden frames produce none.
### Architecture
diff --git a/crates/vp9/src/decoder.rs b/crates/vp9/src/decoder.rs
index 3de847525..117903e63 100644
--- a/crates/vp9/src/decoder.rs
+++ b/crates/vp9/src/decoder.rs
@@ -133,12 +133,22 @@ impl Decoder {
Ok(out)
}
- /// End of stream. VP9 has no reordering delay, so this returns no pictures; it resets the
- /// reference state so that a new stream can follow.
+ /// End of stream. VP9 has no reordering delay, so this always returns no pictures.
pub fn flush(&mut self) -> Vec<Picture> {
Vec::new()
}
+ /// Forget all decoding state (references, probability contexts, segmentation), e.g. before
+ /// decoding from another key frame after a seek. The thread pool and statistics are kept.
+ pub fn reset(&mut self) {
+ self.st = HeaderState::default();
+ self.slots = Default::default();
+ self.prev_mi = None;
+ self.prev_seg_ids = Vec::new();
+ self.last_size = None;
+ self.last_show_frame = false;
+ }
+
fn decode_frame(&mut self, data: &[u8]) -> Result<Option<Arc<Frame>>> {
let refs: [Option<RefInfo>; 8] = std::array::from_fn(|i| self.slots[i].as_ref().map(|f| RefInfo { width: f.width, height: f.height }));
let mut h = parse_uncompressed(data, &mut self.st, &refs)?;
diff --git a/crates/vp9/src/lib.rs b/crates/vp9/src/lib.rs
index a6fe0ff5d..3bdfd2be5 100644
--- a/crates/vp9/src/lib.rs
+++ b/crates/vp9/src/lib.rs
@@ -39,6 +39,48 @@ mod transform;
mod transform_gen;
pub use decoder::{DecodeStats, Decoder};
+
+/// Stream parameters read from a key frame's uncompressed header (see [`keyframe_info`]).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct KeyframeInfo {
+ pub profile: u8,
+ pub width: u32,
+ pub height: u32,
+ pub render_width: u32,
+ pub render_height: u32,
+ pub bit_depth: u32,
+ pub subsampling_x: bool,
+ pub subsampling_y: bool,
+ pub color: ColorInfo,
+}
+
+/// If the first frame of `chunk` (one container sample: a frame or a superframe) is a key frame,
+/// i.e. a random access point, its stream parameters. Intra-only frames and show_existing_frame
+/// are not random access points.
+pub fn keyframe_info(chunk: &[u8]) -> Option<KeyframeInfo> {
+ let first = header::split_superframe(chunk).into_iter().find(|f| !f.is_empty())?;
+ let mut st = header::HeaderState::default();
+ let h = header::parse_uncompressed(first, &mut st, &[None; 8]).ok()?;
+ if h.show_existing_frame || h.frame_type != header::KEY_FRAME {
+ return None;
+ }
+ Some(KeyframeInfo {
+ profile: h.profile,
+ width: h.width,
+ height: h.height,
+ render_width: h.render_width,
+ render_height: h.render_height,
+ bit_depth: h.color.bit_depth as u32,
+ subsampling_x: h.color.subsampling_x,
+ subsampling_y: h.color.subsampling_y,
+ color: ColorInfo { color_space: h.color.color_space, full_range: h.color.color_range },
+ })
+}
+
+/// Whether `chunk` starts with a key frame (decoding can start there).
+pub fn is_keyframe(chunk: &[u8]) -> bool {
+ keyframe_info(chunk).is_some()
+}
pub use error::{Error, Result};
/// Colour information from the uncompressed header.
diff --git a/crates/vp9/tests/conformance.rs b/crates/vp9/tests/conformance.rs
index 1528b6469..dd90b10d2 100644
--- a/crates/vp9/tests/conformance.rs
+++ b/crates/vp9/tests/conformance.rs
@@ -108,3 +108,34 @@ fn compare_detects_mismatch() {
let err = common::compare(&pics, &reference, f.pix_fmt).unwrap_err();
assert!(err.contains("plane V"), "{err}");
}
+
+/// Key frame detection (random access points) and decoder reset: decoding again from the
+/// second key frame after `reset` gives the same pictures as the uninterrupted decode.
+#[test]
+fn keyframes_and_reset() {
+ let f = common::fixture("fade_intra_heavy");
+ let Some((ivf, _)) = common::ensure(f) else { return };
+ let data = std::fs::read(ivf).unwrap();
+ let chunks = common::ivf_frames(&data);
+ let keys: Vec<usize> = (0..chunks.len()).filter(|&i| filmcraft_vp9::is_keyframe(chunks[i])).collect();
+ assert_eq!(keys.first(), Some(&0));
+ assert!(keys.len() >= 2, "key frames {keys:?}");
+ let info = filmcraft_vp9::keyframe_info(chunks[0]).unwrap();
+ assert_eq!((info.width, info.height, info.bit_depth), (f.width, f.height, 8));
+ assert!(info.subsampling_x && info.subsampling_y);
+ let mut dec = filmcraft_vp9::Decoder::with_threads(1);
+ let mut all = Vec::new();
+ for (i, c) in chunks.iter().enumerate() {
+ all.extend(dec.decode(c, i as i64).unwrap());
+ }
+ // Garbage in between, then a reset and a restart at the second key frame.
+ let _ = dec.decode(&[0x82, 0x49, 0x83, 0x42, 0x00], 0);
+ dec.reset();
+ let k = keys[1];
+ for (i, c) in chunks.iter().enumerate().skip(k) {
+ for p in dec.decode(c, i as i64).unwrap() {
+ let want = all.iter().find(|q| q.pts == p.pts).unwrap();
+ assert!(p.y == want.y && p.u == want.u && p.v == want.v, "picture {} differs after reset", p.pts);
+ }
+ }
+}