Repository navigation
Speed up JPEG decoding, ICC conversion, pixel alpha conversions and resize - #3269
Merged
Merged
Conversation
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.
4 tasks done
The resize output can differ in the last bit between CPUs. The other decode resize tests already use a tolerant comparer.
4 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prerequisites
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:
DecoderOptions.TargetSizeMagicImageProcessor.ProcessImagewithProcessImageSettingsSKCodec.GetScaledDimensions, thenSKBitmap.Decodeat that sizeImage.Thumbnail, which uses the shrink-on-load of libvipsMachine: AMD Ryzen AI Max+ 395, Windows 11, .NET 10.0.14, x86-64-v4. BenchmarkDotNet v0.15.8, ShortRun.
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_FASTDCTandTJPARAM_FASTUPSAMPLE.Encode from RGB.
JPEG decoder
TargetSizewithResizeMode.Max. Then it selects the smallest IDCT scale that covers the fitted size.DecoderOptions.Sampleris nowLanczos3, notBox.Boxgave visible distortion when the scaled decode was only a little larger than the target.Decoding to a target size
ScaleToTargetSizeresizes 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
IIccColorConverterhas one bulkConvert. JPEG, HEIF, TIFF and WebP convert their ICC rows in place.PowOperatoraccepts only bases that are zero or more. All callers clamp the base, or use its magnitude.Pixel formats
SimdUtilsdo the alpha step in the same pass.Numerics.UnPremultiply(source, maximum)is the only unpremultiply rule.ref Vector4forms inNumericsandColorNumericsare removed.ColorNumerics.Transformhas the form of the runtimeVector4.Transform.Resize
ResizeWorker.mdreplacesResizeWorker.pptx. It shows the buffers and the SIMD operators in text diagrams.Reference images
Lanczos3and the fitted size.ResizeMode.Maxsize of 804 x 1198 in 150 x 150.Tests
IccRgbConversionandResize_Bicubic_Rgba32_Thumbnail.