Skip to content

Reset the DC prediction at restart markers when optimizing Huffman tables - #42

Open
wleeaf wants to merge 1 commit into
vstroebel:mainfrom
wleeaf:optimized-huffman-restart-dc
Open

wleeaf wants to merge 1 commit into
vstroebel:mainfrom
wleeaf:optimized-huffman-restart-dc

Conversation

@wleeaf

@wleeaf wleeaf commented Oct 26, 2026

Copy link
Copy Markdown

With both set_optimized_huffman_tables(true) and set_restart_interval(n), the encoder can write a JPEG that doesn't decode.

optimize_huffman_table counts the DC differences of each component's blocks as if the prediction ran through the whole scan. When the blocks are written, though, each restart marker resets the prediction to 0, so the first DC difference after a marker is the DC value itself. That difference often falls in a category the optimized table has no code for. get_for_value then returns a zero-length code: release builds write nothing for the symbol, and debug builds hit the debug_assert! in huffman.rs.

For example, I encoded a 17x1 image with RGB, quality 95, F_1_1, a restart interval of 1 and optimized tables:

  • libjpeg-turbo's djpeg and jpeginfo -c report "Corrupt JPEG data: 7 extraneous bytes before marker 0xd1".
  • The decoded pixels are 15 dB PSNR from the source; the same image without the restart interval is 49 dB.

I tried every combination of Luma and RGB; 17x1, 300x3, 37x29 and 64x64; restart intervals 0, 1, 2, 3 and 7; optimized tables on and off; progressive on and off; and F_1_1 and F_2_2.

  • Before: all 70 corrupt or degraded files had optimized tables together with a restart interval.
  • After: none are flagged by jpeginfo -c, and every image decodes within 1 dB of the same image encoded without a restart interval.

The DC statistics now reset the prediction at the same blocks where encode_image_sequential and the DC scan of encode_image_progressive write a restart marker. With optimized tables, every scan is non-interleaved, so that is every restart_interval blocks of a component. AC statistics don't depend on the prediction and are unchanged.

Tests: test_restart_interval_optimized (RGB, interval 32) and test_restart_interval_optimized_progressive (grayscale, interval 1). Both fail on main at the debug_assert! in huffman.rs.

cargo test passes with the default features, --features simd, --features use_wide and --no-default-features --tests. cargo fmt -- --check is clean. The clippy warnings are the ones already on main.

@Shnatsel Shnatsel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not the maintainer but this looks good to me. Thank you for the PR and the detailed explanation!

