FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
media: decode uncompressed and PackBits YCbCr TIFF stills (#1293)
lloydd6df5c6abde5
diff --git a/crates/media/src/still.rs b/crates/media/src/still.rsindex f2825d08f..debc3a9cc 100644--- a/crates/media/src/still.rs+++ b/crates/media/src/still.rs@@ -11,6 +11,7 @@ use crate::{FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result,pub mod dng;pub mod exr;+mod ycbcr_tiff;/// Default still duration (Premiere's preference default is 5 seconds).pub const DEFAULT_STILL_DURATION: Tick = Tick(5 * TICKS_PER_SECOND);@@ -46,6 +47,9 @@ pub fn decode_raster(name: &str, bytes: &[u8]) -> Result<Raster> {if crate::tga::sniff(name, bytes) {return crate::tga::decode(name, bytes);}+ if ycbcr_tiff::sniff(bytes) {+ return ycbcr_tiff::decode(name, bytes);+ }let img = image::load_from_memory(bytes).map_err(|e| MediaError::Decode(format!("{name}: {e}")))?;let has_alpha = img.color().has_alpha();let rgba = img.to_rgba8();diff --git a/crates/media/src/still/ycbcr_tiff.rs b/crates/media/src/still/ycbcr_tiff.rsnew file mode 100644index 000000000..74ab74cb0--- /dev/null+++ b/crates/media/src/still/ycbcr_tiff.rs@@ -0,0 +1,174 @@+//! Uncompressed and PackBits YCbCr TIFFs (TIFF 6.0 §21), as ffmpeg writes from YUV sources. The+//! image crate reads YCbCr only inside JPEG compression, so these are decoded here: 8-bit chunky+//! data units of any subsampling (1, 2 or 4 each way), converted to RGB with the file's+//! YCbCrCoefficients and ReferenceBlackWhite (§20), chroma repeated across each data unit.+//!+//! Every number comes from the file: sizes, strip offsets and counts are checked before use, the+//! picture is capped at [`MAX_PIXELS`], and PackBits output stops at the bytes the image needs.++use filmcraft_dng::tiff::{Tiff, tags};++use super::Raster;+use crate::{MediaError, Result};++/// Largest picture decoded (1 GiB of RGBA), as for animated images.+const MAX_PIXELS: u64 = 1 << 28;++const PHOTOMETRIC_YCBCR: u64 = 6;+const COMPRESSION_NONE: u64 = 1;+const COMPRESSION_PACKBITS: u64 = 32773;+const YCBCR_COEFFICIENTS: u16 = 529;+const YCBCR_SUBSAMPLING: u16 = 530;+const REFERENCE_BLACK_WHITE: u16 = 532;++/// Whether `bytes` is a TIFF whose first image is uncompressed or PackBits YCbCr (the ones this+/// module decodes instead of the image crate).+pub fn sniff(bytes: &[u8]) -> bool {+ let Ok((t, first)) = Tiff::new(bytes) else { return false };+ let Ok((ifd, _)) = t.read_ifd(first, 0) else { return false };+ let num = |tag| ifd.get(tag).and_then(|e| t.uint(e).ok());+ num(tags::PHOTOMETRIC) == Some(PHOTOMETRIC_YCBCR) && matches!(num(tags::COMPRESSION).unwrap_or(COMPRESSION_NONE), COMPRESSION_NONE | COMPRESSION_PACKBITS)+}++/// Decode the first image of a YCbCr TIFF (see [`sniff`]) to RGBA.+pub fn decode(name: &str, bytes: &[u8]) -> Result<Raster> {+ let bad = |what: &str| MediaError::Decode(format!("{name}: YCbCr TIFF: {what}"));+ let unsupported = |what: &str| MediaError::Unsupported(format!("{name}: YCbCr TIFF with {what}"));+ let (t, first) = Tiff::new(bytes).map_err(|_| bad("not a TIFF"))?;+ let (ifd, _) = t.read_ifd(first, 0).map_err(|_| bad("unreadable image directory"))?;+ let uints = |tag: u16| -> Result<Option<Vec<u64>>> { ifd.get(tag).map(|e| t.uints(e).map_err(|_| bad("unreadable field"))).transpose() };+ let one = |tag: u16| -> Result<Option<u64>> { Ok(uints(tag)?.and_then(|v| v.first().copied())) };++ let width = one(tags::IMAGE_WIDTH)?.ok_or_else(|| bad("no ImageWidth"))?;+ let height = one(tags::IMAGE_LENGTH)?.ok_or_else(|| bad("no ImageLength"))?;+ if width == 0 || height == 0 {+ return Err(bad("empty image"));+ }+ if width.saturating_mul(height) > MAX_PIXELS {+ return Err(unsupported("more than 268 million pixels"));+ }+ if one(tags::SAMPLES_PER_PIXEL)?.unwrap_or(1) != 3 {+ return Err(unsupported("other than three samples per pixel"));+ }+ if uints(tags::BITS_PER_SAMPLE)?.unwrap_or_else(|| vec![1]).iter().any(|&b| b != 8) {+ return Err(unsupported("other than 8 bits per sample"));+ }+ if one(tags::PLANAR_CONFIGURATION)?.unwrap_or(1) != 1 {+ return Err(unsupported("separate planes"));+ }+ if ifd.get(tags::TILE_OFFSETS).is_some() {+ return Err(unsupported("tiles"));+ }+ let compression = one(tags::COMPRESSION)?.unwrap_or(COMPRESSION_NONE);+ let sub = uints(YCBCR_SUBSAMPLING)?.unwrap_or_else(|| vec![2, 2]);+ let (sh, sv) = match sub.as_slice() {+ [h, v, ..] if [1, 2, 4].contains(h) && [1, 2, 4].contains(v) => (*h, *v),+ _ => return Err(bad("invalid YCbCrSubSampling")),+ };+ // §21: the data units cover the image rounded up to whole units.+ let (units_x, units_y) = (width.div_ceil(sh), height.div_ceil(sv));+ let unit_len = sh * sv + 2;+ let need = usize::try_from(units_x.saturating_mul(units_y).saturating_mul(unit_len)).map_err(|_| bad("too large"))?;++ let offsets = uints(tags::STRIP_OFFSETS)?.ok_or_else(|| bad("no StripOffsets"))?;+ let counts = uints(tags::STRIP_BYTE_COUNTS)?.ok_or_else(|| bad("no StripByteCounts"))?;+ let mut units: Vec<u8> = Vec::with_capacity(need);+ for (&off, &len) in offsets.iter().zip(&counts) {+ if units.len() >= need {+ break;+ }+ let strip = usize::try_from(off)+ .ok()+ .zip(usize::try_from(len).ok())+ .and_then(|(o, l)| bytes.get(o..o.checked_add(l)?))+ .ok_or_else(|| bad("strip outside the file"))?;+ match compression {+ COMPRESSION_NONE => units.extend_from_slice(strip.get(..need - units.len()).unwrap_or(strip)),+ _ => unpackbits(strip, &mut units, need),+ }+ }+ if units.len() < need {+ return Err(bad("image data shorter than the image"));+ }++ let coeffs = match ifd.get(YCBCR_COEFFICIENTS) {+ Some(e) => t.floats(e).map_err(|_| bad("unreadable YCbCrCoefficients"))?,+ None => vec![0.299, 0.587, 0.114],+ };+ let [lr, lg, lb] = coeffs.get(..3).and_then(|c| <[f64; 3]>::try_from(c).ok()).ok_or_else(|| bad("invalid YCbCrCoefficients"))?;+ if lg.abs() < 1e-6 {+ return Err(bad("invalid YCbCrCoefficients"));+ }+ let rbw = match ifd.get(REFERENCE_BLACK_WHITE) {+ Some(e) => t.floats(e).map_err(|_| bad("unreadable ReferenceBlackWhite"))?,+ None => vec![0.0, 255.0, 128.0, 255.0, 128.0, 255.0],+ };+ let [yb, yw, cbb, cbw, crb, crw] = rbw.get(..6).and_then(|c| <[f64; 6]>::try_from(c).ok()).ok_or_else(|| bad("invalid ReferenceBlackWhite"))?;+ if (yw - yb).abs() < 1e-6 || (cbw - cbb).abs() < 1e-6 || (crw - crb).abs() < 1e-6 {+ return Err(bad("invalid ReferenceBlackWhite"));+ }+ // §20: luma to 0–255, chroma to ±127 about its reference black; §21: back to R'G'B'.+ let to_rgb = |y: u8, cb: u8, cr: u8| -> [u8; 3] {+ let y = (f64::from(y) - yb) * 255.0 / (yw - yb);+ let cb = (f64::from(cb) - cbb) * 127.0 / (cbw - cbb);+ let cr = (f64::from(cr) - crb) * 127.0 / (crw - crb);+ let r = cr * (2.0 - 2.0 * lr) + y;+ let b = cb * (2.0 - 2.0 * lb) + y;+ let g = (y - lb * b - lr * r) / lg;+ [r, g, b].map(|v| v.round().clamp(0.0, 255.0) as u8)+ };++ let (w, h) = (width as usize, height as usize);+ let (sh, sv, units_x) = (sh as usize, sv as usize, units_x as usize);+ let mut rgba = vec![255u8; w * h * 4];+ for (i, unit) in units.chunks_exact(sh * sv + 2).take(need / (sh * sv + 2)).enumerate() {+ let (ux, uy) = (i % units_x, i / units_x);+ let (cb, cr) = (unit[sh * sv], unit[sh * sv + 1]);+ for (k, &y) in unit[..sh * sv].iter().enumerate() {+ let (x, row) = (ux * sh + k % sh, uy * sv + k / sh);+ if x < w && row < h {+ let at = (row * w + x) * 4;+ rgba[at..at + 3].copy_from_slice(&to_rgb(y, cb, cr));+ }+ }+ }+ Ok(Raster { width: width as u32, height: height as u32, rgba, has_alpha: false })+}++/// PackBits (TIFF 6.0 §9) from `src` appended to `out`, stopping at `limit` bytes of output or at+/// a run that the data ends inside.+fn unpackbits(src: &[u8], out: &mut Vec<u8>, limit: usize) {+ let mut p = 0;+ while out.len() < limit {+ let Some(&n) = src.get(p) else { return };+ let n = n as i8;+ p += 1;+ if n >= 0 {+ let len = n as usize + 1;+ let Some(lit) = src.get(p..p + len) else { return };+ out.extend_from_slice(&lit[..len.min(limit - out.len())]);+ p += len;+ } else if n != -128 {+ let Some(&b) = src.get(p) else { return };+ let len = (1 - n as isize) as usize;+ out.extend(std::iter::repeat_n(b, len.min(limit - out.len())));+ p += 1;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn packbits_runs_literals_and_noops() {+ let mut out = Vec::new();+ // literal 2, a no-op, a run of 3, then a literal cut short by the end of the data+ unpackbits(&[1, 10, 11, 0x80, 0xFE, 7, 4, 1], &mut out, 100);+ assert_eq!(out, [10, 11, 7, 7, 7]);+ let mut capped = Vec::new();+ unpackbits(&[0xFE, 7, 0xFE, 8], &mut capped, 4);+ assert_eq!(capped, [7, 7, 7, 8]);+ }+}diff --git a/crates/media/tests/tiff_ycbcr.rs b/crates/media/tests/tiff_ycbcr.rsnew file mode 100644index 000000000..f6474db2f--- /dev/null+++ b/crates/media/tests/tiff_ycbcr.rs@@ -0,0 +1,156 @@+//! YCbCr TIFF stills (#1293): uncompressed and PackBits files with PhotometricInterpretation 6, as+//! ffmpeg writes from YUV sources. The files are built here from TIFF 6.0 (§21 YCbCr images, §9+//! PackBits), little-endian, one strip.++use filmcraft_media::still::decode_raster;++/// A YCbCr TIFF: `width` × `height`, subsampling `sub` (horizontal, vertical), `data` the strip+/// as stored (data units, already compressed when `compression` is 32773), plus `extra` entries+/// (tag, type, values).+fn ycbcr_tiff(width: u32, height: u32, sub: (u16, u16), compression: u16, data: &[u8], extra: &[(u16, u16, Vec<u32>)]) -> Vec<u8> {+ let mut entries: Vec<(u16, u16, Vec<u32>)> = vec![+ (256, 4, vec![width]),+ (257, 4, vec![height]),+ (258, 3, vec![8, 8, 8]),+ (259, 3, vec![u32::from(compression)]),+ (262, 3, vec![6]),+ (273, 4, vec![0]), // patched below+ (277, 3, vec![3]),+ (278, 4, vec![height]),+ (279, 4, vec![data.len() as u32]),+ (530, 3, vec![u32::from(sub.0), u32::from(sub.1)]),+ ];+ entries.extend(extra.iter().cloned());+ entries.sort_by_key(|e| e.0);+ let ifd_at = 8u32;+ let ifd_len = 2 + 12 * entries.len() as u32 + 4;+ let mut extra_data: Vec<u8> = Vec::new();+ let mut ifd: Vec<u8> = (entries.len() as u16).to_le_bytes().to_vec();+ let data_at = ifd_at + ifd_len;+ let mut values_at = data_at + data.len() as u32;+ for (tag, ty, vals) in &entries {+ let vals = if *tag == 273 { vec![data_at] } else { vals.clone() };+ let mut bytes: Vec<u8> = Vec::new();+ for v in &vals {+ match ty {+ 3 => bytes.extend((*v as u16).to_le_bytes()),+ 5 => bytes.extend(v.to_le_bytes()), // rationals are passed as num, den pairs+ _ => bytes.extend(v.to_le_bytes()),+ }+ }+ let count = if *ty == 5 { vals.len() / 2 } else { vals.len() };+ ifd.extend(tag.to_le_bytes());+ ifd.extend(ty.to_le_bytes());+ ifd.extend((count as u32).to_le_bytes());+ if bytes.len() <= 4 {+ bytes.resize(4, 0);+ ifd.extend(&bytes);+ } else {+ ifd.extend(values_at.to_le_bytes());+ values_at += bytes.len() as u32;+ extra_data.extend(bytes);+ }+ }+ ifd.extend(0u32.to_le_bytes());+ let mut out = b"II*\0".to_vec();+ out.extend(ifd_at.to_le_bytes());+ out.extend(ifd);+ out.extend(data);+ out.extend(extra_data);+ out+}++fn px(r: &filmcraft_media::still::Raster, x: u32, y: u32) -> [u8; 4] {+ let i = ((y * r.width + x) * 4) as usize;+ [r.rgba[i], r.rgba[i + 1], r.rgba[i + 2], r.rgba[i + 3]]+}++fn near(a: [u8; 4], b: [u8; 4]) -> bool {+ a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 2)+}++#[test]+fn subsampled_ycbcr_places_each_data_unit() {+ // 4 × 2 at 2 × 2: two data units (four Y, then Cb, Cr). Left grey, right red (BT.601, the+ // default YCbCrCoefficients, full range: the default ReferenceBlackWhite).+ let data = [128, 128, 128, 128, 128, 128, 76, 76, 76, 76, 85, 255];+ let r = decode_raster("frame.tiff", &ycbcr_tiff(4, 2, (2, 2), 1, &data, &[])).unwrap();+ assert_eq!((r.width, r.height), (4, 2));+ for y in 0..2 {+ assert!(near(px(&r, 0, y), [128, 128, 128, 255]) && near(px(&r, 1, y), [128, 128, 128, 255]), "{:?}", px(&r, 0, y));+ assert!(near(px(&r, 2, y), [254, 0, 0, 255]) && near(px(&r, 3, y), [254, 0, 0, 255]), "{:?}", px(&r, 2, y));+ }+}++#[test]+fn packbits_ycbcr_with_video_range_reference_levels() {+ // 2 × 1 at 1 × 1 (4:4:4): white then black in video range (16–235, chroma 128 ± 112), the+ // ReferenceBlackWhite ffmpeg writes. PackBits: a literal run of 6 bytes.+ let units = [235, 128, 128, 16, 128, 128];+ let mut data = vec![5u8];+ data.extend(units);+ let rbw = vec![16, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1];+ let r = decode_raster("frame.tif", &ycbcr_tiff(2, 1, (1, 1), 32773, &data, &[(532, 5, rbw)])).unwrap();+ assert!(near(px(&r, 0, 0), [255, 255, 255, 255]), "{:?}", px(&r, 0, 0));+ assert!(near(px(&r, 1, 0), [0, 0, 0, 255]), "{:?}", px(&r, 1, 0));+}++#[test]+fn sizes_that_are_not_a_whole_number_of_data_units_are_padded() {+ // 3 × 3 at 2 × 2: the data units cover 4 × 4 (TIFF 6.0 §21), the extra column and row dropped.+ let unit = |y: u8| [y, y, y, y, 128, 128];+ let data: Vec<u8> = [unit(50), unit(100), unit(150), unit(200)].concat();+ let r = decode_raster("frame.tiff", &ycbcr_tiff(3, 3, (2, 2), 1, &data, &[])).unwrap();+ assert_eq!((r.width, r.height, r.rgba.len()), (3, 3, 36));+ assert!(near(px(&r, 0, 0), [50, 50, 50, 255]) && near(px(&r, 2, 0), [100, 100, 100, 255]));+ assert!(near(px(&r, 0, 2), [150, 150, 150, 255]) && near(px(&r, 2, 2), [200, 200, 200, 255]));+}++#[test]+fn damaged_ycbcr_tiffs_fail_without_panicking() {+ let data: Vec<u8> = (0..4 * 4 / 4 * 6).map(|i| (i * 37 % 256) as u8).collect();+ let good = ycbcr_tiff(4, 4, (2, 2), 1, &data, &[]);+ let mut cases: Vec<Vec<u8>> = (0..good.len()).map(|n| good[..n].to_vec()).collect();+ for i in 0..good.len() {+ for bit in [0, 3, 7] {+ let mut b = good.clone();+ b[i] ^= 1 << bit;+ cases.push(b);+ }+ }+ // A huge size, a zero subsampling factor, and a PackBits run past the strip.+ cases.push(ycbcr_tiff(65_535, 65_535, (2, 2), 1, &data, &[]));+ cases.push(ycbcr_tiff(4, 4, (0, 2), 1, &data, &[]));+ cases.push(ycbcr_tiff(4, 4, (2, 2), 32773, &[0x81, 7], &[]));+ for (i, b) in cases.into_iter().enumerate() {+ assert!(std::panic::catch_unwind(|| decode_raster("damaged.tiff", &b).map(|r| r.rgba.len())).is_ok(), "case {i} panicked");+ }+}++/// ffmpeg (an external oracle) writes YCbCr TIFFs from YUV frames; our decode must match ffmpeg's+/// own RGB decode of the same file. A smooth gradient, so the chroma upsampling (we repeat chroma+/// across a data unit) does not dominate; 95 × 63 so the data units do not line up.+#[test]+fn ffmpeg_ycbcr_tiffs_match_ffmpeg_decode() {+ let Some(ff) = filmcraft_testkit::oracle::ffmpeg_or_skip("YCbCr TIFF oracle") else { return };+ let dir = filmcraft_testkit::fixtures::fixtures_dir("media/tiff_ycbcr");+ for pix_fmt in ["yuv420p", "yuv422p", "yuv444p"] {+ let tiff = dir.join(format!("gradient_{pix_fmt}.tiff"));+ let made = filmcraft_testkit::fixtures::generate(&tiff, |tmp| {+ std::process::Command::new(&ff)+ .args(["-y", "-v", "error", "-f", "lavfi", "-i", "gradients=size=95x63:seed=7", "-frames:v", "1", "-pix_fmt", pix_fmt])+ .arg(tmp)+ .status()+ .is_ok_and(|s| s.success())+ });+ let Some(tiff) = made else { continue };+ let out = std::process::Command::new(&ff).args(["-v", "error", "-i"]).arg(&tiff).args(["-f", "rawvideo", "-pix_fmt", "rgb24", "-"]).output().unwrap();+ let ours = decode_raster("gradient.tiff", &std::fs::read(&tiff).unwrap()).unwrap();+ assert_eq!((ours.width, ours.height), (95, 63), "{pix_fmt}");+ let theirs = out.stdout;+ assert_eq!(theirs.len(), 95 * 63 * 3, "{pix_fmt}");+ let worst =+ ours.rgba.as_chunks::<4>().0.iter().zip(theirs.as_chunks::<3>().0).flat_map(|(a, b)| (0..3).map(move |c| a[c].abs_diff(b[c]))).max().unwrap();+ assert!(worst <= 6, "{pix_fmt}: worst channel difference {worst}");+ }+}