Skip to content

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

M9.5: ProRes decode in the codec hub and ProRes 422 HQ export; decoder colour metadata takes precedence unless the container has an explicit colr

Brandon Thomasf4d3efe32a2d
diff --git a/Cargo.lock b/Cargo.lock
index c8e289557..124738ce6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1267,6 +1267,7 @@ dependencies = [
"filmcraft-h264",
"filmcraft-isobmff",
"filmcraft-media",
+ "filmcraft-prores",
"filmcraft-time",
"image",
"log",
@@ -1322,6 +1323,7 @@ dependencies = [
"filmcraft-isobmff",
"filmcraft-media",
"filmcraft-project",
+ "filmcraft-prores",
"filmcraft-render",
"filmcraft-time",
"image",
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index f364c5025..aad209a15 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -17,6 +17,7 @@ filmcraft-media = { workspace = true }
filmcraft-isobmff = { workspace = true }
filmcraft-bitstream = { workspace = true }
filmcraft-h264 = { workspace = true }
+filmcraft-prores = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
image = { version = "0.25", default-features = false, features = ["jpeg"] }
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 65b7de89b..b0f5e43e9 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -43,7 +43,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::mjpeg_factory]))
+ F.get_or_init(|| RwLock::new(vec![video::h264_factory, video::prores_factory, video::mjpeg_factory]))
}
/// Register a video decoder factory (tried before previously registered ones).
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 65ddc5b6c..2d5dd7286 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -43,6 +43,8 @@ pub struct Mp4Source {
video: Mutex<VideoState>,
audio: Mutex<AudioState>,
color: ColorInfo,
+ /// Colour from an explicit `colr` box, if the file has one.
+ explicit_color: Option<ColorInfo>,
/// Cumulative sample start frames for the audio track (for packet lookup).
audio_starts: Vec<i64>,
cache_budget: usize,
@@ -91,6 +93,7 @@ impl Mp4Source {
return Err(CodecError::Unsupported("no playable tracks".into()));
}
let mut color = ColorInfo::REC709;
+ let mut explicit_color = None;
let video = vtrack.map(|i| {
let t = &file.tracks[i];
let entry = &t.entries[0];
@@ -102,6 +105,13 @@ impl Mp4Source {
let d = durs.get(durs.len() / 2).copied().unwrap_or(1).max(1);
let rate = FrameRate::from_f64(t.timescale as f64 / d as f64);
color = color_from(entry, w, h);
+ if entry
+ .video
+ .as_ref()
+ .is_some_and(|v| matches!(v.color, Some(filmcraft_isobmff::ColorInfo::Nclx { .. } | filmcraft_isobmff::ColorInfo::Nclc { .. })))
+ {
+ explicit_color = Some(color);
+ }
let bitrate = (t.samples.iter().map(|s| s.size as u64).sum::<u64>() * 8 * t.timescale as u64).checked_div(t.duration);
VideoStreamInfo {
width: w,
@@ -178,6 +188,7 @@ impl Mp4Source {
video: Mutex::new(VideoState { decoder: None, next: usize::MAX, frames: BTreeMap::new(), bytes: 0 }),
audio: Mutex::new(AudioState { decoder: None, packets: HashMap::new(), order: Vec::new(), last_decoded: None }),
color,
+ explicit_color,
audio_starts,
cache_budget: 384 << 20,
})
@@ -188,13 +199,11 @@ impl Mp4Source {
}
fn store(&self, st: &mut VideoState, pts: i64, mut f: VideoFrame) {
- if f.color == ColorInfo::SRGB_FULL && !matches!(f.data, filmcraft_frame::PixelData::Rgba8(_)) {
- f.color = self.color;
- } else if !matches!(f.data, filmcraft_frame::PixelData::Rgba8(_) | filmcraft_frame::PixelData::RgbaF32(_)) {
- // decoders fill in what they know; fall back to the container's colour description
- if f.color == ColorInfo::default() {
- f.color = self.color;
- }
+ // An explicit container `colr` box wins; otherwise keep what the decoder signalled.
+ if let Some(c) = self.explicit_color
+ && !matches!(f.data, filmcraft_frame::PixelData::Rgba8(_) | filmcraft_frame::PixelData::RgbaF32(_))
+ {
+ f.color = c;
}
st.bytes += f.byte_size();
st.frames.insert(pts, Arc::new(f));
diff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rs
index ca49d929f..77abc20fd 100644
--- a/crates/codecs/src/tests.rs
+++ b/crates/codecs/src/tests.rs
@@ -122,3 +122,16 @@ fn h264_mp4_decodes_and_seeks() {
src.video_frame(FrameRequest::full(rate.tick_of(f))).unwrap();
}
}
+
+#[test]
+fn prores_mov_decodes() {
+ let Some(b) = fixture("bars_prores.mov", &["-f", "lavfi", "-i", "smptehdbars=s=640x360:r=24:d=1", "-c:v", "prores_ks", "-profile:v", "3"]) else { return };
+ let src = crate::open_bytes("bars_prores.mov", b).unwrap();
+ assert!(src.info().video.as_ref().unwrap().codec.contains("ProRes"));
+ let f = src.video_frame(FrameRequest::full(Tick(TICKS_PER_SECOND / 2))).unwrap();
+ assert!(f.format_label().contains("4:2:2"));
+ let px = f.to_rgba8();
+ // leftmost bars area is 40% grey
+ let c = &px[(100 * 640 + 20) * 4..][..3];
+ assert!((c[0] as i32 - 104).abs() < 6, "{c:?}");
+}
diff --git a/crates/codecs/src/video.rs b/crates/codecs/src/video.rs
index cc7394d9f..66e5d8bcf 100644
--- a/crates/codecs/src/video.rs
+++ b/crates/codecs/src/video.rs
@@ -124,3 +124,49 @@ pub fn h264_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
_ => None,
}
}
+
+/// Our ProRes decoder (every frame is intra; slices decode in parallel).
+pub struct ProResDecoder;
+
+impl VideoDecoder for ProResDecoder {
+ fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
+ use std::sync::Arc;
+ let f = filmcraft_prores::decode_frame(sample).map_err(|e| CodecError::Decode(e.to_string()))?;
+ let chroma = match f.chroma {
+ filmcraft_prores::ChromaFormat::Yuv422 => filmcraft_frame::Chroma::C422,
+ filmcraft_prores::ChromaFormat::Yuv444 => filmcraft_frame::Chroma::C444,
+ };
+ let mut color = filmcraft_color::ColorInfo::REC709;
+ if let Some(m) = filmcraft_color::Matrix::from_code(f.color.matrix) {
+ color.matrix = m;
+ }
+ if let Some(t) = filmcraft_color::Transfer::from_code(f.color.transfer) {
+ color.transfer = t;
+ }
+ let frame = VideoFrame {
+ width: f.width,
+ height: f.height,
+ data: filmcraft_frame::PixelData::Yuv16 {
+ planes: [Arc::new(f.y), Arc::new(f.cb), Arc::new(f.cr)],
+ chroma,
+ bits: f.bit_depth as u32,
+ alpha: f.alpha.map(Arc::new),
+ },
+ color,
+ par: (1, 1),
+ pts: filmcraft_time::Tick::ZERO,
+ };
+ Ok(vec![DecodedFrame { pts, frame }])
+ }
+ fn flush(&mut self) -> Vec<DecodedFrame> {
+ Vec::new()
+ }
+ fn reset(&mut self) {}
+ fn name(&self) -> &str {
+ "FilmCraft ProRes"
+ }
+}
+
+pub fn prores_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
+ matches!(e.codec, CodecConfig::ProRes { .. }).then(|| Ok(Box::new(ProResDecoder) as Box<dyn VideoDecoder>))
+}
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 17ffe6f53..b5f24cbc6 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -16,6 +16,7 @@ filmcraft-media = { workspace = true }
filmcraft-project = { workspace = true }
filmcraft-render = { workspace = true }
filmcraft-isobmff = { workspace = true }
+filmcraft-prores = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 7a1e08deb..54015363b 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -178,7 +178,7 @@ pub type AudioEncoderFactory = fn(format: Format, sample_rate: u32, channels: u3
fn video_factories() -> &'static RwLock<Vec<EncoderFactory>> {
static F: OnceLock<RwLock<Vec<EncoderFactory>>> = OnceLock::new();
- F.get_or_init(|| RwLock::new(vec![mjpeg_factory]))
+ F.get_or_init(|| RwLock::new(vec![prores_factory, mjpeg_factory]))
}
fn audio_factories() -> &'static RwLock<Vec<AudioEncoderFactory>> {
static F: OnceLock<RwLock<Vec<AudioEncoderFactory>>> = OnceLock::new();
@@ -233,6 +233,62 @@ fn mjpeg_factory(format: Format, w: u32, h: u32, rate: FrameRate, s: &ExportSett
(format == Format::Mjpeg).then(|| Ok(Box::new(MjpegEncoder { w: w as u16, h: h as u16, quality: s.quality.clamp(1, 100), rate }) as Box<dyn VideoEncoder>))
}
+/// ProRes 422 HQ encoder: sRGB/709 RGBA8 → 10-bit limited-range BT.709 4:2:2.
+struct ProResEncoder {
+ enc: filmcraft_prores::Encoder,
+ w: u32,
+ h: u32,
+ rate: FrameRate,
+}
+
+impl VideoEncoder for ProResEncoder {
+ fn sample_entry(&self) -> SampleEntry {
+ SampleEntry::prores(filmcraft_isobmff::FourCc(*b"apch"), self.w as u16, self.h as u16)
+ }
+ fn timescale(&self) -> u32 {
+ self.rate.num as u32
+ }
+ fn encode(&mut self, f: &EncoderFrame) -> Result<Vec<EncodedPacket>> {
+ let mut fr = filmcraft_prores::Frame::new(f.width, f.height, filmcraft_prores::ChromaFormat::Yuv422, 10, false);
+ rgba_to_yuv422_10(f.rgba, f.width as usize, f.height as usize, &mut fr.y, &mut fr.cb, &mut fr.cr);
+ let data = self.enc.encode(&fr).map_err(|e| ExportError::Encode(e.to_string()))?;
+ Ok(vec![EncodedPacket { data, key: true, duration: self.rate.den as u32, composition_offset: 0 }])
+ }
+ fn flush(&mut self) -> Result<Vec<EncodedPacket>> {
+ Ok(Vec::new())
+ }
+}
+
+/// BT.709 limited-range 10-bit 4:2:2 from straight RGBA8 (chroma averaged horizontally).
+pub fn rgba_to_yuv422_10(rgba: &[u8], w: usize, h: usize, y: &mut [u16], cb: &mut [u16], cr: &mut [u16]) {
+ let cw = w.div_ceil(2);
+ y.par_chunks_mut(w).zip(cb.par_chunks_mut(cw).zip(cr.par_chunks_mut(cw))).enumerate().for_each(|(row, (yr, (cbr, crr)))| {
+ let src = &rgba[row * w * 4..(row + 1) * w * 4];
+ let mut us = vec![0f32; w];
+ let mut vs = vec![0f32; w];
+ for x in 0..w {
+ let (r, g, b) = (src[x * 4] as f32 / 255.0, src[x * 4 + 1] as f32 / 255.0, src[x * 4 + 2] as f32 / 255.0);
+ let yy = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ yr[x] = (64.0 + 876.0 * yy).round().clamp(4.0, 1019.0) as u16;
+ us[x] = (b - yy) / 1.8556;
+ vs[x] = (r - yy) / 1.5748;
+ }
+ for cx in 0..cw {
+ let a = cx * 2;
+ let b2 = (a + 1).min(w - 1);
+ let u = (us[a] + us[b2]) * 0.5;
+ let v = (vs[a] + vs[b2]) * 0.5;
+ cbr[cx] = (512.0 + 896.0 * u).round().clamp(4.0, 1019.0) as u16;
+ crr[cx] = (512.0 + 896.0 * v).round().clamp(4.0, 1019.0) as u16;
+ }
+ });
+}
+
+fn prores_factory(format: Format, w: u32, h: u32, rate: FrameRate, _s: &ExportSettings) -> Option<Result<Box<dyn VideoEncoder>>> {
+ (format == Format::ProRes)
+ .then(|| Ok(Box::new(ProResEncoder { enc: filmcraft_prores::Encoder::new(filmcraft_prores::Profile::Hq, w, h), w, h, rate }) as Box<dyn VideoEncoder>))
+}
+
/// The range to export (settings → In/Out → whole sequence).
pub fn export_range(project: &Project, seq: ItemId, settings: &ExportSettings) -> Result<TimeRange> {
let q = project.sequence(seq).ok_or(ExportError::NoSequence)?;
diff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rs
index 003cc5213..7747a75b8 100644
--- a/crates/export/src/tests.rs
+++ b/crates/export/src/tests.rs
@@ -89,8 +89,13 @@ fn wav_png_gif() {
}
#[test]
-fn unavailable_encoder_errors_cleanly() {
+fn prores_export_roundtrip() {
let (p, seq, m) = project();
- let r = export(&p, seq, &ExportSettings { format: Format::ProRes, path: tmp("x.mov"), ..Default::default() }, &m, &Progress::default());
- assert!(matches!(r, Err(ExportError::Unsupported(_))));
+ let path = tmp("pr.mov");
+ export(&p, seq, &ExportSettings { format: Format::ProRes, path: path.clone(), ..Default::default() }, &m, &Progress::default()).unwrap();
+ let bytes: Arc<[u8]> = std::fs::read(&path).unwrap().into();
+ let src = filmcraft_codecs::open_bytes("pr.mov", bytes).unwrap();
+ assert!(src.info().video.as_ref().unwrap().codec.contains("ProRes 422 HQ"));
+ let f = src.video_frame(FrameRequest::full(Tick(TICKS_PER_SECOND / 3))).unwrap().to_rgba8();
+ assert!(f[0] > 240 && f[1] < 15 && f[2] < 15, "{:?}", &f[..4]);
}