Files
97c83dc9e8 craft-jpeg: decode sequential 8-bit JPEG a band of rows at a time (#743)
* craft-jpeg: decode sequential 8-bit JPEG a band of rows at a time

Bands reads the headers of a sequential Huffman-coded (SOF0, SOF1) 8-bit file whose first scan
holds every component, and a Reader decodes it one line of MCUs at a time: Huffman decoding,
dequantization, inverse transform, upsampling and colour conversion, holding at most three MCU
lines of samples. Nothing the size of the image is allocated, so a frame up to the format's
65,535 px sides can be decoded straight into the caller's storage.

The samples equal decode()'s for the same rows: both go through the same block transform
(idct_block, factored out of reconstruct), the same upsampling maps and the same colour
conversion (to_color, to_u8). A component subsampled down reads the MCU line above and below
its band, as the whole-image upsampling does.

A band that begins a restart interval is a seek point once find_seek_points has found every
restart marker, in sequence; readers on other threads can decode from there. Damaged data
leaves the rest of its restart interval at zero and decoding resumes at the next marker, so the
result is the same however the bands were read. Bits::restart now also clears the exhausted
flag: decode() never restarts after running out of data, the band decoder does.

parse_frame is split into parse_header (validation and geometry) and the whole-image
allocation; parse_scan takes the component identifiers. decode() is unchanged.

Tests: bands against decode() sample for sample over jpeg-encoder streams (gray, YCbCr, CMYK,
YCCK; 4:4:4, 4:2:2, 4:2:0, 4:4:0; four restart intervals) and a test-only encoder's interleaved
layouts with factors of 3 and 4, in order and by seeking; zune-jpeg within the existing
tolerance; damage with and without restarts; limits; unsupported files; the libjpeg test
images; the mutation run with a seek-equals-in-order check; and a `bands` fuzz target.

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

* craft-jpeg: faster inverse transform, rounding, Huffman codes and band rows

Each change keeps every sample as it was: decode() and the bands give bit-identical output
before and after on the test images, 12-bit and arithmetic-coded files, 48 generated streams
and a 48,000 × 34,200 file decoded in bands.

- idct_block works on rows of eight: each sum keeps its order (over u, then over v), eight
  values of x at a time, and rows of zero coefficients are skipped (a zero term changes only the
  sign of a zero, which the level shift removes). The transposed basis is built once.
- to_u8 rounds half away from zero as truncation plus one from .5 up, exact on 0..=255, instead
  of the `round` library call targets without SSE4.1 make.
- Huffman::decode resolves codes of up to 9 bits from a table of the next 9 bits, built by
  running the bit-by-bit procedure on each, so both give the same symbol.
- The band rows are colour converted in loops written out for gray, YCbCr and RGB; YCbCr to
  RGB is one helper shared with the whole-image decode.

On the 48,000 × 34,200 4:4:4 file with a restart interval per line of MCUs (Ryzen 7 7800X3D,
idle), one thread decodes a band of 8 rows in about 3.0 ms (5.8 ms before), and 16 threads
decode the whole image in 2.05 s (3.8 s before).

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

* craft-jpeg: bands report damage, never fail on it, and see data left before a restart

Two cases a mutation run through PhotoCraft's import turned up.

- Data that fails in the first MCU made a band read fail, as decode() refuses a stream with no
  image data. The baseline decoder PhotoCraft uses for other files opens such files (grey, with
  restarts the rest of the image), so a band read now marks it damaged and goes on: with
  restart intervals everything after the first decodes. Refusing a file with nothing
  decodable is the caller's, from the size of its scan data.
- An interval that decodes without an invalid code but leaves whole bytes before its restart
  marker was decoded from cut, shifted or added data. It now counts as damage (libjpeg warns
  "extraneous bytes before marker"). The check runs after an interval's last MCU, so readers
  that seek and readers that read in order agree.

Over 1,074 sequential 8-bit JPEGs on one machine the damage flag agrees with djpeg's warnings on
every file, reading from seek points equals reading in order on all 151 with restart intervals,
and the samples are within mean 0.57, max 8 of zune-jpeg's.

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

* craft-jpeg: seek points follow the restart markers in the data, as reading in order does

find_seek_points gave up on a file whose markers were not all there in sequence, so a damaged
or cut-short file with a restart interval at every line of MCUs decoded in order on one core
(about 13 s for an undamaged 48,000 × 34,200 file on an idle 8-core machine, against 2 s on
16 threads). With these seek points the same file with one marker renumbered, cut at 60%, or
its first interval overwritten decodes in 2.8 to 4.4 s on 16 threads. A reader that reads in
order pairs the k-th restart marker in the data with interval k, whatever its number, and
resumes after each, so seek points built the same way give the same samples for any data:
missing, misnumbered or added markers only change which bands are seek points.

Tested: misnumbered, missing (file cut), added and removed markers read in order and by
seeking; the mutation run's seek-equals-in-order check (more of its cases now seek); 600,000
runs of the bands fuzz target, which asserts the same; 169 local files with restarts.

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

* craft-jpeg: Bands::halo, the MCU lines a reader decodes around its bands

A reader that seeks decodes the MCU line above and below its bands when a component is
subsampled down. A caller splitting the work across threads needs to know it: reading one band
from each seek point of a 4:2:0 file decodes three lines per band (4.97 s for a 48,000 × 34,200
file on 16 threads, against 3.09 s reading four bands from each), while for 4:4:4 the run length
makes no difference. Tested against the sampling factors of every interleaved layout.

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

* craft-jpeg: band decoder review fixes

- Data left over after the last MCU, before EOI, is damage, as it already
  was before a restart marker.
- A scan that names a component twice is Malformed (T.81 B.2.3), not
  Unsupported.
- The upsampling maps are sized from the header and checked against
  max_alloc before they are made.
- The bands fuzz target and the mutation test fail on a read or seek error
  once Bands::new has accepted a stream; damage never surfaces as an error.
- Known-sample CMYK and YCCK fixtures check the ink polarity directly; the
  bands-equal-decode tests cannot, since both share the colour conversion.
- Docs: a single-component frame's bands are 8 rows; Reader::damaged and
  the scan's size cannot tell a failure at the first MCU from later damage;
  with a halo a seek decodes from the previous seek point; each fuzz target
  writes to its own corpus; doc comments on the remaining new functions.

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

* craft-jpeg: test YCCK chroma and trailing-data samples

- The ink fixture gains a YCCK case with Cb and Cr away from neutral, with
  the T.871 values worked out by hand: a conversion that drops or swaps
  the chroma now fails it.
- Bytes added before EOI leave the samples as the clean stream's; the test
  now checks that, not only that reading in order and seeking agree.

Co-Authored-By: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>

---------

Co-authored-by: Νύξ (Nyx, AI) 🌑 <nyx@despotak.is>
Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-11 07:37:06 -05:00

154 lines
6.7 KiB
Rust

//! Decodes of the libjpeg-turbo test images (tests/data, see SOURCE.md there).
use craft_jpeg::{Decoded, Limits, Samples, decode};
fn fixture(name: &str) -> Vec<u8> {
let path = format!("{}/tests/data/{name}", env!("CARGO_MANIFEST_DIR"));
std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"))
}
fn decode_clean(name: &str) -> Decoded {
let img = decode(&fixture(name), &Limits::default(), None).unwrap_or_else(|e| panic!("{name}: {e}"));
assert!(!img.damaged, "{name}");
img
}
fn decode_fixture(name: &str) -> Decoded {
let img = decode_clean(name);
assert_eq!((img.width, img.height, img.components), (227, 149, 3), "{name}");
img
}
/// Mean and maximum absolute difference.
fn diff(a: impl Iterator<Item = f64>, b: impl Iterator<Item = f64>) -> (f64, f64) {
let (mut sum, mut max, mut n) = (0.0, 0.0f64, 0usize);
for (a, b) in a.zip(b) {
let d = (a - b).abs();
sum += d;
max = max.max(d);
n += 1;
}
(sum / n.max(1) as f64, max)
}
/// testimgari-huffman.jpg is testimgari.jpg transcoded by jpegtran: the same coefficients, only
/// the entropy coding differs, so the samples must be identical.
#[test]
fn arithmetic_coded_image_matches_its_huffman_transcode() {
let huffman = decode_fixture("testimgari-huffman.jpg");
let arithmetic = decode_fixture("testimgari.jpg");
assert!(matches!(huffman.samples, Samples::U8(_)));
assert!(huffman.samples == arithmetic.samples, "testimgari.jpg decodes differently from testimgari-huffman.jpg");
}
/// The arithmetic and progressive arithmetic transcodes jpegtran made of testorig.jpg and
/// testorig12.jpg hold their coefficients, so they decode to exactly the same samples.
#[test]
fn arithmetic_transcodes_match_their_huffman_sources() {
for (source, transcodes) in [
("testorig.jpg", &["testorig-ari-progressive.jpg", "testorig-ari-progressive-restart.jpg"]),
("testorig12.jpg", &["testorig12-ari.jpg", "testorig12-ari-progressive.jpg"]),
] {
let reference = decode_fixture(source);
for name in transcodes {
assert!(decode_fixture(name).samples == reference.samples, "{name} decodes differently from {source}");
}
}
}
/// libjpeg's arithmetic encoder drops the trailing zero bytes of a scan, so the white lower
/// part of whitetail-ari.jpg decodes from zeros supplied at the EOI marker. It must decode
/// whole and match its Huffman transcode.
#[test]
fn arithmetic_white_tail_decodes_from_implied_zeros() {
let arithmetic = decode_clean("whitetail-ari.jpg");
assert_eq!((arithmetic.width, arithmetic.height, arithmetic.components), (512, 512, 1));
assert!(decode_clean("whitetail-huffman.jpg").samples == arithmetic.samples, "whitetail-ari.jpg decodes differently from whitetail-huffman.jpg");
}
/// The 8-bit path against zune-jpeg. Both use centered linear chroma upsampling; the residual is
/// float against integer IDCT and color conversion.
#[test]
fn baseline_image_matches_zune_jpeg() {
let bytes = fixture("testorig.jpg");
let mut zune = zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&bytes[..]));
let reference = zune.decode().unwrap_or_else(|e| panic!("zune-jpeg: {e:?}"));
let img = decode_fixture("testorig.jpg");
let Samples::U8(px) = &img.samples else { panic!("testorig.jpg: expected 8-bit samples") };
assert_eq!(px.len(), reference.len());
let (mean, max) = diff(px.iter().map(|&v| f64::from(v)), reference.iter().map(|&v| f64::from(v)));
eprintln!("testorig.jpg vs zune-jpeg: mean {mean:.3}, max {max}");
assert!(mean < MAX_MEAN_8 && max <= MAX_ABS_8, "mean {mean}, max {max}");
}
// Observed: mean 0.52, max 3.
const MAX_MEAN_8: f64 = 0.75;
const MAX_ABS_8: f64 = 4.0;
/// Parse a binary PPM with 16-bit big-endian samples.
fn ppm16(bytes: &[u8]) -> (u32, u32, u32, Vec<u16>) {
let mut fields = Vec::new();
let mut at = 0;
while fields.len() < 4 {
while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
at += 1;
}
let start = at;
while bytes.get(at).is_some_and(|b| !b.is_ascii_whitespace()) {
at += 1;
}
fields.push(std::str::from_utf8(&bytes[start..at]).unwrap_or_default().to_owned());
}
assert_eq!(fields[0], "P6");
let num = |s: &str| s.parse::<u32>().unwrap_or_else(|e| panic!("PPM header {s}: {e}"));
let (w, h, maxval) = (num(&fields[1]), num(&fields[2]), num(&fields[3]));
let data = &bytes[at + 1..];
let px: Vec<u16> = data.as_chunks::<2>().0.iter().map(|&c| u16::from_be_bytes(c)).collect();
assert_eq!(px.len(), (w * h * 3) as usize);
(w, h, maxval, px)
}
/// testorig12.jpg against libjpeg-turbo's decode (testorig12.ppm, 12-bit RGB; SOURCE.md says how
/// it was made). libjpeg-turbo uses an integer IDCT and integer color conversion, craft-jpeg
/// floats; the comparison is on the 12-bit scale.
#[test]
fn twelve_bit_image_matches_libjpeg_turbo() {
let (w, h, maxval, reference) = ppm16(&fixture("testorig12.ppm"));
assert_eq!((w, h, maxval), (227, 149, 4095));
let img = decode_fixture("testorig12.jpg");
let Samples::U16(px) = &img.samples else { panic!("testorig12.jpg: expected 16-bit samples") };
assert_eq!(px.len(), reference.len());
let (mean, max) = diff(px.iter().map(|&v| f64::from(v) * 4095.0 / 65535.0), reference.iter().map(|&v| f64::from(v)));
eprintln!("testorig12.jpg vs libjpeg-turbo (12-bit units): mean {mean:.3}, max {max:.2}");
assert!(mean < MAX_MEAN_12 && max <= MAX_ABS_12, "mean {mean}, max {max}");
}
// Observed: mean 0.50, max 2.46 (of 4095).
const MAX_MEAN_12: f64 = 0.75;
const MAX_ABS_12: f64 = 4.0;
/// Every band of each Huffman-coded 8-bit test image, read in order, joined.
fn bands_of(bytes: &[u8]) -> (Vec<u8>, bool) {
let bands = craft_jpeg::Bands::new(bytes, &Limits::default(), None).unwrap_or_else(|e| panic!("bands: {e}"));
let mut reader = bands.reader();
let mut out = Vec::new();
while let Some(band) = reader.next_band().unwrap_or_else(|e| panic!("band: {e}")) {
out.extend_from_slice(band.samples);
}
(out, reader.damaged())
}
/// The sequential Huffman-coded 8-bit test images (4:2:0 colour, gray, and gray from the
/// arithmetic white-tail test) decode in bands to exactly the whole-image decode's samples.
#[test]
fn baseline_images_decode_in_bands_as_whole() {
for name in ["testorig.jpg", "testimgari-huffman.jpg", "whitetail-huffman.jpg"] {
let bytes = fixture(name);
let whole = decode_clean(name);
let Samples::U8(px) = &whole.samples else { panic!("{name}: expected 8-bit samples") };
let (bands, damaged) = bands_of(&bytes);
assert!(!damaged, "{name}");
assert!(&bands == px, "{name}: bands differ from the whole-image decode");
}
}