From 8d3cd561a42420ae345c799719debd79ef3ae745 Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 17 Nov 2026 10:07:43 +0100 Subject: [PATCH] craft-video: Motion JPEG frames convert to VideoFrame (#1231) --- crates/video/README.md | 3 +- crates/video/src/frame/convert.rs | 43 +++++++++++++++++++++++++++ crates/video/src/frame/tests.rs | 49 +++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/crates/video/README.md b/crates/video/README.md index f9db3a6e6..562a63eb3 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -41,7 +41,8 @@ comes with its codec's feature): - Planes are `[Y, Cb, Cr]`, `[R, G, B]` or `[Y]` (`ColorFamily`), plus an optional alpha plane. DNx, VP9 and AV1 (identity matrix) store RGB as G, B, R; the conversion reorders them. - Samples keep the decoder's storage, `u8` or `u16`, with a bit depth per plane (HEVC chroma may - differ from luma). Converting moves the buffers and copies no samples. + differ from luma). Converting moves the buffers and copies no samples, except Motion JPEG, + whose decoder returns interleaved samples: they are split into planes. - Chroma subsampling is a log2 shift per axis, 0 to 3 (FFV1 codes up to 3). - Colour is given as ITU-T H.273 code points (`ColorTags`), mapped from each codec's own signalling. Codecs that do not signal a value leave it unspecified (2). diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 4089f7148..054d09204 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -178,6 +178,49 @@ impl TryFrom for VideoFrame { } } +#[cfg(feature = "mjpeg")] +impl TryFrom for VideoFrame { + type Error = FrameError; + + /// A gray or RGB frame, full range (a JPEG's YCbCr is converted to RGB by the decoder, so RGB + /// frames carry the identity matrix). 8-bit pictures keep 8-bit storage; 12-bit ones are + /// stored scaled to 16 bits and say so. The decoder returns interleaved samples, so this is + /// the one conversion that copies them, into planes. + fn try_from(p: crate::mjpeg::Frame) -> Result { + use crate::mjpeg::Samples as S; + let (w, h) = (p.width, p.height); + let channels = usize::from(p.channels); + let family = match channels { + 1 => ColorFamily::Gray, + 3 => ColorFamily::Rgb, + _ => return Err(FrameError::Shape("a Motion JPEG frame has 1 or 3 channels")), + }; + let pixels = usize::try_from(w) + .ok() + .zip(usize::try_from(h).ok()) + .and_then(|(w, h)| w.checked_mul(h)) + .ok_or(FrameError::Plane("plane size overflows"))?; + let stored = match &p.samples { + S::U8(v) => v.len(), + S::U16(v) => v.len(), + }; + if pixels.checked_mul(channels) != Some(stored) { + return Err(FrameError::Shape("sample count does not fit the frame")); + } + let planes = match p.samples { + S::U8(v) => (0..channels) + .map(|c| Plane::packed(w, h, 8, Samples::U8(v.iter().skip(c).step_by(channels).copied().collect()))) + .collect::, _>>()?, + S::U16(v) => (0..channels) + .map(|c| Plane::packed(w, h, 16, Samples::U16(v.iter().skip(c).step_by(channels).copied().collect()))) + .collect::, _>>()?, + }; + let mut f = VideoFrame::new(w, h, family, Subsampling::S444, planes, None)?; + f.color = ColorTags { matrix: if family == ColorFamily::Rgb { 0 } else { 2 }, full_range: true, ..ColorTags::UNSPECIFIED }; + Ok(f) + } +} + #[cfg(feature = "mpeg2-decode")] impl TryFrom for VideoFrame { type Error = FrameError; diff --git a/crates/video/src/frame/tests.rs b/crates/video/src/frame/tests.rs index cba664af4..0a5e4c7bf 100644 --- a/crates/video/src/frame/tests.rs +++ b/crates/video/src/frame/tests.rs @@ -226,6 +226,55 @@ fn vp9_color_space_maps_to_a_matrix() { assert_eq!([0, 1, 2, 3, 4, 5, 6, 7].map(convert::vp9_matrix), [2, 5, 1, 6, 7, 9, 2, 0]); } +#[cfg(feature = "mjpeg")] +#[test] +fn mjpeg_frames_split_into_planes() { + use crate::mjpeg::{Frame as M, Samples as S}; + // 2x2 RGB: pixels (1,2,3) (4,5,6) (7,8,9) (10,11,12). + let rgb = M { width: 2, height: 2, channels: 3, samples: S::U8((1..=12).collect()), damaged: false }; + let f = VideoFrame::try_from(rgb).unwrap(); + assert_eq!((f.family(), f.subsampling(), f.bit_depth()), (ColorFamily::Rgb, Subsampling::S444, 8)); + assert_eq!(f.color, ColorTags { matrix: 0, full_range: true, ..ColorTags::UNSPECIFIED }); + let plane = |i: usize| f.plane(i).unwrap().samples().clone(); + assert_eq!(plane(0), Samples::U8(vec![1, 4, 7, 10])); + assert_eq!(plane(1), Samples::U8(vec![2, 5, 8, 11])); + assert_eq!(plane(2), Samples::U8(vec![3, 6, 9, 12])); + assert!(f.alpha().is_none() && f.pts.is_none()); + // A 12-bit gray frame is stored at 16 bits. + let gray = M { width: 3, height: 1, channels: 1, samples: S::U16(vec![0, 32768, 65535]), damaged: false }; + let f = VideoFrame::try_from(gray).unwrap(); + assert_eq!((f.family(), f.bit_depth(), f.planes().len()), (ColorFamily::Gray, 16, 1)); + assert_eq!(f.plane(0).unwrap().samples(), &Samples::U16(vec![0, 32768, 65535])); +} + +#[cfg(feature = "mjpeg")] +#[test] +fn mjpeg_frames_that_do_not_fit_are_errors() { + use crate::mjpeg::{Frame as M, Samples as S}; + let bad = |channels: u8, n: usize| M { width: 2, height: 2, channels, samples: S::U8(vec![0; n]), damaged: false }; + assert!(VideoFrame::try_from(bad(2, 8)).is_err(), "two channels is not a Motion JPEG frame"); + assert!(VideoFrame::try_from(bad(3, 11)).is_err(), "a short buffer"); + assert!(VideoFrame::try_from(bad(1, 5)).is_err(), "a long buffer"); + assert!(VideoFrame::try_from(M { width: u32::MAX, height: u32::MAX, channels: 3, samples: S::U8(Vec::new()), damaged: false }).is_err()); +} + +#[cfg(feature = "mjpeg")] +#[test] +fn a_decoded_mjpeg_picture_converts() { + use crate::mjpeg::{Decoder, Encoder, EncoderConfig}; + let (w, h) = (24usize, 16usize); + let px: Vec = (0..w * h * 3).map(|i| (i * 7 % 251) as u8).collect(); + let packet = Encoder::new(EncoderConfig::default()).unwrap().encode(w as u32, h as u32, 3, &px).unwrap(); + let decoded = Decoder::new().decode(&packet).unwrap(); + let want_r: Vec = match &decoded.samples { + crate::mjpeg::Samples::U8(v) => v.iter().step_by(3).copied().collect(), + crate::mjpeg::Samples::U16(_) => panic!("an 8-bit picture"), + }; + let f = VideoFrame::try_from(decoded).unwrap(); + assert_eq!((f.width(), f.height(), f.family()), (24, 16, ColorFamily::Rgb)); + assert_eq!(f.plane(0).unwrap().samples(), &Samples::U8(want_r)); +} + #[cfg(feature = "mpeg2-decode")] #[test] fn mpeg2_picture_converts() {