Repository navigation
Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds
Encoder::set_exact_quantization, an opt-in quantizer that matches libjpeg-turbo'scompute_reciprocal(16-bit, variable shift) while keeping the existing 15-bit fixed-shift path as the default. Also fixes bottom-edge padding forChromaSubsamplingMethod::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
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 largeCustomdivisors (e.g. divisor 1032, |v| = 32768 → ~2.16e9). An exhaustive test checks everyCustomdivisor against round-half-up division for all i16 inputs.expand_bottom_edgedoes) instead of averaging the repeated input row.AlignedBlockexported underbenchmark:fdctandfdct_avx2were already exported there but took apub(crate)type, so nothing outside the crate could call them andcriterion/benches/fdct.rsdid not compile. The normal public API is unchanged.avx2_matches_scalar: assertsfdct_avx2==fdcton level-shifted blocks andRgbImageAVX2==RgbImageon 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_tablefix:a + b << 8parsed 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.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.fuzzjob: builds all fuzz targets on nightly and runsavx2_matches_scalarfor 60 s.Risks / notes
fdct_avx2into a#[target_feature]fn, so the call infuzz/fuzz_targets/avx2_matches_scalar.rswill need anunsafeblock (the target already checks for AVX2) after whichever PR lands second.Customto 1..=255 keeps every divisor inside the range the u32 overflow analysis covers, so it only conflicts textually, not in behaviour.encode_roundtripcurrently finds two known bugs onmainwithin minutes: 34..=64 progressive scans write an empty AC range (Split progressive AC scans so every scan range is non-empty #47), and optimized Huffman tables with a restart interval miss the DC prediction reset (Reset the DC prediction at restart markers when optimizing Huffman tables #42). With both applied it runs clean, so CI builds it but does not run it yet; a 60 s run can be added once those merge.taiki-e/install-action.How to review
Start with
compute_reciprocal_exactand the u32 quantize loop insrc/quantization.rs; the overflow bound is the part worth checking by hand. Then theexact_quantizationplumbing and theget_block_averagedrow clamp insrc/encoder.rs. The fuzzing commits are small and independent:fuzz/fuzz_targets/avx2_matches_scalar.rsandfuzz/fuzz_targets/encode_roundtrip.rsare the only new logic (the round-trip header layout is described in a comment at the start offuzz_target!), and the rest is thebenchmarkexport and CI wiring.