Skip to content

Add opt-in exact quantization and AVX2/scalar differential fuzzing - #50

Open
sunsided wants to merge 7 commits into
vstroebel:mainfrom
sunsided:feature/exact-quantization-u32
Open

sunsided wants to merge 7 commits into
vstroebel:mainfrom
sunsided:feature/exact-quantization-u32

Conversation

@sunsided

@sunsided sunsided commented Nov 23, 2026 •

Copy link
Copy Markdown

Summary

Adds Encoder::set_exact_quantization, an opt-in quantizer that matches libjpeg-turbo's compute_reciprocal (16-bit, variable shift) while keeping the existing 15-bit fixed-shift path as the default. Also fixes bottom-edge padding for ChromaSubsamplingMethod::Average, and adds fuzzing that compares the AVX2 and scalar paths byte for byte and round-trips encoder output through jpeg-decoder.

Why

The default 15-bit fixed-shift reciprocals don't match libjpeg-turbo's quantizer, so output differs from libjpeg-turbo for the same tables; the exact mode makes that match possible without changing the default. The fuzzing part exists because #40 fixed an AVX2/scalar FDCT mismatch that no test caught; a differential target would have found it within a minute.

Key changes

  • Exact quantization (src/quantization.rs, src/encoder.rs): opt-in reciprocals with a variable shift. Quantization now runs in u32, because the 16-bit reciprocals overflow i32 for large Custom divisors (e.g. divisor 1032, |v| = 32768 → ~2.16e9). An exhaustive test checks every Custom divisor against round-half-up division for all i16 inputs.
  • Average-subsampling bottom padding: when the height isn't a multiple of the MCU height, padding now repeats the last downsampled row (as libjpeg's expand_bottom_edge does) instead of averaging the repeated input row.
  • AlignedBlock exported under benchmark: fdct and fdct_avx2 were already exported there but took a pub(crate) type, so nothing outside the crate could call them and criterion/benches/fdct.rs did not compile. The normal public API is unchanged.
  • New fuzz target avx2_matches_scalar: asserts fdct_avx2 == fdct on level-shifted blocks and RgbImageAVX2 == RgbImage on rows of arbitrary width. With the pre-Fix a mismatch between AVX2 and scalar FDCT paths #40 AVX2 FDCT restored, it reports a mismatch within 60 s.
  • encode_rgb_custom_q_table fix: a + b << 8 parsed as (a + b) << 8, so every fuzzed table entry was a multiple of 256. Entries are now decoded little-endian, and one input byte toggles exact quantization.
  • New fuzz target encode_roundtrip: the fuzzer picks every encoder setting (color type, quality, sampling factor, optimized Huffman, exact quantization, average subsampling, progressive with 2..=64 scans, restart interval, width); successful output must decode with jpeg-decoder to the same dimensions, pixel format and length. Pixel values are not compared.
  • CI fuzz job: builds all fuzz targets on nightly and runs avx2_matches_scalar for 60 s.

Risks / notes

How to review

Start with compute_reciprocal_exact and the u32 quantize loop in src/quantization.rs; the overflow bound is the part worth checking by hand. Then the exact_quantization plumbing and the get_block_averaged row clamp in src/encoder.rs. The fuzzing commits are small and independent: fuzz/fuzz_targets/avx2_matches_scalar.rs and fuzz/fuzz_targets/encode_roundtrip.rs are the only new logic (the round-trip header layout is described in a comment at the start of fuzz_target!), and the rest is the benchmark export and CI wiring.

telecos and others added 7 commits November 10, 2026 12:05
…bottom padding

Add Encoder::set_exact_quantization to opt into 16-bit variable-shift
reciprocal quantization matching libjpeg-turbo's compute_reciprocal,
while keeping the existing 15-bit fixed shift as the default.

When ChromaSubsamplingMethod::Average is used on images whose height is
not a multiple of the vertical MCU size, clamp the vertical row index in
get_block_averaged so bottom padding repeats the last downsampled row
(matching libjpeg's expand_bottom_edge) instead of averaging the
repeated bottom input row.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
With the variable shift from `compute_reciprocal_exact`, the reciprocal
keeps 16 significant bits, so `(|v| + correction) * reciprocal` can
exceed i32::MAX: for divisor 1032 and |v| = 32768 it is ~2.16e9. In i32
that panics in debug builds and wraps in release, where -32768 / 1032
quantized to +32 instead of -32.

Store reciprocals and corrections as u32 and do the multiply and shift
in u32; the product stays below ~2^31.3 for every divisor `Custom` can
produce. The 15-bit default path gives the same results as before.

Adds an exhaustive test: for every `Custom` divisor (t << 3, t in
1..=2048) and every i16, exact quantization equals round-half-up
division with the sign restored.
The benchmark feature re-exports fdct and fdct_avx2, but both take
&mut AlignedBlock, which was pub(crate). Nothing outside the crate could
call them, and criterion/benches/fdct.rs did not compile because it
passed a plain [i16; 64].

Make AlignedBlock pub and re-export it only with `benchmark`; the
encoder module stays private, so the normal public API is unchanged.
The fdct bench now wraps its input in AlignedBlock::new.
avx2_matches_scalar asserts that fdct_avx2 and RgbImageAVX2 produce
exactly the same output as fdct and RgbImage. FDCT input is
level-shifted bytes (-128..=127), the range the encoder feeds it; the
RGB part is a single row of arbitrary width so both the vector body and
the remainder are hit. The target returns early without AVX2, since the
AVX2 entry points do not check for it themselves.

With the AVX2 FDCT from before ffbfcdb restored, the target reports an
fdct mismatch within 60 seconds. The fuzz crate now enables the
benchmark feature to reach these internals.
`a as u16 + (b as u16) << 8` parses as `(a + b) << 8`, so every fuzzed
table entry was a multiple of 256 and small divisors were never tried.
Decode entries with u16::from_le_bytes instead.

Byte 128 of the input now toggles set_exact_quantization, so the u32
exact-reciprocal path gets fuzzed with arbitrary Custom tables. Pixels
start at byte 129; existing corpora are still valid input, just
reinterpreted.
The fuzz targets were never built in CI, so they could rot unnoticed.
A new fuzz job installs nightly and cargo-fuzz, builds every target, and
runs avx2_matches_scalar for 60 seconds to catch AVX2/scalar mismatches
on GitHub's AVX2-capable runners.
encode_roundtrip lets the fuzzer pick every encoder setting from an
8-byte header: color type, quality, sampling factor, optimized Huffman
tables, exact quantization, average subsampling, progressive mode with
2..=64 scans, restart interval and width. When encoding succeeds, the
output must decode with jpeg-decoder to the same dimensions, pixel
format and buffer length. Pixel values are not compared, since
arbitrary input has no meaningful error bound.

On main it currently finds two known bugs within minutes: progressive
scan counts of 34..=64 write an empty AC range (fixed by vstroebel#47), and
optimized Huffman tables with a restart interval miss the DC prediction
reset (fixed by vstroebel#42). With both applied, 589k runs pass. CI builds the
target but does not run it until those land.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants