Skip to content

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

M9.7: AV1 import from MP4 (av01/av1C) and Matroska/WebM (V_AV1)

Brandon Thomas35a2d2a8619a
diff --git a/Cargo.lock b/Cargo.lock
index fce3e6473..d87d930a7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1399,6 +1399,7 @@ name = "filmcraft-codecs"
version = "0.1.0"
dependencies = [
"filmcraft-aac",
+ "filmcraft-av1",
"filmcraft-bitstream",
"filmcraft-color",
"filmcraft-dnx",
diff --git a/crates/av1/src/lib.rs b/crates/av1/src/lib.rs
index a184b8ef4..00576ddbb 100644
--- a/crates/av1/src/lib.rs
+++ b/crates/av1/src/lib.rs
@@ -65,8 +65,8 @@ impl Picture {
}
}
-/// Whether a temporal unit starts a random access point: it contains a sequence header and a
-/// shown key frame (used for keyframe detection by demuxers without sync-sample tables).
+/// Whether a temporal unit starts a random access point: its first frame is a shown key frame
+/// (used for keyframe detection: containers may flag samples as sync that are not).
pub fn is_key_frame_unit(data: &[u8]) -> bool {
let mut pos = 0;
let mut seq_seen = false;
@@ -98,7 +98,8 @@ pub fn is_key_frame_unit(data: &[u8]) -> bool {
let show_existing = b >> 7;
let frame_type = (b >> 5) & 3;
let show_frame = (b >> 4) & 1;
- return seq_seen && show_existing == 0 && frame_type == 0 && show_frame == 1;
+ let _ = seq_seen;
+ return show_existing == 0 && frame_type == 0 && show_frame == 1;
}
_ => {}
}
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index a672f68d2..aa2b951f2 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -22,6 +22,7 @@ filmcraft-hevc = { workspace = true }
filmcraft-vp9 = { workspace = true }
filmcraft-prores = { workspace = true }
filmcraft-dnx = { workspace = true }
+filmcraft-av1 = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-opus = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 4eee8d9eb..6d61bb75c 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -52,7 +52,15 @@ 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::vp9_factory, video::prores_factory, video::dnx_factory, video::mjpeg_factory])
+ RwLock::new(vec![
+ video::h264_factory,
+ video::hevc_factory,
+ video::vp9_factory,
+ video::av1_factory,
+ video::prores_factory,
+ video::dnx_factory,
+ video::mjpeg_factory,
+ ])
})
}
diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rs
index b6c56a395..339ebb981 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, VP9, ProRes, MJPEG; AV1 once its decoder lands). Audio: AAC and Opus
+//! containers (H.264, HEVC, VP9, AV1, ProRes, MJPEG). 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
@@ -141,6 +141,7 @@ fn vp9_config(private: &[u8], v: Option<&filmcraft_matroska::VideoInfo>) -> VpcC
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::Av1 { av1c } => SampleEntry::video(FourCc(*b"av01"), CodecConfig::Av1(filmcraft_isobmff::Av1Config::parse(av1c).unwrap_or_default()), 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),
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 071939d64..7c156f0ef 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -394,6 +394,7 @@ fn codec_label(c: &CodecConfig) -> String {
),
CodecConfig::Hevc(_) => "HEVC".into(),
CodecConfig::Vp9(c) => format!("VP9 (Profile {})", c.profile),
+ CodecConfig::Av1(c) => format!("AV1 ({} Profile)", ["Main", "High", "Professional"].get(c.seq_profile as usize).unwrap_or(&"Main")),
CodecConfig::ProRes { fourcc } => match &fourcc.0 {
b"apco" => "Apple ProRes 422 Proxy".into(),
b"apcs" => "Apple ProRes 422 LT".into(),
diff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rs
index d07dbbe99..9663d9395 100644
--- a/crates/codecs/src/tests.rs
+++ b/crates/codecs/src/tests.rs
@@ -270,6 +270,57 @@ fn check_vp9_seeks(name: &str, container: &str, pix_fmt: &str, extra: &[&str], f
}
}
+/// All-intra AV1 (libsvtav1) in MP4 / WebM: random access is sample-exact against libdav1d.
+fn check_av1_seeks(name: &str, container: &str, pix_fmt: &str, frames: usize) {
+ let n = frames.to_string();
+ let args = [
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=s=320x240:r=25,noise=alls=8:allf=t",
+ "-frames:v",
+ &n,
+ "-c:v",
+ "libsvtav1",
+ "-pix_fmt",
+ pix_fmt,
+ "-preset",
+ "8",
+ "-crf",
+ "40",
+ "-svtav1-params",
+ "keyint=1",
+ ];
+ let Some(path) = fixture_path(name, &args) else { return };
+ let ref_name = format!("{name}.{pix_fmt}.yuv");
+ let p = path.to_str().unwrap();
+ let Some(reference) = fixture(&ref_name, &["-c:v", "libdav1d", "-i", p, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", 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("AV1"), "{}", v.codec);
+ assert_eq!((v.width, v.height), (320, 240));
+ let frame_len = reference.len() / frames;
+ let rate = info.frame_rate();
+ for k in [frames - 1, 2, 7, 0, 5, 6, 3] {
+ let f = src.video_frame(FrameRequest::full(rate.tick_of(k as i64))).unwrap();
+ assert_eq!((f.width, f.height), (320, 240));
+ assert!(yuv_bytes(&f) == reference[k * frame_len..(k + 1) * frame_len], "{name}: frame {k} differs from libdav1d");
+ }
+}
+
+#[test]
+fn mp4_av1_intra_seeks_bit_exact() {
+ check_av1_seeks("noise_av1_intra.mp4", "MPEG-4", "yuv420p", 10);
+}
+
+#[test]
+fn webm_av1_intra_10bit_seeks_bit_exact() {
+ check_av1_seeks("noise_av1_intra_10bit.webm", "WebM", "yuv420p10le", 10);
+}
+
#[test]
fn webm_vp9_seeks_bit_exact() {
check_vp9_seeks("noise_vp9.webm", "WebM", "yuv420p", &["-deadline", "realtime", "-speed", "8"], 60);
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index b473ce253..2ced3d537 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -361,6 +361,97 @@ pub fn vp9_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
}
}
+/// Our AV1 decoder. The `av1C` configuration OBUs (sequence header) are fed before the first
+/// sample and again after every reset.
+pub struct Av1Decoder {
+ dec: filmcraft_av1::Decoder,
+ config_obus: Vec<u8>,
+ primed: bool,
+}
+
+impl Av1Decoder {
+ pub fn new(config_obus: Vec<u8>) -> Av1Decoder {
+ Av1Decoder { dec: filmcraft_av1::Decoder::new(), config_obus, primed: false }
+ }
+
+ fn convert(p: filmcraft_av1::Picture, pts: i64) -> DecodedFrame {
+ use std::sync::Arc;
+ let w = p.width as usize;
+ let h = p.height as usize;
+ let mut color = filmcraft_color::ColorInfo::REC709;
+ if let Some(m) = filmcraft_color::Matrix::from_code(p.matrix_coefficients) {
+ color.matrix = m;
+ } else {
+ color.matrix = filmcraft_frame::default_matrix(p.width, p.height);
+ }
+ if let Some(t) = filmcraft_color::Transfer::from_code(p.transfer_characteristics) {
+ color.transfer = t;
+ }
+ color.primaries = match p.color_primaries {
+ 9 => filmcraft_color::Primaries::Bt2020,
+ 12 => filmcraft_color::Primaries::P3D65,
+ 5 => filmcraft_color::Primaries::Bt601_625,
+ 6 => filmcraft_color::Primaries::Bt601_525,
+ _ => filmcraft_color::Primaries::Bt709,
+ };
+ if p.full_range {
+ color.range = filmcraft_color::Range::Full;
+ }
+ let chroma = match (p.subsampling_x, p.subsampling_y) {
+ (1, 1) => filmcraft_frame::Chroma::C420,
+ (1, 0) => filmcraft_frame::Chroma::C422,
+ _ => filmcraft_frame::Chroma::C444,
+ };
+ let cw = (w + p.subsampling_x as usize) >> p.subsampling_x;
+ let ch = (h + p.subsampling_y as usize) >> p.subsampling_y;
+ let [y, mut u, mut v] = p.planes;
+ if p.mono_chrome {
+ u = vec![1u16 << (p.bit_depth - 1); cw * ch];
+ v = u.clone();
+ }
+ let data = if p.bit_depth == 8 {
+ let to8 = |p: Vec<u16>| Arc::new(p.into_iter().map(|v| v as u8).collect::<Vec<u8>>());
+ filmcraft_frame::PixelData::Yuv8 { planes: [to8(y), to8(u), to8(v)], chroma, alpha: None }
+ } else {
+ filmcraft_frame::PixelData::Yuv16 { planes: [Arc::new(y), Arc::new(u), Arc::new(v)], chroma, bits: p.bit_depth as u32, alpha: None }
+ };
+ DecodedFrame { pts, frame: VideoFrame { width: p.width, height: p.height, data, color, par: (1, 1), pts: filmcraft_time::Tick::ZERO } }
+ }
+}
+
+impl VideoDecoder for Av1Decoder {
+ fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
+ if !self.primed {
+ self.primed = true;
+ if !self.config_obus.is_empty() {
+ self.dec.decode(&self.config_obus).map_err(|e| CodecError::Decode(e.to_string()))?;
+ }
+ }
+ let pics = self.dec.decode(sample).map_err(|e| CodecError::Decode(e.to_string()))?;
+ Ok(pics.into_iter().map(|p| Self::convert(p, pts)).collect())
+ }
+ fn flush(&mut self) -> Vec<DecodedFrame> {
+ Vec::new()
+ }
+ fn reset(&mut self) {
+ self.dec = filmcraft_av1::Decoder::new();
+ self.primed = false;
+ }
+ fn name(&self) -> &str {
+ "FilmCraft AV1"
+ }
+ fn is_random_access(&self, sample: &[u8]) -> Option<bool> {
+ Some(filmcraft_av1::is_key_frame_unit(sample))
+ }
+}
+
+pub fn av1_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
+ match &e.codec {
+ CodecConfig::Av1(c) => Some(Ok(Box::new(Av1Decoder::new(c.config_obus.clone())) as Box<dyn VideoDecoder>)),
+ _ => None,
+ }
+}
+
/// Our ProRes decoder (every frame is intra; slices decode in parallel).
pub struct ProResDecoder;
diff --git a/docs/architecture.md b/docs/architecture.md
index 9694eb036..a3bdb2af7 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -181,7 +181,7 @@ pub struct CommandSpec {
```text
file ──► codecs (MP4/MOV, MKV, audio) demux + decode, GOP-aware seek
- │ decoder registry: h264, hevc, vp9, prores, dnx, mjpeg (+ any registered first)
+ │ decoder registry: h264, hevc, vp9, av1, prores, dnx, mjpeg (+ any registered first)
▼
media::MediaSource ──► frame cache (byte-budgeted LRU, shared)
▼