Repository navigation
Add opt-in exact reciprocal quantization and fix bottom-edge padding for box-averaged subsampling - #44
Add opt-in exact reciprocal quantization and fix bottom-edge padding for box-averaged subsampling#44telecos wants to merge 9 commits into
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>
When encoding JPEGs through SkJpegRustEncoder, opt into two jpeg-encoder settings so decoded output matches SkJpegEncoder (libjpeg-turbo): - ChromaSubsamplingMethod::Average (2x2 box filter matching libjpeg's h2v2_downsample instead of top-left nearest-neighbor point sampling), along with upstream PR #44's bottom-edge downsampled row clamping on partial-iMCU heights. - Encoder::set_exact_quantization(true) (16-bit variable-shift reciprocal division matching libjpeg-turbo's compute_reciprocal). This changes brings PR from jpeg-encoder: vstroebel/jpeg-encoder#44 Bug: 493315750 Change-Id: Id63bd04e2a8bff05e38c3799a838f0c9c5440741 Reviewed-on: https://skia-review.googlesource.com/c/skia/+/1423196 Reviewed-by: Łukasz Anforowicz <lukasza@google.com> Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.com> Reviewed-by: Florin Malita <fmalita@google.com>
…on parity" This reverts commit 2605c4a. Reason for revert: Failing Chromium skia roll [1032/11600] RUST obj/skia/librust_jpeg_ffi_e866329c.rlib obj/skia/librust_jpeg_ffi_e866329c.rmeta obj/skia/rust_jpeg_ffi.rustflags.json obj/skia/rust_jpeg_ffi.rsp.rust ../../third_party/cpython3/host/bin/python3 ../../build/rust/gni_impl/rustc_wrapper.py --dump-rustc-env-and-flags=obj/skia/rust_jpeg_ffi.rustflags.json --rsp=obj/skia/rust_jpeg_ffi.rsp --rustc=../../third_party/rust-toolchain/bin/rustc --depfile=obj/skia/librust_jpeg_ffi_e866329c.rlib.d --emit=dep-info=obj/skia/librust_jpeg_ffi_e866329c.rlib.d,link,metadata=obj/skia/librust_jpeg_ffi_e866329c.rmeta -o obj/skia/librust_jpeg_ffi_e866329c.rlib -- -Clinker=../../third_party/llvm-build/Release+Asserts/bin/clang++ ../../third_party/skia/experimental/rust_jpeg/ffi/FFI.rs LDFLAGS RUSTENV OUT_DIR=gen/skia/rust_jpeg_ffi CLIPPY_CONF_DIR=../../build/config error[E0599]: no method named `set_exact_quantization` found for struct `Encoder` in the current scope --> ../../third_party/skia/experimental/rust_jpeg/ffi/FFI.rs:1899:13 Failure Link: https://ci.chromium.org/ui/p/chromium/builders/try/android-arm64-rel/1778305/overview Original change's description: > [rust jpeg] Opt into libjpeg-turbo subsampling and quantization parity > > When encoding JPEGs through SkJpegRustEncoder, opt into two jpeg-encoder > settings so decoded output matches SkJpegEncoder (libjpeg-turbo): > > - ChromaSubsamplingMethod::Average (2x2 box filter matching libjpeg's > h2v2_downsample instead of top-left nearest-neighbor point sampling), > along with upstream PR #44's bottom-edge downsampled row clamping on > partial-iMCU heights. > - Encoder::set_exact_quantization(true) (16-bit variable-shift > reciprocal division matching libjpeg-turbo's compute_reciprocal). > > This changes brings PR from jpeg-encoder: > > vstroebel/jpeg-encoder#44 > > Bug: 493315750 > Change-Id: Id63bd04e2a8bff05e38c3799a838f0c9c5440741 > Reviewed-on: https://skia-review.googlesource.com/c/skia/+/1423196 > Reviewed-by: Łukasz Anforowicz <lukasza@google.com> > Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.com> > Reviewed-by: Florin Malita <fmalita@google.com> Bug: 493315750 No-Presubmit: true No-Tree-Checks: true No-Try: true Change-Id: Ibd45e5f3060f2cb03c998d5e371981b7d16aed35 Reviewed-on: https://skia-review.googlesource.com/c/skia/+/1424396 Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.com> Bot-Commit: rubber-stamper@appspot.gserviceaccount.com <rubber-stamper@appspot.gserviceaccount.com>
|
This patch has been incorporated to Chromium through its vendoring system in this change: https://chromium-review.googlesource.com/c/chromium/src/+/8778239 |
…tization parity - Add opt-in Encoder::set_exact_quantization(bool) (default false) to use 16-bit variable-shift reciprocal division matching libjpeg-turbo instead of a fixed 15-bit shift that rounded down on non-power-of-two quantization divisors (causing 1-step DCT differences in ViewTransitionPixelTest#testDialog). - Clamp downsampled vertical block indices at partial-iMCU bottom edges when ChromaSubsamplingMethod::Average is used, matching libjpeg's expand_bottom_edge behavior. Upstream PR: vstroebel/jpeg-encoder#44 Bug: 493315750 Change-Id: I1ad6ef6a0cf280246b3596df77704dfba050f62b Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8778239 Reviewed-by: Anton Yarkov <antonyarkov@microsoft.com> Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.com> Cr-Commit-Position: refs/heads/main@{#1741599}
…tization parity - Add opt-in Encoder::set_exact_quantization(bool) (default false) to use 16-bit variable-shift reciprocal division matching libjpeg-turbo instead of a fixed 15-bit shift that rounded down on non-power-of-two quantization divisors (causing 1-step DCT differences in ViewTransitionPixelTest#testDialog). - Clamp downsampled vertical block indices at partial-iMCU bottom edges when ChromaSubsamplingMethod::Average is used, matching libjpeg's expand_bottom_edge behavior. Upstream PR: vstroebel/jpeg-encoder#44 Bug: 493315750 Change-Id: I1ad6ef6a0cf280246b3596df77704dfba050f62b Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8778239 Reviewed-by: Anton Yarkov <antonyarkov@microsoft.com> Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.com> Cr-Commit-Position: refs/heads/main@{#1741599} NOKEYCHECK=True GitOrigin-RevId: 4fb2da04fa9ad0d180577c0135039f3872df94f1
…on parity" This is a reland of commit 2605c4a Reason of failure was that we were missing patch in jpeg-encoder crate so the newly added method was not found. No change has been done in the original skia CL. Reland should complete after following Chromium CL completes: https://chromium-review.googlesource.com/c/chromium/src/+/8778239 Original change's description: > [rust jpeg] Opt into libjpeg-turbo subsampling and quantization parity > > When encoding JPEGs through SkJpegRustEncoder, opt into two jpeg-encoder > settings so decoded output matches SkJpegEncoder (libjpeg-turbo): > > - ChromaSubsamplingMethod::Average (2x2 box filter matching libjpeg's > h2v2_downsample instead of top-left nearest-neighbor point sampling), > along with upstream PR #44's bottom-edge downsampled row clamping on > partial-iMCU heights. > - Encoder::set_exact_quantization(true) (16-bit variable-shift > reciprocal division matching libjpeg-turbo's compute_reciprocal). > > This changes brings PR from jpeg-encoder: > > vstroebel/jpeg-encoder#44 > > Bug: 493315750 > Change-Id: Id63bd04e2a8bff05e38c3799a838f0c9c5440741 > Reviewed-on: https://skia-review.googlesource.com/c/skia/+/1423196 > Reviewed-by: Łukasz Anforowicz <lukasza@google.com> > Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.com> > Reviewed-by: Florin Malita <fmalita@google.com> Bug: 493315750 Change-Id: I15f5403e1c046aa747ed385ad73f7f05f289238b Reviewed-on: https://skia-review.googlesource.com/c/skia/+/1424397 Reviewed-by: Florin Malita <fmalita@google.com> Reviewed-by: Łukasz Anforowicz <lukasza@google.com> Commit-Queue: Sergio Gonzalez Martin <sergiog@microsoft.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.
|
Thanks for this. We hit the same precision issue independently. Checked exhaustively, the fixed 15-bit shift is off by one on roughly 1–3% of reachable coefficients, in both directions (for example 999 / 80 gives 13 instead of 12). The libjpeg-turbo reciprocal here fixes that. One gap: Also, since exact rounding matches plain round-half-up division, it might be worth considering as the default rather than opt-in. That's your and @vstroebel's call, though. |
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.
Quantize in u32 so exact reciprocals cannot overflow
Guard AVX2-only fuzz code at compile time and build fuzz targets on ARM64 in CI. Select each runner's GNU target explicitly so musl-built cargo-fuzz binaries do not select an incompatible sanitizer target. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
Addressed the fuzz portability and CI issues in 6a455aa:
All nine upstream checks now pass, including both fuzz jobs: https://github.com/vstroebel/jpeg-encoder/actions/runs/45289014435 |
While enabling the experimental Rust JPEG encoder in Chromium (CL 8539408), Android pixel tests (
ViewTransitionPixelTest) failed Skia Gold comparisons because screenshots encoded at quality 85 differed slightly from thelibjpeg-turbobaseline even withChromaSubsamplingMethod::Averageenabled.Root cause
Reciprocal quantization precision (
src/quantization.rs):compute_reciprocaluses a fixed shift ofSHIFT = 15(32768 / divisor). Because quantization divisors are premultiplied by 8 (q << 3, up to2040for 8-bit tables), a fixed 15-bit shift leaves fewer than 16 bits of mantissa whendivisor > 16. Whenfractional = (1 << 15) % divisor <= divisor / 2, incrementingcorrectionby 1 only addsreciprocalto the numerator, which can be smaller thanfractional. For example, at quality 85 (q = 34,divisor = 272),reciprocal = 120andfractional = 128, so the exact midpointin_value = 136(136 / 272 = 0.5) computes((136 + 137) * 120) >> 15 = 32760 >> 15 = 0instead of1.Bottom-edge padding in
get_block_averaged(src/encoder.rs):When an image height is not a multiple of
8 * max_v_sampling(e.g.height = 1848or24with 4:2:0), the raw YCbCr buffer is padded to the full MCU height by repeating the last input row (height - 1) beforeget_block_averagedruns. Padded chroma rows therefore average(row[height - 1], row[height - 1]), whereaslibjpeg-turbo(jcprepct.c) downsamples the valid row pairs first and repeats the last downsampled row (the average ofrow[height - 2]androw[height - 1]).Proposed fix
Encoder::set_exact_quantization(bool)(defaultfalse) to opt intolibjpeg-turbo's 16-bit variable-shift reciprocal (r = 16 + divisor.ilog2()), which keeps 16 significant bits in the reciprocal and matches rounded integer division(abs_value + divisor / 2) / divisorfor all divisors. Existing default behavior (SHIFT = 15) is unchanged.get_block_averaged(used only when opting intoChromaSubsamplingMethod::Average), clamp the vertical sample index at the bottom edge so padded rows repeat the last downsampled row.