Merge pull request #2640 from dotCooCoo/feat/craft-video-mjpeg-decode-into

craft-video: MJPEG decodes into a caller's RGBA or BGRA buffer
This commit is contained in:
BFlat authored and GitHub committed 2026-11-26 10:09:43 +07:00
commit fc252e9276
4 files changed
+453 -2

No files matched your search

+10
View File
@@ -14,6 +14,16 @@ all-features = true
[lints]
workspace = true
# Files of other crates that this crate's build or tests read. CI selects this crate's tests
# when one of them changes (craft-common-actions' select-platforms).
[package.metadata.craft]
reads = [
"crates/jpeg/tests/data/testorig-huffman-progressive.jpg",
"crates/jpeg/tests/data/testorig.jpg",
"crates/jpeg/tests/data/testorig12.jpg",
"crates/jpeg/tests/data/testorig12.ppm",
]
[features]
# FLV codec 3 / SWF Screen Video key frames.
screen-video = ["dep:miniz_oxide"]
+1 -1
View File
@@ -24,7 +24,7 @@ No codec feature is on by default.
| `mpeg2` | [`mpeg2`](src/mpeg2/README.md) | MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode` alone); MPEG-2 encoder with I, P and B pictures and constant or variable bitrate within the VBV buffer (`mpeg2-encode`, which also turns on the decoder) |
| `mpeg4` | [`mpeg4`](src/mpeg4/README.md) | MPEG-4 Part 2 video (ISO/IEC 14496-2, the Xvid/DivX format): Simple profile encoder (`mpeg4-encode`) |
| `hap` | `hap` | Vidvox Hap: Hap, Hap Alpha, Hap Q, Hap Q Alpha and Hap Alpha-Only, decoder and encoder, with the Snappy and chunked second stages. DXT1, DXT5, scaled YCoCg-DXT5 and BC4 pictures decode in software; BC7 (Hap R) and BC6 (Hap HDR) frames are read and their blocks returned but not decoded to pictures. |
| `mjpeg` | `mjpeg` | Motion JPEG: a decoder (baseline, extended and progressive Huffman JPEG; the Annex K tables for AVI `MJPG` packets that have none) and a baseline encoder, both over `craft-jpeg`. No two-field (MJPEG-A/B) packets and no lossless JPEG. |
| `mjpeg` | `mjpeg` | Motion JPEG: a decoder (baseline, extended and progressive Huffman JPEG; the Annex K tables for AVI `MJPG` packets that have none; `Decoder::decode_into` writes RGBA or BGRA pixels into a caller's buffer at any row stride) and a baseline encoder, both over `craft-jpeg`. No two-field (MJPEG-A/B) packets and no lossless JPEG. |
| `prores` | `prores` | Apple ProRes (SMPTE RDD 36): decoder and encoder |
| `h264` | [`h264`](src/h264/decode/README.md) | ITU-T H.264 / AVC: decoder (`h264-decode` alone) and encoder (`h264-encode` alone) |
| `hevc` | [`hevc`](src/hevc/decode/README.md) | ITU-T H.265 / HEVC: decoder (`hevc-decode` alone) and encoder (`hevc-encode` alone) |
+220
View File
@@ -6,6 +6,9 @@
//! and progressive Huffman JPEG, grayscale or YCbCr (as RGB) with any chroma subsampling. Packets
//! of AVI `MJPG` streams (the "AVI1" framing) often leave out the Huffman tables: the Annex K
//! tables are put in when a packet has none.
//! - [`Decoder::decode_into`] decodes one packet straight into a caller's buffer of RGBA or BGRA
//! pixels, with any row stride, and [`picture_size`] reads the size to make that buffer from
//! the headers.
//! - [`Encoder`] writes each frame as a complete baseline JPEG (SOI to EOI, tables in the packet)
//! with Huffman tables made for the picture, which is what AVI `MJPG`, QuickTime `jpeg`, Matroska
//! `V_MJPEG` and the other containers carry as a sample.
@@ -65,11 +68,153 @@ pub struct Frame {
pub damaged: bool,
}
/// Byte order of the four-byte pixels [`Decoder::decode_into`] writes. Alpha is always 255.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelFormat {
/// Red, green, blue, alpha.
Rgba8,
/// Blue, green, red, alpha.
Bgra8,
}
/// The picture [`Decoder::decode_into`] wrote.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Picture {
pub width: u32,
pub height: u32,
/// The entropy-coded data was damaged or cut short, as for [`Frame::damaged`].
pub damaged: bool,
}
/// Whether `packet` starts like a JPEG image (the SOI marker followed by another marker).
pub fn is_packet(packet: &[u8]) -> bool {
matches!(packet, [0xFF, 0xD8, 0xFF, ..])
}
/// The width and height in the frame header (SOFn) of `packet`, read from the marker segments
/// before it without decoding anything, to size the buffer for [`Decoder::decode_into`].
///
/// A height of 0 (the height given later in a DNL marker) is [`Error::Unsupported`], as the
/// decoder does not decode such frames.
pub fn picture_size(packet: &[u8]) -> Result<(u32, u32)> {
if !is_packet(packet) {
return Err(Error::Invalid("the packet does not start with a JPEG SOI marker".to_string()));
}
let mut at = 2usize;
while let Some(&v) = packet.get(at) {
if v != 0xFF {
at += 1;
continue;
}
let Some(&m) = packet.get(at + 1) else { break };
match m {
0xFF => at += 1,
0x00 | 0x01 | 0xD0..=0xD8 => at += 2,
0xD9 | 0xDA => break,
_ => {
let len = packet.get(at + 2..at + 4).map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])));
let Some(len) = len.filter(|&l| l >= 2) else { return Err(Error::Invalid("bad marker segment length".to_string())) };
let seg =
packet.get(at + 4..at + 2 + len).ok_or_else(|| Error::Invalid("marker segment runs past the end of the packet".to_string()))?;
if matches!(m, 0xC0..=0xCF) && !matches!(m, 0xC4 | 0xC8 | 0xCC) {
let [_, h0, h1, w0, w1, ..] = *seg else { return Err(Error::Invalid("frame header too short".to_string())) };
let (width, height) = (u32::from(u16::from_be_bytes([w0, w1])), u32::from(u16::from_be_bytes([h0, h1])));
if width == 0 {
return Err(Error::Invalid("frame header with a width of 0".to_string()));
}
if height == 0 {
return Err(Error::Unsupported("JPEG with the height in a DNL marker".to_string()));
}
return Ok((width, height));
}
at += 2 + len;
}
}
}
Err(Error::Invalid("no frame header before the scan".to_string()))
}
/// Whether the first scan of `packet` is followed by EOI or by the end of the packet: no other
/// marker after its entropy-coded data, restart markers aside. The band decoder reads only the
/// first scan, so a packet with more after it is decoded whole, as [`Decoder::decode`] does.
fn first_scan_is_last(packet: &[u8]) -> bool {
let mut at = 2usize;
loop {
match (packet.get(at), packet.get(at + 1)) {
(Some(0xFF), Some(0xFF)) => at += 1,
(Some(0xFF), Some(0x00 | 0x01 | 0xD0..=0xD8)) => at += 2,
(Some(0xFF), Some(&m)) => {
let Some(len) = packet.get(at + 2..at + 4).map(|b| usize::from(u16::from_be_bytes([b[0], b[1]]))) else { return false };
at += 2 + len;
if m == 0xDA {
break;
}
}
(Some(_), _) => at += 1,
(None, _) => return false,
}
}
while let Some(p) = packet.get(at..).and_then(|r| r.iter().position(|&v| v == 0xFF)) {
at += p;
match packet.get(at + 1) {
None => return true,
Some(0x00 | 0xD0..=0xD7) => at += 2,
Some(0xFF) => at += 1,
Some(&m) => return m == 0xD9,
}
}
true
}
/// Checks that `len` bytes hold `height` rows `stride` bytes apart, the last one `width × 4`
/// bytes long.
fn check_buffer(width: u32, height: u32, len: usize, stride: usize) -> Result<()> {
let row = (width as usize).checked_mul(4).ok_or_else(|| Error::Input("row size overflows".to_string()))?;
if stride < row {
return Err(Error::Input(format!("a stride of {stride} bytes is shorter than a row of {width} pixels ({row} bytes)")));
}
let need = stride.checked_mul(height.saturating_sub(1) as usize).and_then(|n| n.checked_add(row));
match need {
Some(need) if need <= len => Ok(()),
_ => Err(Error::Input(format!("a buffer of {len} bytes cannot hold {width} × {height} pixels at a stride of {stride} bytes"))),
}
}
/// Samples per pixel that [`Decoder::decode_into`] converts: gray, RGB and CMYK.
fn check_components(components: u8) -> Result<()> {
match components {
1 | 3 | 4 => Ok(()),
n => Err(Error::Unsupported(format!("{n}-component pictures cannot be converted to RGBA"))),
}
}
/// One row of interleaved 8-bit samples (`components` per pixel) into four-byte pixels.
fn put_row(src: &[u8], components: u8, format: PixelFormat, dst: &mut [u8]) {
let (r, b) = match format {
PixelFormat::Rgba8 => (0, 2),
PixelFormat::Bgra8 => (2, 0),
};
let dst = dst.as_chunks_mut::<4>().0.iter_mut();
match components {
1 => dst.zip(src).for_each(|(o, &g)| *o = [g, g, g, 255]),
3 => dst.zip(src.as_chunks::<3>().0).for_each(|(o, p)| {
o[r] = p[0];
o[1] = p[1];
o[b] = p[2];
o[3] = 255;
}),
// Ink amounts, as `craft_jpeg::to_rgba8` converts them.
_ => dst.zip(src.as_chunks::<4>().0).for_each(|(o, p)| {
let k = 255 - u16::from(p[3]);
let ink = |c: u8| ((255 - u16::from(c)) * k / 255) as u8;
o[r] = ink(p[0]);
o[1] = ink(p[1]);
o[b] = ink(p[2]);
o[3] = 255;
}),
}
}
/// A Motion JPEG decoder. Every packet is independent, so one decoder can decode packets in any
/// order and from several threads.
#[derive(Clone, Debug)]
@@ -114,6 +259,81 @@ impl Decoder {
let d = craft_jpeg::decode(&packet, &self.limits, adobe)?;
Ok(Frame { width: d.width, height: d.height, channels: d.components, samples: d.samples, damaged: d.damaged })
}
/// Decode one packet into `out` as four-byte `format` pixels, rows top to bottom and
/// `stride` bytes apart. Row `y` starts at `y × stride`; the bytes past each row's
/// `width × 4` are left as they were. [`picture_size`] gives the size to make `out` for.
///
/// Gray pictures become gray pixels and CMYK ones are converted as
/// `craft_jpeg::to_rgba8` converts them. 12-bit pictures are rounded to 8 bits.
///
/// Sequential 8-bit packets with one scan that holds every component, which is what cameras
/// and AVI `MJPG` streams send, are decoded a band of rows at a time straight into `out`
/// (`craft_jpeg::Bands`), so no buffer the size of the picture is made. Their pixels are
/// those of [`Decoder::decode`] for intact data. In damaged data the band decoder starts
/// again at the next restart marker, and a packet whose data fails at its first code gives a
/// gray, damaged picture where [`Decoder::decode`] returns an error. Other packets
/// (progressive, 12-bit, components in separate scans, any marker but EOI after the scan)
/// are decoded whole first.
///
/// A buffer too small for the picture, or a stride shorter than a row, is
/// [`Error::Input`], and `out` is not written then.
pub fn decode_into(&self, packet: &[u8], format: PixelFormat, out: &mut [u8], stride: usize) -> Result<Picture> {
if !is_packet(packet) {
return Err(Error::Invalid("the packet does not start with a JPEG SOI marker".to_string()));
}
let adobe = craft_jpeg::adobe_transform(packet);
let packet = craft_jpeg::with_avi1_default_huffman(packet);
let bands = first_scan_is_last(&packet).then(|| craft_jpeg::Bands::new(&packet, &self.limits, adobe).ok()).flatten();
let Some(bands) = bands else {
return self.decode_whole_into(&packet, adobe, format, out, stride);
};
let (width, height, components) = (bands.width(), bands.height(), bands.components());
check_components(components)?;
check_buffer(width, height, out.len(), stride)?;
let (row_in, row_out) = (width as usize * usize::from(components), width as usize * 4);
let mut reader = bands.reader();
while let Some(band) = reader.next_band()? {
for (r, src) in band.samples.chunks_exact(row_in).enumerate() {
let at = (band.y as usize + r) * stride;
let dst = out.get_mut(at..at + row_out).ok_or_else(|| Error::Input("buffer too small".to_string()))?;
put_row(src, components, format, dst);
}
}
Ok(Picture { width, height, damaged: reader.damaged() })
}
/// [`Decoder::decode_into`] for packets the band decoder does not take: the whole picture
/// first, then its rows.
fn decode_whole_into(&self, packet: &[u8], adobe: Option<u8>, format: PixelFormat, out: &mut [u8], stride: usize) -> Result<Picture> {
// The buffer is checked against the frame header before the picture is decoded, and
// against the decoded size after. A picture above the pixel limit is left to the decoder,
// which reports the limit, as the band path does.
if let Ok((width, height)) = picture_size(packet)
&& u64::from(width) * u64::from(height) <= self.limits.max_pixels
{
check_buffer(width, height, out.len(), stride)?;
}
let d = craft_jpeg::decode(packet, &self.limits, adobe)?;
check_components(d.components)?;
check_buffer(d.width, d.height, out.len(), stride)?;
let (row_in, row_out) = (d.width as usize * usize::from(d.components), d.width as usize * 4);
let mut wide = Vec::new();
for y in 0..d.height as usize {
let src = match &d.samples {
Samples::U8(s) => s.get(y * row_in..(y + 1) * row_in),
Samples::U16(s) => s.get(y * row_in..(y + 1) * row_in).map(|s| {
wide.clear();
wide.extend(s.iter().map(|&v| ((u32::from(v) * 255 + 32_767) / 65_535) as u8));
wide.as_slice()
}),
};
let src = src.ok_or_else(|| Error::Invalid("decoded picture shorter than its size".to_string()))?;
let dst = out.get_mut(y * stride..y * stride + row_out).ok_or_else(|| Error::Input("buffer too small".to_string()))?;
put_row(src, d.components, format, dst);
}
Ok(Picture { width: d.width, height: d.height, damaged: d.damaged })
}
}
/// Encoder settings.
+222 -1
View File
@@ -2,7 +2,7 @@
//! (oracle; skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`), and on
//! hostile packets.
use craft_video::mjpeg::{ChromaSubsampling, Decoder, Encoder, EncoderConfig, Frame, Samples, is_packet};
use craft_video::mjpeg::{ChromaSubsampling, Decoder, Encoder, EncoderConfig, Error, Frame, PixelFormat, Samples, is_packet, picture_size};
use std::path::Path;
use std::process::Command;
@@ -249,6 +249,227 @@ fn adobe_transform_zero_keeps_numeric_id_components_as_rgb() {
}
}
/// libjpeg-turbo's test images, kept with `craft-jpeg` (`crates/jpeg/tests/data/SOURCE.md`).
const TESTORIG: &[u8] = include_bytes!("../../../jpeg/tests/data/testorig.jpg");
const TESTORIG_PROGRESSIVE: &[u8] = include_bytes!("../../../jpeg/tests/data/testorig-huffman-progressive.jpg");
const TESTORIG12: &[u8] = include_bytes!("../../../jpeg/tests/data/testorig12.jpg");
/// libjpeg-turbo's decode of `testorig12.jpg`: binary PPM, maxval 4095.
const TESTORIG12_PPM: &[u8] = include_bytes!("../../../jpeg/tests/data/testorig12.ppm");
/// A byte the padding of a row starts as, to see that `decode_into` leaves it alone.
const PAD: u8 = 0xA5;
/// `f` as `format` pixels, rows `stride` bytes apart with [`PAD`] after each row.
fn expected_pixels(f: &Frame, format: PixelFormat, stride: usize) -> Vec<u8> {
let (w, h, ch) = (f.width as usize, f.height as usize, usize::from(f.channels));
let eight: Vec<u8> = match &f.samples {
Samples::U8(v) => v.clone(),
Samples::U16(v) => v.iter().map(|&s| ((u32::from(s) * 255 + 32_767) / 65_535) as u8).collect(),
};
let mut out = vec![PAD; stride * h];
for y in 0..h {
for x in 0..w {
let s = &eight[(y * w + x) * ch..][..ch];
let rgb = match ch {
1 => [s[0]; 3],
3 => [s[0], s[1], s[2]],
_ => panic!("{ch} channels"),
};
let px = match format {
PixelFormat::Rgba8 => [rgb[0], rgb[1], rgb[2], 255],
PixelFormat::Bgra8 => [rgb[2], rgb[1], rgb[0], 255],
};
out[y * stride + x * 4..][..4].copy_from_slice(&px);
}
}
out
}
/// `decode_into` of `packet` at a stride of `pad` bytes past each row.
fn decoded_into(packet: &[u8], format: PixelFormat, pad: usize) -> (craft_video::mjpeg::Picture, Vec<u8>, usize) {
let (w, h) = picture_size(packet).expect("size");
let stride = w as usize * 4 + pad;
let mut out = vec![PAD; stride * h as usize];
let p = Decoder::new().decode_into(packet, format, &mut out, stride).expect("decode_into");
(p, out, stride)
}
#[test]
fn decode_into_writes_the_pixels_of_decode_at_any_stride() {
let enc = |w: usize, h: usize, ch: usize, sub| {
Encoder::new(EncoderConfig { quality: 85, subsampling: sub })
.expect("encoder")
.encode(w as u32, h as u32, ch as u8, &picture(w, h, ch))
.expect("encode")
};
let packets = [
("420", enc(67, 41, 3, ChromaSubsampling::S420)),
("422", enc(67, 41, 3, ChromaSubsampling::S422)),
("444", enc(64, 48, 3, ChromaSubsampling::S444)),
("1x1", enc(1, 1, 3, ChromaSubsampling::S420)),
("gray", enc(33, 17, 1, ChromaSubsampling::S420)),
("adobe0", with_app14(&enc(16, 16, 3, ChromaSubsampling::S444), 0)),
("testorig", TESTORIG.to_vec()),
("progressive", TESTORIG_PROGRESSIVE.to_vec()),
("12-bit", TESTORIG12.to_vec()),
];
for (name, packet) in &packets {
let f = Decoder::new().decode(packet).expect("decode");
for format in [PixelFormat::Rgba8, PixelFormat::Bgra8] {
for pad in [0, 3, 64] {
let (p, out, stride) = decoded_into(packet, format, pad);
assert_eq!((p.width, p.height, p.damaged), (f.width, f.height, f.damaged), "{name}");
assert!(out == expected_pixels(&f, format, stride), "{name} {format:?} pad {pad}: pixels differ from decode's");
}
}
}
}
#[test]
fn decode_into_reads_past_the_first_scan_as_decode_does() {
let packet = Encoder::default().encode(40, 24, 3, &picture(40, 24, 3)).expect("encode");
let sos = packet.windows(2).position(|w| w == [0xFF, 0xDA]).expect("SOS");
let eoi = packet.len() - 2;
let mut sof = packet.clone();
sof.truncate(eoi);
// a second frame header, and a second copy of the scan, after the first scan
let frame = packet.windows(2).position(|w| w == [0xFF, 0xC0]).expect("SOF0");
let frame_len = usize::from(u16::from_be_bytes([packet[frame + 2], packet[frame + 3]]));
sof.extend_from_slice(&packet[frame..frame + 2 + frame_len]);
sof.extend_from_slice(&packet[eoi..]);
let mut two_scans = packet[..eoi].to_vec();
two_scans.extend_from_slice(&packet[sos..]);
// a comment before EOI is read by decode too
let mut comment = packet[..eoi].to_vec();
comment.extend_from_slice(&[0xFF, 0xFE, 0, 4, b'h', b'i']);
comment.extend_from_slice(&packet[eoi..]);
for (name, p) in [("second SOF", sof), ("second SOS", two_scans), ("COM", comment)] {
let whole = Decoder::new().decode(&p);
let mut out = vec![PAD; 40 * 4 * 24];
let into = Decoder::new().decode_into(&p, PixelFormat::Rgba8, &mut out, 40 * 4);
match whole {
Err(e) => assert_eq!(into.err(), Some(e), "{name}"),
Ok(f) => {
assert_eq!(into.map(|p| (p.width, p.height, p.damaged)), Ok((f.width, f.height, f.damaged)), "{name}");
assert!(out == expected_pixels(&f, PixelFormat::Rgba8, 40 * 4), "{name}: pixels differ from decode's");
}
}
}
}
#[test]
fn decode_into_rounds_12_bit_pictures_close_to_libjpeg_turbo() {
// The PPM's header is "P6\n227 149\n4095\n" and its samples are big-endian 16-bit.
let header = b"P6\n227 149\n4095\n";
assert_eq!(&TESTORIG12_PPM[..header.len()], header);
let reference: Vec<u8> =
TESTORIG12_PPM[header.len()..].as_chunks::<2>().0.iter().map(|b| ((u32::from(u16::from_be_bytes(*b)) * 255 + 2047) / 4095) as u8).collect();
let (p, out, stride) = decoded_into(TESTORIG12, PixelFormat::Rgba8, 0);
assert_eq!((p.width, p.height, stride), (227, 149, 227 * 4));
let rgb: Vec<u8> = out.as_chunks::<4>().0.iter().flat_map(|px| [px[0], px[1], px[2]]).collect();
let worst = rgb.iter().zip(&reference).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
assert!(worst <= 1, "{worst} levels from libjpeg-turbo's decode");
assert!(out.as_chunks::<4>().0.iter().all(|px| px[3] == 255));
}
#[test]
fn decode_into_refuses_a_buffer_or_stride_too_small_without_writing() {
let packet = Encoder::default().encode(20, 10, 3, &picture(20, 10, 3)).expect("encode");
assert_eq!(picture_size(&packet).expect("size"), (20, 10));
let dec = Decoder::new();
let progressive = (TESTORIG_PROGRESSIVE, 227 * 4, 149);
for (packet, row, rows) in [(&packet[..], 80, 10), progressive] {
// one byte short of the last row, and a stride under a row
for (len, stride) in [(row * rows - 1, row), (row * rows, row - 1), (0, row)] {
let mut out = vec![PAD; len];
assert!(matches!(dec.decode_into(packet, PixelFormat::Rgba8, &mut out, stride), Err(Error::Input(_))), "{len} {stride}");
assert!(out.iter().all(|&b| b == PAD), "nothing is written");
}
// the last row needs no padding after it
let mut out = vec![PAD; row * 2 * (rows - 1) + row];
assert!(dec.decode_into(packet, PixelFormat::Rgba8, &mut out, row * 2).is_ok());
// a stride the buffer size overflows
assert!(matches!(dec.decode_into(packet, PixelFormat::Rgba8, &mut out, usize::MAX), Err(Error::Input(_))));
}
// A packet decoded whole is checked against its frame header before it is decoded: the
// progressive one cut before its first scan has no picture to decode.
let sos = TESTORIG_PROGRESSIVE.windows(2).position(|w| w == [0xFF, 0xDA]).expect("SOS");
let mut out = vec![PAD; 64];
assert!(matches!(dec.decode_into(&TESTORIG_PROGRESSIVE[..sos], PixelFormat::Rgba8, &mut out, 227 * 4), Err(Error::Input(_))));
let mut out = vec![0; 64];
assert!(matches!(dec.decode_into(b"not a jpeg", PixelFormat::Rgba8, &mut out, 4), Err(Error::Invalid(_))));
let mut out = vec![0; 80 * 10];
assert!(matches!(dec.clone().max_pixels(199).decode_into(&packet, PixelFormat::Rgba8, &mut out, 80), Err(Error::Limit(_))));
assert!(matches!(dec.max_pixels(199).decode_into(TESTORIG_PROGRESSIVE, PixelFormat::Rgba8, &mut out, 80), Err(Error::Limit(_))));
}
#[test]
fn picture_size_reads_the_frame_header_only() {
for packet in [TESTORIG, TESTORIG_PROGRESSIVE, TESTORIG12] {
assert_eq!(picture_size(packet).expect("size"), (227, 149));
// the headers alone are enough
let sos = packet.windows(2).position(|w| w == [0xFF, 0xDA]).expect("SOS");
assert_eq!(picture_size(&packet[..sos]).expect("size"), (227, 149));
}
let packet = Encoder::default().encode(20, 10, 1, &[9; 200]).expect("encode");
let sof = packet.windows(2).position(|w| w == [0xFF, 0xC0]).expect("SOF0");
let mut dnl = packet.clone();
dnl[sof + 5..sof + 7].copy_from_slice(&[0, 0]);
assert!(matches!(picture_size(&dnl), Err(Error::Unsupported(_))));
let mut no_width = packet.clone();
no_width[sof + 7..sof + 9].copy_from_slice(&[0, 0]);
assert!(matches!(picture_size(&no_width), Err(Error::Invalid(_))));
for n in 0..sof + 9 {
assert!(picture_size(&packet[..n]).is_err(), "cut at {n}");
}
for junk in [&b"RIFF"[..], &[0xFF, 0xD8, 0xFF, 0xD9], &[0xFF, 0xD8, 0xFF, 0xDA, 0, 2], &[0xFF, 0xD8, 0xFF, 0xE0, 0, 1]] {
assert!(picture_size(junk).is_err());
}
}
#[test]
fn hostile_packets_decode_into_errors_never_panics() {
let packet = Encoder::default().encode(48, 40, 3, &picture(48, 40, 3)).expect("encode");
let dec = Decoder::new();
let mut out = vec![0u8; 48 * 4 * 40];
for n in 0..packet.len() {
let _ = dec.decode_into(&packet[..n], PixelFormat::Bgra8, &mut out, 48 * 4);
}
let mut x = 0x9E37_79B9u32;
for i in 0..packet.len() {
let mut p = packet.clone();
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
p[i] ^= (x >> 8) as u8 | 1;
// a flipped size byte can ask for more than the buffer holds: an error, not a panic
let _ = dec.decode_into(&p, PixelFormat::Rgba8, &mut out, 48 * 4);
let _ = picture_size(&p);
}
}
#[test]
fn ffmpeg_decodes_to_the_rgba_and_bgra_of_decode_into() {
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
let dir = craft_media_testkit::fixture_subdir("mjpeg");
let s = |p: &Path| p.to_str().expect("path").to_string();
for (name, sub) in [("into420", ChromaSubsampling::S420), ("into422", ChromaSubsampling::S422)] {
let packet =
Encoder::new(EncoderConfig { quality: 90, subsampling: sub }).expect("encoder").encode(67, 41, 3, &picture(67, 41, 3)).expect("encode");
let jpg = dir.join(format!("{name}.jpg"));
std::fs::write(&jpg, &packet).expect("write");
for (format, pix_fmt) in [(PixelFormat::Rgba8, "rgba"), (PixelFormat::Bgra8, "bgra")] {
let raw = dir.join(format!("{name}_{pix_fmt}.raw"));
ffmpeg(&ff, &["-i", &s(&jpg), "-f", "rawvideo", "-pix_fmt", pix_fmt, &s(&raw)]);
let theirs = std::fs::read(&raw).expect("read");
let (_, ours, _) = decoded_into(&packet, format, 0);
let p = psnr(&theirs, &ours);
println!("{name} {pix_fmt}: ffmpeg against decode_into {p:.1} dB");
assert!(p >= 38.0, "{name} {pix_fmt}: {p:.1} dB");
}
}
}
#[test]
fn track_dispatch_preserves_mjpeg_frames_and_timestamps() {
use craft_media::{CodecId, CodecParams};