jburnhams pushed a commit to jburnhams/jpeg-encoder that referenced this pull request Nov 9, 2026
leaflet-node's direct push to main was rejected by its PR-only ruleset, so
release.yml now opens and merges a release/vX.Y.Z pull request and tags the
merge commit (copied from leaflet-node PR vstroebel#42). Differences for this fork:
the last release comes from the package.json version's tag, since the
history also has upstream crate tags, and the first release publishes the
package.json version unchanged. npm-publish.yml skips versions already on
npm so a hand-published first release doesn't fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa
jburnhams added a commit to jburnhams/jpeg-encoder that referenced this pull request Nov 9, 2026
…e npm package (#8)

* Bump MSRV to 1.86

* AVX ycbcr: safety: always access the slice in &self with bounds checks instead of raw pointers

* Split the transmute into a helper function

* AVX ycbcr: safety: Always perform bounds checks on the ycbcr output buffers. Verify that there is enough capacity to hold the data before filling them to avoid buffer overflows. Treat them as MaybeUninit until they're filled to avoid exposining uninitialized memory.

* AVX ycbcr: the function no longer needs to be `unsafe`, all unsafe operations are now wrapped in safe abstractions that verify preconditions

* refactor for slightly better codegen

* cargo fmt

* expand safety comment

* Replace manual bookkeeping and unsafe{set_len()} with safe Vec methods

* Add a test verifying that AVX2 result is identical to scalar

* add a TODO

* Add a note about scalar loads

* Don't attempt to run AVX2 test on machines without AVX2

* Address compiler warning

* bump MSRV

* bump github workflow version to match MSRV

* work

* add cargo

* make sure old version still works unchanged

* remove changes

* updated fdct.rs

* Increase MSRV and bump version to 0.7.0

* Add a convenience function for embedding Exif metadata

* WIP replacement of pixel density unit enum with the struct definition from `image`

* Adjust the code to use the new struct definition

* Export PixelDensityUnit as a toplevel type

* Fix doctest

* Add ycbcr benchmark

* Fewer copies when writing metadata

* Change the public API to accept Vec now that we can make breaking changes

* Optimize ycbcr conversion

* add align on blocks so that we process on simd aligned to allow for future optimizations and auto vectorization

* aligned block

* fix avx2

* fdct: don't mark AVX helper functions as unsafe fn

* Add safe wrappers for AVX loads/stores

* Use the safe loads/store wrappers inside the AVX FDCT, drop the 'unsafe fn' from it now that it contains no unsafe ops

* Roll back to last working configuration; something must be wrong with the stores

* Fix subtle bug due to intermediate arrays being created by the try_into() call

* Switch simd feature back to opt-in, it can be flipped in a subsequent PR

* Explicitly vectorize i32x8 to u8x8 conversion for storing into YCbCr

Remove unsafe transmute in AVX2 YCbCr conversion

Prior to this, the conversion was scalarized and used a bswap.
Rewriting the code to avoid reversing the array resulted in worse
codegen that extracted the bytes and manually re-inserted them
back into the SIMD register to store 8 bytes at once.

* fix merge

* update to wide 1.0 with new policy

* add test to github action

* Implement Error in no_std

* Add cargo fmt --check to github actions

* Run cargo fmt

* Replace open coded div_ceil

* fix merge errors

* remove changes

* Add ChromaSubsamplingMethod option for box-average downsampling

Adds an opt-in ChromaSubsamplingMethod::Average that box-averages chroma
samples when subsampling, matching libjpeg/libjpeg-turbo's default
h2v2_downsample behavior — including its per-column dither of the rounding
bias so that rounding error averages to zero across each row.

The existing point-sampling behavior remains the default (Nearest), so this
is fully backward-compatible.

Box-averaging produces noticeably better quality on images with sharp
colored edges (screenshots, rendered/antialiased text), where point-sampling
can stamp an entire 2x2 block with one outlier pixel's chroma.

* Trim doc comments to match existing style

* Add missing LICENSE-IJG file

The crate's Cargo.toml declares 'license = "(MIT OR Apache-2.0) AND IJG"'
but the IJG license file was not shipped alongside LICENSE-APACHE and
LICENSE-MIT, which breaks downstream license auditing (e.g. Chromium's
README.chromium generator via gnrt expects a License File for each SPDX
component).

The IJG license text added here is the LEGAL ISSUES section reproduced
verbatim from libjpeg-turbo's README.ijg, which SPDX lists as a canonical
source for the IJG license identifier:

  https://github.com/libjpeg-turbo/libjpeg-turbo/blob/main/README.ijg
  https://spdx.org/licenses/IJG.html

The copyright line '(C) 1991-2020, Thomas G. Lane, Guido Vollbeding' matches
the IJG notice already used inside this crate's own source headers
(see src/fdct.rs).

No code or behavior changes.

* Add quality getter and setter to `Encoder`

* Add license file

* Bump vesion to 0.7.1

* Increase MSRV to 1.89

Needed for wide

* Add fuzz test for avaraged subsampling

* Cargo fmt

* Faster get_block and quantize_block on the scalar path

* Fix a mismatch between AVX2 and scalar FDCT paths

* Expose upstream encoder options in JS; add visual quality tests and a benchmark

JS API:
- StreamingJpegEncoder and encodeJpeg accept an options object: quality,
  samplingFactor, chromaSubsampling ('nearest' | 'average'), dpi, density,
  quantizationTable (WasmQuantizationTable presets), restartInterval, exif,
  iccProfile. The positional (quality, samplingFactor) form still works.
- Out-of-range quality now throws a RangeError instead of being accepted.
- The wrapper class lives once in js/encoder.js and is shared by the ESM and
  CommonJS entry points.

Tests:
- Option tests check the JFIF/APP1/APP2/DRI/DQT segments actually written.
- test/quality.test.js decodes output and checks PSNR floors per quality,
  monotonic quality/size/PSNR, parity with jpeg-js at 4:4:4, that averaged
  chroma beats nearest, and all quantization presets.
- Golden SHA-256 hashes (test/golden.json) catch any change to encoded bytes;
  accept intended changes with npm run test:golden:update.
- npm run report writes an HTML page with each case, a difference image, size
  and PSNR; CI uploads it as an artifact.
- npm run bench measures Mpx/s with jpeg-js as a baseline; CI posts a quick
  run to the job summary.

WebAssembly SIMD (simd128, with or without use_wide) was measured and not
adopted: no gain alone, about 35% slower with use_wide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

* Require Node 22 or newer and test on Node 22, 24 and 26

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

* Update dependencies: wasm-bindgen 0.2.130, TypeScript 7, GitHub Actions

- wasm-bindgen 0.2.105 -> 0.2.130 and js-sys 0.3.82 -> 0.3.107 (latest);
  CI installs the matching wasm-bindgen-cli from Cargo.lock
- cargo update for the rest of the lockfile
- TypeScript 5.9 -> 7.0 for the type check
- actions/checkout v7, setup-node v7, upload-artifact v7,
  download-artifact v8, upload-pages-artifact v5, deploy-pages v5
  (rust.yml is left as upstream's)

Encoded output is unchanged (golden hashes pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

* Match leaflet-node tooling: Biome, coverage thresholds, automatic releases

- Biome lints and formats JS, TS, JSON and workflow files (same config as
  leaflet-node); npm run lint runs in CI. Upstream's rust.yml is excluded.
- npm run test:coverage uses Node's built-in coverage on the JS entry points
  with 90% line, 80% branch and 80% function thresholds; CI runs it on
  Node 22, 24 and 26.
- engines matches leaflet-node: ^22.22.2 || ^24.15.0 || >=26.0.0
- release.yml bumps the version from commit wording and creates a GitHub
  release after CI passes on main (needs a RELEASE_TOKEN secret), which
  triggers npm-publish.yml; publishing runs on Node 24.
- Demo page buttons get explicit type attributes (Biome a11y rule).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

* Release through a version-bump pull request, as leaflet-node now does

leaflet-node's direct push to main was rejected by its PR-only ruleset, so
release.yml now opens and merges a release/vX.Y.Z pull request and tags the
merge commit (copied from leaflet-node PR vstroebel#42). Differences for this fork:
the last release comes from the package.json version's tag, since the
history also has upstream crate tags, and the first release publishes the
package.json version unchanged. npm-publish.yml skips versions already on
npm so a hand-published first release doesn't fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

* Release: bump from latest main and survive re-runs (as leaflet-node)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

* npm-publish: allow publishing an existing tag by hand (as leaflet-node)

Already triggers on release published rather than created, which is what
broke leaflet-node v3.0.0; documented why. Adds workflow_dispatch with a
tag input and checks out that tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QhgcP1BYAwmixeYzEhMNJa

---------

Co-authored-by: Sergey "Shnatsel" Davidoff <shnatsel@gmail.com>
Co-authored-by: Kristof <kristofr@gmail.com>
Co-authored-by: Volker Ströbel <volkerstroebel@mysurdity.de>
Co-authored-by: Volker Ströbel <vstroebel@users.noreply.github.com>
Co-authored-by: okaneco <47607823+okaneco@users.noreply.github.com>
Co-authored-by: tn <tn@anthropic.com>
Co-authored-by: Sergio Gonzalez <sergiog@microsoft.com>
Co-authored-by: RunDevelopment <mitchi5000.ms@googlemail.com>
Co-authored-by: Ivan Murashka <imurashka.me@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
sunsided added a commit to sunsided/jpeg-encoder that referenced this pull request Nov 23, 2026
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