Repository navigation
fix(encode): four encoder defects found by property tests and Kani - #38
Conversation
Prove the small, loop-free helpers that every decode and encode leans on: - `extend` matches T.81 F.2.2.1 for categories 1..=15 - `extend(get_code(v)) == v` for every nonzero |v| < 2^14, i.e. the encoder's magnitude coding and the decoder's sign extension agree - `get_code(0)` is category 0 - `choose_idct_size` never overflows and returns 1, 2, 4 or 8 for any frame the parser accepts - `far_row` stays inside the plane and next to the near row Kani also showed `get_code` overflows on `(1i16 << 15) - 1` at |v| >= 2^14 (category 15). The encoder never gets past category 11 for 8-bit samples, so the roundtrip proof is bounded to the reachable range. Run with `cargo kani --lib --no-default-features`. `get_code` is re-exported under `cfg(kani)` so the decoder-side proof can reach it.
New proptest suites (in-crate for internals, tests/properties.rs for the
public round trip). These tests FAIL on purpose until the defects are
fixed:
- streaming_optimize_matches_materialized / encoded_file_decodes:
optimized Huffman + trellis + streaming optimize emits symbols the
optimized table has no code for. Pass 1 trellises against the default
tables, `optimize_huffman_table_from_stats` swaps them, pass 2
trellises against the new ones. Debug panics ("Got zero size code");
release decodes Ok with MAE ~75-100 instead of ~18. Hit by default
above the 256 MiB block budget, or always with
`set_streaming_optimize(true)`.
- custom_table_dqt_matches_request / custom_dqt_value_matches_divisor:
`QuantizationTableType::Custom` accepts values up to 2048 but DQT is
written 8-bit, so 256 is stored as 0, 300 as 44.
- fibonacci_depth: `new_optimized` indexes past `bits[33]` when code
depth exceeds 32 (33 symbols, ~18.5M total count). libjpeg errors here.
- reciprocal_equals_rounded_division: the 15-bit reciprocal quantizer is
off by one on ~1-3% of reachable coefficients (999/80 -> 13).
- total_over_u32 (debug only): `freq[v1] += freq[v2]` overflows when a
table's total count exceeds u32::MAX.
Passing properties: optimized Huffman tables are prefix-free, cover
every used symbol, stay within 16 bits and keep the all-ones code
reserved; q100 luma round-trips within 3 levels; every encoder option
combination decodes via decode() and decode_planar(); the threaded
decoder matches the single-threaded one byte for byte.
With optimized Huffman tables, trellis and the streaming optimize route,
pass 1 trellised against the default AC tables and counted the result,
then `optimize_huffman_table_from_stats` replaced `huffman_tables` and
pass 2 trellised against the optimized ones. Different rate estimates
truncate differently, so pass 2 wrote symbols the optimized tables had
no code for: a debug panic ("Got zero size code"), and in release a
file that decodes Ok with MAE ~75-100 instead of ~18 (q39 luma, 256^2
to 4096^2). The route is chosen automatically above the 256 MiB block
budget, or always with `set_streaming_optimize(true)`.
Trellis now always rates against the default AC tables, held in their
own field that nothing replaces. That is also what the materializing
route already did, since it trellises before optimizing, so both routes
again decode to the same pixels
(`streaming_optimize_matches_materialized`).
`QuantizationTableType::Custom` clamped to 1..=2048, but the DQT segment is written one byte per value, so `get()` truncated: 256 was declared as 0 (an invalid table), 300 as 44, while the encoder quantized with the real value. Decoders then dequantized with a different table than the one used to encode. Clamp to 1..=255, the range baseline JPEG allows for 8-bit samples, and document it on the variant. A 16-bit DQT (Pq=1) would keep the larger values but is not valid in a baseline frame.
`new_optimized` follows T.81 K.2-K.4 literally, which sizes the code length histogram at 33 and sorts symbols by sizes 1..=32. Skewed counts build deeper trees than that: 33 symbols with near-Fibonacci counts (~18.5M total, a ~19 Mpx image with adversarial content) index past `bits[33]` and panic in debug and release. libjpeg reports an error there; this crate aborted the caller. Size the histogram for the deepest tree 257 symbols can form and sort over every size, so K.3 limits any depth to 16 bits. Also merge counts in u64: `freq[v1] += freq[v2]` overflowed (debug panic) once a table's total exceeded u32::MAX.
The quantizer divided by multiplying with a reciprocal at a fixed 15-bit shift. For large divisors that leaves only a few significant bits, and the result was off by one on ~1-3% of reachable coefficients, in both directions (999 / 80 gave 13, not 12). Use libjpeg-turbo's per-divisor shift, `16 + floor(log2 d)`, so the reciprocal keeps 16 significant bits. Checked exhaustively: equal to round-half-up division for every divisor 8..=2040 and every i16 (`reciprocal_equals_rounded_division`). The product now reaches ~2^31.01, so scalar math is u32, AVX2 uses `srlv_epi32` (the low 32 bits of `mullo_epi32` are the exact unsigned product) and NEON uses `vmulq_u32` + `vshlq_u32`. Measured on three 3840x2160 photos at q50/75/92: file size within +-0.05%, PSNR unchanged to 0.003 dB, encode time unchanged. The golden hashes for the q92 progressive and q60 trellis encodes move; baseline q75 is unchanged. The NEON kernel type-checks for aarch64 but has not run here (x86 only); `neon_matches_scalar` gates it on ARM.
The per-symbol counters are u32. The chroma slot of a 4:4:4 color image of roughly 46,700x46,700 px or more can push one symbol past u32::MAX (63 per block, Cb and Cr sharing the slot): a debug panic, or in release a wrapped count and a wrong or missing code. Luma never gets there, even at 65535x65535. Documented as a known limit at all three counting sites instead of widening the hot-path counters.
CHANGES.md is what makes re-syncing with jpeg-decoder/jpeg-encoder possible. Note which fixes are local (trellis + streaming optimize) and which also apply to jpeg-encoder 0.7.1 (custom table clamp, Huffman depth, reciprocal precision).
…ings Mutation testing showed both could be silently disabled without any test noticing: `unread_bytes` returning 0 dropped the ExtraneousBytes warning, and `unexpected_code` returning Ok(()) dropped BadHuffmanCode for refinement scans and let strict mode accept the stream. Neither warning was asserted anywhere for these cases. - extraneous_bytes_before_marker_warn: two stray bytes at the end of a scan, and at the end of a restart interval, decode to the clean image with [ExtraneousBytes]; strict mode refuses. - refinement_coefficient_of_size_two_is_a_bad_code: an AC refinement scan coding a new coefficient with size 2 decodes with [BadHuffmanCode] (libjpeg-turbo reads it as size 1); strict mode refuses with a Huffman error. Each test fails under its mutant and passes on the real code.
|
Merged and released in rusty_jpeg 0.4.13. Thank you. This is the kind of bug report we can't produce ourselves: the fuzzers only prove we don't panic and that our output decodes, and every one of these was valid output that was wrong. Writing the tests to fail first made review quick. I checked each defect out of Reproduced on
What we checked before merging:
For callers: encoder output bytes change slightly because quantization now rounds exactly. If you're up for more of this, we'd welcome the same treatment on our other crates. Property tests against a real oracle plus Kani on the small arithmetic helpers would fit most of the Remade-With-Rust codecs and parsers, and issues or PRs on any of them are welcome. Is there a repo you'd like to look at next? |
Summary
Adds proptest property tests and Kani proofs for the encoder and decoder arithmetic, and fixes the four encoder defects they found. The most serious one silently corrupted images: with optimized Huffman tables, trellis and the streaming optimize route together,
decode()returnedOkwith badly wrong pixels.Why
The fuzz targets check that malformed input never panics and that our own output decodes, but they can't see wrong-but-valid output: a file that decodes cleanly to the wrong image, or a quantized value off by one. Property tests with real oracles (streaming vs buffered output, DQT bytes vs actual divisors, exact rounded division) and Kani proofs for the small helpers cover that gap.
Key changes
QuantizationTableType::Customclamped to 1..=255. The 8-bit DQT segment truncated larger values: 256 was written as 0, while the encoder quantized with 256.HuffmanTable::new_optimizedhandles any code depth. Skewed symbol counts built trees deeper than the 32 levels the T.81 K.2 reference assumes, and indexing pastbits[33]panicked (33 symbols, ~18.5M total counts). Merged counts are now summed inu64.srlv_epi32) and NEON (vshlq_u32) kernels change together, and an exhaustive test checks every divisor against everyi16.tests/properties.rscovers the public encode → decode round trip. In-crate proptests cover Huffman table construction. Kani harnesses coverextend/get_code,choose_idct_sizeandfar_row.Risks / notes
tests/no_std_surface.rsare updated for the q92 progressive and q60 trellis encodes; baseline q75 is unchanged.Customtable values above 255 used to produce broken files and now clamp. This changes behaviour only for callers who were already getting broken output.proptestis a new dev-dependency. The Kani harnesses are gated oncfg(kani)and run withcargo kani --lib --no-default-features.u32. They can overflow on 4:4:4 color images of roughly 46,700×46,700 px and up, and this is documented in code as a known limit.jpeg-encoder0.7.1;CHANGES.mdrecords which is which. Upstream: custom DQT clamp Clamp custom quantization table values to 255 vstroebel/jpeg-encoder#45, Huffman depth Build optimized Huffman tables for any code depth vstroebel/jpeg-encoder#46. The reciprocal fix goes through the existing Add opt-in exact reciprocal quantization and fix bottom-edge padding for box-averaged subsampling vstroebel/jpeg-encoder#44 (opt-in exact quantization), with a u32-overflow fix proposed in Quantize in u32 so exact reciprocals cannot overflow telecos/jpeg-encoder#1.Review instructions
Start with the trellis commit (
d0cafc3): it's the only fix that corrupted output silently, and the newtrellis_rate_tablesfield inencoder.rsis the whole change. Then look atcompute_reciprocaland the two SIMD kernels inquantization.rs, which carry the most risk. The u32 product reaches ~2^31.01, so check that nothing on that path does signed arithmetic.new_optimized(K.2–K.4 widening) and theCustomclamp are small. The tests ina0563f1were written to fail first, so reading that commit shows each defect's reproduction before its fix.