Skip to content

Speed up JPEG decoding, ICC conversion, pixel alpha conversions and resize - #3269

Merged
JimBobSquarePants merged 10 commits into
mainfrom
js/perf-jpeg-decode
Nov 11, 2026
Merged

JimBobSquarePants merged 10 commits into
mainfrom
js/perf-jpeg-decode

Conversation

@JimBobSquarePants

@JimBobSquarePants JimBobSquarePants commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Prerequisites

  • I have written a descriptive pull-request title
  • I have verified that there are no overlapping pull-requests open
  • I have verified that I am following the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules 👮.
  • I have provided test coverage for my change (where applicable)

Description

This PR makes JPEG decoding, ICC conversion, the pixel alpha conversions and the resize faster. It also corrects faults in the decode to a target size.

Results

Load, resize and save of JPEG images to a thumbnail that fits in 150 x 150.

"TD" is a targeted decode. The library gets the thumbnail size before it decodes the image. It decodes the JPEG at a reduced scale (n/8 of the full size), then resizes the smaller image. The other rows decode the full image, then resize it. Each library uses its own API for the targeted decode:

Library Targeted decode API
ImageSharp DecoderOptions.TargetSize
MagicScaler MagicImageProcessor.ProcessImage with ProcessImageSettings
SkiaSharp SKCodec.GetScaledDimensions, then SKBitmap.Decode at that size
NetVips Image.Thumbnail, which uses the shrink-on-load of libvips

Machine: AMD Ryzen AI Max+ 395, Windows 11, .NET 10.0.14, x86-64-v4. BenchmarkDotNet v0.15.8, ShortRun.

Method Mean Error StdDev Ratio
ImageSharp (TD) Load, Resize, Save 24.62 ms 0.645 ms 0.167 ms 0.13
MagicScaler (TD) Load, Resize, Save 32.61 ms 1.037 ms 0.269 ms 0.17
SkiaSharp (TD) Load, Resize, Save 33.56 ms 0.829 ms 0.215 ms 0.17
NetVips (TD) Load, Resize, Save 56.14 ms 3.213 ms 0.834 ms 0.29
ImageSharp Load, Resize, Save 69.93 ms 5.581 ms 0.864 ms 0.36
SkiaSharp Load, Resize, Save 75.21 ms 3.284 ms 0.508 ms 0.39
ImageFree Load, Resize, Save 134.40 ms 1.621 ms 0.251 ms 0.70
ImageFlow Load, Resize, Save 139.84 ms 5.187 ms 1.347 ms 0.73
System.Drawing Load, Resize, Save 192.58 ms 5.445 ms 1.414 ms 1.00
ImageMagick Load, Resize, Save 203.04 ms 4.601 ms 1.195 ms 1.05

JPEG codec compared with libjpeg-turbo

One 12 MP image (landscape-almsee), on the same machine. BenchmarkDotNet ShortRun.

Decode to RGBA. "libjpeg-turbo (fast)" sets TJPARAM_FASTDCT and TJPARAM_FASTUPSAMPLE.

Subsampling, quality libjpeg-turbo libjpeg-turbo (fast) ImageSharp ImageSharp / libjpeg-turbo
4:2:0, q75 19.10 ms 16.84 ms 16.04 ms 0.84
4:2:0, q90 25.89 ms 23.62 ms 21.65 ms 0.84
4:4:4, q90 34.38 ms 33.30 ms 28.84 ms 0.84

Encode from RGB.

Subsampling, quality libjpeg-turbo ImageSharp ImageSharp / libjpeg-turbo
4:2:0, q75 18.81 ms 16.02 ms 0.85
4:4:4, q90 34.55 ms 23.27 ms 0.67

JPEG decoder

  • The forward and inverse DCT, the scaled IDCT, the zig-zag reorder and the block operations are static abstract operators. Each has Vector512, Vector256, Vector128 and scalar forms.
  • A block with only a DC coefficient does not go through the IDCT. The block gets the dequantized DC value.
  • Planar components convert to RGB bytes in one pass.
  • The refill fast path of the Huffman bit reader is inlined.
  • The decoder fits the source into TargetSize with ResizeMode.Max. Then it selects the smallest IDCT scale that covers the fitted size.
  • The default DecoderOptions.Sampler is now Lanczos3, not Box. Box gave visible distortion when the scaled decode was only a little larger than the target.

Decoding to a target size

  • ScaleToTargetSize resizes when the image does not have the fitted size. Before, it did not resize when one dimension was equal to the target, for example 500 x 150 for a 150 x 150 target.

ICC and companding

  • IIccColorConverter has one bulk Convert. JPEG, HEIF, TIFF and WebP convert their ICC rows in place.
  • The ICC row path of the JPEG encoder has 3 passes for RGB profiles, not 7.
  • PowOperator accepts only bases that are zero or more. All callers clamp the base, or use its magnitude.
  • The companding lookup tables are removed. All curves use the SIMD formulas.

Pixel formats

  • The alpha operators own the premultiply and unpremultiply arithmetic. The scalar and the bulk paths call the same operators.
  • The byte and ushort conversions in SimdUtils do the alpha step in the same pass.
  • Numerics.UnPremultiply(source, maximum) is the only unpremultiply rule.
  • The ref Vector4 forms in Numerics and ColorNumerics are removed. ColorNumerics.Transform has the form of the runtime Vector4.Transform.

Resize

  • Each horizontal operator convolves 4, 2 or 1 kernels and returns a full register of destination pixels.
  • The horizontal operators convolve 2 source rows in each step. Each weight load serves both rows.
  • The horizontal kernels start at multiples of 4 pixels, and the workers align their source rows to 64 bytes. Thus the pixel loads do not cross cache lines. The results have the same bits.
  • A periodic kernel map calculates the weights of each kernel of the period one time.
  • The first pass is row-major. A slide of the window is one block copy.
  • ResizeWorker.md replaces ResizeWorker.pptx. It shows the buffers and the SIMD operators in text diagrams.

Reference images

  • The references of decodes to a target size are updated for Lanczos3 and the fitted size.
  • The Bokeh and resize references are updated. The companding formulas are closer to the exact curves near black than the old tables.
  • The four Calliphora resize references are 101 x 150, the ResizeMode.Max size of 804 x 1198 in 150 x 150.

Tests

  • New tests for the IDCT scale selection, the DC-only blocks, the bit reader stream position, the alpha operators and the aligned resize kernel maps.
  • New benchmarks: IccRgbConversion and Resize_Bicubic_Rgba32_Thumbnail.

ICC
- One bulk IIccColorConverter.Convert(source, destination, convertW).
  IccTransform.ConvertsW comes from the profile device spaces.
- JPEG, HEIF, TIFF and WebP ICC rows convert Vector4 rows in place.
  The 3-byte pack stages Rgba32 in the source row, so it does not allocate.
- Pow fast path skips special-value handling when all lanes are normal.
- 128-bit gamma TRC call is not inlined, to stop register spills.

Companding
- Remove the companding lookup tables. All curves use the SIMD formulas.
  Bokeh and resize reference images are updated: the formula output is
  closer to the exact curve than the old table near black.

JPEG
- 11-bit combined Huffman lookup table in pooled memory owned by
  HuffmanScanDecoder. One read decodes most code and value pairs,
  including end of block and ZRL.
- Baseline blocks decode with a left-justified bit buffer in locals.
- JpegBitReader reads entropy data ahead into a pinned buffer from the
  memory allocator, and refills six bytes at once when none is 0xFF.
  EndScan and RewindToMarker keep the stream position as before.
- IJpegScanDecoder is IDisposable. JpegDecoderCore owns its scan decoder.

Benchmarks
- LoadResizeSave: ImageSharp full-decode case.
Decoder
- ScaleToTargetSize resizes when the image does not have the fitted size.
  It uses ResizeHelper, as the resize processor does. Before, it did not
  resize an image when one dimension was equal to the target, for example
  500 x 150 for a 150 x 150 target.

JPEG
- A block with only a DC coefficient does not go through the IDCT. The block
  gets the dequantized DC. A test shows that the IDCT gives the same values.
- Block8x8.IsDcOnly finds these blocks with no branch that depends on data.
- The refill fast path of the bit reader is inlined.
- At the end of a block without an end-of-block code, the bit reader refills
  as Receive did. Thus, NoData changes at the same block as before.
- New tests for the stream position after EndScan and RewindToMarker.

ICC
- The RGB row Convert keeps alpha also for four-channel profiles.
- The HEIF decode path does not allocate the unused RGB row.

Benchmarks
- IccRgbConversion measures the transform setup and the row conversion.
- New results in IccRgbConversion, CompandingComparison and
  LoadResizeSaveStressBenchmarks.

Documentation
- Comments and docs of this branch use simple technical English.
JPEG encoder
- The ICC row path for RGB profiles has three passes, not seven. The
  encoder unpacks the pixels to Vector4 rows, the shared Convert(row)
  converts them in place, and the packer reads them directly.
- The copies to Rgb and back are removed. They did not change R, G or B.
- The clamp to [0,1] occurs in the packer registers, with the same
  ClampToFinite rules as the removed span clamp.
- Gray, CMYK and YCbCr profiles keep the conversion through Rgb.

Measurements
- EncodeJpegIcc, time with ICC divided by time without ICC:
  issue_2723.jpg 4.45 to 4.16, issue-129.jpg 4.51 to 4.41,
  Momiji-AdobeRGB-yes.jpg 2.12 to 1.93.
Power
- PowOperator requires bases that are zero or more. All callers in main
  clamp the base, or use its magnitude and restore the sign themselves.
- The Abs, the odd-power CopySign, the negative-base NaN test and the
  IntegerMask and OddMask fields are removed from all paths.
- The scalar path gives +0 or +infinity for a zero base, the same as the
  SIMD helpers.

ICC
- SRgbCurveOperator and GammaTrcOperator call the power directly after
  their clamp at zero.

Tests
- The power tests use bases that are zero or more. The gamma test
  compares only the magnitude for a negative zero base.

Measurements
- IccRgbConversion.ConvertImageRows, in-process: 1,443 us before,
  1,362 us and 1,244 us after.

The JPEG XL fork HLG OOTF passes negative luminance to the power. That
caller must make its own decision for negative values before it merges.
JPEG decoder
- The decoder fits the source into TargetSize with ResizeMode.Max, as
  ScaleToTargetSize does. Before, it compared the block scales with the
  full target box, so the selected scale depended on the aspect ratio.
- In Combined mode a resize follows the scaled decode. The scaled image
  keeps at least two times the fitted size, because a block scale is a
  box filter inside each 8x8 block. libvips uses the same rule.
- In IdctOnly mode the scaled decode is the output. The decoder selects
  the smallest block scale that covers the fitted size.

Tests
- New scale cases for the factor of two and for a fitted target.
- The four Calliphora resize references are updated. 101 x 150 is the
  ResizeMode.Max size of 804 x 1198 in 150 x 150. The old references were
  100 x 150 because Round(100.5) of the 201 x 300 decode gave 100.
… decode

- Move the forward and inverse DCT, the scaled IDCT, the zig-zag reorder and the
  block operations to static abstract operators, with Vector512, Vector256,
  Vector128 and scalar forms.
- Make each full inverse transform a separate JIT root, so the JIT inlines all
  of its store operators. Inline the DC-only path into the row loop.
- Convert planar JPEG components to RGB bytes in one pass.
- Select the smallest IDCT scale that covers the fitted target size. The 2x
  margin is no longer necessary.
- Change the default DecoderOptions.Sampler from Box to Lanczos3. Box caused
  visible distortion when the scaled decode was only a little larger than the
  target size.
- Update the reference images for TargetSize decodes, and test the Box sampler
  at a target size where the decoder resizes.
- Rewrite the changed docs and comments in Simplified Technical English.
- Numerics owns one premultiply and one unpremultiply rule. Every
  unpremultiply form, including the integer magnitude form, uses one core.
- The pixel layer guards alpha before unpremultiply, as before.
- PixelOperations<TPixel> owns the shared per-pixel alpha conversions.
  Pixel formats call them.
- Alpha operators fuse the alpha step into the shared byte and ushort
  conversions in SimdUtils.
- The alpha operators own their arithmetic. AssociateOperator multiplies
  RGB by alpha. UnassociateOperator makes alpha a valid divisor, divides
  and bounds the result. Scalar and bulk code call the same operators.
- ClampToPixelRange<TAlpha> bounds once, then applies the operator, at
  each register width. The span loops use the 128-bit form for the last
  pixels.
- Numerics.UnPremultiply(source, maximum) is the only unpremultiply rule.
  The byte and SNORM paths call it.
- The byte and SNORM associate operators own their arithmetic. Their
  scalar forms call the operators.
- Remove the ref Vector4 forms from Numerics and ColorNumerics. Callers
  pass Vector128<float> by value.
- ColorNumerics.Transform follows the runtime Vector4.Transform form.
- Straight destinations of associated byte pixels divide the stored
  magnitudes one time. The RgbaVector bulk path does the same.
- Associated float pixels clamp before they unassociate on the scalar
  and the bulk paths.
…loads

- Horizontal operators convolve 4/2/1 kernels per register and 2 source rows per step, so each weight load serves both rows.
- Horizontal kernel maps can start kernels at multiples of 4 pixels; workers align their source rows to 64 bytes, so pixel loads do not cross cache lines.
- Periodic maps compute each period kernel once and copy shifted weight variants.
- The first pass is row-major; the slide is one block copy.
- Replace ResizeWorker.pptx with ResizeWorker.md.
- Add a thumbnail resize benchmark and aligned kernel map tests.
The resize output can differ in the last bit between CPUs. The other decode resize tests already use a tolerant comparer.
@JimBobSquarePants JimBobSquarePants linked an issue Nov 11, 2026 that may be closed by this pull request
4 tasks done
@JimBobSquarePants
JimBobSquarePants merged commit f8b28f6 into main Nov 11, 2026
12 checks passed
@JimBobSquarePants
JimBobSquarePants deleted the js/perf-jpeg-decode branch November 11, 2026 23:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JpegDecoder: Optimize HuffmanScanDecoder

1 participant