Skip to content

Add opt-in exact reciprocal quantization and fix bottom-edge padding for box-averaged subsampling - #44

Open
telecos wants to merge 9 commits into
vstroebel:mainfrom
telecos:feat/exact-quantization
Open

telecos wants to merge 9 commits into
vstroebel:mainfrom
telecos:feat/exact-quantization

Conversation

@telecos

@telecos telecos commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

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 the libjpeg-turbo baseline even with ChromaSubsamplingMethod::Average enabled.

Root cause

  1. Reciprocal quantization precision (src/quantization.rs):
    compute_reciprocal uses a fixed shift of SHIFT = 15 (32768 / divisor). Because quantization divisors are premultiplied by 8 (q << 3, up to 2040 for 8-bit tables), a fixed 15-bit shift leaves fewer than 16 bits of mantissa when divisor > 16. When fractional = (1 << 15) % divisor <= divisor / 2, incrementing correction by 1 only adds reciprocal to the numerator, which can be smaller than fractional. For example, at quality 85 (q = 34, divisor = 272), reciprocal = 120 and fractional = 128, so the exact midpoint in_value = 136 (136 / 272 = 0.5) computes ((136 + 137) * 120) >> 15 = 32760 >> 15 = 0 instead of 1.

  2. 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 = 1848 or 24 with 4:2:0), the raw YCbCr buffer is padded to the full MCU height by repeating the last input row (height - 1) before get_block_averaged runs. Padded chroma rows therefore average (row[height - 1], row[height - 1]), whereas libjpeg-turbo (jcprepct.c) downsamples the valid row pairs first and repeats the last downsampled row (the average of row[height - 2] and row[height - 1]).

Proposed fix

  • Add Encoder::set_exact_quantization(bool) (default false) to opt into libjpeg-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) / divisor for all divisors. Existing default behavior (SHIFT = 15) is unchanged.
  • In get_block_averaged (used only when opting into ChromaSubsamplingMethod::Average), clamp the vertical sample index at the bottom edge so padded rows repeat the last downsampled row.

…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>
@telecos
telecos marked this pull request as ready for review November 10, 2026 12:14
hubot pushed a commit to google/skia that referenced this pull request Nov 10, 2026
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>
hubot pushed a commit to google/skia that referenced this pull request Nov 11, 2026
…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>
@telecos

telecos commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

This patch has been incorporated to Chromium through its vendoring system in this change:

https://chromium-review.googlesource.com/c/chromium/src/+/8778239

beckysiegel pushed a commit to chromium/chromium that referenced this pull request Nov 11, 2026
…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}
mohd-akram pushed a commit to gsource-mirror/chromium-src-third_party-rust that referenced this pull request Nov 11, 2026
…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
hubot pushed a commit to google/skia that referenced this pull request Nov 11, 2026
…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.
@sunsided

sunsided commented Nov 23, 2026 •

Copy link
Copy Markdown

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: quantize still multiplies in i32. With the exact shift, (|v| + correction) * reciprocal can exceed i32::MAX (divisor 1032, |v| = 32768 gives ~2.16e9), so it panics in debug and returns the wrong sign in release. I opened a small PR against your branch that switches the arithmetic to u32 and adds an exhaustive test over every Custom divisor and every i16: telecos#1

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.

sunsided and others added 7 commits November 23, 2026 22:51
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>
@telecos

telecos commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the fuzz portability and CI issues in 6a455aa:

  • Compile-time guard the AVX2-only imports and harness, and document that this differential target is inactive on non-x86 architectures.
  • Explicitly select each runner's GNU target for both cargo-fuzz commands. The failing job installed a musl-built cargo-fuzz binary, which otherwise defaulted to a musl fuzz target incompatible with the sanitizer build.
  • Build all fuzz targets on both x86_64 and ARM64 in CI, while retaining the 60-second AVX2/scalar differential run on x86_64.

All nine upstream checks now pass, including both fuzz jobs: https://github.com/vstroebel/jpeg-encoder/actions/runs/45289014435

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