Skip to content

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

Merge origin/main into #492; ffmpeg oracle: decode unaligned crops, skip clap cases on ffmpeg without clap

Brandon Thomasd8a7b28b2ee9
diff --cc crates/codecs/src/mp4.rs
index b24d98672,9ef2792be..62f4f547c
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@@ -7,9 -7,9 +7,9 @@@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
- use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
+ use filmcraft_color::ColorInfo;
-use filmcraft_frame::{AudioBuffer, VideoFrame};
-use filmcraft_isobmff::{CodecConfig, Mp4File, TrackKind};
+use filmcraft_frame::{AudioBuffer, Region, VideoFrame};
+use filmcraft_isobmff::{CleanAperture, CodecConfig, Mp4File, TrackKind};
use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};
use filmcraft_time::{FrameRate, Tick};
@@@ -104,70 -104,40 +104,62 @@@ fn hdr_metadata(md: Option<&filmcraft_i
})
}
+/// The clean aperture (`clap`, ISO/IEC 14496-12 / QuickTime) of a `w`×`h` decoded picture as a
+/// pixel rectangle: its size, centred on the picture and moved by its offsets, rounded to whole
+/// samples. `None` (the whole picture is shown) when it is the whole picture or makes no sense: a
+/// zero denominator, an empty or larger-than-the-picture size, a rectangle outside the picture.
+/// [`VideoFrame::cropped`] moves an odd corner onto the chroma grid.
+fn clean_aperture(c: CleanAperture, (w, h): (u32, u32)) -> Option<Region> {
+ let q = |(n, d): (u32, u32)| (d != 0).then(|| f64::from(n) / f64::from(d));
+ let qs = |(n, d): (i32, u32)| (d != 0).then(|| f64::from(n) / f64::from(d));
+ let (cw, ch, dx, dy) = (q(c.width)?.round(), q(c.height)?.round(), qs(c.horiz_offset)?, qs(c.vert_offset)?);
+ let (fw, fh) = (f64::from(w), f64::from(h));
+ if !(cw >= 1.0 && ch >= 1.0 && cw <= fw && ch <= fh) {
+ return None;
+ }
+ let (x, y) = (((fw - cw) / 2.0 + dx).round(), ((fh - ch) / 2.0 + dy).round());
+ // also false for NaN
+ if !(x >= 0.0 && y >= 0.0 && x + cw <= fw && y + ch <= fh) {
+ return None;
+ }
+ let r = Region { x: x as usize, y: y as usize, w: cw as usize, h: ch as usize };
+ (!r.is_full(w as usize, h as usize)).then_some(r)
+}
+
+ /// Colour of a video sample entry. The `colr` box (`nclx` / `nclc`) wins; what it leaves
+ /// unspecified, or all of it when there is none (ffmpeg writes MP4 without `colr` by default),
+ /// comes from the stream's own description: `vpcC` / `apvC`, or the SPS VUI in `avcC` / `hvcC`
+ /// and the sequence header in `av1C`. The rest defaults by frame size.
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 };
- // VP9 and APV carry their colour description in vpcC / apvC (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,
+ use crate::stream_color::ColorCodes;
+ use filmcraft_isobmff::ColorInfo as Colr;
+ let colr = match entry.video.as_ref().and_then(|v| v.color.as_ref()) {
+ Some(Colr::Nclx { primaries, transfer, matrix, full_range }) => {
+ Some(ColorCodes::from_wide((*primaries).into(), (*transfer).into(), (*matrix).into(), Some(*full_range)))
+ }
+ // QuickTime `nclc` has no range flag
+ Some(Colr::Nclc { primaries, transfer, matrix }) => Some(ColorCodes::from_wide((*primaries).into(), (*transfer).into(), (*matrix).into(), None)),
+ // an ICC profile, or no `colr`: no code points
+ _ => None,
+ };
+ let stream = match &entry.codec {
+ CodecConfig::Vp9(v) => Some(ColorCodes {
+ primaries: v.colour_primaries,
+ transfer: v.transfer_characteristics,
+ matrix: v.matrix_coefficients,
+ full_range: Some(v.full_range),
}),
- CodecConfig::Apv(a) if a.color_description_present => Some(filmcraft_isobmff::ColorInfo::Nclx {
- primaries: a.color_primaries as u16,
- transfer: a.transfer_characteristics as u16,
- matrix: a.matrix_coefficients as u16,
- full_range: a.full_range,
+ CodecConfig::Apv(a) if a.color_description_present => Some(ColorCodes {
+ primaries: a.color_primaries,
+ transfer: a.transfer_characteristics,
+ matrix: a.matrix_coefficients,
+ full_range: Some(a.full_range),
}),
- _ => None,
+ CodecConfig::Apv(_) => None,
+ codec => crate::stream_color::from_codec_config(codec),
};
- 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),
- _ => return c,
- };
- if let Some(m) = Matrix::from_code(m as u8) {
- c.matrix = m;
- }
- if let Some(t) = Transfer::from_code(t as u8) {
- c.transfer = t;
- }
- c.primaries = match p {
- 9 => Primaries::Bt2020,
- 12 => Primaries::P3D65,
- 5 => Primaries::Bt601_625,
- 6 => Primaries::Bt601_525,
- _ => Primaries::Bt709,
- };
- if full {
- c.range = Range::Full;
- }
- }
- c
+ let sources: Vec<ColorCodes> = [colr, stream].into_iter().flatten().collect();
+ crate::stream_color::resolve(w, h, &sources)
}
impl Mp4Source {
diff --cc crates/codecs/tests/mp4_oracle.rs
index 403da23f7,94ce49d40..bb9794f10
--- a/crates/codecs/tests/mp4_oracle.rs
+++ b/crates/codecs/tests/mp4_oracle.rs
@@@ -53,103 -53,3 +53,113 @@@ fn bframe_mp4_duration_is_the_decoded_f
let src = filmcraft_codecs::open_bytes("bframes_x264.mp4", bytes(&f)).unwrap();
assert_eq!(src.info().duration, filmcraft_time::FrameRate::FPS_30.tick_of(n as i64));
}
+
+/// `mp4` (moov after mdat, as ffmpeg writes it) with a clean aperture (`clap`) of `w`×`h` moved by
+/// (`dx`, `dy`) from the centre, inserted at the end of the first video sample entry.
+fn with_clap(mp4: &[u8], (w, h, dx, dy): (u32, u32, i32, i32)) -> Vec<u8> {
+ let be = |b: &[u8], at: usize| u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) as usize;
+ // the chain moov > trak > mdia > minf > stbl > stsd > avc1 (stsd has 8 bytes before its entries)
+ let mut chain = Vec::new();
+ let (mut off, mut end) = (0, mp4.len());
+ for (want, skip) in [(b"moov", 8), (b"trak", 8), (b"mdia", 8), (b"minf", 8), (b"stbl", 8), (b"stsd", 16), (b"avc1", 0)] {
+ loop {
+ assert!(off + 8 <= end, "no {}", String::from_utf8_lossy(want));
+ let size = be(mp4, off);
+ if &mp4[off + 4..off + 8] == want {
+ chain.push(off);
+ end = off + size;
+ off += skip;
+ break;
+ }
+ off += size;
+ }
+ }
+ let entry = *chain.last().unwrap();
+ assert!(mp4.windows(4).position(|x| x == b"mdat").unwrap() < chain[0], "moov must follow mdat");
+ let mut clap = Vec::new();
+ for v in [40u32, u32::from_be_bytes(*b"clap"), w, 1, h, 1, dx as u32, 1, dy as u32, 1] {
+ clap.extend_from_slice(&v.to_be_bytes());
+ }
+ let mut out = mp4.to_vec();
+ let at = entry + be(mp4, entry);
+ out.splice(at..at, clap);
+ for &b in &chain {
+ let size = (be(&out, b) + 40) as u32;
+ out[b..b + 4].copy_from_slice(&size.to_be_bytes());
+ }
+ out
+}
+
+/// Cropped pictures are the size and the samples ffmpeg decodes (#288): H.264 frame cropping (SPS)
+/// and an HEVC conformance window while the sample entry gives the uncropped size, and a clean
+/// aperture (`clap`, as iPhones write), centred, off-centre, and with a 90° display rotation
+/// applied after it.
+#[test]
+fn cropped_pictures_match_ffmpeg() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let src = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=30:duration=1,noise=alls=10:allf=t", "-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p"];
+ let Some(plain) = fixture(&ff, "crop_plain_x264.mp4", &src) else {
+ eprintln!("SKIPPED: ffmpeg without libx264");
+ return;
+ };
+ let sps =
+ fixture(&ff, "crop_sps_x264.mp4", &[&src[..], &["-bsf:v", "h264_metadata=crop_left=16:crop_right=16:crop_top=8:crop_bottom=8"]].concat()).unwrap();
+ // the display matrix added without re-encoding (an encode would turn the pixels instead)
+ let rotated = fixture(&ff, "crop_rotated_x264.mp4", &["-display_rotation", "90", "-i", plain.to_str().unwrap(), "-c", "copy"]).unwrap();
+ let dir = dir();
+ let mut cases = vec![("SPS crop", sps, (288, 224))];
+ // HEVC: the conformance window
+ let hevc = [
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=320x240:rate=30:duration=1,noise=alls=10:allf=t",
+ "-c:v",
+ "libx265",
+ "-x265-params",
+ "log-level=error:bframes=3",
+ "-tag:v",
+ "hvc1",
+ "-pix_fmt",
+ "yuv420p",
+ ];
+ match fixture(&ff, "crop_conformance_x265.mp4", &[&hevc[..], &["-bsf:v", "hevc_metadata=crop_left=16:crop_right=16:crop_top=8:crop_bottom=8"]].concat()) {
+ Some(p) => cases.push(("HEVC conformance window", p, (288, 224))),
+ None => eprintln!("SKIPPED (HEVC case): ffmpeg without libx265"),
+ }
+ for (name, base, clap, size) in [
+ ("centred clap", &plain, (280, 200, 0, 0), (280, 200)),
+ ("off-centre clap", &plain, (200, 150, -30, 22), (200, 150)),
+ ("clap then rotation", &rotated, (280, 200, 0, 0), (200, 280)),
+ ] {
+ let path = dir.join(format!("crop_{}.mp4", name.replace(' ', "_")));
+ std::fs::write(&path, with_clap(&bytes(base), clap)).unwrap();
+ cases.push((name, path, size));
+ }
+ for (name, path, (w, h)) in cases {
+ let src = filmcraft_codecs::open_bytes(path.file_name().unwrap().to_str().unwrap(), bytes(&path)).unwrap();
+ let v = src.info().video.clone().unwrap();
+ assert_eq!((v.width, v.height), (w, h), "{name}: reported size");
+ let (cw, ch) = (w.div_ceil(2) as usize, h.div_ceil(2) as usize);
- let raw = ffmpeg_frames(&ff, &path, "yuv420p");
++ // `-flags unaligned`: ffmpeg otherwise skips a left crop that would misalign its frame
++ // pointers (on AVX-512 machines it needs 64-byte alignment) and returns wider frames
++ let raw = ffmpeg_out(
++ &ff,
++ &["-flags", "unaligned", "-i", path.to_str().unwrap(), "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"],
++ );
+ let frame_bytes = (w * h) as usize + 2 * cw * ch;
++ if name.contains("clap") && raw.len() % frame_bytes != 0 {
++ // ffmpeg before 7.1 ignores `clap` and decodes the whole picture
++ eprintln!("SKIPPED ({name}): this ffmpeg does not apply the clean aperture");
++ continue;
++ }
+ assert_eq!(raw.len() % frame_bytes, 0, "{name}: ffmpeg's frames are {w}x{h}");
+ let n = raw.len() / frame_bytes;
+ assert_eq!(n, 30, "{name}");
+ for (i, want) in raw.chunks(frame_bytes).enumerate() {
+ let f = src.video_frame(filmcraft_media::FrameRequest::full(v.frame_rate.tick_of(i as i64))).unwrap();
+ assert_eq!((f.width, f.height), (w, h), "{name}: frame {i} size");
+ assert!(planes(&f) == raw_planes(want, w as usize, h as usize, cw, ch, 1), "{name}: frame {i} differs from ffmpeg's");
+ }
+ }
+}